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.

279393 lines
7.5MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #else
  55. #error "Unknown platform!"
  56. #endif
  57. #if JUCE_WINDOWS
  58. #ifdef _MSC_VER
  59. #ifdef _WIN64
  60. #define JUCE_64BIT 1
  61. #else
  62. #define JUCE_32BIT 1
  63. #endif
  64. #endif
  65. #ifdef _DEBUG
  66. #define JUCE_DEBUG 1
  67. #endif
  68. #ifdef __MINGW32__
  69. #define JUCE_MINGW 1
  70. #endif
  71. /** If defined, this indicates that the processor is little-endian. */
  72. #define JUCE_LITTLE_ENDIAN 1
  73. #define JUCE_INTEL 1
  74. #endif
  75. #if JUCE_MAC
  76. #ifndef NDEBUG
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #ifdef __LITTLE_ENDIAN__
  80. #define JUCE_LITTLE_ENDIAN 1
  81. #else
  82. #define JUCE_BIG_ENDIAN 1
  83. #endif
  84. #if defined (__ppc__) || defined (__ppc64__)
  85. #define JUCE_PPC 1
  86. #else
  87. #define JUCE_INTEL 1
  88. #endif
  89. #ifdef __LP64__
  90. #define JUCE_64BIT 1
  91. #else
  92. #define JUCE_32BIT 1
  93. #endif
  94. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  95. #error "Building for OSX 10.3 is no longer supported!"
  96. #endif
  97. #ifndef MAC_OS_X_VERSION_10_5
  98. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  99. #endif
  100. #endif
  101. #if JUCE_IOS
  102. #ifndef NDEBUG
  103. #define JUCE_DEBUG 1
  104. #endif
  105. #ifdef __LITTLE_ENDIAN__
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #else
  108. #define JUCE_BIG_ENDIAN 1
  109. #endif
  110. #endif
  111. #if JUCE_LINUX
  112. #ifdef _DEBUG
  113. #define JUCE_DEBUG 1
  114. #endif
  115. // Allow override for big-endian Linux platforms
  116. #ifndef JUCE_BIG_ENDIAN
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #endif
  119. #if defined (__LP64__) || defined (_LP64)
  120. #define JUCE_64BIT 1
  121. #else
  122. #define JUCE_32BIT 1
  123. #endif
  124. #define JUCE_INTEL 1
  125. #endif
  126. // Compiler type macros.
  127. #ifdef __GNUC__
  128. #define JUCE_GCC 1
  129. #elif defined (_MSC_VER)
  130. #define JUCE_MSVC 1
  131. #if _MSC_VER < 1500
  132. #define JUCE_VC8_OR_EARLIER 1
  133. #if _MSC_VER < 1400
  134. #define JUCE_VC7_OR_EARLIER 1
  135. #if _MSC_VER < 1300
  136. #define JUCE_VC6 1
  137. #endif
  138. #endif
  139. #endif
  140. #if ! JUCE_VC7_OR_EARLIER
  141. #define JUCE_USE_INTRINSICS 1
  142. #endif
  143. #else
  144. #error unknown compiler
  145. #endif
  146. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  147. /*** End of inlined file: juce_TargetPlatform.h ***/
  148. // FORCE_AMALGAMATOR_INCLUDE
  149. /*** Start of inlined file: juce_Config.h ***/
  150. #ifndef __JUCE_CONFIG_JUCEHEADER__
  151. #define __JUCE_CONFIG_JUCEHEADER__
  152. /*
  153. This file contains macros that enable/disable various JUCE features.
  154. */
  155. /** The name of the namespace that all Juce classes and functions will be
  156. put inside. If this is not defined, no namespace will be used.
  157. */
  158. #ifndef JUCE_NAMESPACE
  159. #define JUCE_NAMESPACE juce
  160. #endif
  161. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  162. project settings, but if you define this value, you can override this to force
  163. it to be true or false.
  164. */
  165. #ifndef JUCE_FORCE_DEBUG
  166. //#define JUCE_FORCE_DEBUG 0
  167. #endif
  168. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  169. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  170. Enabling it will also leave this turned on in release builds. When it's disabled,
  171. however, the jassert and jassertfalse macros will not be compiled in a
  172. release build.
  173. @see jassert, jassertfalse, Logger
  174. */
  175. #ifndef JUCE_LOG_ASSERTIONS
  176. #define JUCE_LOG_ASSERTIONS 0
  177. #endif
  178. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  179. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  180. on your Windows build machine.
  181. See the comments in the ASIOAudioIODevice class's header file for more
  182. info about this.
  183. */
  184. #ifndef JUCE_ASIO
  185. #define JUCE_ASIO 0
  186. #endif
  187. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  188. */
  189. #ifndef JUCE_WASAPI
  190. #define JUCE_WASAPI 0
  191. #endif
  192. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  193. */
  194. #ifndef JUCE_DIRECTSOUND
  195. #define JUCE_DIRECTSOUND 1
  196. #endif
  197. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  198. #ifndef JUCE_ALSA
  199. #define JUCE_ALSA 1
  200. #endif
  201. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  202. #ifndef JUCE_JACK
  203. #define JUCE_JACK 0
  204. #endif
  205. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  206. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  207. installed, and its header files will need to be on your include path.
  208. */
  209. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  210. #define JUCE_QUICKTIME 0
  211. #endif
  212. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  213. #undef JUCE_QUICKTIME
  214. #endif
  215. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  216. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  217. */
  218. #ifndef JUCE_OPENGL
  219. #define JUCE_OPENGL 1
  220. #endif
  221. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  222. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  223. */
  224. #ifndef JUCE_DIRECT2D
  225. #define JUCE_DIRECT2D 0
  226. #endif
  227. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  228. If your app doesn't need to read FLAC files, you might want to disable this to
  229. reduce the size of your codebase and build time.
  230. */
  231. #ifndef JUCE_USE_FLAC
  232. #define JUCE_USE_FLAC 1
  233. #endif
  234. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  235. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  236. reduce the size of your codebase and build time.
  237. */
  238. #ifndef JUCE_USE_OGGVORBIS
  239. #define JUCE_USE_OGGVORBIS 1
  240. #endif
  241. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  242. Unless you're using CD-burning, you should probably turn this flag off to
  243. reduce code size.
  244. */
  245. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  246. #define JUCE_USE_CDBURNER 1
  247. #endif
  248. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  249. Unless you're using CD-reading, you should probably turn this flag off to
  250. reduce code size.
  251. */
  252. #ifndef JUCE_USE_CDREADER
  253. #define JUCE_USE_CDREADER 1
  254. #endif
  255. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  256. */
  257. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  258. #define JUCE_USE_CAMERA 0
  259. #endif
  260. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  261. gets repainted will flash in a random colour, so that you can check exactly how much and how
  262. often your components are being drawn.
  263. */
  264. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  265. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  266. #endif
  267. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  268. Unless you specifically want to disable this, it's best to leave this option turned on.
  269. */
  270. #ifndef JUCE_USE_XINERAMA
  271. #define JUCE_USE_XINERAMA 1
  272. #endif
  273. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  274. turned on unless you have a good reason to disable it.
  275. */
  276. #ifndef JUCE_USE_XSHM
  277. #define JUCE_USE_XSHM 1
  278. #endif
  279. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  280. */
  281. #ifndef JUCE_USE_XRENDER
  282. #define JUCE_USE_XRENDER 0
  283. #endif
  284. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  285. unless you have a good reason to disable it.
  286. */
  287. #ifndef JUCE_USE_XCURSOR
  288. #define JUCE_USE_XCURSOR 1
  289. #endif
  290. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  291. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  292. you're building a plugin hosting app.
  293. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  294. */
  295. #ifndef JUCE_PLUGINHOST_VST
  296. #define JUCE_PLUGINHOST_VST 0
  297. #endif
  298. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  299. of course, and should only be enabled if you're building a plugin hosting app.
  300. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  301. */
  302. #ifndef JUCE_PLUGINHOST_AU
  303. #define JUCE_PLUGINHOST_AU 0
  304. #endif
  305. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  306. This should be enabled if you're writing a console application.
  307. */
  308. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  309. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  310. #endif
  311. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  312. If you're not using any embedded web-pages, turning this off may reduce your code size.
  313. */
  314. #ifndef JUCE_WEB_BROWSER
  315. #define JUCE_WEB_BROWSER 1
  316. #endif
  317. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  318. Carbon isn't required for a normal app, but may be needed by specialised classes like
  319. plugin-hosts, which support older APIs.
  320. */
  321. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  322. #define JUCE_SUPPORT_CARBON 1
  323. #endif
  324. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  325. You might need to tweak this if you're linking to an external zlib library in your app,
  326. but for normal apps, this option should be left alone.
  327. */
  328. #ifndef JUCE_INCLUDE_ZLIB_CODE
  329. #define JUCE_INCLUDE_ZLIB_CODE 1
  330. #endif
  331. #ifndef JUCE_INCLUDE_FLAC_CODE
  332. #define JUCE_INCLUDE_FLAC_CODE 1
  333. #endif
  334. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  335. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  336. #endif
  337. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  338. #define JUCE_INCLUDE_PNGLIB_CODE 1
  339. #endif
  340. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  341. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  342. #endif
  343. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  344. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  345. macro for more details about enabling leak checking for specific classes.
  346. */
  347. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  348. #define JUCE_CHECK_MEMORY_LEAKS 1
  349. #endif
  350. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  351. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  352. are passed to the JUCEApplication::unhandledException() callback for logging.
  353. */
  354. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  355. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  356. #endif
  357. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  358. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  359. #undef JUCE_QUICKTIME
  360. #define JUCE_QUICKTIME 0
  361. #undef JUCE_OPENGL
  362. #define JUCE_OPENGL 0
  363. #undef JUCE_USE_CDBURNER
  364. #define JUCE_USE_CDBURNER 0
  365. #undef JUCE_USE_CDREADER
  366. #define JUCE_USE_CDREADER 0
  367. #undef JUCE_WEB_BROWSER
  368. #define JUCE_WEB_BROWSER 0
  369. #undef JUCE_PLUGINHOST_AU
  370. #define JUCE_PLUGINHOST_AU 0
  371. #undef JUCE_PLUGINHOST_VST
  372. #define JUCE_PLUGINHOST_VST 0
  373. #endif
  374. #endif
  375. /*** End of inlined file: juce_Config.h ***/
  376. // FORCE_AMALGAMATOR_INCLUDE
  377. #ifndef JUCE_BUILD_CORE
  378. #define JUCE_BUILD_CORE 1
  379. #endif
  380. #ifndef JUCE_BUILD_MISC
  381. #define JUCE_BUILD_MISC 1
  382. #endif
  383. #ifndef JUCE_BUILD_GUI
  384. #define JUCE_BUILD_GUI 1
  385. #endif
  386. #ifndef JUCE_BUILD_NATIVE
  387. #define JUCE_BUILD_NATIVE 1
  388. #endif
  389. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  390. #undef JUCE_BUILD_MISC
  391. #undef JUCE_BUILD_GUI
  392. #endif
  393. //==============================================================================
  394. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  395. #if JUCE_WINDOWS
  396. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  397. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  398. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  399. #ifndef STRICT
  400. #define STRICT 1
  401. #endif
  402. #undef WIN32_LEAN_AND_MEAN
  403. #define WIN32_LEAN_AND_MEAN 1
  404. #if JUCE_MSVC
  405. #pragma warning (push)
  406. #pragma warning (disable : 4100 4201 4514 4312 4995)
  407. #endif
  408. #define _WIN32_WINNT 0x0500
  409. #define _UNICODE 1
  410. #define UNICODE 1
  411. #ifndef _WIN32_IE
  412. #define _WIN32_IE 0x0400
  413. #endif
  414. #include <windows.h>
  415. #include <windowsx.h>
  416. #include <commdlg.h>
  417. #include <shellapi.h>
  418. #include <mmsystem.h>
  419. #include <vfw.h>
  420. #include <tchar.h>
  421. #include <stddef.h>
  422. #include <ctime>
  423. #include <wininet.h>
  424. #include <nb30.h>
  425. #include <iphlpapi.h>
  426. #include <mapi.h>
  427. #include <float.h>
  428. #include <process.h>
  429. #include <Exdisp.h>
  430. #include <exdispid.h>
  431. #include <shlobj.h>
  432. #if ! JUCE_MINGW
  433. #include <crtdbg.h>
  434. #include <comutil.h>
  435. #endif
  436. #if JUCE_OPENGL
  437. #include <gl/gl.h>
  438. #endif
  439. #undef PACKED
  440. #if JUCE_ASIO
  441. /*
  442. This is very frustrating - we only need to use a handful of definitions from
  443. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  444. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  445. implementation...
  446. ..unfortunately that would break Steinberg's license agreement for use of
  447. their SDK, so I'm not allowed to do this.
  448. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  449. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  450. (see www.steinberg.net/Steinberg/Developers.asp).
  451. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  452. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  453. if you prefer). Make sure that your header search path will find the
  454. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  455. files are actually needed - so to simplify things, you could just copy
  456. these into your JUCE directory).
  457. If you're compiling and you get an error here because you don't have the
  458. ASIO SDK installed, you can disable ASIO support by commenting-out the
  459. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  460. */
  461. #include <iasiodrv.h>
  462. #endif
  463. #if JUCE_USE_CDBURNER
  464. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  465. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  466. flag in juce_Config.h to avoid these includes.
  467. */
  468. #include <imapi.h>
  469. #include <imapierror.h>
  470. #endif
  471. #if JUCE_USE_CAMERA
  472. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  473. These files are provided in the normal Windows SDK, but some Microsoft plonker
  474. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  475. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  476. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  477. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  478. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  479. The dummy file just needs to contain the following content:
  480. #define __IDxtCompositor_INTERFACE_DEFINED__
  481. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  482. #define __IDxtJpeg_INTERFACE_DEFINED__
  483. #define __IDxtKey_INTERFACE_DEFINED__
  484. ..and that should be enough to convince qedit.h that you have the SDK!
  485. */
  486. #include <dshow.h>
  487. #include <qedit.h>
  488. #include <dshowasf.h>
  489. #endif
  490. #if JUCE_WASAPI
  491. #include <MMReg.h>
  492. #include <mmdeviceapi.h>
  493. #include <Audioclient.h>
  494. #include <Avrt.h>
  495. #include <functiondiscoverykeys.h>
  496. #endif
  497. #if JUCE_QUICKTIME
  498. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  499. add its header directory to your include path.
  500. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  501. flag in juce_Config.h
  502. */
  503. #include <Movies.h>
  504. #include <QTML.h>
  505. #include <QuickTimeComponents.h>
  506. #include <MediaHandlers.h>
  507. #include <ImageCodec.h>
  508. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  509. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  510. your include search path to make these import statements work.
  511. */
  512. #import <QTOLibrary.dll>
  513. #import <QTOControl.dll>
  514. #endif
  515. #if JUCE_MSVC
  516. #pragma warning (pop)
  517. #endif
  518. #if JUCE_DIRECT2D
  519. #include <d2d1.h>
  520. #include <dwrite.h>
  521. #endif
  522. /** A simple COM smart pointer.
  523. Avoids having to include ATL just to get one of these.
  524. */
  525. template <class ComClass>
  526. class ComSmartPtr
  527. {
  528. public:
  529. ComSmartPtr() throw() : p (0) {}
  530. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  531. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  532. ~ComSmartPtr() { release(); }
  533. operator ComClass*() const throw() { return p; }
  534. ComClass& operator*() const throw() { return *p; }
  535. ComClass* operator->() const throw() { return p; }
  536. ComSmartPtr& operator= (ComClass* const newP)
  537. {
  538. if (newP != 0) newP->AddRef();
  539. release();
  540. p = newP;
  541. return *this;
  542. }
  543. ComSmartPtr& operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  544. // Releases and nullifies this pointer and returns its address
  545. ComClass** resetAndGetPointerAddress()
  546. {
  547. release();
  548. p = 0;
  549. return &p;
  550. }
  551. HRESULT CoCreateInstance (REFCLSID classUUID, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  552. {
  553. #ifndef __MINGW32__
  554. return ::CoCreateInstance (classUUID, 0, dwClsContext, __uuidof (ComClass), (void**) resetAndGetPointerAddress());
  555. #else
  556. return E_NOTIMPL;
  557. #endif
  558. }
  559. template <class OtherComClass>
  560. HRESULT QueryInterface (REFCLSID classUUID, ComSmartPtr<OtherComClass>& destObject) const
  561. {
  562. if (p == 0)
  563. return E_POINTER;
  564. return p->QueryInterface (classUUID, (void**) destObject.resetAndGetPointerAddress());
  565. }
  566. private:
  567. ComClass* p;
  568. void release() { if (p != 0) p->Release(); }
  569. ComClass** operator&() throw(); // private to avoid it being used accidentally
  570. };
  571. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  572. */
  573. template <class ComClass>
  574. class ComBaseClassHelper : public ComClass
  575. {
  576. public:
  577. ComBaseClassHelper() : refCount (1) {}
  578. virtual ~ComBaseClassHelper() {}
  579. HRESULT __stdcall QueryInterface (REFIID refId, void** result)
  580. {
  581. #ifndef __MINGW32__
  582. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  583. #endif
  584. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  585. *result = 0;
  586. return E_NOINTERFACE;
  587. }
  588. ULONG __stdcall AddRef() { return ++refCount; }
  589. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  590. protected:
  591. int refCount;
  592. };
  593. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  594. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  595. #elif JUCE_LINUX
  596. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  597. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  598. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  599. /*
  600. This file wraps together all the linux-specific headers, so
  601. that we can include them all just once, and compile all our
  602. platform-specific stuff in one big lump, keeping it out of the
  603. way of the rest of the codebase.
  604. */
  605. #include <sched.h>
  606. #include <pthread.h>
  607. #include <sys/time.h>
  608. #include <errno.h>
  609. #include <sys/stat.h>
  610. #include <sys/dir.h>
  611. #include <sys/ptrace.h>
  612. #include <sys/vfs.h>
  613. #include <sys/wait.h>
  614. #include <fnmatch.h>
  615. #include <utime.h>
  616. #include <pwd.h>
  617. #include <fcntl.h>
  618. #include <dlfcn.h>
  619. #include <netdb.h>
  620. #include <arpa/inet.h>
  621. #include <netinet/in.h>
  622. #include <sys/types.h>
  623. #include <sys/ioctl.h>
  624. #include <sys/socket.h>
  625. #include <net/if.h>
  626. #include <sys/sysinfo.h>
  627. #include <sys/file.h>
  628. #include <signal.h>
  629. /* Got a build error here? You'll need to install the freetype library...
  630. The name of the package to install is "libfreetype6-dev".
  631. */
  632. #include <ft2build.h>
  633. #include FT_FREETYPE_H
  634. #include <X11/Xlib.h>
  635. #include <X11/Xatom.h>
  636. #include <X11/Xresource.h>
  637. #include <X11/Xutil.h>
  638. #include <X11/Xmd.h>
  639. #include <X11/keysym.h>
  640. #include <X11/cursorfont.h>
  641. #if JUCE_USE_XINERAMA
  642. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  643. #include <X11/extensions/Xinerama.h>
  644. #endif
  645. #if JUCE_USE_XSHM
  646. #include <X11/extensions/XShm.h>
  647. #include <sys/shm.h>
  648. #include <sys/ipc.h>
  649. #endif
  650. #if JUCE_USE_XRENDER
  651. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  652. #include <X11/extensions/Xrender.h>
  653. #include <X11/extensions/Xcomposite.h>
  654. #endif
  655. #if JUCE_USE_XCURSOR
  656. // If you're missing this header, try installing the libxcursor-dev package
  657. #include <X11/Xcursor/Xcursor.h>
  658. #endif
  659. #if JUCE_OPENGL
  660. /* Got an include error here?
  661. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  662. and "freeglut3-dev".
  663. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  664. want to disable it.
  665. */
  666. #include <GL/glx.h>
  667. #endif
  668. #undef KeyPress
  669. #if JUCE_ALSA
  670. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  671. not got your paths set up correctly to find its header files.
  672. The package you need to install to get ASLA support is "libasound2-dev".
  673. If you don't have the ALSA library and don't want to build Juce with audio support,
  674. just disable the JUCE_ALSA flag in juce_Config.h
  675. */
  676. #include <alsa/asoundlib.h>
  677. #endif
  678. #if JUCE_JACK
  679. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  680. installed, or you've not got your paths set up correctly to find its header files.
  681. The package you need to install to get JACK support is "libjack-dev".
  682. If you don't have the jack-audio-connection-kit library and don't want to build
  683. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  684. */
  685. #include <jack/jack.h>
  686. //#include <jack/transport.h>
  687. #endif
  688. #undef SIZEOF
  689. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  690. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  691. #elif JUCE_MAC || JUCE_IPHONE
  692. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  693. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  694. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  695. /*
  696. This file wraps together all the mac-specific code, so that
  697. we can include all the native headers just once, and compile all our
  698. platform-specific stuff in one big lump, keeping it out of the way of
  699. the rest of the codebase.
  700. */
  701. #define USE_COREGRAPHICS_RENDERING 1
  702. #if JUCE_IOS
  703. #import <Foundation/Foundation.h>
  704. #import <UIKit/UIKit.h>
  705. #import <AudioToolbox/AudioToolbox.h>
  706. #import <AVFoundation/AVFoundation.h>
  707. #import <CoreData/CoreData.h>
  708. #import <MobileCoreServices/MobileCoreServices.h>
  709. #import <QuartzCore/QuartzCore.h>
  710. #include <sys/fcntl.h>
  711. #if JUCE_OPENGL
  712. #include <OpenGLES/ES1/gl.h>
  713. #include <OpenGLES/ES1/glext.h>
  714. #endif
  715. #else
  716. #import <Cocoa/Cocoa.h>
  717. #import <CoreAudio/HostTime.h>
  718. #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. #include <Carbon/Carbon.h>
  729. #include <sys/dir.h>
  730. #endif
  731. #include <sys/socket.h>
  732. #include <sys/sysctl.h>
  733. #include <sys/stat.h>
  734. #include <sys/param.h>
  735. #include <sys/mount.h>
  736. #include <fnmatch.h>
  737. #include <utime.h>
  738. #include <dlfcn.h>
  739. #include <ifaddrs.h>
  740. #include <net/if_dl.h>
  741. #include <mach/mach_time.h>
  742. #include <mach-o/dyld.h>
  743. #if MACOS_10_4_OR_EARLIER
  744. #include <GLUT/glut.h>
  745. #endif
  746. #if ! CGFLOAT_DEFINED
  747. #define CGFloat float
  748. #endif
  749. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  750. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  751. #else
  752. #error "Unknown platform!"
  753. #endif
  754. #endif
  755. //==============================================================================
  756. #define DONT_SET_USING_JUCE_NAMESPACE 1
  757. #undef max
  758. #undef min
  759. #define NO_DUMMY_DECL
  760. #if JUCE_BUILD_NATIVE
  761. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  762. #endif
  763. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  764. #pragma warning (disable: 4309 4305)
  765. #endif
  766. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  767. BEGIN_JUCE_NAMESPACE
  768. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  769. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  770. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  771. /**
  772. Creates a floating carbon window that can be used to hold a carbon UI.
  773. This is a handy class that's designed to be inlined where needed, e.g.
  774. in the audio plugin hosting code.
  775. */
  776. class CarbonViewWrapperComponent : public Component,
  777. public ComponentMovementWatcher,
  778. public Timer
  779. {
  780. public:
  781. CarbonViewWrapperComponent()
  782. : ComponentMovementWatcher (this),
  783. wrapperWindow (0),
  784. carbonWindow (0),
  785. embeddedView (0),
  786. recursiveResize (false)
  787. {
  788. }
  789. virtual ~CarbonViewWrapperComponent()
  790. {
  791. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  792. }
  793. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  794. virtual void removeView (HIViewRef embeddedView) = 0;
  795. virtual void mouseDown (int, int) {}
  796. virtual void paint() {}
  797. virtual bool getEmbeddedViewSize (int& w, int& h)
  798. {
  799. if (embeddedView == 0)
  800. return false;
  801. HIRect bounds;
  802. HIViewGetBounds (embeddedView, &bounds);
  803. w = jmax (1, roundToInt (bounds.size.width));
  804. h = jmax (1, roundToInt (bounds.size.height));
  805. return true;
  806. }
  807. void createWindow()
  808. {
  809. if (wrapperWindow == 0)
  810. {
  811. Rect r;
  812. r.left = getScreenX();
  813. r.top = getScreenY();
  814. r.right = r.left + getWidth();
  815. r.bottom = r.top + getHeight();
  816. CreateNewWindow (kDocumentWindowClass,
  817. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  818. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  819. &r, &wrapperWindow);
  820. jassert (wrapperWindow != 0);
  821. if (wrapperWindow == 0)
  822. return;
  823. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  824. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  825. [ownerWindow addChildWindow: carbonWindow
  826. ordered: NSWindowAbove];
  827. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  828. EventTypeSpec windowEventTypes[] =
  829. {
  830. { kEventClassWindow, kEventWindowGetClickActivation },
  831. { kEventClassWindow, kEventWindowHandleDeactivate },
  832. { kEventClassWindow, kEventWindowBoundsChanging },
  833. { kEventClassMouse, kEventMouseDown },
  834. { kEventClassMouse, kEventMouseMoved },
  835. { kEventClassMouse, kEventMouseDragged },
  836. { kEventClassMouse, kEventMouseUp},
  837. { kEventClassWindow, kEventWindowDrawContent },
  838. { kEventClassWindow, kEventWindowShown },
  839. { kEventClassWindow, kEventWindowHidden }
  840. };
  841. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  842. InstallWindowEventHandler (wrapperWindow, upp,
  843. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  844. windowEventTypes, this, &eventHandlerRef);
  845. setOurSizeToEmbeddedViewSize();
  846. setEmbeddedWindowToOurSize();
  847. creationTime = Time::getCurrentTime();
  848. }
  849. }
  850. void deleteWindow()
  851. {
  852. removeView (embeddedView);
  853. embeddedView = 0;
  854. if (wrapperWindow != 0)
  855. {
  856. RemoveEventHandler (eventHandlerRef);
  857. DisposeWindow (wrapperWindow);
  858. wrapperWindow = 0;
  859. }
  860. }
  861. void setOurSizeToEmbeddedViewSize()
  862. {
  863. int w, h;
  864. if (getEmbeddedViewSize (w, h))
  865. {
  866. if (w != getWidth() || h != getHeight())
  867. {
  868. startTimer (50);
  869. setSize (w, h);
  870. if (getParentComponent() != 0)
  871. getParentComponent()->setSize (w, h);
  872. }
  873. else
  874. {
  875. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  876. }
  877. }
  878. else
  879. {
  880. stopTimer();
  881. }
  882. }
  883. void setEmbeddedWindowToOurSize()
  884. {
  885. if (! recursiveResize)
  886. {
  887. recursiveResize = true;
  888. if (embeddedView != 0)
  889. {
  890. HIRect r;
  891. r.origin.x = 0;
  892. r.origin.y = 0;
  893. r.size.width = (float) getWidth();
  894. r.size.height = (float) getHeight();
  895. HIViewSetFrame (embeddedView, &r);
  896. }
  897. if (wrapperWindow != 0)
  898. {
  899. Rect wr;
  900. wr.left = getScreenX();
  901. wr.top = getScreenY();
  902. wr.right = wr.left + getWidth();
  903. wr.bottom = wr.top + getHeight();
  904. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  905. ShowWindow (wrapperWindow);
  906. }
  907. recursiveResize = false;
  908. }
  909. }
  910. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  911. {
  912. setEmbeddedWindowToOurSize();
  913. }
  914. void componentPeerChanged()
  915. {
  916. deleteWindow();
  917. createWindow();
  918. }
  919. void componentVisibilityChanged (Component&)
  920. {
  921. if (isShowing())
  922. createWindow();
  923. else
  924. deleteWindow();
  925. setEmbeddedWindowToOurSize();
  926. }
  927. static void recursiveHIViewRepaint (HIViewRef view)
  928. {
  929. HIViewSetNeedsDisplay (view, true);
  930. HIViewRef child = HIViewGetFirstSubview (view);
  931. while (child != 0)
  932. {
  933. recursiveHIViewRepaint (child);
  934. child = HIViewGetNextView (child);
  935. }
  936. }
  937. void timerCallback()
  938. {
  939. setOurSizeToEmbeddedViewSize();
  940. // To avoid strange overpainting problems when the UI is first opened, we'll
  941. // repaint it a few times during the first second that it's on-screen..
  942. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  943. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  944. }
  945. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  946. {
  947. switch (GetEventKind (event))
  948. {
  949. case kEventWindowHandleDeactivate:
  950. ActivateWindow (wrapperWindow, TRUE);
  951. return noErr;
  952. case kEventWindowGetClickActivation:
  953. {
  954. getTopLevelComponent()->toFront (false);
  955. [carbonWindow makeKeyAndOrderFront: nil];
  956. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  957. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  958. sizeof (ClickActivationResult), &howToHandleClick);
  959. HIViewSetNeedsDisplay (embeddedView, true);
  960. return noErr;
  961. }
  962. }
  963. return eventNotHandledErr;
  964. }
  965. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  966. {
  967. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  968. }
  969. protected:
  970. WindowRef wrapperWindow;
  971. NSWindow* carbonWindow;
  972. HIViewRef embeddedView;
  973. bool recursiveResize;
  974. Time creationTime;
  975. EventHandlerRef eventHandlerRef;
  976. };
  977. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  978. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  979. END_JUCE_NAMESPACE
  980. #endif
  981. #define JUCE_AMALGAMATED_TEMPLATE 1
  982. //==============================================================================
  983. #if JUCE_BUILD_CORE
  984. /*** Start of inlined file: juce_FileLogger.cpp ***/
  985. BEGIN_JUCE_NAMESPACE
  986. FileLogger::FileLogger (const File& logFile_,
  987. const String& welcomeMessage,
  988. const int maxInitialFileSizeBytes)
  989. : logFile (logFile_)
  990. {
  991. if (maxInitialFileSizeBytes >= 0)
  992. trimFileSize (maxInitialFileSizeBytes);
  993. if (! logFile_.exists())
  994. {
  995. // do this so that the parent directories get created..
  996. logFile_.create();
  997. }
  998. String welcome;
  999. welcome << "\r\n**********************************************************\r\n"
  1000. << welcomeMessage
  1001. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  1002. << "\r\n";
  1003. logMessage (welcome);
  1004. }
  1005. FileLogger::~FileLogger()
  1006. {
  1007. }
  1008. void FileLogger::logMessage (const String& message)
  1009. {
  1010. DBG (message);
  1011. const ScopedLock sl (logLock);
  1012. FileOutputStream out (logFile, 256);
  1013. out << message << "\r\n";
  1014. }
  1015. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1016. {
  1017. if (maxFileSizeBytes <= 0)
  1018. {
  1019. logFile.deleteFile();
  1020. }
  1021. else
  1022. {
  1023. const int64 fileSize = logFile.getSize();
  1024. if (fileSize > maxFileSizeBytes)
  1025. {
  1026. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1027. jassert (in != 0);
  1028. if (in != 0)
  1029. {
  1030. in->setPosition (fileSize - maxFileSizeBytes);
  1031. String content;
  1032. {
  1033. MemoryBlock contentToSave;
  1034. contentToSave.setSize (maxFileSizeBytes + 4);
  1035. contentToSave.fillWith (0);
  1036. in->read (contentToSave.getData(), maxFileSizeBytes);
  1037. in = 0;
  1038. content = contentToSave.toString();
  1039. }
  1040. int newStart = 0;
  1041. while (newStart < fileSize
  1042. && content[newStart] != '\n'
  1043. && content[newStart] != '\r')
  1044. ++newStart;
  1045. logFile.deleteFile();
  1046. logFile.appendText (content.substring (newStart), false, false);
  1047. }
  1048. }
  1049. }
  1050. }
  1051. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1052. const String& logFileName,
  1053. const String& welcomeMessage,
  1054. const int maxInitialFileSizeBytes)
  1055. {
  1056. #if JUCE_MAC
  1057. File logFile ("~/Library/Logs");
  1058. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1059. .getChildFile (logFileName);
  1060. #else
  1061. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1062. if (logFile.isDirectory())
  1063. {
  1064. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1065. .getChildFile (logFileName);
  1066. }
  1067. #endif
  1068. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1069. }
  1070. END_JUCE_NAMESPACE
  1071. /*** End of inlined file: juce_FileLogger.cpp ***/
  1072. /*** Start of inlined file: juce_Logger.cpp ***/
  1073. BEGIN_JUCE_NAMESPACE
  1074. Logger::Logger()
  1075. {
  1076. }
  1077. Logger::~Logger()
  1078. {
  1079. }
  1080. Logger* Logger::currentLogger = 0;
  1081. void Logger::setCurrentLogger (Logger* const newLogger,
  1082. const bool deleteOldLogger)
  1083. {
  1084. Logger* const oldLogger = currentLogger;
  1085. currentLogger = newLogger;
  1086. if (deleteOldLogger)
  1087. delete oldLogger;
  1088. }
  1089. void Logger::writeToLog (const String& message)
  1090. {
  1091. if (currentLogger != 0)
  1092. currentLogger->logMessage (message);
  1093. else
  1094. outputDebugString (message);
  1095. }
  1096. #if JUCE_LOG_ASSERTIONS
  1097. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1098. {
  1099. String m ("JUCE Assertion failure in ");
  1100. m << filename << ", line " << lineNum;
  1101. Logger::writeToLog (m);
  1102. }
  1103. #endif
  1104. END_JUCE_NAMESPACE
  1105. /*** End of inlined file: juce_Logger.cpp ***/
  1106. /*** Start of inlined file: juce_Random.cpp ***/
  1107. BEGIN_JUCE_NAMESPACE
  1108. Random::Random (const int64 seedValue) throw()
  1109. : seed (seedValue)
  1110. {
  1111. }
  1112. Random::~Random() throw()
  1113. {
  1114. }
  1115. void Random::setSeed (const int64 newSeed) throw()
  1116. {
  1117. seed = newSeed;
  1118. }
  1119. void Random::combineSeed (const int64 seedValue) throw()
  1120. {
  1121. seed ^= nextInt64() ^ seedValue;
  1122. }
  1123. void Random::setSeedRandomly()
  1124. {
  1125. combineSeed ((int64) (pointer_sized_int) this);
  1126. combineSeed (Time::getMillisecondCounter());
  1127. combineSeed (Time::getHighResolutionTicks());
  1128. combineSeed (Time::getHighResolutionTicksPerSecond());
  1129. combineSeed (Time::currentTimeMillis());
  1130. }
  1131. int Random::nextInt() throw()
  1132. {
  1133. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1134. return (int) (seed >> 16);
  1135. }
  1136. int Random::nextInt (const int maxValue) throw()
  1137. {
  1138. jassert (maxValue > 0);
  1139. return (nextInt() & 0x7fffffff) % maxValue;
  1140. }
  1141. int64 Random::nextInt64() throw()
  1142. {
  1143. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1144. }
  1145. bool Random::nextBool() throw()
  1146. {
  1147. return (nextInt() & 0x80000000) != 0;
  1148. }
  1149. float Random::nextFloat() throw()
  1150. {
  1151. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1152. }
  1153. double Random::nextDouble() throw()
  1154. {
  1155. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1156. }
  1157. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1158. {
  1159. BigInteger n;
  1160. do
  1161. {
  1162. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1163. }
  1164. while (n >= maximumValue);
  1165. return n;
  1166. }
  1167. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1168. {
  1169. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1170. while ((startBit & 31) != 0 && numBits > 0)
  1171. {
  1172. arrayToChange.setBit (startBit++, nextBool());
  1173. --numBits;
  1174. }
  1175. while (numBits >= 32)
  1176. {
  1177. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1178. startBit += 32;
  1179. numBits -= 32;
  1180. }
  1181. while (--numBits >= 0)
  1182. arrayToChange.setBit (startBit + numBits, nextBool());
  1183. }
  1184. Random& Random::getSystemRandom() throw()
  1185. {
  1186. static Random sysRand (1);
  1187. return sysRand;
  1188. }
  1189. END_JUCE_NAMESPACE
  1190. /*** End of inlined file: juce_Random.cpp ***/
  1191. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1192. BEGIN_JUCE_NAMESPACE
  1193. RelativeTime::RelativeTime (const double seconds_) throw()
  1194. : seconds (seconds_)
  1195. {
  1196. }
  1197. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1198. : seconds (other.seconds)
  1199. {
  1200. }
  1201. RelativeTime::~RelativeTime() throw()
  1202. {
  1203. }
  1204. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1205. {
  1206. return RelativeTime (milliseconds * 0.001);
  1207. }
  1208. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1209. {
  1210. return RelativeTime (milliseconds * 0.001);
  1211. }
  1212. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1213. {
  1214. return RelativeTime (numberOfMinutes * 60.0);
  1215. }
  1216. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1217. {
  1218. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1219. }
  1220. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1221. {
  1222. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1223. }
  1224. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1225. {
  1226. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1227. }
  1228. int64 RelativeTime::inMilliseconds() const throw()
  1229. {
  1230. return (int64) (seconds * 1000.0);
  1231. }
  1232. double RelativeTime::inMinutes() const throw()
  1233. {
  1234. return seconds / 60.0;
  1235. }
  1236. double RelativeTime::inHours() const throw()
  1237. {
  1238. return seconds / (60.0 * 60.0);
  1239. }
  1240. double RelativeTime::inDays() const throw()
  1241. {
  1242. return seconds / (60.0 * 60.0 * 24.0);
  1243. }
  1244. double RelativeTime::inWeeks() const throw()
  1245. {
  1246. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1247. }
  1248. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1249. {
  1250. if (seconds < 0.001 && seconds > -0.001)
  1251. return returnValueForZeroTime;
  1252. String result;
  1253. if (seconds < 0)
  1254. result = "-";
  1255. int fieldsShown = 0;
  1256. int n = abs ((int) inWeeks());
  1257. if (n > 0)
  1258. {
  1259. result << n << ((n == 1) ? TRANS(" week ")
  1260. : TRANS(" weeks "));
  1261. ++fieldsShown;
  1262. }
  1263. n = abs ((int) inDays()) % 7;
  1264. if (n > 0)
  1265. {
  1266. result << n << ((n == 1) ? TRANS(" day ")
  1267. : TRANS(" days "));
  1268. ++fieldsShown;
  1269. }
  1270. if (fieldsShown < 2)
  1271. {
  1272. n = abs ((int) inHours()) % 24;
  1273. if (n > 0)
  1274. {
  1275. result << n << ((n == 1) ? TRANS(" hr ")
  1276. : TRANS(" hrs "));
  1277. ++fieldsShown;
  1278. }
  1279. if (fieldsShown < 2)
  1280. {
  1281. n = abs ((int) inMinutes()) % 60;
  1282. if (n > 0)
  1283. {
  1284. result << n << ((n == 1) ? TRANS(" min ")
  1285. : TRANS(" mins "));
  1286. ++fieldsShown;
  1287. }
  1288. if (fieldsShown < 2)
  1289. {
  1290. n = abs ((int) inSeconds()) % 60;
  1291. if (n > 0)
  1292. {
  1293. result << n << ((n == 1) ? TRANS(" sec ")
  1294. : TRANS(" secs "));
  1295. ++fieldsShown;
  1296. }
  1297. if (fieldsShown < 1)
  1298. {
  1299. n = abs ((int) inMilliseconds()) % 1000;
  1300. if (n > 0)
  1301. {
  1302. result << n << TRANS(" ms");
  1303. ++fieldsShown;
  1304. }
  1305. }
  1306. }
  1307. }
  1308. }
  1309. return result.trimEnd();
  1310. }
  1311. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1312. {
  1313. seconds = other.seconds;
  1314. return *this;
  1315. }
  1316. bool RelativeTime::operator== (const RelativeTime& other) const throw() { return seconds == other.seconds; }
  1317. bool RelativeTime::operator!= (const RelativeTime& other) const throw() { return seconds != other.seconds; }
  1318. bool RelativeTime::operator> (const RelativeTime& other) const throw() { return seconds > other.seconds; }
  1319. bool RelativeTime::operator< (const RelativeTime& other) const throw() { return seconds < other.seconds; }
  1320. bool RelativeTime::operator>= (const RelativeTime& other) const throw() { return seconds >= other.seconds; }
  1321. bool RelativeTime::operator<= (const RelativeTime& other) const throw() { return seconds <= other.seconds; }
  1322. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1323. {
  1324. return RelativeTime (seconds + timeToAdd.seconds);
  1325. }
  1326. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1327. {
  1328. return RelativeTime (seconds - timeToSubtract.seconds);
  1329. }
  1330. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1331. {
  1332. return RelativeTime (seconds + secondsToAdd);
  1333. }
  1334. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1335. {
  1336. return RelativeTime (seconds - secondsToSubtract);
  1337. }
  1338. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1339. {
  1340. seconds += timeToAdd.seconds;
  1341. return *this;
  1342. }
  1343. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1344. {
  1345. seconds -= timeToSubtract.seconds;
  1346. return *this;
  1347. }
  1348. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1349. {
  1350. seconds += secondsToAdd;
  1351. return *this;
  1352. }
  1353. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1354. {
  1355. seconds -= secondsToSubtract;
  1356. return *this;
  1357. }
  1358. END_JUCE_NAMESPACE
  1359. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1360. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1361. BEGIN_JUCE_NAMESPACE
  1362. SystemStats::CPUFlags SystemStats::cpuFlags;
  1363. const String SystemStats::getJUCEVersion()
  1364. {
  1365. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1366. + "." + String (JUCE_MINOR_VERSION)
  1367. + "." + String (JUCE_BUILDNUMBER);
  1368. }
  1369. #ifdef JUCE_DLL
  1370. void* juce_Malloc (int size) { return malloc (size); }
  1371. void* juce_Calloc (int size) { return calloc (1, size); }
  1372. void* juce_Realloc (void* block, int size) { return realloc (block, size); }
  1373. void juce_Free (void* block) { free (block); }
  1374. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1375. void* juce_DebugMalloc (int size, const char* file, int line) { return _malloc_dbg (size, _NORMAL_BLOCK, file, line); }
  1376. void* juce_DebugCalloc (int size, const char* file, int line) { return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line); }
  1377. void* juce_DebugRealloc (void* block, int size, const char* file, int line) { return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line); }
  1378. void juce_DebugFree (void* block) { _free_dbg (block, _NORMAL_BLOCK); }
  1379. #endif
  1380. #endif
  1381. END_JUCE_NAMESPACE
  1382. /*** End of inlined file: juce_SystemStats.cpp ***/
  1383. /*** Start of inlined file: juce_Time.cpp ***/
  1384. #if JUCE_MSVC
  1385. #pragma warning (push)
  1386. #pragma warning (disable: 4514)
  1387. #endif
  1388. #ifndef JUCE_WINDOWS
  1389. #include <sys/time.h>
  1390. #else
  1391. #include <ctime>
  1392. #endif
  1393. #include <sys/timeb.h>
  1394. #if JUCE_MSVC
  1395. #pragma warning (pop)
  1396. #ifdef _INC_TIME_INL
  1397. #define USE_NEW_SECURE_TIME_FNS
  1398. #endif
  1399. #endif
  1400. BEGIN_JUCE_NAMESPACE
  1401. namespace TimeHelpers
  1402. {
  1403. static struct tm millisToLocal (const int64 millis) throw()
  1404. {
  1405. struct tm result;
  1406. const int64 seconds = millis / 1000;
  1407. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1408. {
  1409. // use extended maths for dates beyond 1970 to 2037..
  1410. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1411. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1412. const int days = (int) (jdm / literal64bit (86400));
  1413. const int a = 32044 + days;
  1414. const int b = (4 * a + 3) / 146097;
  1415. const int c = a - (b * 146097) / 4;
  1416. const int d = (4 * c + 3) / 1461;
  1417. const int e = c - (d * 1461) / 4;
  1418. const int m = (5 * e + 2) / 153;
  1419. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1420. result.tm_mon = m + 2 - 12 * (m / 10);
  1421. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1422. result.tm_wday = (days + 1) % 7;
  1423. result.tm_yday = -1;
  1424. int t = (int) (jdm % literal64bit (86400));
  1425. result.tm_hour = t / 3600;
  1426. t %= 3600;
  1427. result.tm_min = t / 60;
  1428. result.tm_sec = t % 60;
  1429. result.tm_isdst = -1;
  1430. }
  1431. else
  1432. {
  1433. time_t now = static_cast <time_t> (seconds);
  1434. #if JUCE_WINDOWS
  1435. #ifdef USE_NEW_SECURE_TIME_FNS
  1436. if (now >= 0 && now <= 0x793406fff)
  1437. localtime_s (&result, &now);
  1438. else
  1439. zeromem (&result, sizeof (result));
  1440. #else
  1441. result = *localtime (&now);
  1442. #endif
  1443. #else
  1444. // more thread-safe
  1445. localtime_r (&now, &result);
  1446. #endif
  1447. }
  1448. return result;
  1449. }
  1450. static int extendedModulo (const int64 value, const int modulo) throw()
  1451. {
  1452. return (int) (value >= 0 ? (value % modulo)
  1453. : (value - ((value / modulo) + 1) * modulo));
  1454. }
  1455. static uint32 lastMSCounterValue = 0;
  1456. }
  1457. Time::Time() throw()
  1458. : millisSinceEpoch (0)
  1459. {
  1460. }
  1461. Time::Time (const Time& other) throw()
  1462. : millisSinceEpoch (other.millisSinceEpoch)
  1463. {
  1464. }
  1465. Time::Time (const int64 ms) throw()
  1466. : millisSinceEpoch (ms)
  1467. {
  1468. }
  1469. Time::Time (const int year,
  1470. const int month,
  1471. const int day,
  1472. const int hours,
  1473. const int minutes,
  1474. const int seconds,
  1475. const int milliseconds,
  1476. const bool useLocalTime) throw()
  1477. {
  1478. jassert (year > 100); // year must be a 4-digit version
  1479. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1480. {
  1481. // use extended maths for dates beyond 1970 to 2037..
  1482. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1483. : 0;
  1484. const int a = (13 - month) / 12;
  1485. const int y = year + 4800 - a;
  1486. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1487. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1488. - 32045;
  1489. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1490. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1491. + milliseconds;
  1492. }
  1493. else
  1494. {
  1495. struct tm t;
  1496. t.tm_year = year - 1900;
  1497. t.tm_mon = month;
  1498. t.tm_mday = day;
  1499. t.tm_hour = hours;
  1500. t.tm_min = minutes;
  1501. t.tm_sec = seconds;
  1502. t.tm_isdst = -1;
  1503. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1504. if (millisSinceEpoch < 0)
  1505. millisSinceEpoch = 0;
  1506. else
  1507. millisSinceEpoch += milliseconds;
  1508. }
  1509. }
  1510. Time::~Time() throw()
  1511. {
  1512. }
  1513. Time& Time::operator= (const Time& other) throw()
  1514. {
  1515. millisSinceEpoch = other.millisSinceEpoch;
  1516. return *this;
  1517. }
  1518. int64 Time::currentTimeMillis() throw()
  1519. {
  1520. static uint32 lastCounterResult = 0xffffffff;
  1521. static int64 correction = 0;
  1522. const uint32 now = getMillisecondCounter();
  1523. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1524. if (now < lastCounterResult)
  1525. {
  1526. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1527. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1528. {
  1529. // get the time once using normal library calls, and store the difference needed to
  1530. // turn the millisecond counter into a real time.
  1531. #if JUCE_WINDOWS
  1532. struct _timeb t;
  1533. #ifdef USE_NEW_SECURE_TIME_FNS
  1534. _ftime_s (&t);
  1535. #else
  1536. _ftime (&t);
  1537. #endif
  1538. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1539. #else
  1540. struct timeval tv;
  1541. struct timezone tz;
  1542. gettimeofday (&tv, &tz);
  1543. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1544. #endif
  1545. }
  1546. }
  1547. lastCounterResult = now;
  1548. return correction + now;
  1549. }
  1550. uint32 juce_millisecondsSinceStartup() throw();
  1551. uint32 Time::getMillisecondCounter() throw()
  1552. {
  1553. const uint32 now = juce_millisecondsSinceStartup();
  1554. if (now < TimeHelpers::lastMSCounterValue)
  1555. {
  1556. // in multi-threaded apps this might be called concurrently, so
  1557. // make sure that our last counter value only increases and doesn't
  1558. // go backwards..
  1559. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1560. TimeHelpers::lastMSCounterValue = now;
  1561. }
  1562. else
  1563. {
  1564. TimeHelpers::lastMSCounterValue = now;
  1565. }
  1566. return now;
  1567. }
  1568. uint32 Time::getApproximateMillisecondCounter() throw()
  1569. {
  1570. jassert (TimeHelpers::lastMSCounterValue != 0);
  1571. return TimeHelpers::lastMSCounterValue;
  1572. }
  1573. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1574. {
  1575. for (;;)
  1576. {
  1577. const uint32 now = getMillisecondCounter();
  1578. if (now >= targetTime)
  1579. break;
  1580. const int toWait = targetTime - now;
  1581. if (toWait > 2)
  1582. {
  1583. Thread::sleep (jmin (20, toWait >> 1));
  1584. }
  1585. else
  1586. {
  1587. // xxx should consider using mutex_pause on the mac as it apparently
  1588. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1589. for (int i = 10; --i >= 0;)
  1590. Thread::yield();
  1591. }
  1592. }
  1593. }
  1594. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1595. {
  1596. return ticks / (double) getHighResolutionTicksPerSecond();
  1597. }
  1598. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1599. {
  1600. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1601. }
  1602. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1603. {
  1604. return Time (currentTimeMillis());
  1605. }
  1606. const String Time::toString (const bool includeDate,
  1607. const bool includeTime,
  1608. const bool includeSeconds,
  1609. const bool use24HourClock) const throw()
  1610. {
  1611. String result;
  1612. if (includeDate)
  1613. {
  1614. result << getDayOfMonth() << ' '
  1615. << getMonthName (true) << ' '
  1616. << getYear();
  1617. if (includeTime)
  1618. result << ' ';
  1619. }
  1620. if (includeTime)
  1621. {
  1622. const int mins = getMinutes();
  1623. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1624. << (mins < 10 ? ":0" : ":") << mins;
  1625. if (includeSeconds)
  1626. {
  1627. const int secs = getSeconds();
  1628. result << (secs < 10 ? ":0" : ":") << secs;
  1629. }
  1630. if (! use24HourClock)
  1631. result << (isAfternoon() ? "pm" : "am");
  1632. }
  1633. return result.trimEnd();
  1634. }
  1635. const String Time::formatted (const String& format) const
  1636. {
  1637. String buffer;
  1638. int bufferSize = 128;
  1639. buffer.preallocateStorage (bufferSize);
  1640. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1641. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1642. {
  1643. bufferSize += 128;
  1644. buffer.preallocateStorage (bufferSize);
  1645. }
  1646. return buffer;
  1647. }
  1648. int Time::getYear() const throw()
  1649. {
  1650. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1651. }
  1652. int Time::getMonth() const throw()
  1653. {
  1654. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1655. }
  1656. int Time::getDayOfMonth() const throw()
  1657. {
  1658. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1659. }
  1660. int Time::getDayOfWeek() const throw()
  1661. {
  1662. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1663. }
  1664. int Time::getHours() const throw()
  1665. {
  1666. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1667. }
  1668. int Time::getHoursInAmPmFormat() const throw()
  1669. {
  1670. const int hours = getHours();
  1671. if (hours == 0)
  1672. return 12;
  1673. else if (hours <= 12)
  1674. return hours;
  1675. else
  1676. return hours - 12;
  1677. }
  1678. bool Time::isAfternoon() const throw()
  1679. {
  1680. return getHours() >= 12;
  1681. }
  1682. int Time::getMinutes() const throw()
  1683. {
  1684. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1685. }
  1686. int Time::getSeconds() const throw()
  1687. {
  1688. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1689. }
  1690. int Time::getMilliseconds() const throw()
  1691. {
  1692. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1693. }
  1694. bool Time::isDaylightSavingTime() const throw()
  1695. {
  1696. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1697. }
  1698. const String Time::getTimeZone() const throw()
  1699. {
  1700. String zone[2];
  1701. #if JUCE_WINDOWS
  1702. _tzset();
  1703. #ifdef USE_NEW_SECURE_TIME_FNS
  1704. {
  1705. char name [128];
  1706. size_t length;
  1707. for (int i = 0; i < 2; ++i)
  1708. {
  1709. zeromem (name, sizeof (name));
  1710. _get_tzname (&length, name, 127, i);
  1711. zone[i] = name;
  1712. }
  1713. }
  1714. #else
  1715. const char** const zonePtr = (const char**) _tzname;
  1716. zone[0] = zonePtr[0];
  1717. zone[1] = zonePtr[1];
  1718. #endif
  1719. #else
  1720. tzset();
  1721. const char** const zonePtr = (const char**) tzname;
  1722. zone[0] = zonePtr[0];
  1723. zone[1] = zonePtr[1];
  1724. #endif
  1725. if (isDaylightSavingTime())
  1726. {
  1727. zone[0] = zone[1];
  1728. if (zone[0].length() > 3
  1729. && zone[0].containsIgnoreCase ("daylight")
  1730. && zone[0].contains ("GMT"))
  1731. zone[0] = "BST";
  1732. }
  1733. return zone[0].substring (0, 3);
  1734. }
  1735. const String Time::getMonthName (const bool threeLetterVersion) const
  1736. {
  1737. return getMonthName (getMonth(), threeLetterVersion);
  1738. }
  1739. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1740. {
  1741. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1742. }
  1743. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1744. {
  1745. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1746. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1747. monthNumber %= 12;
  1748. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1749. : longMonthNames [monthNumber]);
  1750. }
  1751. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1752. {
  1753. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1754. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1755. day %= 7;
  1756. return TRANS (threeLetterVersion ? shortDayNames [day]
  1757. : longDayNames [day]);
  1758. }
  1759. END_JUCE_NAMESPACE
  1760. /*** End of inlined file: juce_Time.cpp ***/
  1761. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1762. BEGIN_JUCE_NAMESPACE
  1763. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1764. #endif
  1765. #if JUCE_WINDOWS
  1766. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1767. #endif
  1768. #if JUCE_DEBUG
  1769. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1770. #endif
  1771. static bool juceInitialisedNonGUI = false;
  1772. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1773. {
  1774. if (! juceInitialisedNonGUI)
  1775. {
  1776. juceInitialisedNonGUI = true;
  1777. JUCE_AUTORELEASEPOOL
  1778. DBG (SystemStats::getJUCEVersion());
  1779. SystemStats::initialiseStats();
  1780. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1781. }
  1782. // Some basic tests, to keep an eye on things and make sure these types work ok
  1783. // on all platforms. Let me know if any of these assertions fail on your system!
  1784. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1785. static_jassert (sizeof (int8) == 1);
  1786. static_jassert (sizeof (uint8) == 1);
  1787. static_jassert (sizeof (int16) == 2);
  1788. static_jassert (sizeof (uint16) == 2);
  1789. static_jassert (sizeof (int32) == 4);
  1790. static_jassert (sizeof (uint32) == 4);
  1791. static_jassert (sizeof (int64) == 8);
  1792. static_jassert (sizeof (uint64) == 8);
  1793. }
  1794. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1795. {
  1796. if (juceInitialisedNonGUI)
  1797. {
  1798. juceInitialisedNonGUI = false;
  1799. JUCE_AUTORELEASEPOOL
  1800. LocalisedStrings::setCurrentMappings (0);
  1801. Thread::stopAllThreads (3000);
  1802. #if JUCE_WINDOWS
  1803. juce_shutdownWin32Sockets();
  1804. #endif
  1805. #if JUCE_DEBUG
  1806. juce_CheckForDanglingStreams();
  1807. #endif
  1808. }
  1809. }
  1810. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1811. void juce_setCurrentThreadName (const String& name);
  1812. static bool juceInitialisedGUI = false;
  1813. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1814. {
  1815. if (! juceInitialisedGUI)
  1816. {
  1817. juceInitialisedGUI = true;
  1818. JUCE_AUTORELEASEPOOL
  1819. initialiseJuce_NonGUI();
  1820. MessageManager::getInstance();
  1821. LookAndFeel::setDefaultLookAndFeel (0);
  1822. juce_setCurrentThreadName ("Juce Message Thread");
  1823. #if JUCE_DEBUG
  1824. // This section is just for catching people who mess up their project settings and
  1825. // turn RTTI off..
  1826. try
  1827. {
  1828. MemoryOutputStream mo;
  1829. OutputStream* o = &mo;
  1830. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1831. o = dynamic_cast <MemoryOutputStream*> (o);
  1832. jassert (o != 0);
  1833. }
  1834. catch (...)
  1835. {
  1836. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1837. jassertfalse;
  1838. }
  1839. #endif
  1840. }
  1841. }
  1842. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1843. {
  1844. if (juceInitialisedGUI)
  1845. {
  1846. juceInitialisedGUI = false;
  1847. JUCE_AUTORELEASEPOOL
  1848. DeletedAtShutdown::deleteAll();
  1849. LookAndFeel::clearDefaultLookAndFeel();
  1850. delete MessageManager::getInstance();
  1851. shutdownJuce_NonGUI();
  1852. }
  1853. }
  1854. #endif
  1855. #if JUCE_UNIT_TESTS
  1856. class AtomicTests : public UnitTest
  1857. {
  1858. public:
  1859. AtomicTests() : UnitTest ("Atomics") {}
  1860. void runTest()
  1861. {
  1862. beginTest ("Misc");
  1863. char a1[7];
  1864. expect (numElementsInArray(a1) == 7);
  1865. int a2[3];
  1866. expect (numElementsInArray(a2) == 3);
  1867. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1868. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1869. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1870. beginTest ("Atomic types");
  1871. AtomicTester <int>::testInteger (*this);
  1872. AtomicTester <unsigned int>::testInteger (*this);
  1873. AtomicTester <int32>::testInteger (*this);
  1874. AtomicTester <uint32>::testInteger (*this);
  1875. AtomicTester <long>::testInteger (*this);
  1876. AtomicTester <void*>::testInteger (*this);
  1877. AtomicTester <int*>::testInteger (*this);
  1878. AtomicTester <float>::testFloat (*this);
  1879. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1880. AtomicTester <int64>::testInteger (*this);
  1881. AtomicTester <uint64>::testInteger (*this);
  1882. AtomicTester <double>::testFloat (*this);
  1883. #endif
  1884. }
  1885. template <typename Type>
  1886. class AtomicTester
  1887. {
  1888. public:
  1889. AtomicTester() {}
  1890. static void testInteger (UnitTest& test)
  1891. {
  1892. Atomic<Type> a, b;
  1893. a.set ((Type) 10);
  1894. a += (Type) 15;
  1895. a.memoryBarrier();
  1896. a -= (Type) 5;
  1897. ++a; ++a; --a;
  1898. a.memoryBarrier();
  1899. testFloat (test);
  1900. }
  1901. static void testFloat (UnitTest& test)
  1902. {
  1903. Atomic<Type> a, b;
  1904. a = (Type) 21;
  1905. a.memoryBarrier();
  1906. /* These are some simple test cases to check the atomics - let me know
  1907. if any of these assertions fail on your system!
  1908. */
  1909. test.expect (a.get() == (Type) 21);
  1910. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1911. test.expect (a.get() == (Type) 21);
  1912. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1913. test.expect (a.get() == (Type) 101);
  1914. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1915. test.expect (a.get() == (Type) 101);
  1916. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1917. test.expect (a.get() == (Type) 200);
  1918. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1919. test.expect (a.get() == (Type) 300);
  1920. b = a;
  1921. test.expect (b.get() == a.get());
  1922. }
  1923. };
  1924. };
  1925. static AtomicTests atomicUnitTests;
  1926. #endif
  1927. END_JUCE_NAMESPACE
  1928. /*** End of inlined file: juce_Initialisation.cpp ***/
  1929. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1930. BEGIN_JUCE_NAMESPACE
  1931. AbstractFifo::AbstractFifo (const int capacity) throw()
  1932. : bufferSize (capacity)
  1933. {
  1934. jassert (bufferSize > 0);
  1935. }
  1936. AbstractFifo::~AbstractFifo() {}
  1937. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1938. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1939. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1940. void AbstractFifo::reset() throw()
  1941. {
  1942. validEnd = 0;
  1943. validStart = 0;
  1944. }
  1945. void AbstractFifo::setTotalSize (int newSize) throw()
  1946. {
  1947. jassert (newSize > 0);
  1948. reset();
  1949. bufferSize = newSize;
  1950. }
  1951. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1952. {
  1953. const int vs = validStart.get();
  1954. const int ve = validEnd.get();
  1955. const int freeSpace = bufferSize - (ve - vs);
  1956. numToWrite = jmin (numToWrite, freeSpace);
  1957. if (numToWrite <= 0)
  1958. {
  1959. startIndex1 = 0;
  1960. startIndex2 = 0;
  1961. blockSize1 = 0;
  1962. blockSize2 = 0;
  1963. }
  1964. else
  1965. {
  1966. startIndex1 = (int) (ve % bufferSize);
  1967. startIndex2 = 0;
  1968. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1969. numToWrite -= blockSize1;
  1970. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  1971. }
  1972. }
  1973. void AbstractFifo::finishedWrite (int numWritten) throw()
  1974. {
  1975. jassert (numWritten >= 0 && numWritten < bufferSize);
  1976. validEnd += numWritten;
  1977. }
  1978. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1979. {
  1980. const int vs = validStart.get();
  1981. const int ve = validEnd.get();
  1982. const int numReady = ve - vs;
  1983. numWanted = jmin (numWanted, numReady);
  1984. if (numWanted <= 0)
  1985. {
  1986. startIndex1 = 0;
  1987. startIndex2 = 0;
  1988. blockSize1 = 0;
  1989. blockSize2 = 0;
  1990. }
  1991. else
  1992. {
  1993. startIndex1 = (int) (vs % bufferSize);
  1994. startIndex2 = 0;
  1995. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  1996. numWanted -= blockSize1;
  1997. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  1998. }
  1999. }
  2000. void AbstractFifo::finishedRead (int numRead) throw()
  2001. {
  2002. jassert (numRead >= 0 && numRead < bufferSize);
  2003. validStart += numRead;
  2004. }
  2005. END_JUCE_NAMESPACE
  2006. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2007. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2008. BEGIN_JUCE_NAMESPACE
  2009. BigInteger::BigInteger()
  2010. : numValues (4),
  2011. highestBit (-1),
  2012. negative (false)
  2013. {
  2014. values.calloc (numValues + 1);
  2015. }
  2016. BigInteger::BigInteger (const int32 value)
  2017. : numValues (4),
  2018. highestBit (31),
  2019. negative (value < 0)
  2020. {
  2021. values.calloc (numValues + 1);
  2022. values[0] = abs (value);
  2023. highestBit = getHighestBit();
  2024. }
  2025. BigInteger::BigInteger (const uint32 value)
  2026. : numValues (4),
  2027. highestBit (31),
  2028. negative (false)
  2029. {
  2030. values.calloc (numValues + 1);
  2031. values[0] = value;
  2032. highestBit = getHighestBit();
  2033. }
  2034. BigInteger::BigInteger (int64 value)
  2035. : numValues (4),
  2036. highestBit (63),
  2037. negative (value < 0)
  2038. {
  2039. values.calloc (numValues + 1);
  2040. if (value < 0)
  2041. value = -value;
  2042. values[0] = (uint32) value;
  2043. values[1] = (uint32) (value >> 32);
  2044. highestBit = getHighestBit();
  2045. }
  2046. BigInteger::BigInteger (const BigInteger& other)
  2047. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2048. highestBit (other.getHighestBit()),
  2049. negative (other.negative)
  2050. {
  2051. values.malloc (numValues + 1);
  2052. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2053. }
  2054. BigInteger::~BigInteger()
  2055. {
  2056. }
  2057. void BigInteger::swapWith (BigInteger& other) throw()
  2058. {
  2059. values.swapWith (other.values);
  2060. swapVariables (numValues, other.numValues);
  2061. swapVariables (highestBit, other.highestBit);
  2062. swapVariables (negative, other.negative);
  2063. }
  2064. BigInteger& BigInteger::operator= (const BigInteger& other)
  2065. {
  2066. if (this != &other)
  2067. {
  2068. highestBit = other.getHighestBit();
  2069. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2070. negative = other.negative;
  2071. values.malloc (numValues + 1);
  2072. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2073. }
  2074. return *this;
  2075. }
  2076. void BigInteger::ensureSize (const int numVals)
  2077. {
  2078. if (numVals + 2 >= numValues)
  2079. {
  2080. int oldSize = numValues;
  2081. numValues = ((numVals + 2) * 3) / 2;
  2082. values.realloc (numValues + 1);
  2083. while (oldSize < numValues)
  2084. values [oldSize++] = 0;
  2085. }
  2086. }
  2087. bool BigInteger::operator[] (const int bit) const throw()
  2088. {
  2089. return bit <= highestBit && bit >= 0
  2090. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2091. }
  2092. int BigInteger::toInteger() const throw()
  2093. {
  2094. const int n = (int) (values[0] & 0x7fffffff);
  2095. return negative ? -n : n;
  2096. }
  2097. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2098. {
  2099. BigInteger r;
  2100. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2101. r.ensureSize (bitToIndex (numBits));
  2102. r.highestBit = numBits;
  2103. int i = 0;
  2104. while (numBits > 0)
  2105. {
  2106. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2107. numBits -= 32;
  2108. startBit += 32;
  2109. }
  2110. r.highestBit = r.getHighestBit();
  2111. return r;
  2112. }
  2113. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2114. {
  2115. if (numBits > 32)
  2116. {
  2117. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2118. numBits = 32;
  2119. }
  2120. numBits = jmin (numBits, highestBit + 1 - startBit);
  2121. if (numBits <= 0)
  2122. return 0;
  2123. const int pos = bitToIndex (startBit);
  2124. const int offset = startBit & 31;
  2125. const int endSpace = 32 - numBits;
  2126. uint32 n = ((uint32) values [pos]) >> offset;
  2127. if (offset > endSpace)
  2128. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2129. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2130. }
  2131. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2132. {
  2133. if (numBits > 32)
  2134. {
  2135. jassertfalse;
  2136. numBits = 32;
  2137. }
  2138. for (int i = 0; i < numBits; ++i)
  2139. {
  2140. setBit (startBit + i, (valueToSet & 1) != 0);
  2141. valueToSet >>= 1;
  2142. }
  2143. }
  2144. void BigInteger::clear()
  2145. {
  2146. if (numValues > 16)
  2147. {
  2148. numValues = 4;
  2149. values.calloc (numValues + 1);
  2150. }
  2151. else
  2152. {
  2153. zeromem (values, sizeof (uint32) * (numValues + 1));
  2154. }
  2155. highestBit = -1;
  2156. negative = false;
  2157. }
  2158. void BigInteger::setBit (const int bit)
  2159. {
  2160. if (bit >= 0)
  2161. {
  2162. if (bit > highestBit)
  2163. {
  2164. ensureSize (bitToIndex (bit));
  2165. highestBit = bit;
  2166. }
  2167. values [bitToIndex (bit)] |= bitToMask (bit);
  2168. }
  2169. }
  2170. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2171. {
  2172. if (shouldBeSet)
  2173. setBit (bit);
  2174. else
  2175. clearBit (bit);
  2176. }
  2177. void BigInteger::clearBit (const int bit) throw()
  2178. {
  2179. if (bit >= 0 && bit <= highestBit)
  2180. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2181. }
  2182. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2183. {
  2184. while (--numBits >= 0)
  2185. setBit (startBit++, shouldBeSet);
  2186. }
  2187. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2188. {
  2189. if (bit >= 0)
  2190. shiftBits (1, bit);
  2191. setBit (bit, shouldBeSet);
  2192. }
  2193. bool BigInteger::isZero() const throw()
  2194. {
  2195. return getHighestBit() < 0;
  2196. }
  2197. bool BigInteger::isOne() const throw()
  2198. {
  2199. return getHighestBit() == 0 && ! negative;
  2200. }
  2201. bool BigInteger::isNegative() const throw()
  2202. {
  2203. return negative && ! isZero();
  2204. }
  2205. void BigInteger::setNegative (const bool neg) throw()
  2206. {
  2207. negative = neg;
  2208. }
  2209. void BigInteger::negate() throw()
  2210. {
  2211. negative = (! negative) && ! isZero();
  2212. }
  2213. #if JUCE_USE_INTRINSICS
  2214. #pragma intrinsic (_BitScanReverse)
  2215. #endif
  2216. namespace BitFunctions
  2217. {
  2218. inline int countBitsInInt32 (uint32 n) throw()
  2219. {
  2220. n -= ((n >> 1) & 0x55555555);
  2221. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2222. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2223. n += (n >> 8);
  2224. n += (n >> 16);
  2225. return n & 0x3f;
  2226. }
  2227. inline int highestBitInInt (uint32 n) throw()
  2228. {
  2229. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2230. #if JUCE_GCC
  2231. return 31 - __builtin_clz (n);
  2232. #elif JUCE_USE_INTRINSICS
  2233. unsigned long highest;
  2234. _BitScanReverse (&highest, n);
  2235. return (int) highest;
  2236. #else
  2237. n |= (n >> 1);
  2238. n |= (n >> 2);
  2239. n |= (n >> 4);
  2240. n |= (n >> 8);
  2241. n |= (n >> 16);
  2242. return countBitsInInt32 (n >> 1);
  2243. #endif
  2244. }
  2245. }
  2246. int BigInteger::countNumberOfSetBits() const throw()
  2247. {
  2248. int total = 0;
  2249. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2250. total += BitFunctions::countBitsInInt32 (values[i]);
  2251. return total;
  2252. }
  2253. int BigInteger::getHighestBit() const throw()
  2254. {
  2255. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2256. {
  2257. const uint32 n = values[i];
  2258. if (n != 0)
  2259. return BitFunctions::highestBitInInt (n) + (i << 5);
  2260. }
  2261. return -1;
  2262. }
  2263. int BigInteger::findNextSetBit (int i) const throw()
  2264. {
  2265. for (; i <= highestBit; ++i)
  2266. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2267. return i;
  2268. return -1;
  2269. }
  2270. int BigInteger::findNextClearBit (int i) const throw()
  2271. {
  2272. for (; i <= highestBit; ++i)
  2273. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2274. break;
  2275. return i;
  2276. }
  2277. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2278. {
  2279. if (other.isNegative())
  2280. return operator-= (-other);
  2281. if (isNegative())
  2282. {
  2283. if (compareAbsolute (other) < 0)
  2284. {
  2285. BigInteger temp (*this);
  2286. temp.negate();
  2287. *this = other;
  2288. operator-= (temp);
  2289. }
  2290. else
  2291. {
  2292. negate();
  2293. operator-= (other);
  2294. negate();
  2295. }
  2296. }
  2297. else
  2298. {
  2299. if (other.highestBit > highestBit)
  2300. highestBit = other.highestBit;
  2301. ++highestBit;
  2302. const int numInts = bitToIndex (highestBit) + 1;
  2303. ensureSize (numInts);
  2304. int64 remainder = 0;
  2305. for (int i = 0; i <= numInts; ++i)
  2306. {
  2307. if (i < numValues)
  2308. remainder += values[i];
  2309. if (i < other.numValues)
  2310. remainder += other.values[i];
  2311. values[i] = (uint32) remainder;
  2312. remainder >>= 32;
  2313. }
  2314. jassert (remainder == 0);
  2315. highestBit = getHighestBit();
  2316. }
  2317. return *this;
  2318. }
  2319. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2320. {
  2321. if (other.isNegative())
  2322. return operator+= (-other);
  2323. if (! isNegative())
  2324. {
  2325. if (compareAbsolute (other) < 0)
  2326. {
  2327. BigInteger temp (other);
  2328. swapWith (temp);
  2329. operator-= (temp);
  2330. negate();
  2331. return *this;
  2332. }
  2333. }
  2334. else
  2335. {
  2336. negate();
  2337. operator+= (other);
  2338. negate();
  2339. return *this;
  2340. }
  2341. const int numInts = bitToIndex (highestBit) + 1;
  2342. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2343. int64 amountToSubtract = 0;
  2344. for (int i = 0; i <= numInts; ++i)
  2345. {
  2346. if (i <= maxOtherInts)
  2347. amountToSubtract += (int64) other.values[i];
  2348. if (values[i] >= amountToSubtract)
  2349. {
  2350. values[i] = (uint32) (values[i] - amountToSubtract);
  2351. amountToSubtract = 0;
  2352. }
  2353. else
  2354. {
  2355. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2356. values[i] = (uint32) n;
  2357. amountToSubtract = 1;
  2358. }
  2359. }
  2360. return *this;
  2361. }
  2362. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2363. {
  2364. BigInteger total;
  2365. highestBit = getHighestBit();
  2366. const bool wasNegative = isNegative();
  2367. setNegative (false);
  2368. for (int i = 0; i <= highestBit; ++i)
  2369. {
  2370. if (operator[](i))
  2371. {
  2372. BigInteger n (other);
  2373. n.setNegative (false);
  2374. n <<= i;
  2375. total += n;
  2376. }
  2377. }
  2378. total.setNegative (wasNegative ^ other.isNegative());
  2379. swapWith (total);
  2380. return *this;
  2381. }
  2382. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2383. {
  2384. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2385. const int divHB = divisor.getHighestBit();
  2386. const int ourHB = getHighestBit();
  2387. if (divHB < 0 || ourHB < 0)
  2388. {
  2389. // division by zero
  2390. remainder.clear();
  2391. clear();
  2392. }
  2393. else
  2394. {
  2395. const bool wasNegative = isNegative();
  2396. swapWith (remainder);
  2397. remainder.setNegative (false);
  2398. clear();
  2399. BigInteger temp (divisor);
  2400. temp.setNegative (false);
  2401. int leftShift = ourHB - divHB;
  2402. temp <<= leftShift;
  2403. while (leftShift >= 0)
  2404. {
  2405. if (remainder.compareAbsolute (temp) >= 0)
  2406. {
  2407. remainder -= temp;
  2408. setBit (leftShift);
  2409. }
  2410. if (--leftShift >= 0)
  2411. temp >>= 1;
  2412. }
  2413. negative = wasNegative ^ divisor.isNegative();
  2414. remainder.setNegative (wasNegative);
  2415. }
  2416. }
  2417. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2418. {
  2419. BigInteger remainder;
  2420. divideBy (other, remainder);
  2421. return *this;
  2422. }
  2423. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2424. {
  2425. // this operation doesn't take into account negative values..
  2426. jassert (isNegative() == other.isNegative());
  2427. if (other.highestBit >= 0)
  2428. {
  2429. ensureSize (bitToIndex (other.highestBit));
  2430. int n = bitToIndex (other.highestBit) + 1;
  2431. while (--n >= 0)
  2432. values[n] |= other.values[n];
  2433. if (other.highestBit > highestBit)
  2434. highestBit = other.highestBit;
  2435. highestBit = getHighestBit();
  2436. }
  2437. return *this;
  2438. }
  2439. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2440. {
  2441. // this operation doesn't take into account negative values..
  2442. jassert (isNegative() == other.isNegative());
  2443. int n = numValues;
  2444. while (n > other.numValues)
  2445. values[--n] = 0;
  2446. while (--n >= 0)
  2447. values[n] &= other.values[n];
  2448. if (other.highestBit < highestBit)
  2449. highestBit = other.highestBit;
  2450. highestBit = getHighestBit();
  2451. return *this;
  2452. }
  2453. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2454. {
  2455. // this operation will only work with the absolute values
  2456. jassert (isNegative() == other.isNegative());
  2457. if (other.highestBit >= 0)
  2458. {
  2459. ensureSize (bitToIndex (other.highestBit));
  2460. int n = bitToIndex (other.highestBit) + 1;
  2461. while (--n >= 0)
  2462. values[n] ^= other.values[n];
  2463. if (other.highestBit > highestBit)
  2464. highestBit = other.highestBit;
  2465. highestBit = getHighestBit();
  2466. }
  2467. return *this;
  2468. }
  2469. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2470. {
  2471. BigInteger remainder;
  2472. divideBy (divisor, remainder);
  2473. swapWith (remainder);
  2474. return *this;
  2475. }
  2476. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2477. {
  2478. shiftBits (numBitsToShift, 0);
  2479. return *this;
  2480. }
  2481. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2482. {
  2483. return operator<<= (-numBitsToShift);
  2484. }
  2485. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2486. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2487. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2488. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2489. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2490. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2491. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2492. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2493. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2494. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2495. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2496. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2497. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2498. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2499. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2500. int BigInteger::compare (const BigInteger& other) const throw()
  2501. {
  2502. if (isNegative() == other.isNegative())
  2503. {
  2504. const int absComp = compareAbsolute (other);
  2505. return isNegative() ? -absComp : absComp;
  2506. }
  2507. else
  2508. {
  2509. return isNegative() ? -1 : 1;
  2510. }
  2511. }
  2512. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2513. {
  2514. const int h1 = getHighestBit();
  2515. const int h2 = other.getHighestBit();
  2516. if (h1 > h2)
  2517. return 1;
  2518. else if (h1 < h2)
  2519. return -1;
  2520. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2521. if (values[i] != other.values[i])
  2522. return (values[i] > other.values[i]) ? 1 : -1;
  2523. return 0;
  2524. }
  2525. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2526. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2527. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2528. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2529. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2530. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2531. void BigInteger::shiftBits (int bits, const int startBit)
  2532. {
  2533. if (highestBit < 0)
  2534. return;
  2535. if (startBit > 0)
  2536. {
  2537. if (bits < 0)
  2538. {
  2539. // right shift
  2540. for (int i = startBit; i <= highestBit; ++i)
  2541. setBit (i, operator[] (i - bits));
  2542. highestBit = getHighestBit();
  2543. }
  2544. else if (bits > 0)
  2545. {
  2546. // left shift
  2547. for (int i = highestBit + 1; --i >= startBit;)
  2548. setBit (i + bits, operator[] (i));
  2549. while (--bits >= 0)
  2550. clearBit (bits + startBit);
  2551. }
  2552. }
  2553. else
  2554. {
  2555. if (bits < 0)
  2556. {
  2557. // right shift
  2558. bits = -bits;
  2559. if (bits > highestBit)
  2560. {
  2561. clear();
  2562. }
  2563. else
  2564. {
  2565. const int wordsToMove = bitToIndex (bits);
  2566. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2567. highestBit -= bits;
  2568. if (wordsToMove > 0)
  2569. {
  2570. int i;
  2571. for (i = 0; i < top; ++i)
  2572. values [i] = values [i + wordsToMove];
  2573. for (i = 0; i < wordsToMove; ++i)
  2574. values [top + i] = 0;
  2575. bits &= 31;
  2576. }
  2577. if (bits != 0)
  2578. {
  2579. const int invBits = 32 - bits;
  2580. --top;
  2581. for (int i = 0; i < top; ++i)
  2582. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2583. values[top] = (values[top] >> bits);
  2584. }
  2585. highestBit = getHighestBit();
  2586. }
  2587. }
  2588. else if (bits > 0)
  2589. {
  2590. // left shift
  2591. ensureSize (bitToIndex (highestBit + bits) + 1);
  2592. const int wordsToMove = bitToIndex (bits);
  2593. int top = 1 + bitToIndex (highestBit);
  2594. highestBit += bits;
  2595. if (wordsToMove > 0)
  2596. {
  2597. int i;
  2598. for (i = top; --i >= 0;)
  2599. values [i + wordsToMove] = values [i];
  2600. for (i = 0; i < wordsToMove; ++i)
  2601. values [i] = 0;
  2602. bits &= 31;
  2603. }
  2604. if (bits != 0)
  2605. {
  2606. const int invBits = 32 - bits;
  2607. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2608. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2609. values [wordsToMove] = values [wordsToMove] << bits;
  2610. }
  2611. highestBit = getHighestBit();
  2612. }
  2613. }
  2614. }
  2615. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2616. {
  2617. while (! m->isZero())
  2618. {
  2619. if (n->compareAbsolute (*m) > 0)
  2620. swapVariables (m, n);
  2621. *m -= *n;
  2622. }
  2623. return *n;
  2624. }
  2625. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2626. {
  2627. BigInteger m (*this);
  2628. while (! n.isZero())
  2629. {
  2630. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2631. return simpleGCD (&m, &n);
  2632. BigInteger temp1 (m), temp2;
  2633. temp1.divideBy (n, temp2);
  2634. m = n;
  2635. n = temp2;
  2636. }
  2637. return m;
  2638. }
  2639. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2640. {
  2641. BigInteger exp (exponent);
  2642. exp %= modulus;
  2643. BigInteger value (1);
  2644. swapWith (value);
  2645. value %= modulus;
  2646. while (! exp.isZero())
  2647. {
  2648. if (exp [0])
  2649. {
  2650. operator*= (value);
  2651. operator%= (modulus);
  2652. }
  2653. value *= value;
  2654. value %= modulus;
  2655. exp >>= 1;
  2656. }
  2657. }
  2658. void BigInteger::inverseModulo (const BigInteger& modulus)
  2659. {
  2660. if (modulus.isOne() || modulus.isNegative())
  2661. {
  2662. clear();
  2663. return;
  2664. }
  2665. if (isNegative() || compareAbsolute (modulus) >= 0)
  2666. operator%= (modulus);
  2667. if (isOne())
  2668. return;
  2669. if (! (*this)[0])
  2670. {
  2671. // not invertible
  2672. clear();
  2673. return;
  2674. }
  2675. BigInteger a1 (modulus);
  2676. BigInteger a2 (*this);
  2677. BigInteger b1 (modulus);
  2678. BigInteger b2 (1);
  2679. while (! a2.isOne())
  2680. {
  2681. BigInteger temp1, temp2, multiplier (a1);
  2682. multiplier.divideBy (a2, temp1);
  2683. temp1 = a2;
  2684. temp1 *= multiplier;
  2685. temp2 = a1;
  2686. temp2 -= temp1;
  2687. a1 = a2;
  2688. a2 = temp2;
  2689. temp1 = b2;
  2690. temp1 *= multiplier;
  2691. temp2 = b1;
  2692. temp2 -= temp1;
  2693. b1 = b2;
  2694. b2 = temp2;
  2695. }
  2696. while (b2.isNegative())
  2697. b2 += modulus;
  2698. b2 %= modulus;
  2699. swapWith (b2);
  2700. }
  2701. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2702. {
  2703. return stream << value.toString (10);
  2704. }
  2705. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2706. {
  2707. String s;
  2708. BigInteger v (*this);
  2709. if (base == 2 || base == 8 || base == 16)
  2710. {
  2711. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2712. static const char* const hexDigits = "0123456789abcdef";
  2713. for (;;)
  2714. {
  2715. const int remainder = v.getBitRangeAsInt (0, bits);
  2716. v >>= bits;
  2717. if (remainder == 0 && v.isZero())
  2718. break;
  2719. s = String::charToString (hexDigits [remainder]) + s;
  2720. }
  2721. }
  2722. else if (base == 10)
  2723. {
  2724. const BigInteger ten (10);
  2725. BigInteger remainder;
  2726. for (;;)
  2727. {
  2728. v.divideBy (ten, remainder);
  2729. if (remainder.isZero() && v.isZero())
  2730. break;
  2731. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2732. }
  2733. }
  2734. else
  2735. {
  2736. jassertfalse; // can't do the specified base!
  2737. return String::empty;
  2738. }
  2739. s = s.paddedLeft ('0', minimumNumCharacters);
  2740. return isNegative() ? "-" + s : s;
  2741. }
  2742. void BigInteger::parseString (const String& text, const int base)
  2743. {
  2744. clear();
  2745. const juce_wchar* t = text;
  2746. if (base == 2 || base == 8 || base == 16)
  2747. {
  2748. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2749. for (;;)
  2750. {
  2751. const juce_wchar c = *t++;
  2752. const int digit = CharacterFunctions::getHexDigitValue (c);
  2753. if (((uint32) digit) < (uint32) base)
  2754. {
  2755. operator<<= (bits);
  2756. operator+= (digit);
  2757. }
  2758. else if (c == 0)
  2759. {
  2760. break;
  2761. }
  2762. }
  2763. }
  2764. else if (base == 10)
  2765. {
  2766. const BigInteger ten ((uint32) 10);
  2767. for (;;)
  2768. {
  2769. const juce_wchar c = *t++;
  2770. if (c >= '0' && c <= '9')
  2771. {
  2772. operator*= (ten);
  2773. operator+= ((int) (c - '0'));
  2774. }
  2775. else if (c == 0)
  2776. {
  2777. break;
  2778. }
  2779. }
  2780. }
  2781. setNegative (text.trimStart().startsWithChar ('-'));
  2782. }
  2783. const MemoryBlock BigInteger::toMemoryBlock() const
  2784. {
  2785. const int numBytes = (getHighestBit() + 8) >> 3;
  2786. MemoryBlock mb ((size_t) numBytes);
  2787. for (int i = 0; i < numBytes; ++i)
  2788. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2789. return mb;
  2790. }
  2791. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2792. {
  2793. clear();
  2794. for (int i = (int) data.getSize(); --i >= 0;)
  2795. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2796. }
  2797. END_JUCE_NAMESPACE
  2798. /*** End of inlined file: juce_BigInteger.cpp ***/
  2799. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2800. BEGIN_JUCE_NAMESPACE
  2801. MemoryBlock::MemoryBlock() throw()
  2802. : size (0)
  2803. {
  2804. }
  2805. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2806. {
  2807. if (initialSize > 0)
  2808. {
  2809. size = initialSize;
  2810. data.allocate (initialSize, initialiseToZero);
  2811. }
  2812. else
  2813. {
  2814. size = 0;
  2815. }
  2816. }
  2817. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2818. : size (other.size)
  2819. {
  2820. if (size > 0)
  2821. {
  2822. jassert (other.data != 0);
  2823. data.malloc (size);
  2824. memcpy (data, other.data, size);
  2825. }
  2826. }
  2827. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2828. : size (jmax ((size_t) 0, sizeInBytes))
  2829. {
  2830. jassert (sizeInBytes >= 0);
  2831. if (size > 0)
  2832. {
  2833. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2834. data.malloc (size);
  2835. if (dataToInitialiseFrom != 0)
  2836. memcpy (data, dataToInitialiseFrom, size);
  2837. }
  2838. }
  2839. MemoryBlock::~MemoryBlock() throw()
  2840. {
  2841. jassert (size >= 0); // should never happen
  2842. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2843. }
  2844. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2845. {
  2846. if (this != &other)
  2847. {
  2848. setSize (other.size, false);
  2849. memcpy (data, other.data, size);
  2850. }
  2851. return *this;
  2852. }
  2853. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2854. {
  2855. return matches (other.data, other.size);
  2856. }
  2857. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2858. {
  2859. return ! operator== (other);
  2860. }
  2861. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2862. {
  2863. return size == dataSize
  2864. && memcmp (data, dataToCompare, size) == 0;
  2865. }
  2866. // this will resize the block to this size
  2867. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2868. {
  2869. if (size != newSize)
  2870. {
  2871. if (newSize <= 0)
  2872. {
  2873. data.free();
  2874. size = 0;
  2875. }
  2876. else
  2877. {
  2878. if (data != 0)
  2879. {
  2880. data.realloc (newSize);
  2881. if (initialiseToZero && (newSize > size))
  2882. zeromem (data + size, newSize - size);
  2883. }
  2884. else
  2885. {
  2886. data.allocate (newSize, initialiseToZero);
  2887. }
  2888. size = newSize;
  2889. }
  2890. }
  2891. }
  2892. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2893. {
  2894. if (size < minimumSize)
  2895. setSize (minimumSize, initialiseToZero);
  2896. }
  2897. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2898. {
  2899. swapVariables (size, other.size);
  2900. data.swapWith (other.data);
  2901. }
  2902. void MemoryBlock::fillWith (const uint8 value) throw()
  2903. {
  2904. memset (data, (int) value, size);
  2905. }
  2906. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2907. {
  2908. if (numBytes > 0)
  2909. {
  2910. const size_t oldSize = size;
  2911. setSize (size + numBytes);
  2912. memcpy (data + oldSize, srcData, numBytes);
  2913. }
  2914. }
  2915. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2916. {
  2917. const char* d = static_cast<const char*> (src);
  2918. if (offset < 0)
  2919. {
  2920. d -= offset;
  2921. num -= offset;
  2922. offset = 0;
  2923. }
  2924. if (offset + num > size)
  2925. num = size - offset;
  2926. if (num > 0)
  2927. memcpy (data + offset, d, num);
  2928. }
  2929. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2930. {
  2931. char* d = static_cast<char*> (dst);
  2932. if (offset < 0)
  2933. {
  2934. zeromem (d, -offset);
  2935. d -= offset;
  2936. num += offset;
  2937. offset = 0;
  2938. }
  2939. if (offset + num > size)
  2940. {
  2941. const size_t newNum = size - offset;
  2942. zeromem (d + newNum, num - newNum);
  2943. num = newNum;
  2944. }
  2945. if (num > 0)
  2946. memcpy (d, data + offset, num);
  2947. }
  2948. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2949. {
  2950. if (startByte < 0)
  2951. {
  2952. numBytesToRemove += startByte;
  2953. startByte = 0;
  2954. }
  2955. if (startByte + numBytesToRemove >= size)
  2956. {
  2957. setSize (startByte);
  2958. }
  2959. else if (numBytesToRemove > 0)
  2960. {
  2961. memmove (data + startByte,
  2962. data + startByte + numBytesToRemove,
  2963. size - (startByte + numBytesToRemove));
  2964. setSize (size - numBytesToRemove);
  2965. }
  2966. }
  2967. const String MemoryBlock::toString() const
  2968. {
  2969. return String (static_cast <const char*> (getData()), size);
  2970. }
  2971. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2972. {
  2973. int res = 0;
  2974. size_t byte = bitRangeStart >> 3;
  2975. int offsetInByte = (int) bitRangeStart & 7;
  2976. size_t bitsSoFar = 0;
  2977. while (numBits > 0 && (size_t) byte < size)
  2978. {
  2979. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2980. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2981. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2982. bitsSoFar += bitsThisTime;
  2983. numBits -= bitsThisTime;
  2984. ++byte;
  2985. offsetInByte = 0;
  2986. }
  2987. return res;
  2988. }
  2989. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2990. {
  2991. size_t byte = bitRangeStart >> 3;
  2992. int offsetInByte = (int) bitRangeStart & 7;
  2993. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2994. while (numBits > 0 && (size_t) byte < size)
  2995. {
  2996. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2997. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2998. const unsigned int tempBits = bitsToSet << offsetInByte;
  2999. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3000. ++byte;
  3001. numBits -= bitsThisTime;
  3002. bitsToSet >>= bitsThisTime;
  3003. mask >>= bitsThisTime;
  3004. offsetInByte = 0;
  3005. }
  3006. }
  3007. void MemoryBlock::loadFromHexString (const String& hex)
  3008. {
  3009. ensureSize (hex.length() >> 1);
  3010. char* dest = data;
  3011. int i = 0;
  3012. for (;;)
  3013. {
  3014. int byte = 0;
  3015. for (int loop = 2; --loop >= 0;)
  3016. {
  3017. byte <<= 4;
  3018. for (;;)
  3019. {
  3020. const juce_wchar c = hex [i++];
  3021. if (c >= '0' && c <= '9')
  3022. {
  3023. byte |= c - '0';
  3024. break;
  3025. }
  3026. else if (c >= 'a' && c <= 'z')
  3027. {
  3028. byte |= c - ('a' - 10);
  3029. break;
  3030. }
  3031. else if (c >= 'A' && c <= 'Z')
  3032. {
  3033. byte |= c - ('A' - 10);
  3034. break;
  3035. }
  3036. else if (c == 0)
  3037. {
  3038. setSize (static_cast <size_t> (dest - data));
  3039. return;
  3040. }
  3041. }
  3042. }
  3043. *dest++ = (char) byte;
  3044. }
  3045. }
  3046. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3047. const String MemoryBlock::toBase64Encoding() const
  3048. {
  3049. const size_t numChars = ((size << 3) + 5) / 6;
  3050. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3051. const int initialLen = destString.length();
  3052. destString.preallocateStorage (initialLen + 2 + numChars);
  3053. juce_wchar* d = destString;
  3054. d += initialLen;
  3055. *d++ = '.';
  3056. for (size_t i = 0; i < numChars; ++i)
  3057. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3058. *d++ = 0;
  3059. return destString;
  3060. }
  3061. bool MemoryBlock::fromBase64Encoding (const String& s)
  3062. {
  3063. const int startPos = s.indexOfChar ('.') + 1;
  3064. if (startPos <= 0)
  3065. return false;
  3066. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3067. setSize (numBytesNeeded, true);
  3068. const int numChars = s.length() - startPos;
  3069. const juce_wchar* srcChars = s;
  3070. srcChars += startPos;
  3071. int pos = 0;
  3072. for (int i = 0; i < numChars; ++i)
  3073. {
  3074. const char c = (char) srcChars[i];
  3075. for (int j = 0; j < 64; ++j)
  3076. {
  3077. if (encodingTable[j] == c)
  3078. {
  3079. setBitRange (pos, 6, j);
  3080. pos += 6;
  3081. break;
  3082. }
  3083. }
  3084. }
  3085. return true;
  3086. }
  3087. END_JUCE_NAMESPACE
  3088. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3089. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3090. BEGIN_JUCE_NAMESPACE
  3091. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3092. : properties (ignoreCaseOfKeyNames),
  3093. fallbackProperties (0),
  3094. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3095. {
  3096. }
  3097. PropertySet::PropertySet (const PropertySet& other)
  3098. : properties (other.properties),
  3099. fallbackProperties (other.fallbackProperties),
  3100. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3101. {
  3102. }
  3103. PropertySet& PropertySet::operator= (const PropertySet& other)
  3104. {
  3105. properties = other.properties;
  3106. fallbackProperties = other.fallbackProperties;
  3107. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3108. propertyChanged();
  3109. return *this;
  3110. }
  3111. PropertySet::~PropertySet()
  3112. {
  3113. }
  3114. void PropertySet::clear()
  3115. {
  3116. const ScopedLock sl (lock);
  3117. if (properties.size() > 0)
  3118. {
  3119. properties.clear();
  3120. propertyChanged();
  3121. }
  3122. }
  3123. const String PropertySet::getValue (const String& keyName,
  3124. const String& defaultValue) const throw()
  3125. {
  3126. const ScopedLock sl (lock);
  3127. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3128. if (index >= 0)
  3129. return properties.getAllValues() [index];
  3130. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3131. : defaultValue;
  3132. }
  3133. int PropertySet::getIntValue (const String& keyName,
  3134. const int defaultValue) const throw()
  3135. {
  3136. const ScopedLock sl (lock);
  3137. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3138. if (index >= 0)
  3139. return properties.getAllValues() [index].getIntValue();
  3140. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3141. : defaultValue;
  3142. }
  3143. double PropertySet::getDoubleValue (const String& keyName,
  3144. const double defaultValue) const throw()
  3145. {
  3146. const ScopedLock sl (lock);
  3147. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3148. if (index >= 0)
  3149. return properties.getAllValues()[index].getDoubleValue();
  3150. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3151. : defaultValue;
  3152. }
  3153. bool PropertySet::getBoolValue (const String& keyName,
  3154. const bool defaultValue) const throw()
  3155. {
  3156. const ScopedLock sl (lock);
  3157. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3158. if (index >= 0)
  3159. return properties.getAllValues() [index].getIntValue() != 0;
  3160. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3161. : defaultValue;
  3162. }
  3163. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3164. {
  3165. return XmlDocument::parse (getValue (keyName));
  3166. }
  3167. void PropertySet::setValue (const String& keyName, const var& v)
  3168. {
  3169. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3170. if (keyName.isNotEmpty())
  3171. {
  3172. const String value (v.toString());
  3173. const ScopedLock sl (lock);
  3174. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3175. if (index < 0 || properties.getAllValues() [index] != value)
  3176. {
  3177. properties.set (keyName, value);
  3178. propertyChanged();
  3179. }
  3180. }
  3181. }
  3182. void PropertySet::removeValue (const String& keyName)
  3183. {
  3184. if (keyName.isNotEmpty())
  3185. {
  3186. const ScopedLock sl (lock);
  3187. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3188. if (index >= 0)
  3189. {
  3190. properties.remove (keyName);
  3191. propertyChanged();
  3192. }
  3193. }
  3194. }
  3195. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3196. {
  3197. setValue (keyName, xml == 0 ? var::null
  3198. : var (xml->createDocument (String::empty, true)));
  3199. }
  3200. bool PropertySet::containsKey (const String& keyName) const throw()
  3201. {
  3202. const ScopedLock sl (lock);
  3203. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3204. }
  3205. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3206. {
  3207. const ScopedLock sl (lock);
  3208. fallbackProperties = fallbackProperties_;
  3209. }
  3210. XmlElement* PropertySet::createXml (const String& nodeName) const
  3211. {
  3212. const ScopedLock sl (lock);
  3213. XmlElement* const xml = new XmlElement (nodeName);
  3214. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3215. {
  3216. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3217. e->setAttribute ("name", properties.getAllKeys()[i]);
  3218. e->setAttribute ("val", properties.getAllValues()[i]);
  3219. }
  3220. return xml;
  3221. }
  3222. void PropertySet::restoreFromXml (const XmlElement& xml)
  3223. {
  3224. const ScopedLock sl (lock);
  3225. clear();
  3226. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3227. {
  3228. if (e->hasAttribute ("name")
  3229. && e->hasAttribute ("val"))
  3230. {
  3231. properties.set (e->getStringAttribute ("name"),
  3232. e->getStringAttribute ("val"));
  3233. }
  3234. }
  3235. if (properties.size() > 0)
  3236. propertyChanged();
  3237. }
  3238. void PropertySet::propertyChanged()
  3239. {
  3240. }
  3241. END_JUCE_NAMESPACE
  3242. /*** End of inlined file: juce_PropertySet.cpp ***/
  3243. /*** Start of inlined file: juce_Identifier.cpp ***/
  3244. BEGIN_JUCE_NAMESPACE
  3245. StringPool& Identifier::getPool()
  3246. {
  3247. static StringPool pool;
  3248. return pool;
  3249. }
  3250. Identifier::Identifier() throw()
  3251. : name (0)
  3252. {
  3253. }
  3254. Identifier::Identifier (const Identifier& other) throw()
  3255. : name (other.name)
  3256. {
  3257. }
  3258. Identifier& Identifier::operator= (const Identifier& other) throw()
  3259. {
  3260. name = other.name;
  3261. return *this;
  3262. }
  3263. Identifier::Identifier (const String& name_)
  3264. : name (Identifier::getPool().getPooledString (name_))
  3265. {
  3266. /* An Identifier string must be suitable for use as a script variable or XML
  3267. attribute, so it can only contain this limited set of characters.. */
  3268. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3269. }
  3270. Identifier::Identifier (const char* const name_)
  3271. : name (Identifier::getPool().getPooledString (name_))
  3272. {
  3273. /* An Identifier string must be suitable for use as a script variable or XML
  3274. attribute, so it can only contain this limited set of characters.. */
  3275. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3276. }
  3277. Identifier::~Identifier()
  3278. {
  3279. }
  3280. END_JUCE_NAMESPACE
  3281. /*** End of inlined file: juce_Identifier.cpp ***/
  3282. /*** Start of inlined file: juce_Variant.cpp ***/
  3283. BEGIN_JUCE_NAMESPACE
  3284. class var::VariantType
  3285. {
  3286. public:
  3287. VariantType() {}
  3288. virtual ~VariantType() {}
  3289. virtual int toInt (const ValueUnion&) const { return 0; }
  3290. virtual double toDouble (const ValueUnion&) const { return 0; }
  3291. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3292. virtual bool toBool (const ValueUnion&) const { return false; }
  3293. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3294. virtual bool isVoid() const throw() { return false; }
  3295. virtual bool isInt() const throw() { return false; }
  3296. virtual bool isBool() const throw() { return false; }
  3297. virtual bool isDouble() const throw() { return false; }
  3298. virtual bool isString() const throw() { return false; }
  3299. virtual bool isObject() const throw() { return false; }
  3300. virtual bool isMethod() const throw() { return false; }
  3301. virtual void cleanUp (ValueUnion&) const throw() {}
  3302. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3303. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3304. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3305. };
  3306. class var::VariantType_Void : public var::VariantType
  3307. {
  3308. public:
  3309. VariantType_Void() {}
  3310. static const VariantType_Void instance;
  3311. bool isVoid() const throw() { return true; }
  3312. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3313. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3314. };
  3315. class var::VariantType_Int : public var::VariantType
  3316. {
  3317. public:
  3318. VariantType_Int() {}
  3319. static const VariantType_Int instance;
  3320. int toInt (const ValueUnion& data) const { return data.intValue; };
  3321. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3322. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3323. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3324. bool isInt() const throw() { return true; }
  3325. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3326. {
  3327. return otherType.toInt (otherData) == data.intValue;
  3328. }
  3329. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3330. {
  3331. output.writeCompressedInt (5);
  3332. output.writeByte (1);
  3333. output.writeInt (data.intValue);
  3334. }
  3335. };
  3336. class var::VariantType_Double : public var::VariantType
  3337. {
  3338. public:
  3339. VariantType_Double() {}
  3340. static const VariantType_Double instance;
  3341. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3342. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3343. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3344. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3345. bool isDouble() const throw() { return true; }
  3346. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3347. {
  3348. return otherType.toDouble (otherData) == data.doubleValue;
  3349. }
  3350. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3351. {
  3352. output.writeCompressedInt (9);
  3353. output.writeByte (4);
  3354. output.writeDouble (data.doubleValue);
  3355. }
  3356. };
  3357. class var::VariantType_Bool : public var::VariantType
  3358. {
  3359. public:
  3360. VariantType_Bool() {}
  3361. static const VariantType_Bool instance;
  3362. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3363. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3364. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3365. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3366. bool isBool() const throw() { return true; }
  3367. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3368. {
  3369. return otherType.toBool (otherData) == data.boolValue;
  3370. }
  3371. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3372. {
  3373. output.writeCompressedInt (1);
  3374. output.writeByte (data.boolValue ? 2 : 3);
  3375. }
  3376. };
  3377. class var::VariantType_String : public var::VariantType
  3378. {
  3379. public:
  3380. VariantType_String() {}
  3381. static const VariantType_String instance;
  3382. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3383. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3384. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3385. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3386. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3387. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3388. || data.stringValue->trim().equalsIgnoreCase ("true")
  3389. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3390. bool isString() const throw() { return true; }
  3391. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3392. {
  3393. return otherType.toString (otherData) == *data.stringValue;
  3394. }
  3395. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3396. {
  3397. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3398. output.writeCompressedInt (len + 1);
  3399. output.writeByte (5);
  3400. HeapBlock<char> temp (len);
  3401. data.stringValue->copyToUTF8 (temp, len);
  3402. output.write (temp, len);
  3403. }
  3404. };
  3405. class var::VariantType_Object : public var::VariantType
  3406. {
  3407. public:
  3408. VariantType_Object() {}
  3409. static const VariantType_Object instance;
  3410. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3411. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3412. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3413. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3414. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3415. bool isObject() const throw() { return true; }
  3416. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3417. {
  3418. return otherType.toObject (otherData) == data.objectValue;
  3419. }
  3420. void writeToStream (const ValueUnion&, OutputStream& output) const
  3421. {
  3422. jassertfalse; // Can't write an object to a stream!
  3423. output.writeCompressedInt (0);
  3424. }
  3425. };
  3426. class var::VariantType_Method : public var::VariantType
  3427. {
  3428. public:
  3429. VariantType_Method() {}
  3430. static const VariantType_Method instance;
  3431. const String toString (const ValueUnion&) const { return "Method"; }
  3432. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3433. bool isMethod() const throw() { return true; }
  3434. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3435. {
  3436. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3437. }
  3438. void writeToStream (const ValueUnion&, OutputStream& output) const
  3439. {
  3440. jassertfalse; // Can't write a method to a stream!
  3441. output.writeCompressedInt (0);
  3442. }
  3443. };
  3444. const var::VariantType_Void var::VariantType_Void::instance;
  3445. const var::VariantType_Int var::VariantType_Int::instance;
  3446. const var::VariantType_Bool var::VariantType_Bool::instance;
  3447. const var::VariantType_Double var::VariantType_Double::instance;
  3448. const var::VariantType_String var::VariantType_String::instance;
  3449. const var::VariantType_Object var::VariantType_Object::instance;
  3450. const var::VariantType_Method var::VariantType_Method::instance;
  3451. var::var() throw() : type (&VariantType_Void::instance)
  3452. {
  3453. }
  3454. var::~var() throw()
  3455. {
  3456. type->cleanUp (value);
  3457. }
  3458. const var var::null;
  3459. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3460. {
  3461. type->createCopy (value, valueToCopy.value);
  3462. }
  3463. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3464. {
  3465. value.intValue = value_;
  3466. }
  3467. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3468. {
  3469. value.boolValue = value_;
  3470. }
  3471. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3472. {
  3473. value.doubleValue = value_;
  3474. }
  3475. var::var (const String& value_) : type (&VariantType_String::instance)
  3476. {
  3477. value.stringValue = new String (value_);
  3478. }
  3479. var::var (const char* const value_) : type (&VariantType_String::instance)
  3480. {
  3481. value.stringValue = new String (value_);
  3482. }
  3483. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3484. {
  3485. value.stringValue = new String (value_);
  3486. }
  3487. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3488. {
  3489. value.objectValue = object;
  3490. if (object != 0)
  3491. object->incReferenceCount();
  3492. }
  3493. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3494. {
  3495. value.methodValue = method_;
  3496. }
  3497. bool var::isVoid() const throw() { return type->isVoid(); }
  3498. bool var::isInt() const throw() { return type->isInt(); }
  3499. bool var::isBool() const throw() { return type->isBool(); }
  3500. bool var::isDouble() const throw() { return type->isDouble(); }
  3501. bool var::isString() const throw() { return type->isString(); }
  3502. bool var::isObject() const throw() { return type->isObject(); }
  3503. bool var::isMethod() const throw() { return type->isMethod(); }
  3504. var::operator int() const { return type->toInt (value); }
  3505. var::operator bool() const { return type->toBool (value); }
  3506. var::operator float() const { return (float) type->toDouble (value); }
  3507. var::operator double() const { return type->toDouble (value); }
  3508. const String var::toString() const { return type->toString (value); }
  3509. var::operator const String() const { return type->toString (value); }
  3510. DynamicObject* var::getObject() const { return type->toObject (value); }
  3511. void var::swapWith (var& other) throw()
  3512. {
  3513. swapVariables (type, other.type);
  3514. swapVariables (value, other.value);
  3515. }
  3516. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3517. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3518. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3519. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3520. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3521. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3522. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3523. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3524. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3525. bool var::equals (const var& other) const throw()
  3526. {
  3527. return type->equals (value, other.value, *other.type);
  3528. }
  3529. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3530. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3531. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3532. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3533. void var::writeToStream (OutputStream& output) const
  3534. {
  3535. type->writeToStream (value, output);
  3536. }
  3537. const var var::readFromStream (InputStream& input)
  3538. {
  3539. const int numBytes = input.readCompressedInt();
  3540. if (numBytes > 0)
  3541. {
  3542. switch (input.readByte())
  3543. {
  3544. case 1: return var (input.readInt());
  3545. case 2: return var (true);
  3546. case 3: return var (false);
  3547. case 4: return var (input.readDouble());
  3548. case 5:
  3549. {
  3550. MemoryOutputStream mo;
  3551. mo.writeFromInputStream (input, numBytes - 1);
  3552. return var (mo.toUTF8());
  3553. }
  3554. default: input.skipNextBytes (numBytes - 1); break;
  3555. }
  3556. }
  3557. return var::null;
  3558. }
  3559. const var var::operator[] (const Identifier& propertyName) const
  3560. {
  3561. DynamicObject* const o = getObject();
  3562. return o != 0 ? o->getProperty (propertyName) : var::null;
  3563. }
  3564. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3565. {
  3566. DynamicObject* const o = getObject();
  3567. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3568. }
  3569. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3570. {
  3571. if (isMethod())
  3572. {
  3573. DynamicObject* const target = targetObject.getObject();
  3574. if (target != 0)
  3575. return (target->*(value.methodValue)) (arguments, numArguments);
  3576. }
  3577. return var::null;
  3578. }
  3579. const var var::call (const Identifier& method) const
  3580. {
  3581. return invoke (method, 0, 0);
  3582. }
  3583. const var var::call (const Identifier& method, const var& arg1) const
  3584. {
  3585. return invoke (method, &arg1, 1);
  3586. }
  3587. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3588. {
  3589. var args[] = { arg1, arg2 };
  3590. return invoke (method, args, 2);
  3591. }
  3592. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3593. {
  3594. var args[] = { arg1, arg2, arg3 };
  3595. return invoke (method, args, 3);
  3596. }
  3597. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3598. {
  3599. var args[] = { arg1, arg2, arg3, arg4 };
  3600. return invoke (method, args, 4);
  3601. }
  3602. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3603. {
  3604. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3605. return invoke (method, args, 5);
  3606. }
  3607. END_JUCE_NAMESPACE
  3608. /*** End of inlined file: juce_Variant.cpp ***/
  3609. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3610. BEGIN_JUCE_NAMESPACE
  3611. NamedValueSet::NamedValue::NamedValue() throw()
  3612. {
  3613. }
  3614. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3615. : name (name_), value (value_)
  3616. {
  3617. }
  3618. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3619. {
  3620. return name == other.name && value == other.value;
  3621. }
  3622. NamedValueSet::NamedValueSet() throw()
  3623. {
  3624. }
  3625. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3626. : values (other.values)
  3627. {
  3628. }
  3629. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3630. {
  3631. values = other.values;
  3632. return *this;
  3633. }
  3634. NamedValueSet::~NamedValueSet()
  3635. {
  3636. }
  3637. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3638. {
  3639. return values == other.values;
  3640. }
  3641. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3642. {
  3643. return ! operator== (other);
  3644. }
  3645. int NamedValueSet::size() const throw()
  3646. {
  3647. return values.size();
  3648. }
  3649. const var& NamedValueSet::operator[] (const Identifier& name) const
  3650. {
  3651. for (int i = values.size(); --i >= 0;)
  3652. {
  3653. const NamedValue& v = values.getReference(i);
  3654. if (v.name == name)
  3655. return v.value;
  3656. }
  3657. return var::null;
  3658. }
  3659. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3660. {
  3661. const var* v = getVarPointer (name);
  3662. return v != 0 ? *v : defaultReturnValue;
  3663. }
  3664. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3665. {
  3666. for (int i = values.size(); --i >= 0;)
  3667. {
  3668. NamedValue& v = values.getReference(i);
  3669. if (v.name == name)
  3670. return &(v.value);
  3671. }
  3672. return 0;
  3673. }
  3674. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3675. {
  3676. for (int i = values.size(); --i >= 0;)
  3677. {
  3678. NamedValue& v = values.getReference(i);
  3679. if (v.name == name)
  3680. {
  3681. if (v.value == newValue)
  3682. return false;
  3683. v.value = newValue;
  3684. return true;
  3685. }
  3686. }
  3687. values.add (NamedValue (name, newValue));
  3688. return true;
  3689. }
  3690. bool NamedValueSet::contains (const Identifier& name) const
  3691. {
  3692. return getVarPointer (name) != 0;
  3693. }
  3694. bool NamedValueSet::remove (const Identifier& name)
  3695. {
  3696. for (int i = values.size(); --i >= 0;)
  3697. {
  3698. if (values.getReference(i).name == name)
  3699. {
  3700. values.remove (i);
  3701. return true;
  3702. }
  3703. }
  3704. return false;
  3705. }
  3706. const Identifier NamedValueSet::getName (const int index) const
  3707. {
  3708. jassert (((unsigned int) index) < (unsigned int) values.size());
  3709. return values [index].name;
  3710. }
  3711. const var NamedValueSet::getValueAt (const int index) const
  3712. {
  3713. jassert (((unsigned int) index) < (unsigned int) values.size());
  3714. return values [index].value;
  3715. }
  3716. void NamedValueSet::clear()
  3717. {
  3718. values.clear();
  3719. }
  3720. END_JUCE_NAMESPACE
  3721. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3722. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3723. BEGIN_JUCE_NAMESPACE
  3724. DynamicObject::DynamicObject()
  3725. {
  3726. }
  3727. DynamicObject::~DynamicObject()
  3728. {
  3729. }
  3730. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3731. {
  3732. var* const v = properties.getVarPointer (propertyName);
  3733. return v != 0 && ! v->isMethod();
  3734. }
  3735. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3736. {
  3737. return properties [propertyName];
  3738. }
  3739. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3740. {
  3741. properties.set (propertyName, newValue);
  3742. }
  3743. void DynamicObject::removeProperty (const Identifier& propertyName)
  3744. {
  3745. properties.remove (propertyName);
  3746. }
  3747. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3748. {
  3749. return getProperty (methodName).isMethod();
  3750. }
  3751. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3752. const var* parameters,
  3753. int numParameters)
  3754. {
  3755. return properties [methodName].invoke (var (this), parameters, numParameters);
  3756. }
  3757. void DynamicObject::setMethod (const Identifier& name,
  3758. var::MethodFunction methodFunction)
  3759. {
  3760. properties.set (name, var (methodFunction));
  3761. }
  3762. void DynamicObject::clear()
  3763. {
  3764. properties.clear();
  3765. }
  3766. END_JUCE_NAMESPACE
  3767. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3768. /*** Start of inlined file: juce_Expression.cpp ***/
  3769. BEGIN_JUCE_NAMESPACE
  3770. class Expression::Helpers
  3771. {
  3772. public:
  3773. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3774. // This helper function is needed to work around VC6 scoping bugs
  3775. static const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  3776. friend class Expression::Term; // (also only needed as a VC6 workaround)
  3777. class Constant : public Term
  3778. {
  3779. public:
  3780. Constant (const double value_, bool isResolutionTarget_)
  3781. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3782. Type getType() const throw() { return constantType; }
  3783. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3784. double evaluate (const EvaluationContext&, int) const { return value; }
  3785. int getNumInputs() const { return 0; }
  3786. Term* getInput (int) const { return 0; }
  3787. const TermPtr negated()
  3788. {
  3789. return new Constant (-value, isResolutionTarget);
  3790. }
  3791. const String toString() const
  3792. {
  3793. if (isResolutionTarget)
  3794. return "@" + String (value);
  3795. return String (value);
  3796. }
  3797. double value;
  3798. bool isResolutionTarget;
  3799. };
  3800. class Symbol : public Term
  3801. {
  3802. public:
  3803. explicit Symbol (const String& symbol_)
  3804. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3805. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3806. {}
  3807. Symbol (const String& symbol_, const String& member_)
  3808. : mainSymbol (symbol_),
  3809. member (member_)
  3810. {}
  3811. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3812. {
  3813. if (++recursionDepth > 256)
  3814. throw EvaluationError ("Recursive symbol references");
  3815. try
  3816. {
  3817. return getTermFor (c.getSymbolValue (mainSymbol, member))->evaluate (c, recursionDepth);
  3818. }
  3819. catch (...)
  3820. {}
  3821. return 0;
  3822. }
  3823. Type getType() const throw() { return symbolType; }
  3824. Term* clone() const { return new Symbol (mainSymbol, member); }
  3825. int getNumInputs() const { return 0; }
  3826. Term* getInput (int) const { return 0; }
  3827. const String getSymbolName() const { return toString(); }
  3828. const String toString() const
  3829. {
  3830. return member.isEmpty() ? mainSymbol
  3831. : mainSymbol + "." + member;
  3832. }
  3833. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3834. {
  3835. if (s == mainSymbol)
  3836. return true;
  3837. if (++recursionDepth > 256)
  3838. throw EvaluationError ("Recursive symbol references");
  3839. try
  3840. {
  3841. return c != 0 && getTermFor (c->getSymbolValue (mainSymbol, member))->referencesSymbol (s, c, recursionDepth);
  3842. }
  3843. catch (EvaluationError&)
  3844. {
  3845. return false;
  3846. }
  3847. }
  3848. String mainSymbol, member;
  3849. };
  3850. class Function : public Term
  3851. {
  3852. public:
  3853. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3854. : functionName (functionName_), parameters (parameters_)
  3855. {}
  3856. Term* clone() const { return new Function (functionName, parameters); }
  3857. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3858. {
  3859. HeapBlock <double> params (parameters.size());
  3860. for (int i = 0; i < parameters.size(); ++i)
  3861. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3862. return c.evaluateFunction (functionName, params, parameters.size());
  3863. }
  3864. Type getType() const throw() { return functionType; }
  3865. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3866. int getNumInputs() const { return parameters.size(); }
  3867. Term* getInput (int i) const { return parameters [i]; }
  3868. const String getFunctionName() const { return functionName; }
  3869. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3870. {
  3871. for (int i = 0; i < parameters.size(); ++i)
  3872. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3873. return true;
  3874. return false;
  3875. }
  3876. const String toString() const
  3877. {
  3878. if (parameters.size() == 0)
  3879. return functionName + "()";
  3880. String s (functionName + " (");
  3881. for (int i = 0; i < parameters.size(); ++i)
  3882. {
  3883. s << parameters.getUnchecked(i)->toString();
  3884. if (i < parameters.size() - 1)
  3885. s << ", ";
  3886. }
  3887. s << ')';
  3888. return s;
  3889. }
  3890. const String functionName;
  3891. ReferenceCountedArray<Term> parameters;
  3892. };
  3893. class Negate : public Term
  3894. {
  3895. public:
  3896. Negate (const TermPtr& input_) : input (input_)
  3897. {
  3898. jassert (input_ != 0);
  3899. }
  3900. Type getType() const throw() { return operatorType; }
  3901. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3902. int getNumInputs() const { return 1; }
  3903. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3904. Term* clone() const { return new Negate (input->clone()); }
  3905. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3906. const String getFunctionName() const { return "-"; }
  3907. const TermPtr negated()
  3908. {
  3909. return input;
  3910. }
  3911. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3912. {
  3913. (void) input_;
  3914. jassert (input_ == input);
  3915. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3916. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3917. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3918. }
  3919. const String toString() const
  3920. {
  3921. if (input->getOperatorPrecedence() > 0)
  3922. return "-(" + input->toString() + ")";
  3923. else
  3924. return "-" + input->toString();
  3925. }
  3926. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3927. {
  3928. return input->referencesSymbol (s, c, recursionDepth);
  3929. }
  3930. private:
  3931. const TermPtr input;
  3932. };
  3933. class BinaryTerm : public Term
  3934. {
  3935. public:
  3936. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3937. {
  3938. jassert (left_ != 0 && right_ != 0);
  3939. }
  3940. int getInputIndexFor (const Term* possibleInput) const
  3941. {
  3942. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3943. }
  3944. Type getType() const throw() { return operatorType; }
  3945. int getNumInputs() const { return 2; }
  3946. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3947. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3948. {
  3949. return left->referencesSymbol (s, c, recursionDepth)
  3950. || right->referencesSymbol (s, c, recursionDepth);
  3951. }
  3952. const String toString() const
  3953. {
  3954. String s;
  3955. const int ourPrecendence = getOperatorPrecedence();
  3956. if (left->getOperatorPrecedence() > ourPrecendence)
  3957. s << '(' << left->toString() << ')';
  3958. else
  3959. s = left->toString();
  3960. s << ' ' << getFunctionName() << ' ';
  3961. if (right->getOperatorPrecedence() >= ourPrecendence)
  3962. s << '(' << right->toString() << ')';
  3963. else
  3964. s << right->toString();
  3965. return s;
  3966. }
  3967. protected:
  3968. const TermPtr left, right;
  3969. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3970. {
  3971. jassert (input == left || input == right);
  3972. if (input != left && input != right)
  3973. return 0;
  3974. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3975. if (dest == 0)
  3976. return new Constant (overallTarget, false);
  3977. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3978. }
  3979. };
  3980. class Add : public BinaryTerm
  3981. {
  3982. public:
  3983. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3984. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3985. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3986. int getOperatorPrecedence() const { return 2; }
  3987. const String getFunctionName() const { return "+"; }
  3988. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3989. {
  3990. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3991. if (newDest == 0)
  3992. return 0;
  3993. return new Subtract (newDest, (input == left ? right : left)->clone());
  3994. }
  3995. private:
  3996. JUCE_DECLARE_NON_COPYABLE (Add);
  3997. };
  3998. class Subtract : public BinaryTerm
  3999. {
  4000. public:
  4001. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4002. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4003. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  4004. int getOperatorPrecedence() const { return 2; }
  4005. const String getFunctionName() const { return "-"; }
  4006. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4007. {
  4008. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4009. if (newDest == 0)
  4010. return 0;
  4011. if (input == left)
  4012. return new Add (newDest, right->clone());
  4013. else
  4014. return new Subtract (left->clone(), newDest);
  4015. }
  4016. private:
  4017. JUCE_DECLARE_NON_COPYABLE (Subtract);
  4018. };
  4019. class Multiply : public BinaryTerm
  4020. {
  4021. public:
  4022. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4023. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4024. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4025. const String getFunctionName() const { return "*"; }
  4026. int getOperatorPrecedence() const { return 1; }
  4027. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4028. {
  4029. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4030. if (newDest == 0)
  4031. return 0;
  4032. return new Divide (newDest, (input == left ? right : left)->clone());
  4033. }
  4034. private:
  4035. JUCE_DECLARE_NON_COPYABLE (Multiply);
  4036. };
  4037. class Divide : public BinaryTerm
  4038. {
  4039. public:
  4040. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4041. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4042. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4043. const String getFunctionName() const { return "/"; }
  4044. int getOperatorPrecedence() const { return 1; }
  4045. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4046. {
  4047. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4048. if (newDest == 0)
  4049. return 0;
  4050. if (input == left)
  4051. return new Multiply (newDest, right->clone());
  4052. else
  4053. return new Divide (left->clone(), newDest);
  4054. }
  4055. private:
  4056. JUCE_DECLARE_NON_COPYABLE (Divide);
  4057. };
  4058. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4059. {
  4060. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4061. if (inputIndex >= 0)
  4062. return topLevel;
  4063. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4064. {
  4065. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4066. if (t != 0)
  4067. return t;
  4068. }
  4069. return 0;
  4070. }
  4071. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4072. {
  4073. Constant* c = dynamic_cast<Constant*> (term);
  4074. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4075. return c;
  4076. if (dynamic_cast<Function*> (term) != 0)
  4077. return 0;
  4078. int i;
  4079. const int numIns = term->getNumInputs();
  4080. for (i = 0; i < numIns; ++i)
  4081. {
  4082. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4083. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4084. return c;
  4085. }
  4086. for (i = 0; i < numIns; ++i)
  4087. {
  4088. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4089. if (c != 0)
  4090. return c;
  4091. }
  4092. return 0;
  4093. }
  4094. static bool containsAnySymbols (const Term* const t)
  4095. {
  4096. if (dynamic_cast <const Symbol*> (t) != 0)
  4097. return true;
  4098. for (int i = t->getNumInputs(); --i >= 0;)
  4099. if (containsAnySymbols (t->getInput (i)))
  4100. return true;
  4101. return false;
  4102. }
  4103. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4104. {
  4105. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4106. if (sym != 0 && sym->mainSymbol == oldName)
  4107. {
  4108. sym->mainSymbol = newName;
  4109. return true;
  4110. }
  4111. bool anyChanged = false;
  4112. for (int i = t->getNumInputs(); --i >= 0;)
  4113. if (renameSymbol (t->getInput (i), oldName, newName))
  4114. anyChanged = true;
  4115. return anyChanged;
  4116. }
  4117. class Parser
  4118. {
  4119. public:
  4120. Parser (const String& stringToParse, int& textIndex_)
  4121. : textString (stringToParse), textIndex (textIndex_)
  4122. {
  4123. text = textString;
  4124. }
  4125. const TermPtr readExpression()
  4126. {
  4127. TermPtr lhs (readMultiplyOrDivideExpression());
  4128. char opType;
  4129. while (lhs != 0 && readOperator ("+-", &opType))
  4130. {
  4131. TermPtr rhs (readMultiplyOrDivideExpression());
  4132. if (rhs == 0)
  4133. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4134. if (opType == '+')
  4135. lhs = new Add (lhs, rhs);
  4136. else
  4137. lhs = new Subtract (lhs, rhs);
  4138. }
  4139. return lhs;
  4140. }
  4141. private:
  4142. const String textString;
  4143. const juce_wchar* text;
  4144. int& textIndex;
  4145. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4146. {
  4147. return c >= '0' && c <= '9';
  4148. }
  4149. void skipWhitespace (int& i)
  4150. {
  4151. while (CharacterFunctions::isWhitespace (text [i]))
  4152. ++i;
  4153. }
  4154. bool readChar (const juce_wchar required)
  4155. {
  4156. if (text[textIndex] == required)
  4157. {
  4158. ++textIndex;
  4159. return true;
  4160. }
  4161. return false;
  4162. }
  4163. bool readOperator (const char* ops, char* const opType = 0)
  4164. {
  4165. skipWhitespace (textIndex);
  4166. while (*ops != 0)
  4167. {
  4168. if (readChar (*ops))
  4169. {
  4170. if (opType != 0)
  4171. *opType = *ops;
  4172. return true;
  4173. }
  4174. ++ops;
  4175. }
  4176. return false;
  4177. }
  4178. bool readIdentifier (String& identifier)
  4179. {
  4180. skipWhitespace (textIndex);
  4181. int i = textIndex;
  4182. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4183. {
  4184. ++i;
  4185. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4186. ++i;
  4187. }
  4188. if (i > textIndex)
  4189. {
  4190. identifier = String (text + textIndex, i - textIndex);
  4191. textIndex = i;
  4192. return true;
  4193. }
  4194. return false;
  4195. }
  4196. Term* readNumber()
  4197. {
  4198. skipWhitespace (textIndex);
  4199. int i = textIndex;
  4200. const bool isResolutionTarget = (text[i] == '@');
  4201. if (isResolutionTarget)
  4202. {
  4203. ++i;
  4204. skipWhitespace (i);
  4205. textIndex = i;
  4206. }
  4207. if (text[i] == '-')
  4208. {
  4209. ++i;
  4210. skipWhitespace (i);
  4211. }
  4212. int numDigits = 0;
  4213. while (isDecimalDigit (text[i]))
  4214. {
  4215. ++i;
  4216. ++numDigits;
  4217. }
  4218. const bool hasPoint = (text[i] == '.');
  4219. if (hasPoint)
  4220. {
  4221. ++i;
  4222. while (isDecimalDigit (text[i]))
  4223. {
  4224. ++i;
  4225. ++numDigits;
  4226. }
  4227. }
  4228. if (numDigits == 0)
  4229. return 0;
  4230. juce_wchar c = text[i];
  4231. const bool hasExponent = (c == 'e' || c == 'E');
  4232. if (hasExponent)
  4233. {
  4234. ++i;
  4235. c = text[i];
  4236. if (c == '+' || c == '-')
  4237. ++i;
  4238. int numExpDigits = 0;
  4239. while (isDecimalDigit (text[i]))
  4240. {
  4241. ++i;
  4242. ++numExpDigits;
  4243. }
  4244. if (numExpDigits == 0)
  4245. return 0;
  4246. }
  4247. const int start = textIndex;
  4248. textIndex = i;
  4249. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4250. }
  4251. const TermPtr readMultiplyOrDivideExpression()
  4252. {
  4253. TermPtr lhs (readUnaryExpression());
  4254. char opType;
  4255. while (lhs != 0 && readOperator ("*/", &opType))
  4256. {
  4257. TermPtr rhs (readUnaryExpression());
  4258. if (rhs == 0)
  4259. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4260. if (opType == '*')
  4261. lhs = new Multiply (lhs, rhs);
  4262. else
  4263. lhs = new Divide (lhs, rhs);
  4264. }
  4265. return lhs;
  4266. }
  4267. const TermPtr readUnaryExpression()
  4268. {
  4269. char opType;
  4270. if (readOperator ("+-", &opType))
  4271. {
  4272. TermPtr term (readUnaryExpression());
  4273. if (term == 0)
  4274. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4275. if (opType == '-')
  4276. term = term->negated();
  4277. return term;
  4278. }
  4279. return readPrimaryExpression();
  4280. }
  4281. const TermPtr readPrimaryExpression()
  4282. {
  4283. TermPtr e (readParenthesisedExpression());
  4284. if (e != 0)
  4285. return e;
  4286. e = readNumber();
  4287. if (e != 0)
  4288. return e;
  4289. String identifier;
  4290. if (readIdentifier (identifier))
  4291. {
  4292. if (readOperator ("(")) // method call...
  4293. {
  4294. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4295. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4296. TermPtr param (readExpression());
  4297. if (param == 0)
  4298. {
  4299. if (readOperator (")"))
  4300. return func.release();
  4301. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4302. }
  4303. f->parameters.add (param);
  4304. while (readOperator (","))
  4305. {
  4306. param = readExpression();
  4307. if (param == 0)
  4308. throw ParseError ("Expected expression after \",\"");
  4309. f->parameters.add (param);
  4310. }
  4311. if (readOperator (")"))
  4312. return func.release();
  4313. throw ParseError ("Expected \")\"");
  4314. }
  4315. else // just a symbol..
  4316. {
  4317. return new Symbol (identifier);
  4318. }
  4319. }
  4320. return 0;
  4321. }
  4322. const TermPtr readParenthesisedExpression()
  4323. {
  4324. if (! readOperator ("("))
  4325. return 0;
  4326. const TermPtr e (readExpression());
  4327. if (e == 0 || ! readOperator (")"))
  4328. return 0;
  4329. return e;
  4330. }
  4331. JUCE_DECLARE_NON_COPYABLE (Parser);
  4332. };
  4333. };
  4334. Expression::Expression()
  4335. : term (new Expression::Helpers::Constant (0, false))
  4336. {
  4337. }
  4338. Expression::~Expression()
  4339. {
  4340. }
  4341. Expression::Expression (Term* const term_)
  4342. : term (term_)
  4343. {
  4344. jassert (term != 0);
  4345. }
  4346. Expression::Expression (const double constant)
  4347. : term (new Expression::Helpers::Constant (constant, false))
  4348. {
  4349. }
  4350. Expression::Expression (const Expression& other)
  4351. : term (other.term)
  4352. {
  4353. }
  4354. Expression& Expression::operator= (const Expression& other)
  4355. {
  4356. term = other.term;
  4357. return *this;
  4358. }
  4359. Expression::Expression (const String& stringToParse)
  4360. {
  4361. int i = 0;
  4362. Helpers::Parser parser (stringToParse, i);
  4363. term = parser.readExpression();
  4364. if (term == 0)
  4365. term = new Helpers::Constant (0, false);
  4366. }
  4367. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4368. {
  4369. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4370. const Helpers::TermPtr term (parser.readExpression());
  4371. if (term != 0)
  4372. return Expression (term);
  4373. return Expression();
  4374. }
  4375. double Expression::evaluate() const
  4376. {
  4377. return evaluate (Expression::EvaluationContext());
  4378. }
  4379. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4380. {
  4381. return term->evaluate (context, 0);
  4382. }
  4383. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4384. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4385. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4386. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4387. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4388. const String Expression::toString() const
  4389. {
  4390. return term->toString();
  4391. }
  4392. const Expression Expression::symbol (const String& symbol)
  4393. {
  4394. return Expression (new Helpers::Symbol (symbol));
  4395. }
  4396. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4397. {
  4398. ReferenceCountedArray<Term> params;
  4399. for (int i = 0; i < parameters.size(); ++i)
  4400. params.add (parameters.getReference(i).term);
  4401. return Expression (new Helpers::Function (functionName, params));
  4402. }
  4403. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4404. const Expression::EvaluationContext& context) const
  4405. {
  4406. ScopedPointer<Term> newTerm (term->clone());
  4407. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4408. if (termToAdjust == 0)
  4409. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4410. if (termToAdjust == 0)
  4411. {
  4412. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4413. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4414. }
  4415. jassert (termToAdjust != 0);
  4416. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4417. if (parent == 0)
  4418. {
  4419. termToAdjust->value = targetValue;
  4420. }
  4421. else
  4422. {
  4423. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4424. if (reverseTerm == 0)
  4425. return Expression (targetValue);
  4426. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4427. }
  4428. return Expression (newTerm.release());
  4429. }
  4430. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4431. {
  4432. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4433. Expression newExpression (term->clone());
  4434. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4435. return newExpression;
  4436. }
  4437. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4438. {
  4439. return term->referencesSymbol (symbol, context, 0);
  4440. }
  4441. bool Expression::usesAnySymbols() const
  4442. {
  4443. return Helpers::containsAnySymbols (term);
  4444. }
  4445. Expression::Type Expression::getType() const throw()
  4446. {
  4447. return term->getType();
  4448. }
  4449. const String Expression::getSymbol() const
  4450. {
  4451. return term->getSymbolName();
  4452. }
  4453. const String Expression::getFunction() const
  4454. {
  4455. return term->getFunctionName();
  4456. }
  4457. const String Expression::getOperator() const
  4458. {
  4459. return term->getFunctionName();
  4460. }
  4461. int Expression::getNumInputs() const
  4462. {
  4463. return term->getNumInputs();
  4464. }
  4465. const Expression Expression::getInput (int index) const
  4466. {
  4467. return Expression (term->getInput (index));
  4468. }
  4469. int Expression::Term::getOperatorPrecedence() const
  4470. {
  4471. return 0;
  4472. }
  4473. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4474. {
  4475. return false;
  4476. }
  4477. int Expression::Term::getInputIndexFor (const Term*) const
  4478. {
  4479. return -1;
  4480. }
  4481. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4482. {
  4483. jassertfalse;
  4484. return 0;
  4485. }
  4486. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4487. {
  4488. return new Helpers::Negate (this);
  4489. }
  4490. const String Expression::Term::getSymbolName() const
  4491. {
  4492. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4493. return String::empty;
  4494. }
  4495. const String Expression::Term::getFunctionName() const
  4496. {
  4497. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4498. return String::empty;
  4499. }
  4500. Expression::ParseError::ParseError (const String& message)
  4501. : description (message)
  4502. {
  4503. DBG ("Expression::ParseError: " + message);
  4504. }
  4505. Expression::EvaluationError::EvaluationError (const String& message)
  4506. : description (message)
  4507. {
  4508. DBG ("Expression::EvaluationError: " + description);
  4509. }
  4510. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4511. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4512. {
  4513. DBG ("Expression::EvaluationError: " + description);
  4514. }
  4515. Expression::EvaluationContext::EvaluationContext() {}
  4516. Expression::EvaluationContext::~EvaluationContext() {}
  4517. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4518. {
  4519. throw EvaluationError (symbol, member);
  4520. }
  4521. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4522. {
  4523. if (numParams > 0)
  4524. {
  4525. if (functionName == "min")
  4526. {
  4527. double v = parameters[0];
  4528. for (int i = 1; i < numParams; ++i)
  4529. v = jmin (v, parameters[i]);
  4530. return v;
  4531. }
  4532. else if (functionName == "max")
  4533. {
  4534. double v = parameters[0];
  4535. for (int i = 1; i < numParams; ++i)
  4536. v = jmax (v, parameters[i]);
  4537. return v;
  4538. }
  4539. else if (numParams == 1)
  4540. {
  4541. if (functionName == "sin") return sin (parameters[0]);
  4542. else if (functionName == "cos") return cos (parameters[0]);
  4543. else if (functionName == "tan") return tan (parameters[0]);
  4544. else if (functionName == "abs") return std::abs (parameters[0]);
  4545. }
  4546. }
  4547. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4548. }
  4549. END_JUCE_NAMESPACE
  4550. /*** End of inlined file: juce_Expression.cpp ***/
  4551. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4552. BEGIN_JUCE_NAMESPACE
  4553. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4554. {
  4555. jassert (keyData != 0);
  4556. jassert (keyBytes > 0);
  4557. static const uint32 initialPValues [18] =
  4558. {
  4559. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4560. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4561. 0x9216d5d9, 0x8979fb1b
  4562. };
  4563. static const uint32 initialSValues [4 * 256] =
  4564. {
  4565. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4566. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4567. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4568. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4569. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4570. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4571. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4572. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4573. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4574. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4575. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4576. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4577. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4578. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4579. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4580. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4581. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4582. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4583. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4584. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4585. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4586. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4587. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4588. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4589. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4590. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4591. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4592. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4593. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4594. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4595. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4596. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4597. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4598. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4599. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4600. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4601. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4602. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4603. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4604. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4605. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4606. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4607. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4608. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4609. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4610. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4611. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4612. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4613. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4614. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4615. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4616. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4617. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4618. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4619. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4620. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4621. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4622. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4623. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4624. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4625. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4626. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4627. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4628. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4629. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4630. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4631. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4632. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4633. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4634. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4635. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4636. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4637. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4638. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4639. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4640. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4641. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4642. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4643. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4644. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4645. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4646. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4647. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4648. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4649. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4650. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4651. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4652. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4653. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4654. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4655. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4656. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4657. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4658. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4659. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4660. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4661. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4662. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4663. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4664. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4665. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4666. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4667. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4668. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4669. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4670. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4671. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4672. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4673. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4674. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4675. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4676. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4677. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4678. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4679. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4680. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4681. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4682. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4683. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4684. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4685. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4686. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4687. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4688. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4689. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4690. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4691. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4692. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4693. };
  4694. memcpy (p, initialPValues, sizeof (p));
  4695. int i, j = 0;
  4696. for (i = 4; --i >= 0;)
  4697. {
  4698. s[i].malloc (256);
  4699. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4700. }
  4701. for (i = 0; i < 18; ++i)
  4702. {
  4703. uint32 d = 0;
  4704. for (int k = 0; k < 4; ++k)
  4705. {
  4706. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4707. if (++j >= keyBytes)
  4708. j = 0;
  4709. }
  4710. p[i] = initialPValues[i] ^ d;
  4711. }
  4712. uint32 l = 0, r = 0;
  4713. for (i = 0; i < 18; i += 2)
  4714. {
  4715. encrypt (l, r);
  4716. p[i] = l;
  4717. p[i + 1] = r;
  4718. }
  4719. for (i = 0; i < 4; ++i)
  4720. {
  4721. for (j = 0; j < 256; j += 2)
  4722. {
  4723. encrypt (l, r);
  4724. s[i][j] = l;
  4725. s[i][j + 1] = r;
  4726. }
  4727. }
  4728. }
  4729. BlowFish::BlowFish (const BlowFish& other)
  4730. {
  4731. for (int i = 4; --i >= 0;)
  4732. s[i].malloc (256);
  4733. operator= (other);
  4734. }
  4735. BlowFish& BlowFish::operator= (const BlowFish& other)
  4736. {
  4737. memcpy (p, other.p, sizeof (p));
  4738. for (int i = 4; --i >= 0;)
  4739. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4740. return *this;
  4741. }
  4742. BlowFish::~BlowFish()
  4743. {
  4744. }
  4745. uint32 BlowFish::F (const uint32 x) const throw()
  4746. {
  4747. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4748. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4749. }
  4750. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4751. {
  4752. uint32 l = data1;
  4753. uint32 r = data2;
  4754. for (int i = 0; i < 16; ++i)
  4755. {
  4756. l ^= p[i];
  4757. r ^= F(l);
  4758. swapVariables (l, r);
  4759. }
  4760. data1 = r ^ p[17];
  4761. data2 = l ^ p[16];
  4762. }
  4763. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4764. {
  4765. uint32 l = data1;
  4766. uint32 r = data2;
  4767. for (int i = 17; i > 1; --i)
  4768. {
  4769. l ^= p[i];
  4770. r ^= F(l);
  4771. swapVariables (l, r);
  4772. }
  4773. data1 = r ^ p[0];
  4774. data2 = l ^ p[1];
  4775. }
  4776. END_JUCE_NAMESPACE
  4777. /*** End of inlined file: juce_BlowFish.cpp ***/
  4778. /*** Start of inlined file: juce_MD5.cpp ***/
  4779. BEGIN_JUCE_NAMESPACE
  4780. MD5::MD5()
  4781. {
  4782. zerostruct (result);
  4783. }
  4784. MD5::MD5 (const MD5& other)
  4785. {
  4786. memcpy (result, other.result, sizeof (result));
  4787. }
  4788. MD5& MD5::operator= (const MD5& other)
  4789. {
  4790. memcpy (result, other.result, sizeof (result));
  4791. return *this;
  4792. }
  4793. MD5::MD5 (const MemoryBlock& data)
  4794. {
  4795. ProcessContext context;
  4796. context.processBlock (data.getData(), data.getSize());
  4797. context.finish (result);
  4798. }
  4799. MD5::MD5 (const void* data, const size_t numBytes)
  4800. {
  4801. ProcessContext context;
  4802. context.processBlock (data, numBytes);
  4803. context.finish (result);
  4804. }
  4805. MD5::MD5 (const String& text)
  4806. {
  4807. ProcessContext context;
  4808. const int len = text.length();
  4809. const juce_wchar* const t = text;
  4810. for (int i = 0; i < len; ++i)
  4811. {
  4812. // force the string into integer-sized unicode characters, to try to make it
  4813. // get the same results on all platforms + compilers.
  4814. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4815. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4816. }
  4817. context.finish (result);
  4818. }
  4819. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4820. {
  4821. ProcessContext context;
  4822. if (numBytesToRead < 0)
  4823. numBytesToRead = std::numeric_limits<int64>::max();
  4824. while (numBytesToRead > 0)
  4825. {
  4826. uint8 tempBuffer [512];
  4827. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4828. if (bytesRead <= 0)
  4829. break;
  4830. numBytesToRead -= bytesRead;
  4831. context.processBlock (tempBuffer, bytesRead);
  4832. }
  4833. context.finish (result);
  4834. }
  4835. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4836. {
  4837. processStream (input, numBytesToRead);
  4838. }
  4839. MD5::MD5 (const File& file)
  4840. {
  4841. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4842. if (fin != 0)
  4843. processStream (*fin, -1);
  4844. else
  4845. zerostruct (result);
  4846. }
  4847. MD5::~MD5()
  4848. {
  4849. }
  4850. namespace MD5Functions
  4851. {
  4852. void encode (void* const output, const void* const input, const int numBytes) throw()
  4853. {
  4854. for (int i = 0; i < (numBytes >> 2); ++i)
  4855. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4856. }
  4857. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4858. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4859. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4860. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4861. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4862. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4863. {
  4864. a += F (b, c, d) + x + ac;
  4865. a = rotateLeft (a, s) + b;
  4866. }
  4867. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4868. {
  4869. a += G (b, c, d) + x + ac;
  4870. a = rotateLeft (a, s) + b;
  4871. }
  4872. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4873. {
  4874. a += H (b, c, d) + x + ac;
  4875. a = rotateLeft (a, s) + b;
  4876. }
  4877. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4878. {
  4879. a += I (b, c, d) + x + ac;
  4880. a = rotateLeft (a, s) + b;
  4881. }
  4882. }
  4883. MD5::ProcessContext::ProcessContext()
  4884. {
  4885. state[0] = 0x67452301;
  4886. state[1] = 0xefcdab89;
  4887. state[2] = 0x98badcfe;
  4888. state[3] = 0x10325476;
  4889. count[0] = 0;
  4890. count[1] = 0;
  4891. }
  4892. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4893. {
  4894. int bufferPos = ((count[0] >> 3) & 0x3F);
  4895. count[0] += (uint32) (dataSize << 3);
  4896. if (count[0] < ((uint32) dataSize << 3))
  4897. count[1]++;
  4898. count[1] += (uint32) (dataSize >> 29);
  4899. const size_t spaceLeft = 64 - bufferPos;
  4900. size_t i = 0;
  4901. if (dataSize >= spaceLeft)
  4902. {
  4903. memcpy (buffer + bufferPos, data, spaceLeft);
  4904. transform (buffer);
  4905. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4906. transform (static_cast <const char*> (data) + i);
  4907. bufferPos = 0;
  4908. }
  4909. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4910. }
  4911. void MD5::ProcessContext::finish (void* const result)
  4912. {
  4913. unsigned char encodedLength[8];
  4914. MD5Functions::encode (encodedLength, count, 8);
  4915. // Pad out to 56 mod 64.
  4916. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4917. const int paddingLength = (index < 56) ? (56 - index)
  4918. : (120 - index);
  4919. uint8 paddingBuffer [64];
  4920. zeromem (paddingBuffer, paddingLength);
  4921. paddingBuffer [0] = 0x80;
  4922. processBlock (paddingBuffer, paddingLength);
  4923. processBlock (encodedLength, 8);
  4924. MD5Functions::encode (result, state, 16);
  4925. zerostruct (buffer);
  4926. }
  4927. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4928. {
  4929. using namespace MD5Functions;
  4930. uint32 a = state[0];
  4931. uint32 b = state[1];
  4932. uint32 c = state[2];
  4933. uint32 d = state[3];
  4934. uint32 x[16];
  4935. encode (x, bufferToTransform, 64);
  4936. enum Constants
  4937. {
  4938. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4939. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4940. };
  4941. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4942. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4943. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4944. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4945. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4946. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4947. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4948. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4949. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4950. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4951. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4952. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4953. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4954. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4955. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4956. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4957. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4958. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4959. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4960. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4961. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4962. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4963. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4964. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4965. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4966. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4967. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4968. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4969. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4970. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4971. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4972. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4973. state[0] += a;
  4974. state[1] += b;
  4975. state[2] += c;
  4976. state[3] += d;
  4977. zerostruct (x);
  4978. }
  4979. const MemoryBlock MD5::getRawChecksumData() const
  4980. {
  4981. return MemoryBlock (result, sizeof (result));
  4982. }
  4983. const String MD5::toHexString() const
  4984. {
  4985. return String::toHexString (result, sizeof (result), 0);
  4986. }
  4987. bool MD5::operator== (const MD5& other) const
  4988. {
  4989. return memcmp (result, other.result, sizeof (result)) == 0;
  4990. }
  4991. bool MD5::operator!= (const MD5& other) const
  4992. {
  4993. return ! operator== (other);
  4994. }
  4995. END_JUCE_NAMESPACE
  4996. /*** End of inlined file: juce_MD5.cpp ***/
  4997. /*** Start of inlined file: juce_Primes.cpp ***/
  4998. BEGIN_JUCE_NAMESPACE
  4999. namespace PrimesHelpers
  5000. {
  5001. void createSmallSieve (const int numBits, BigInteger& result)
  5002. {
  5003. result.setBit (numBits);
  5004. result.clearBit (numBits); // to enlarge the array
  5005. result.setBit (0);
  5006. int n = 2;
  5007. do
  5008. {
  5009. for (int i = n + n; i < numBits; i += n)
  5010. result.setBit (i);
  5011. n = result.findNextClearBit (n + 1);
  5012. }
  5013. while (n <= (numBits >> 1));
  5014. }
  5015. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5016. const BigInteger& smallSieve, const int smallSieveSize)
  5017. {
  5018. jassert (! base[0]); // must be even!
  5019. result.setBit (numBits);
  5020. result.clearBit (numBits); // to enlarge the array
  5021. int index = smallSieve.findNextClearBit (0);
  5022. do
  5023. {
  5024. const int prime = (index << 1) + 1;
  5025. BigInteger r (base), remainder;
  5026. r.divideBy (prime, remainder);
  5027. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5028. if (r.isZero())
  5029. i += prime;
  5030. if ((i & 1) == 0)
  5031. i += prime;
  5032. i = (i - 1) >> 1;
  5033. while (i < numBits)
  5034. {
  5035. result.setBit (i);
  5036. i += prime;
  5037. }
  5038. index = smallSieve.findNextClearBit (index + 1);
  5039. }
  5040. while (index < smallSieveSize);
  5041. }
  5042. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5043. const int numBits, BigInteger& result, const int certainty)
  5044. {
  5045. for (int i = 0; i < numBits; ++i)
  5046. {
  5047. if (! sieve[i])
  5048. {
  5049. result = base + (unsigned int) ((i << 1) + 1);
  5050. if (Primes::isProbablyPrime (result, certainty))
  5051. return true;
  5052. }
  5053. }
  5054. return false;
  5055. }
  5056. bool passesMillerRabin (const BigInteger& n, int iterations)
  5057. {
  5058. const BigInteger one (1), two (2);
  5059. const BigInteger nMinusOne (n - one);
  5060. BigInteger d (nMinusOne);
  5061. const int s = d.findNextSetBit (0);
  5062. d >>= s;
  5063. BigInteger smallPrimes;
  5064. int numBitsInSmallPrimes = 0;
  5065. for (;;)
  5066. {
  5067. numBitsInSmallPrimes += 256;
  5068. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5069. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5070. if (numPrimesFound > iterations + 1)
  5071. break;
  5072. }
  5073. int smallPrime = 2;
  5074. while (--iterations >= 0)
  5075. {
  5076. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5077. BigInteger r (smallPrime);
  5078. r.exponentModulo (d, n);
  5079. if (r != one && r != nMinusOne)
  5080. {
  5081. for (int j = 0; j < s; ++j)
  5082. {
  5083. r.exponentModulo (two, n);
  5084. if (r == nMinusOne)
  5085. break;
  5086. }
  5087. if (r != nMinusOne)
  5088. return false;
  5089. }
  5090. }
  5091. return true;
  5092. }
  5093. }
  5094. const BigInteger Primes::createProbablePrime (const int bitLength,
  5095. const int certainty,
  5096. const int* randomSeeds,
  5097. int numRandomSeeds)
  5098. {
  5099. using namespace PrimesHelpers;
  5100. int defaultSeeds [16];
  5101. if (numRandomSeeds <= 0)
  5102. {
  5103. randomSeeds = defaultSeeds;
  5104. numRandomSeeds = numElementsInArray (defaultSeeds);
  5105. Random r (0);
  5106. for (int j = 10; --j >= 0;)
  5107. {
  5108. r.setSeedRandomly();
  5109. for (int i = numRandomSeeds; --i >= 0;)
  5110. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5111. }
  5112. }
  5113. BigInteger smallSieve;
  5114. const int smallSieveSize = 15000;
  5115. createSmallSieve (smallSieveSize, smallSieve);
  5116. BigInteger p;
  5117. for (int i = numRandomSeeds; --i >= 0;)
  5118. {
  5119. BigInteger p2;
  5120. Random r (randomSeeds[i]);
  5121. r.fillBitsRandomly (p2, 0, bitLength);
  5122. p ^= p2;
  5123. }
  5124. p.setBit (bitLength - 1);
  5125. p.clearBit (0);
  5126. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5127. while (p.getHighestBit() < bitLength)
  5128. {
  5129. p += 2 * searchLen;
  5130. BigInteger sieve;
  5131. bigSieve (p, searchLen, sieve,
  5132. smallSieve, smallSieveSize);
  5133. BigInteger candidate;
  5134. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5135. return candidate;
  5136. }
  5137. jassertfalse;
  5138. return BigInteger();
  5139. }
  5140. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5141. {
  5142. using namespace PrimesHelpers;
  5143. if (! number[0])
  5144. return false;
  5145. if (number.getHighestBit() <= 10)
  5146. {
  5147. const int num = number.getBitRangeAsInt (0, 10);
  5148. for (int i = num / 2; --i > 1;)
  5149. if (num % i == 0)
  5150. return false;
  5151. return true;
  5152. }
  5153. else
  5154. {
  5155. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5156. return false;
  5157. return passesMillerRabin (number, certainty);
  5158. }
  5159. }
  5160. END_JUCE_NAMESPACE
  5161. /*** End of inlined file: juce_Primes.cpp ***/
  5162. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5163. BEGIN_JUCE_NAMESPACE
  5164. RSAKey::RSAKey()
  5165. {
  5166. }
  5167. RSAKey::RSAKey (const String& s)
  5168. {
  5169. if (s.containsChar (','))
  5170. {
  5171. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5172. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5173. }
  5174. else
  5175. {
  5176. // the string needs to be two hex numbers, comma-separated..
  5177. jassertfalse;
  5178. }
  5179. }
  5180. RSAKey::~RSAKey()
  5181. {
  5182. }
  5183. bool RSAKey::operator== (const RSAKey& other) const throw()
  5184. {
  5185. return part1 == other.part1 && part2 == other.part2;
  5186. }
  5187. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5188. {
  5189. return ! operator== (other);
  5190. }
  5191. const String RSAKey::toString() const
  5192. {
  5193. return part1.toString (16) + "," + part2.toString (16);
  5194. }
  5195. bool RSAKey::applyToValue (BigInteger& value) const
  5196. {
  5197. if (part1.isZero() || part2.isZero() || value <= 0)
  5198. {
  5199. jassertfalse; // using an uninitialised key
  5200. value.clear();
  5201. return false;
  5202. }
  5203. BigInteger result;
  5204. while (! value.isZero())
  5205. {
  5206. result *= part2;
  5207. BigInteger remainder;
  5208. value.divideBy (part2, remainder);
  5209. remainder.exponentModulo (part1, part2);
  5210. result += remainder;
  5211. }
  5212. value.swapWith (result);
  5213. return true;
  5214. }
  5215. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5216. {
  5217. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5218. // are fast to divide + multiply
  5219. for (int i = 2; i <= 65536; i *= 2)
  5220. {
  5221. const BigInteger e (1 + i);
  5222. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5223. return e;
  5224. }
  5225. BigInteger e (4);
  5226. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5227. ++e;
  5228. return e;
  5229. }
  5230. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5231. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5232. {
  5233. jassert (numBits > 16); // not much point using less than this..
  5234. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5235. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5236. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5237. const BigInteger n (p * q);
  5238. const BigInteger m (--p * --q);
  5239. const BigInteger e (findBestCommonDivisor (p, q));
  5240. BigInteger d (e);
  5241. d.inverseModulo (m);
  5242. publicKey.part1 = e;
  5243. publicKey.part2 = n;
  5244. privateKey.part1 = d;
  5245. privateKey.part2 = n;
  5246. }
  5247. END_JUCE_NAMESPACE
  5248. /*** End of inlined file: juce_RSAKey.cpp ***/
  5249. /*** Start of inlined file: juce_InputStream.cpp ***/
  5250. BEGIN_JUCE_NAMESPACE
  5251. char InputStream::readByte()
  5252. {
  5253. char temp = 0;
  5254. read (&temp, 1);
  5255. return temp;
  5256. }
  5257. bool InputStream::readBool()
  5258. {
  5259. return readByte() != 0;
  5260. }
  5261. short InputStream::readShort()
  5262. {
  5263. char temp[2];
  5264. if (read (temp, 2) == 2)
  5265. return (short) ByteOrder::littleEndianShort (temp);
  5266. return 0;
  5267. }
  5268. short InputStream::readShortBigEndian()
  5269. {
  5270. char temp[2];
  5271. if (read (temp, 2) == 2)
  5272. return (short) ByteOrder::bigEndianShort (temp);
  5273. return 0;
  5274. }
  5275. int InputStream::readInt()
  5276. {
  5277. char temp[4];
  5278. if (read (temp, 4) == 4)
  5279. return (int) ByteOrder::littleEndianInt (temp);
  5280. return 0;
  5281. }
  5282. int InputStream::readIntBigEndian()
  5283. {
  5284. char temp[4];
  5285. if (read (temp, 4) == 4)
  5286. return (int) ByteOrder::bigEndianInt (temp);
  5287. return 0;
  5288. }
  5289. int InputStream::readCompressedInt()
  5290. {
  5291. const unsigned char sizeByte = readByte();
  5292. if (sizeByte == 0)
  5293. return 0;
  5294. const int numBytes = (sizeByte & 0x7f);
  5295. if (numBytes > 4)
  5296. {
  5297. jassertfalse; // trying to read corrupt data - this method must only be used
  5298. // to read data that was written by OutputStream::writeCompressedInt()
  5299. return 0;
  5300. }
  5301. char bytes[4] = { 0, 0, 0, 0 };
  5302. if (read (bytes, numBytes) != numBytes)
  5303. return 0;
  5304. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5305. return (sizeByte >> 7) ? -num : num;
  5306. }
  5307. int64 InputStream::readInt64()
  5308. {
  5309. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5310. if (read (n.asBytes, 8) == 8)
  5311. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5312. return 0;
  5313. }
  5314. int64 InputStream::readInt64BigEndian()
  5315. {
  5316. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5317. if (read (n.asBytes, 8) == 8)
  5318. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5319. return 0;
  5320. }
  5321. float InputStream::readFloat()
  5322. {
  5323. // the union below relies on these types being the same size...
  5324. static_jassert (sizeof (int32) == sizeof (float));
  5325. union { int32 asInt; float asFloat; } n;
  5326. n.asInt = (int32) readInt();
  5327. return n.asFloat;
  5328. }
  5329. float InputStream::readFloatBigEndian()
  5330. {
  5331. union { int32 asInt; float asFloat; } n;
  5332. n.asInt = (int32) readIntBigEndian();
  5333. return n.asFloat;
  5334. }
  5335. double InputStream::readDouble()
  5336. {
  5337. union { int64 asInt; double asDouble; } n;
  5338. n.asInt = readInt64();
  5339. return n.asDouble;
  5340. }
  5341. double InputStream::readDoubleBigEndian()
  5342. {
  5343. union { int64 asInt; double asDouble; } n;
  5344. n.asInt = readInt64BigEndian();
  5345. return n.asDouble;
  5346. }
  5347. const String InputStream::readString()
  5348. {
  5349. MemoryBlock buffer (256);
  5350. char* data = static_cast<char*> (buffer.getData());
  5351. size_t i = 0;
  5352. while ((data[i] = readByte()) != 0)
  5353. {
  5354. if (++i >= buffer.getSize())
  5355. {
  5356. buffer.setSize (buffer.getSize() + 512);
  5357. data = static_cast<char*> (buffer.getData());
  5358. }
  5359. }
  5360. return String::fromUTF8 (data, (int) i);
  5361. }
  5362. const String InputStream::readNextLine()
  5363. {
  5364. MemoryBlock buffer (256);
  5365. char* data = static_cast<char*> (buffer.getData());
  5366. size_t i = 0;
  5367. while ((data[i] = readByte()) != 0)
  5368. {
  5369. if (data[i] == '\n')
  5370. break;
  5371. if (data[i] == '\r')
  5372. {
  5373. const int64 lastPos = getPosition();
  5374. if (readByte() != '\n')
  5375. setPosition (lastPos);
  5376. break;
  5377. }
  5378. if (++i >= buffer.getSize())
  5379. {
  5380. buffer.setSize (buffer.getSize() + 512);
  5381. data = static_cast<char*> (buffer.getData());
  5382. }
  5383. }
  5384. return String::fromUTF8 (data, (int) i);
  5385. }
  5386. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5387. {
  5388. MemoryOutputStream mo (block, true);
  5389. return mo.writeFromInputStream (*this, numBytes);
  5390. }
  5391. const String InputStream::readEntireStreamAsString()
  5392. {
  5393. MemoryOutputStream mo;
  5394. mo.writeFromInputStream (*this, -1);
  5395. return mo.toString();
  5396. }
  5397. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5398. {
  5399. if (numBytesToSkip > 0)
  5400. {
  5401. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5402. HeapBlock<char> temp (skipBufferSize);
  5403. while (numBytesToSkip > 0 && ! isExhausted())
  5404. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5405. }
  5406. }
  5407. END_JUCE_NAMESPACE
  5408. /*** End of inlined file: juce_InputStream.cpp ***/
  5409. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5410. BEGIN_JUCE_NAMESPACE
  5411. #if JUCE_DEBUG
  5412. static Array<void*, CriticalSection> activeStreams;
  5413. void juce_CheckForDanglingStreams()
  5414. {
  5415. /*
  5416. It's always a bad idea to leak any object, but if you're leaking output
  5417. streams, then there's a good chance that you're failing to flush a file
  5418. to disk properly, which could result in corrupted data and other similar
  5419. nastiness..
  5420. */
  5421. jassert (activeStreams.size() == 0);
  5422. };
  5423. #endif
  5424. OutputStream::OutputStream()
  5425. {
  5426. #if JUCE_DEBUG
  5427. activeStreams.add (this);
  5428. #endif
  5429. }
  5430. OutputStream::~OutputStream()
  5431. {
  5432. #if JUCE_DEBUG
  5433. activeStreams.removeValue (this);
  5434. #endif
  5435. }
  5436. void OutputStream::writeBool (const bool b)
  5437. {
  5438. writeByte (b ? (char) 1
  5439. : (char) 0);
  5440. }
  5441. void OutputStream::writeByte (char byte)
  5442. {
  5443. write (&byte, 1);
  5444. }
  5445. void OutputStream::writeShort (short value)
  5446. {
  5447. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5448. write (&v, 2);
  5449. }
  5450. void OutputStream::writeShortBigEndian (short value)
  5451. {
  5452. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5453. write (&v, 2);
  5454. }
  5455. void OutputStream::writeInt (int value)
  5456. {
  5457. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5458. write (&v, 4);
  5459. }
  5460. void OutputStream::writeIntBigEndian (int value)
  5461. {
  5462. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5463. write (&v, 4);
  5464. }
  5465. void OutputStream::writeCompressedInt (int value)
  5466. {
  5467. unsigned int un = (value < 0) ? (unsigned int) -value
  5468. : (unsigned int) value;
  5469. uint8 data[5];
  5470. int num = 0;
  5471. while (un > 0)
  5472. {
  5473. data[++num] = (uint8) un;
  5474. un >>= 8;
  5475. }
  5476. data[0] = (uint8) num;
  5477. if (value < 0)
  5478. data[0] |= 0x80;
  5479. write (data, num + 1);
  5480. }
  5481. void OutputStream::writeInt64 (int64 value)
  5482. {
  5483. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5484. write (&v, 8);
  5485. }
  5486. void OutputStream::writeInt64BigEndian (int64 value)
  5487. {
  5488. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5489. write (&v, 8);
  5490. }
  5491. void OutputStream::writeFloat (float value)
  5492. {
  5493. union { int asInt; float asFloat; } n;
  5494. n.asFloat = value;
  5495. writeInt (n.asInt);
  5496. }
  5497. void OutputStream::writeFloatBigEndian (float value)
  5498. {
  5499. union { int asInt; float asFloat; } n;
  5500. n.asFloat = value;
  5501. writeIntBigEndian (n.asInt);
  5502. }
  5503. void OutputStream::writeDouble (double value)
  5504. {
  5505. union { int64 asInt; double asDouble; } n;
  5506. n.asDouble = value;
  5507. writeInt64 (n.asInt);
  5508. }
  5509. void OutputStream::writeDoubleBigEndian (double value)
  5510. {
  5511. union { int64 asInt; double asDouble; } n;
  5512. n.asDouble = value;
  5513. writeInt64BigEndian (n.asInt);
  5514. }
  5515. void OutputStream::writeString (const String& text)
  5516. {
  5517. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5518. // if lots of large, persistent strings were to be written to streams).
  5519. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5520. HeapBlock<char> temp (numBytes);
  5521. text.copyToUTF8 (temp, numBytes);
  5522. write (temp, numBytes);
  5523. }
  5524. void OutputStream::writeText (const String& text, const bool asUnicode,
  5525. const bool writeUnicodeHeaderBytes)
  5526. {
  5527. if (asUnicode)
  5528. {
  5529. if (writeUnicodeHeaderBytes)
  5530. write ("\x0ff\x0fe", 2);
  5531. const juce_wchar* src = text;
  5532. bool lastCharWasReturn = false;
  5533. while (*src != 0)
  5534. {
  5535. if (*src == L'\n' && ! lastCharWasReturn)
  5536. writeShort ((short) L'\r');
  5537. lastCharWasReturn = (*src == L'\r');
  5538. writeShort ((short) *src++);
  5539. }
  5540. }
  5541. else
  5542. {
  5543. const char* src = text.toUTF8();
  5544. const char* t = src;
  5545. for (;;)
  5546. {
  5547. if (*t == '\n')
  5548. {
  5549. if (t > src)
  5550. write (src, (int) (t - src));
  5551. write ("\r\n", 2);
  5552. src = t + 1;
  5553. }
  5554. else if (*t == '\r')
  5555. {
  5556. if (t[1] == '\n')
  5557. ++t;
  5558. }
  5559. else if (*t == 0)
  5560. {
  5561. if (t > src)
  5562. write (src, (int) (t - src));
  5563. break;
  5564. }
  5565. ++t;
  5566. }
  5567. }
  5568. }
  5569. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5570. {
  5571. if (numBytesToWrite < 0)
  5572. numBytesToWrite = std::numeric_limits<int64>::max();
  5573. int numWritten = 0;
  5574. while (numBytesToWrite > 0 && ! source.isExhausted())
  5575. {
  5576. char buffer [8192];
  5577. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5578. if (num <= 0)
  5579. break;
  5580. write (buffer, num);
  5581. numBytesToWrite -= num;
  5582. numWritten += num;
  5583. }
  5584. return numWritten;
  5585. }
  5586. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5587. {
  5588. return stream << String (number);
  5589. }
  5590. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5591. {
  5592. return stream << String (number);
  5593. }
  5594. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5595. {
  5596. stream.writeByte (character);
  5597. return stream;
  5598. }
  5599. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5600. {
  5601. stream.write (text, (int) strlen (text));
  5602. return stream;
  5603. }
  5604. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5605. {
  5606. stream.write (data.getData(), (int) data.getSize());
  5607. return stream;
  5608. }
  5609. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5610. {
  5611. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5612. if (in != 0)
  5613. stream.writeFromInputStream (*in, -1);
  5614. return stream;
  5615. }
  5616. END_JUCE_NAMESPACE
  5617. /*** End of inlined file: juce_OutputStream.cpp ***/
  5618. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5619. BEGIN_JUCE_NAMESPACE
  5620. DirectoryIterator::DirectoryIterator (const File& directory,
  5621. bool isRecursive_,
  5622. const String& wildCard_,
  5623. const int whatToLookFor_)
  5624. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5625. wildCard (wildCard_),
  5626. path (File::addTrailingSeparator (directory.getFullPathName())),
  5627. index (-1),
  5628. totalNumFiles (-1),
  5629. whatToLookFor (whatToLookFor_),
  5630. isRecursive (isRecursive_),
  5631. hasBeenAdvanced (false)
  5632. {
  5633. // you have to specify the type of files you're looking for!
  5634. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5635. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5636. }
  5637. DirectoryIterator::~DirectoryIterator()
  5638. {
  5639. }
  5640. bool DirectoryIterator::next()
  5641. {
  5642. return next (0, 0, 0, 0, 0, 0);
  5643. }
  5644. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5645. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5646. {
  5647. hasBeenAdvanced = true;
  5648. if (subIterator != 0)
  5649. {
  5650. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5651. return true;
  5652. subIterator = 0;
  5653. }
  5654. String filename;
  5655. bool isDirectory, isHidden;
  5656. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5657. {
  5658. ++index;
  5659. if (! filename.containsOnly ("."))
  5660. {
  5661. const File fileFound (path + filename, 0);
  5662. bool matches = false;
  5663. if (isDirectory)
  5664. {
  5665. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5666. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5667. matches = (whatToLookFor & File::findDirectories) != 0;
  5668. }
  5669. else
  5670. {
  5671. matches = (whatToLookFor & File::findFiles) != 0;
  5672. }
  5673. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5674. if (matches && isRecursive)
  5675. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5676. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5677. matches = ! isHidden;
  5678. if (matches)
  5679. {
  5680. currentFile = fileFound;
  5681. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5682. if (isDirResult != 0) *isDirResult = isDirectory;
  5683. return true;
  5684. }
  5685. else if (subIterator != 0)
  5686. {
  5687. return next();
  5688. }
  5689. }
  5690. }
  5691. return false;
  5692. }
  5693. const File DirectoryIterator::getFile() const
  5694. {
  5695. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5696. return subIterator->getFile();
  5697. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5698. jassert (hasBeenAdvanced);
  5699. return currentFile;
  5700. }
  5701. float DirectoryIterator::getEstimatedProgress() const
  5702. {
  5703. if (totalNumFiles < 0)
  5704. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5705. if (totalNumFiles <= 0)
  5706. return 0.0f;
  5707. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5708. : (float) index;
  5709. return detailedIndex / totalNumFiles;
  5710. }
  5711. END_JUCE_NAMESPACE
  5712. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5713. /*** Start of inlined file: juce_File.cpp ***/
  5714. #if ! JUCE_WINDOWS
  5715. #include <pwd.h>
  5716. #endif
  5717. BEGIN_JUCE_NAMESPACE
  5718. File::File (const String& fullPathName)
  5719. : fullPath (parseAbsolutePath (fullPathName))
  5720. {
  5721. }
  5722. File::File (const String& path, int)
  5723. : fullPath (path)
  5724. {
  5725. }
  5726. const File File::createFileWithoutCheckingPath (const String& path)
  5727. {
  5728. return File (path, 0);
  5729. }
  5730. File::File (const File& other)
  5731. : fullPath (other.fullPath)
  5732. {
  5733. }
  5734. File& File::operator= (const String& newPath)
  5735. {
  5736. fullPath = parseAbsolutePath (newPath);
  5737. return *this;
  5738. }
  5739. File& File::operator= (const File& other)
  5740. {
  5741. fullPath = other.fullPath;
  5742. return *this;
  5743. }
  5744. const File File::nonexistent;
  5745. const String File::parseAbsolutePath (const String& p)
  5746. {
  5747. if (p.isEmpty())
  5748. return String::empty;
  5749. #if JUCE_WINDOWS
  5750. // Windows..
  5751. String path (p.replaceCharacter ('/', '\\'));
  5752. if (path.startsWithChar (File::separator))
  5753. {
  5754. if (path[1] != File::separator)
  5755. {
  5756. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5757. If you're trying to parse a string that may be either a relative path or an absolute path,
  5758. you MUST provide a context against which the partial path can be evaluated - you can do
  5759. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5760. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5761. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5762. */
  5763. jassertfalse;
  5764. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5765. }
  5766. }
  5767. else if (! path.containsChar (':'))
  5768. {
  5769. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5770. If you're trying to parse a string that may be either a relative path or an absolute path,
  5771. you MUST provide a context against which the partial path can be evaluated - you can do
  5772. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5773. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5774. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5775. */
  5776. jassertfalse;
  5777. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5778. }
  5779. #else
  5780. // Mac or Linux..
  5781. String path (p.replaceCharacter ('\\', '/'));
  5782. if (path.startsWithChar ('~'))
  5783. {
  5784. if (path[1] == File::separator || path[1] == 0)
  5785. {
  5786. // expand a name of the form "~/abc"
  5787. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5788. + path.substring (1);
  5789. }
  5790. else
  5791. {
  5792. // expand a name of type "~dave/abc"
  5793. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5794. struct passwd* const pw = getpwnam (userName.toUTF8());
  5795. if (pw != 0)
  5796. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5797. }
  5798. }
  5799. else if (! path.startsWithChar (File::separator))
  5800. {
  5801. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5802. If you're trying to parse a string that may be either a relative path or an absolute path,
  5803. you MUST provide a context against which the partial path can be evaluated - you can do
  5804. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5805. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5806. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5807. */
  5808. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5809. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5810. }
  5811. #endif
  5812. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5813. path = path.dropLastCharacters (1);
  5814. return path;
  5815. }
  5816. const String File::addTrailingSeparator (const String& path)
  5817. {
  5818. return path.endsWithChar (File::separator) ? path
  5819. : path + File::separator;
  5820. }
  5821. #if JUCE_LINUX
  5822. #define NAMES_ARE_CASE_SENSITIVE 1
  5823. #endif
  5824. bool File::areFileNamesCaseSensitive()
  5825. {
  5826. #if NAMES_ARE_CASE_SENSITIVE
  5827. return true;
  5828. #else
  5829. return false;
  5830. #endif
  5831. }
  5832. bool File::operator== (const File& other) const
  5833. {
  5834. #if NAMES_ARE_CASE_SENSITIVE
  5835. return fullPath == other.fullPath;
  5836. #else
  5837. return fullPath.equalsIgnoreCase (other.fullPath);
  5838. #endif
  5839. }
  5840. bool File::operator!= (const File& other) const
  5841. {
  5842. return ! operator== (other);
  5843. }
  5844. bool File::operator< (const File& other) const
  5845. {
  5846. #if NAMES_ARE_CASE_SENSITIVE
  5847. return fullPath < other.fullPath;
  5848. #else
  5849. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5850. #endif
  5851. }
  5852. bool File::operator> (const File& other) const
  5853. {
  5854. #if NAMES_ARE_CASE_SENSITIVE
  5855. return fullPath > other.fullPath;
  5856. #else
  5857. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5858. #endif
  5859. }
  5860. bool File::setReadOnly (const bool shouldBeReadOnly,
  5861. const bool applyRecursively) const
  5862. {
  5863. bool worked = true;
  5864. if (applyRecursively && isDirectory())
  5865. {
  5866. Array <File> subFiles;
  5867. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5868. for (int i = subFiles.size(); --i >= 0;)
  5869. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5870. }
  5871. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5872. }
  5873. bool File::deleteRecursively() const
  5874. {
  5875. bool worked = true;
  5876. if (isDirectory())
  5877. {
  5878. Array<File> subFiles;
  5879. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5880. for (int i = subFiles.size(); --i >= 0;)
  5881. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5882. }
  5883. return deleteFile() && worked;
  5884. }
  5885. bool File::moveFileTo (const File& newFile) const
  5886. {
  5887. if (newFile.fullPath == fullPath)
  5888. return true;
  5889. #if ! NAMES_ARE_CASE_SENSITIVE
  5890. if (*this != newFile)
  5891. #endif
  5892. if (! newFile.deleteFile())
  5893. return false;
  5894. return moveInternal (newFile);
  5895. }
  5896. bool File::copyFileTo (const File& newFile) const
  5897. {
  5898. return (*this == newFile)
  5899. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5900. }
  5901. bool File::copyDirectoryTo (const File& newDirectory) const
  5902. {
  5903. if (isDirectory() && newDirectory.createDirectory())
  5904. {
  5905. Array<File> subFiles;
  5906. findChildFiles (subFiles, File::findFiles, false);
  5907. int i;
  5908. for (i = 0; i < subFiles.size(); ++i)
  5909. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5910. return false;
  5911. subFiles.clear();
  5912. findChildFiles (subFiles, File::findDirectories, false);
  5913. for (i = 0; i < subFiles.size(); ++i)
  5914. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5915. return false;
  5916. return true;
  5917. }
  5918. return false;
  5919. }
  5920. const String File::getPathUpToLastSlash() const
  5921. {
  5922. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5923. if (lastSlash > 0)
  5924. return fullPath.substring (0, lastSlash);
  5925. else if (lastSlash == 0)
  5926. return separatorString;
  5927. else
  5928. return fullPath;
  5929. }
  5930. const File File::getParentDirectory() const
  5931. {
  5932. return File (getPathUpToLastSlash(), (int) 0);
  5933. }
  5934. const String File::getFileName() const
  5935. {
  5936. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5937. }
  5938. int File::hashCode() const
  5939. {
  5940. return fullPath.hashCode();
  5941. }
  5942. int64 File::hashCode64() const
  5943. {
  5944. return fullPath.hashCode64();
  5945. }
  5946. const String File::getFileNameWithoutExtension() const
  5947. {
  5948. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5949. const int lastDot = fullPath.lastIndexOfChar ('.');
  5950. if (lastDot > lastSlash)
  5951. return fullPath.substring (lastSlash, lastDot);
  5952. else
  5953. return fullPath.substring (lastSlash);
  5954. }
  5955. bool File::isAChildOf (const File& potentialParent) const
  5956. {
  5957. if (potentialParent == File::nonexistent)
  5958. return false;
  5959. const String ourPath (getPathUpToLastSlash());
  5960. #if NAMES_ARE_CASE_SENSITIVE
  5961. if (potentialParent.fullPath == ourPath)
  5962. #else
  5963. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5964. #endif
  5965. {
  5966. return true;
  5967. }
  5968. else if (potentialParent.fullPath.length() >= ourPath.length())
  5969. {
  5970. return false;
  5971. }
  5972. else
  5973. {
  5974. return getParentDirectory().isAChildOf (potentialParent);
  5975. }
  5976. }
  5977. bool File::isAbsolutePath (const String& path)
  5978. {
  5979. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5980. #if JUCE_WINDOWS
  5981. || (path.isNotEmpty() && path[1] == ':');
  5982. #else
  5983. || path.startsWithChar ('~');
  5984. #endif
  5985. }
  5986. const File File::getChildFile (String relativePath) const
  5987. {
  5988. if (isAbsolutePath (relativePath))
  5989. {
  5990. // the path is really absolute..
  5991. return File (relativePath);
  5992. }
  5993. else
  5994. {
  5995. // it's relative, so remove any ../ or ./ bits at the start.
  5996. String path (fullPath);
  5997. if (relativePath[0] == '.')
  5998. {
  5999. #if JUCE_WINDOWS
  6000. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6001. #else
  6002. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6003. #endif
  6004. while (relativePath[0] == '.')
  6005. {
  6006. if (relativePath[1] == '.')
  6007. {
  6008. if (relativePath [2] == 0 || relativePath[2] == separator)
  6009. {
  6010. const int lastSlash = path.lastIndexOfChar (separator);
  6011. if (lastSlash >= 0)
  6012. path = path.substring (0, lastSlash);
  6013. relativePath = relativePath.substring (3);
  6014. }
  6015. else
  6016. {
  6017. break;
  6018. }
  6019. }
  6020. else if (relativePath[1] == separator)
  6021. {
  6022. relativePath = relativePath.substring (2);
  6023. }
  6024. else
  6025. {
  6026. break;
  6027. }
  6028. }
  6029. }
  6030. return File (addTrailingSeparator (path) + relativePath);
  6031. }
  6032. }
  6033. const File File::getSiblingFile (const String& fileName) const
  6034. {
  6035. return getParentDirectory().getChildFile (fileName);
  6036. }
  6037. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6038. {
  6039. if (bytes == 1)
  6040. {
  6041. return "1 byte";
  6042. }
  6043. else if (bytes < 1024)
  6044. {
  6045. return String ((int) bytes) + " bytes";
  6046. }
  6047. else if (bytes < 1024 * 1024)
  6048. {
  6049. return String (bytes / 1024.0, 1) + " KB";
  6050. }
  6051. else if (bytes < 1024 * 1024 * 1024)
  6052. {
  6053. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6054. }
  6055. else
  6056. {
  6057. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6058. }
  6059. }
  6060. bool File::create() const
  6061. {
  6062. if (exists())
  6063. return true;
  6064. {
  6065. const File parentDir (getParentDirectory());
  6066. if (parentDir == *this || ! parentDir.createDirectory())
  6067. return false;
  6068. FileOutputStream fo (*this, 8);
  6069. }
  6070. return exists();
  6071. }
  6072. bool File::createDirectory() const
  6073. {
  6074. if (! isDirectory())
  6075. {
  6076. const File parentDir (getParentDirectory());
  6077. if (parentDir == *this || ! parentDir.createDirectory())
  6078. return false;
  6079. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6080. return isDirectory();
  6081. }
  6082. return true;
  6083. }
  6084. const Time File::getCreationTime() const
  6085. {
  6086. int64 m, a, c;
  6087. getFileTimesInternal (m, a, c);
  6088. return Time (c);
  6089. }
  6090. const Time File::getLastModificationTime() const
  6091. {
  6092. int64 m, a, c;
  6093. getFileTimesInternal (m, a, c);
  6094. return Time (m);
  6095. }
  6096. const Time File::getLastAccessTime() const
  6097. {
  6098. int64 m, a, c;
  6099. getFileTimesInternal (m, a, c);
  6100. return Time (a);
  6101. }
  6102. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6103. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6104. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6105. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6106. {
  6107. if (! existsAsFile())
  6108. return false;
  6109. FileInputStream in (*this);
  6110. return getSize() == in.readIntoMemoryBlock (destBlock);
  6111. }
  6112. const String File::loadFileAsString() const
  6113. {
  6114. if (! existsAsFile())
  6115. return String::empty;
  6116. FileInputStream in (*this);
  6117. return in.readEntireStreamAsString();
  6118. }
  6119. int File::findChildFiles (Array<File>& results,
  6120. const int whatToLookFor,
  6121. const bool searchRecursively,
  6122. const String& wildCardPattern) const
  6123. {
  6124. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6125. int total = 0;
  6126. while (di.next())
  6127. {
  6128. results.add (di.getFile());
  6129. ++total;
  6130. }
  6131. return total;
  6132. }
  6133. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6134. {
  6135. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6136. int total = 0;
  6137. while (di.next())
  6138. ++total;
  6139. return total;
  6140. }
  6141. bool File::containsSubDirectories() const
  6142. {
  6143. if (isDirectory())
  6144. {
  6145. DirectoryIterator di (*this, false, "*", findDirectories);
  6146. return di.next();
  6147. }
  6148. return false;
  6149. }
  6150. const File File::getNonexistentChildFile (const String& prefix_,
  6151. const String& suffix,
  6152. bool putNumbersInBrackets) const
  6153. {
  6154. File f (getChildFile (prefix_ + suffix));
  6155. if (f.exists())
  6156. {
  6157. int num = 2;
  6158. String prefix (prefix_);
  6159. // remove any bracketed numbers that may already be on the end..
  6160. if (prefix.trim().endsWithChar (')'))
  6161. {
  6162. putNumbersInBrackets = true;
  6163. const int openBracks = prefix.lastIndexOfChar ('(');
  6164. const int closeBracks = prefix.lastIndexOfChar (')');
  6165. if (openBracks > 0
  6166. && closeBracks > openBracks
  6167. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6168. {
  6169. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6170. prefix = prefix.substring (0, openBracks);
  6171. }
  6172. }
  6173. // also use brackets if it ends in a digit.
  6174. putNumbersInBrackets = putNumbersInBrackets
  6175. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6176. do
  6177. {
  6178. if (putNumbersInBrackets)
  6179. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6180. else
  6181. f = getChildFile (prefix + String (num++) + suffix);
  6182. } while (f.exists());
  6183. }
  6184. return f;
  6185. }
  6186. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6187. {
  6188. if (exists())
  6189. {
  6190. return getParentDirectory()
  6191. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6192. getFileExtension(),
  6193. putNumbersInBrackets);
  6194. }
  6195. else
  6196. {
  6197. return *this;
  6198. }
  6199. }
  6200. const String File::getFileExtension() const
  6201. {
  6202. String ext;
  6203. if (! isDirectory())
  6204. {
  6205. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6206. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6207. ext = fullPath.substring (indexOfDot);
  6208. }
  6209. return ext;
  6210. }
  6211. bool File::hasFileExtension (const String& possibleSuffix) const
  6212. {
  6213. if (possibleSuffix.isEmpty())
  6214. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6215. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6216. if (semicolon >= 0)
  6217. {
  6218. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6219. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6220. }
  6221. else
  6222. {
  6223. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6224. {
  6225. if (possibleSuffix.startsWithChar ('.'))
  6226. return true;
  6227. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6228. if (dotPos >= 0)
  6229. return fullPath [dotPos] == '.';
  6230. }
  6231. }
  6232. return false;
  6233. }
  6234. const File File::withFileExtension (const String& newExtension) const
  6235. {
  6236. if (fullPath.isEmpty())
  6237. return File::nonexistent;
  6238. String filePart (getFileName());
  6239. int i = filePart.lastIndexOfChar ('.');
  6240. if (i >= 0)
  6241. filePart = filePart.substring (0, i);
  6242. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6243. filePart << '.';
  6244. return getSiblingFile (filePart + newExtension);
  6245. }
  6246. bool File::startAsProcess (const String& parameters) const
  6247. {
  6248. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6249. }
  6250. FileInputStream* File::createInputStream() const
  6251. {
  6252. if (existsAsFile())
  6253. return new FileInputStream (*this);
  6254. return 0;
  6255. }
  6256. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6257. {
  6258. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6259. if (out->failedToOpen())
  6260. return 0;
  6261. return out.release();
  6262. }
  6263. bool File::appendData (const void* const dataToAppend,
  6264. const int numberOfBytes) const
  6265. {
  6266. if (numberOfBytes > 0)
  6267. {
  6268. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6269. if (out == 0)
  6270. return false;
  6271. out->write (dataToAppend, numberOfBytes);
  6272. }
  6273. return true;
  6274. }
  6275. bool File::replaceWithData (const void* const dataToWrite,
  6276. const int numberOfBytes) const
  6277. {
  6278. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6279. if (numberOfBytes <= 0)
  6280. return deleteFile();
  6281. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6282. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6283. return tempFile.overwriteTargetFileWithTemporary();
  6284. }
  6285. bool File::appendText (const String& text,
  6286. const bool asUnicode,
  6287. const bool writeUnicodeHeaderBytes) const
  6288. {
  6289. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6290. if (out != 0)
  6291. {
  6292. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6293. return true;
  6294. }
  6295. return false;
  6296. }
  6297. bool File::replaceWithText (const String& textToWrite,
  6298. const bool asUnicode,
  6299. const bool writeUnicodeHeaderBytes) const
  6300. {
  6301. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6302. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6303. return tempFile.overwriteTargetFileWithTemporary();
  6304. }
  6305. bool File::hasIdenticalContentTo (const File& other) const
  6306. {
  6307. if (other == *this)
  6308. return true;
  6309. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6310. {
  6311. FileInputStream in1 (*this), in2 (other);
  6312. const int bufferSize = 4096;
  6313. HeapBlock <char> buffer1, buffer2;
  6314. buffer1.malloc (bufferSize);
  6315. buffer2.malloc (bufferSize);
  6316. for (;;)
  6317. {
  6318. const int num1 = in1.read (buffer1, bufferSize);
  6319. const int num2 = in2.read (buffer2, bufferSize);
  6320. if (num1 != num2)
  6321. break;
  6322. if (num1 <= 0)
  6323. return true;
  6324. if (memcmp (buffer1, buffer2, num1) != 0)
  6325. break;
  6326. }
  6327. }
  6328. return false;
  6329. }
  6330. const String File::createLegalPathName (const String& original)
  6331. {
  6332. String s (original);
  6333. String start;
  6334. if (s[1] == ':')
  6335. {
  6336. start = s.substring (0, 2);
  6337. s = s.substring (2);
  6338. }
  6339. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6340. .substring (0, 1024);
  6341. }
  6342. const String File::createLegalFileName (const String& original)
  6343. {
  6344. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6345. const int maxLength = 128; // only the length of the filename, not the whole path
  6346. const int len = s.length();
  6347. if (len > maxLength)
  6348. {
  6349. const int lastDot = s.lastIndexOfChar ('.');
  6350. if (lastDot > jmax (0, len - 12))
  6351. {
  6352. s = s.substring (0, maxLength - (len - lastDot))
  6353. + s.substring (lastDot);
  6354. }
  6355. else
  6356. {
  6357. s = s.substring (0, maxLength);
  6358. }
  6359. }
  6360. return s;
  6361. }
  6362. const String File::getRelativePathFrom (const File& dir) const
  6363. {
  6364. String thisPath (fullPath);
  6365. {
  6366. int len = thisPath.length();
  6367. while (--len >= 0 && thisPath [len] == File::separator)
  6368. thisPath [len] = 0;
  6369. }
  6370. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6371. : dir.fullPath));
  6372. const int len = jmin (thisPath.length(), dirPath.length());
  6373. int commonBitLength = 0;
  6374. for (int i = 0; i < len; ++i)
  6375. {
  6376. #if NAMES_ARE_CASE_SENSITIVE
  6377. if (thisPath[i] != dirPath[i])
  6378. #else
  6379. if (CharacterFunctions::toLowerCase (thisPath[i])
  6380. != CharacterFunctions::toLowerCase (dirPath[i]))
  6381. #endif
  6382. {
  6383. break;
  6384. }
  6385. ++commonBitLength;
  6386. }
  6387. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6388. --commonBitLength;
  6389. // if the only common bit is the root, then just return the full path..
  6390. if (commonBitLength <= 0
  6391. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6392. return fullPath;
  6393. thisPath = thisPath.substring (commonBitLength);
  6394. dirPath = dirPath.substring (commonBitLength);
  6395. while (dirPath.isNotEmpty())
  6396. {
  6397. #if JUCE_WINDOWS
  6398. thisPath = "..\\" + thisPath;
  6399. #else
  6400. thisPath = "../" + thisPath;
  6401. #endif
  6402. const int sep = dirPath.indexOfChar (separator);
  6403. if (sep >= 0)
  6404. dirPath = dirPath.substring (sep + 1);
  6405. else
  6406. dirPath = String::empty;
  6407. }
  6408. return thisPath;
  6409. }
  6410. const File File::createTempFile (const String& fileNameEnding)
  6411. {
  6412. const File tempFile (getSpecialLocation (tempDirectory)
  6413. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6414. .withFileExtension (fileNameEnding));
  6415. if (tempFile.exists())
  6416. return createTempFile (fileNameEnding);
  6417. else
  6418. return tempFile;
  6419. }
  6420. #if JUCE_UNIT_TESTS
  6421. class FileTests : public UnitTest
  6422. {
  6423. public:
  6424. FileTests() : UnitTest ("Files") {}
  6425. void runTest()
  6426. {
  6427. beginTest ("Reading");
  6428. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6429. const File temp (File::getSpecialLocation (File::tempDirectory));
  6430. expect (! File::nonexistent.exists());
  6431. expect (home.isDirectory());
  6432. expect (home.exists());
  6433. expect (! home.existsAsFile());
  6434. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6435. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6436. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6437. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6438. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6439. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6440. expect (home.getBytesFreeOnVolume() > 0);
  6441. expect (! home.isHidden());
  6442. expect (home.isOnHardDisk());
  6443. expect (! home.isOnCDRomDrive());
  6444. expect (File::getCurrentWorkingDirectory().exists());
  6445. expect (home.setAsCurrentWorkingDirectory());
  6446. expect (File::getCurrentWorkingDirectory() == home);
  6447. {
  6448. Array<File> roots;
  6449. File::findFileSystemRoots (roots);
  6450. expect (roots.size() > 0);
  6451. int numRootsExisting = 0;
  6452. for (int i = 0; i < roots.size(); ++i)
  6453. if (roots[i].exists())
  6454. ++numRootsExisting;
  6455. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6456. expect (numRootsExisting > 0);
  6457. }
  6458. beginTest ("Writing");
  6459. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6460. expect (demoFolder.deleteRecursively());
  6461. expect (demoFolder.createDirectory());
  6462. expect (demoFolder.isDirectory());
  6463. expect (demoFolder.getParentDirectory() == temp);
  6464. expect (temp.isDirectory());
  6465. {
  6466. Array<File> files;
  6467. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6468. expect (files.contains (demoFolder));
  6469. }
  6470. {
  6471. Array<File> files;
  6472. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6473. expect (files.contains (demoFolder));
  6474. }
  6475. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6476. expect (tempFile.getFileExtension() == ".txt");
  6477. expect (tempFile.hasFileExtension (".txt"));
  6478. expect (tempFile.hasFileExtension ("txt"));
  6479. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6480. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6481. expect (tempFile.hasWriteAccess());
  6482. {
  6483. FileOutputStream fo (tempFile);
  6484. fo.write ("0123456789", 10);
  6485. }
  6486. expect (tempFile.exists());
  6487. expect (tempFile.getSize() == 10);
  6488. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6489. expect (tempFile.loadFileAsString() == "0123456789");
  6490. expect (! demoFolder.containsSubDirectories());
  6491. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6492. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6493. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6494. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6495. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6496. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6497. expect (demoFolder.containsSubDirectories());
  6498. expect (tempFile.hasWriteAccess());
  6499. tempFile.setReadOnly (true);
  6500. expect (! tempFile.hasWriteAccess());
  6501. tempFile.setReadOnly (false);
  6502. expect (tempFile.hasWriteAccess());
  6503. Time t (Time::getCurrentTime());
  6504. tempFile.setLastModificationTime (t);
  6505. Time t2 = tempFile.getLastModificationTime();
  6506. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6507. {
  6508. MemoryBlock mb;
  6509. tempFile.loadFileAsData (mb);
  6510. expect (mb.getSize() == 10);
  6511. expect (mb[0] == '0');
  6512. }
  6513. expect (tempFile.appendData ("abcdefghij", 10));
  6514. expect (tempFile.getSize() == 20);
  6515. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6516. expect (tempFile.getSize() == 10);
  6517. File tempFile2 (tempFile.getNonexistentSibling (false));
  6518. expect (tempFile.copyFileTo (tempFile2));
  6519. expect (tempFile2.exists());
  6520. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6521. expect (tempFile.deleteFile());
  6522. expect (! tempFile.exists());
  6523. expect (tempFile2.moveFileTo (tempFile));
  6524. expect (tempFile.exists());
  6525. expect (! tempFile2.exists());
  6526. expect (demoFolder.deleteRecursively());
  6527. expect (! demoFolder.exists());
  6528. }
  6529. };
  6530. static FileTests fileUnitTests;
  6531. #endif
  6532. END_JUCE_NAMESPACE
  6533. /*** End of inlined file: juce_File.cpp ***/
  6534. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6535. BEGIN_JUCE_NAMESPACE
  6536. int64 juce_fileSetPosition (void* handle, int64 pos);
  6537. FileInputStream::FileInputStream (const File& f)
  6538. : file (f),
  6539. fileHandle (0),
  6540. currentPosition (0),
  6541. totalSize (0),
  6542. needToSeek (true)
  6543. {
  6544. openHandle();
  6545. }
  6546. FileInputStream::~FileInputStream()
  6547. {
  6548. closeHandle();
  6549. }
  6550. int64 FileInputStream::getTotalLength()
  6551. {
  6552. return totalSize;
  6553. }
  6554. int FileInputStream::read (void* buffer, int bytesToRead)
  6555. {
  6556. int num = 0;
  6557. if (needToSeek)
  6558. {
  6559. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6560. return 0;
  6561. needToSeek = false;
  6562. }
  6563. num = readInternal (buffer, bytesToRead);
  6564. currentPosition += num;
  6565. return num;
  6566. }
  6567. bool FileInputStream::isExhausted()
  6568. {
  6569. return currentPosition >= totalSize;
  6570. }
  6571. int64 FileInputStream::getPosition()
  6572. {
  6573. return currentPosition;
  6574. }
  6575. bool FileInputStream::setPosition (int64 pos)
  6576. {
  6577. pos = jlimit ((int64) 0, totalSize, pos);
  6578. needToSeek |= (currentPosition != pos);
  6579. currentPosition = pos;
  6580. return true;
  6581. }
  6582. END_JUCE_NAMESPACE
  6583. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6584. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6585. BEGIN_JUCE_NAMESPACE
  6586. int64 juce_fileSetPosition (void* handle, int64 pos);
  6587. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6588. : file (f),
  6589. fileHandle (0),
  6590. currentPosition (0),
  6591. bufferSize (bufferSize_),
  6592. bytesInBuffer (0),
  6593. buffer (jmax (bufferSize_, 16))
  6594. {
  6595. openHandle();
  6596. }
  6597. FileOutputStream::~FileOutputStream()
  6598. {
  6599. flush();
  6600. closeHandle();
  6601. }
  6602. int64 FileOutputStream::getPosition()
  6603. {
  6604. return currentPosition;
  6605. }
  6606. bool FileOutputStream::setPosition (int64 newPosition)
  6607. {
  6608. if (newPosition != currentPosition)
  6609. {
  6610. flush();
  6611. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6612. }
  6613. return newPosition == currentPosition;
  6614. }
  6615. void FileOutputStream::flush()
  6616. {
  6617. if (bytesInBuffer > 0)
  6618. {
  6619. writeInternal (buffer, bytesInBuffer);
  6620. bytesInBuffer = 0;
  6621. }
  6622. flushInternal();
  6623. }
  6624. bool FileOutputStream::write (const void* const src, const int numBytes)
  6625. {
  6626. if (bytesInBuffer + numBytes < bufferSize)
  6627. {
  6628. memcpy (buffer + bytesInBuffer, src, numBytes);
  6629. bytesInBuffer += numBytes;
  6630. currentPosition += numBytes;
  6631. }
  6632. else
  6633. {
  6634. if (bytesInBuffer > 0)
  6635. {
  6636. // flush the reservoir
  6637. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6638. bytesInBuffer = 0;
  6639. if (! wroteOk)
  6640. return false;
  6641. }
  6642. if (numBytes < bufferSize)
  6643. {
  6644. memcpy (buffer + bytesInBuffer, src, numBytes);
  6645. bytesInBuffer += numBytes;
  6646. currentPosition += numBytes;
  6647. }
  6648. else
  6649. {
  6650. const int bytesWritten = writeInternal (src, numBytes);
  6651. if (bytesWritten < 0)
  6652. return false;
  6653. currentPosition += bytesWritten;
  6654. return bytesWritten == numBytes;
  6655. }
  6656. }
  6657. return true;
  6658. }
  6659. END_JUCE_NAMESPACE
  6660. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6661. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6662. BEGIN_JUCE_NAMESPACE
  6663. FileSearchPath::FileSearchPath()
  6664. {
  6665. }
  6666. FileSearchPath::FileSearchPath (const String& path)
  6667. {
  6668. init (path);
  6669. }
  6670. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6671. : directories (other.directories)
  6672. {
  6673. }
  6674. FileSearchPath::~FileSearchPath()
  6675. {
  6676. }
  6677. FileSearchPath& FileSearchPath::operator= (const String& path)
  6678. {
  6679. init (path);
  6680. return *this;
  6681. }
  6682. void FileSearchPath::init (const String& path)
  6683. {
  6684. directories.clear();
  6685. directories.addTokens (path, ";", "\"");
  6686. directories.trim();
  6687. directories.removeEmptyStrings();
  6688. for (int i = directories.size(); --i >= 0;)
  6689. directories.set (i, directories[i].unquoted());
  6690. }
  6691. int FileSearchPath::getNumPaths() const
  6692. {
  6693. return directories.size();
  6694. }
  6695. const File FileSearchPath::operator[] (const int index) const
  6696. {
  6697. return File (directories [index]);
  6698. }
  6699. const String FileSearchPath::toString() const
  6700. {
  6701. StringArray directories2 (directories);
  6702. for (int i = directories2.size(); --i >= 0;)
  6703. if (directories2[i].containsChar (';'))
  6704. directories2.set (i, directories2[i].quoted());
  6705. return directories2.joinIntoString (";");
  6706. }
  6707. void FileSearchPath::add (const File& dir, const int insertIndex)
  6708. {
  6709. directories.insert (insertIndex, dir.getFullPathName());
  6710. }
  6711. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6712. {
  6713. for (int i = 0; i < directories.size(); ++i)
  6714. if (File (directories[i]) == dir)
  6715. return;
  6716. add (dir);
  6717. }
  6718. void FileSearchPath::remove (const int index)
  6719. {
  6720. directories.remove (index);
  6721. }
  6722. void FileSearchPath::addPath (const FileSearchPath& other)
  6723. {
  6724. for (int i = 0; i < other.getNumPaths(); ++i)
  6725. addIfNotAlreadyThere (other[i]);
  6726. }
  6727. void FileSearchPath::removeRedundantPaths()
  6728. {
  6729. for (int i = directories.size(); --i >= 0;)
  6730. {
  6731. const File d1 (directories[i]);
  6732. for (int j = directories.size(); --j >= 0;)
  6733. {
  6734. const File d2 (directories[j]);
  6735. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6736. {
  6737. directories.remove (i);
  6738. break;
  6739. }
  6740. }
  6741. }
  6742. }
  6743. void FileSearchPath::removeNonExistentPaths()
  6744. {
  6745. for (int i = directories.size(); --i >= 0;)
  6746. if (! File (directories[i]).isDirectory())
  6747. directories.remove (i);
  6748. }
  6749. int FileSearchPath::findChildFiles (Array<File>& results,
  6750. const int whatToLookFor,
  6751. const bool searchRecursively,
  6752. const String& wildCardPattern) const
  6753. {
  6754. int total = 0;
  6755. for (int i = 0; i < directories.size(); ++i)
  6756. total += operator[] (i).findChildFiles (results,
  6757. whatToLookFor,
  6758. searchRecursively,
  6759. wildCardPattern);
  6760. return total;
  6761. }
  6762. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6763. const bool checkRecursively) const
  6764. {
  6765. for (int i = directories.size(); --i >= 0;)
  6766. {
  6767. const File d (directories[i]);
  6768. if (checkRecursively)
  6769. {
  6770. if (fileToCheck.isAChildOf (d))
  6771. return true;
  6772. }
  6773. else
  6774. {
  6775. if (fileToCheck.getParentDirectory() == d)
  6776. return true;
  6777. }
  6778. }
  6779. return false;
  6780. }
  6781. END_JUCE_NAMESPACE
  6782. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6783. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6784. BEGIN_JUCE_NAMESPACE
  6785. NamedPipe::NamedPipe()
  6786. : internal (0)
  6787. {
  6788. }
  6789. NamedPipe::~NamedPipe()
  6790. {
  6791. close();
  6792. }
  6793. bool NamedPipe::openExisting (const String& pipeName)
  6794. {
  6795. currentPipeName = pipeName;
  6796. return openInternal (pipeName, false);
  6797. }
  6798. bool NamedPipe::createNewPipe (const String& pipeName)
  6799. {
  6800. currentPipeName = pipeName;
  6801. return openInternal (pipeName, true);
  6802. }
  6803. bool NamedPipe::isOpen() const
  6804. {
  6805. return internal != 0;
  6806. }
  6807. const String NamedPipe::getName() const
  6808. {
  6809. return currentPipeName;
  6810. }
  6811. // other methods for this class are implemented in the platform-specific files
  6812. END_JUCE_NAMESPACE
  6813. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6814. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6815. BEGIN_JUCE_NAMESPACE
  6816. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6817. {
  6818. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6819. "temp_" + String (Random::getSystemRandom().nextInt()),
  6820. suffix,
  6821. optionFlags);
  6822. }
  6823. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6824. : targetFile (targetFile_)
  6825. {
  6826. // If you use this constructor, you need to give it a valid target file!
  6827. jassert (targetFile != File::nonexistent);
  6828. createTempFile (targetFile.getParentDirectory(),
  6829. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6830. targetFile.getFileExtension(),
  6831. optionFlags);
  6832. }
  6833. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6834. const String& suffix, const int optionFlags)
  6835. {
  6836. if ((optionFlags & useHiddenFile) != 0)
  6837. name = "." + name;
  6838. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6839. }
  6840. TemporaryFile::~TemporaryFile()
  6841. {
  6842. if (! deleteTemporaryFile())
  6843. {
  6844. /* Failed to delete our temporary file! The most likely reason for this would be
  6845. that you've not closed an output stream that was being used to write to file.
  6846. If you find that something beyond your control is changing permissions on
  6847. your temporary files and preventing them from being deleted, you may want to
  6848. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6849. handle them appropriately.
  6850. */
  6851. jassertfalse;
  6852. }
  6853. }
  6854. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6855. {
  6856. // This method only works if you created this object with the constructor
  6857. // that takes a target file!
  6858. jassert (targetFile != File::nonexistent);
  6859. if (temporaryFile.exists())
  6860. {
  6861. // Have a few attempts at overwriting the file before giving up..
  6862. for (int i = 5; --i >= 0;)
  6863. {
  6864. if (temporaryFile.moveFileTo (targetFile))
  6865. return true;
  6866. Thread::sleep (100);
  6867. }
  6868. }
  6869. else
  6870. {
  6871. // There's no temporary file to use. If your write failed, you should
  6872. // probably check, and not bother calling this method.
  6873. jassertfalse;
  6874. }
  6875. return false;
  6876. }
  6877. bool TemporaryFile::deleteTemporaryFile() const
  6878. {
  6879. // Have a few attempts at deleting the file before giving up..
  6880. for (int i = 5; --i >= 0;)
  6881. {
  6882. if (temporaryFile.deleteFile())
  6883. return true;
  6884. Thread::sleep (50);
  6885. }
  6886. return false;
  6887. }
  6888. END_JUCE_NAMESPACE
  6889. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6890. /*** Start of inlined file: juce_Socket.cpp ***/
  6891. #if JUCE_WINDOWS
  6892. #include <winsock2.h>
  6893. #if JUCE_MSVC
  6894. #pragma warning (push)
  6895. #pragma warning (disable : 4127 4389 4018)
  6896. #endif
  6897. #else
  6898. #if JUCE_LINUX
  6899. #include <sys/types.h>
  6900. #include <sys/socket.h>
  6901. #include <sys/errno.h>
  6902. #include <unistd.h>
  6903. #include <netinet/in.h>
  6904. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6905. #include <CoreServices/CoreServices.h>
  6906. #endif
  6907. #include <fcntl.h>
  6908. #include <netdb.h>
  6909. #include <arpa/inet.h>
  6910. #include <netinet/tcp.h>
  6911. #endif
  6912. BEGIN_JUCE_NAMESPACE
  6913. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6914. typedef socklen_t juce_socklen_t;
  6915. #else
  6916. typedef int juce_socklen_t;
  6917. #endif
  6918. #if JUCE_WINDOWS
  6919. namespace SocketHelpers
  6920. {
  6921. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6922. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6923. void initWin32Sockets()
  6924. {
  6925. static CriticalSection lock;
  6926. const ScopedLock sl (lock);
  6927. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6928. {
  6929. WSADATA wsaData;
  6930. const WORD wVersionRequested = MAKEWORD (1, 1);
  6931. WSAStartup (wVersionRequested, &wsaData);
  6932. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6933. }
  6934. }
  6935. }
  6936. void juce_shutdownWin32Sockets()
  6937. {
  6938. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6939. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6940. }
  6941. #endif
  6942. namespace SocketHelpers
  6943. {
  6944. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6945. {
  6946. const int sndBufSize = 65536;
  6947. const int rcvBufSize = 65536;
  6948. const int one = 1;
  6949. return handle > 0
  6950. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6951. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6952. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6953. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6954. }
  6955. bool bindSocketToPort (const int handle, const int port) throw()
  6956. {
  6957. if (handle <= 0 || port <= 0)
  6958. return false;
  6959. struct sockaddr_in servTmpAddr;
  6960. zerostruct (servTmpAddr);
  6961. servTmpAddr.sin_family = PF_INET;
  6962. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6963. servTmpAddr.sin_port = htons ((uint16) port);
  6964. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6965. }
  6966. int readSocket (const int handle,
  6967. void* const destBuffer, const int maxBytesToRead,
  6968. bool volatile& connected,
  6969. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6970. {
  6971. int bytesRead = 0;
  6972. while (bytesRead < maxBytesToRead)
  6973. {
  6974. int bytesThisTime;
  6975. #if JUCE_WINDOWS
  6976. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6977. #else
  6978. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6979. && errno == EINTR
  6980. && connected)
  6981. {
  6982. }
  6983. #endif
  6984. if (bytesThisTime <= 0 || ! connected)
  6985. {
  6986. if (bytesRead == 0)
  6987. bytesRead = -1;
  6988. break;
  6989. }
  6990. bytesRead += bytesThisTime;
  6991. if (! blockUntilSpecifiedAmountHasArrived)
  6992. break;
  6993. }
  6994. return bytesRead;
  6995. }
  6996. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  6997. {
  6998. struct timeval timeout;
  6999. struct timeval* timeoutp;
  7000. if (timeoutMsecs >= 0)
  7001. {
  7002. timeout.tv_sec = timeoutMsecs / 1000;
  7003. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7004. timeoutp = &timeout;
  7005. }
  7006. else
  7007. {
  7008. timeoutp = 0;
  7009. }
  7010. fd_set rset, wset;
  7011. FD_ZERO (&rset);
  7012. FD_SET (handle, &rset);
  7013. FD_ZERO (&wset);
  7014. FD_SET (handle, &wset);
  7015. fd_set* const prset = forReading ? &rset : 0;
  7016. fd_set* const pwset = forReading ? 0 : &wset;
  7017. #if JUCE_WINDOWS
  7018. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7019. return -1;
  7020. #else
  7021. {
  7022. int result;
  7023. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7024. && errno == EINTR)
  7025. {
  7026. }
  7027. if (result < 0)
  7028. return -1;
  7029. }
  7030. #endif
  7031. {
  7032. int opt;
  7033. juce_socklen_t len = sizeof (opt);
  7034. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7035. || opt != 0)
  7036. return -1;
  7037. }
  7038. if ((forReading && FD_ISSET (handle, &rset))
  7039. || ((! forReading) && FD_ISSET (handle, &wset)))
  7040. return 1;
  7041. return 0;
  7042. }
  7043. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7044. {
  7045. #if JUCE_WINDOWS
  7046. u_long nonBlocking = shouldBlock ? 0 : 1;
  7047. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7048. return false;
  7049. #else
  7050. int socketFlags = fcntl (handle, F_GETFL, 0);
  7051. if (socketFlags == -1)
  7052. return false;
  7053. if (shouldBlock)
  7054. socketFlags &= ~O_NONBLOCK;
  7055. else
  7056. socketFlags |= O_NONBLOCK;
  7057. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7058. return false;
  7059. #endif
  7060. return true;
  7061. }
  7062. bool connectSocket (int volatile& handle,
  7063. const bool isDatagram,
  7064. void** serverAddress,
  7065. const String& hostName,
  7066. const int portNumber,
  7067. const int timeOutMillisecs) throw()
  7068. {
  7069. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7070. if (hostEnt == 0)
  7071. return false;
  7072. struct in_addr targetAddress;
  7073. memcpy (&targetAddress.s_addr,
  7074. *(hostEnt->h_addr_list),
  7075. sizeof (targetAddress.s_addr));
  7076. struct sockaddr_in servTmpAddr;
  7077. zerostruct (servTmpAddr);
  7078. servTmpAddr.sin_family = PF_INET;
  7079. servTmpAddr.sin_addr = targetAddress;
  7080. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7081. if (handle < 0)
  7082. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7083. if (handle < 0)
  7084. return false;
  7085. if (isDatagram)
  7086. {
  7087. *serverAddress = new struct sockaddr_in();
  7088. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7089. return true;
  7090. }
  7091. setSocketBlockingState (handle, false);
  7092. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7093. if (result < 0)
  7094. {
  7095. #if JUCE_WINDOWS
  7096. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7097. #else
  7098. if (errno == EINPROGRESS)
  7099. #endif
  7100. {
  7101. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7102. {
  7103. setSocketBlockingState (handle, true);
  7104. return false;
  7105. }
  7106. }
  7107. }
  7108. setSocketBlockingState (handle, true);
  7109. resetSocketOptions (handle, false, false);
  7110. return true;
  7111. }
  7112. }
  7113. StreamingSocket::StreamingSocket()
  7114. : portNumber (0),
  7115. handle (-1),
  7116. connected (false),
  7117. isListener (false)
  7118. {
  7119. #if JUCE_WINDOWS
  7120. SocketHelpers::initWin32Sockets();
  7121. #endif
  7122. }
  7123. StreamingSocket::StreamingSocket (const String& hostName_,
  7124. const int portNumber_,
  7125. const int handle_)
  7126. : hostName (hostName_),
  7127. portNumber (portNumber_),
  7128. handle (handle_),
  7129. connected (true),
  7130. isListener (false)
  7131. {
  7132. #if JUCE_WINDOWS
  7133. SocketHelpers::initWin32Sockets();
  7134. #endif
  7135. SocketHelpers::resetSocketOptions (handle_, false, false);
  7136. }
  7137. StreamingSocket::~StreamingSocket()
  7138. {
  7139. close();
  7140. }
  7141. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7142. {
  7143. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7144. : -1;
  7145. }
  7146. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7147. {
  7148. if (isListener || ! connected)
  7149. return -1;
  7150. #if JUCE_WINDOWS
  7151. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7152. #else
  7153. int result;
  7154. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7155. && errno == EINTR)
  7156. {
  7157. }
  7158. return result;
  7159. #endif
  7160. }
  7161. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7162. const int timeoutMsecs) const
  7163. {
  7164. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7165. : -1;
  7166. }
  7167. bool StreamingSocket::bindToPort (const int port)
  7168. {
  7169. return SocketHelpers::bindSocketToPort (handle, port);
  7170. }
  7171. bool StreamingSocket::connect (const String& remoteHostName,
  7172. const int remotePortNumber,
  7173. const int timeOutMillisecs)
  7174. {
  7175. if (isListener)
  7176. {
  7177. jassertfalse; // a listener socket can't connect to another one!
  7178. return false;
  7179. }
  7180. if (connected)
  7181. close();
  7182. hostName = remoteHostName;
  7183. portNumber = remotePortNumber;
  7184. isListener = false;
  7185. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7186. remotePortNumber, timeOutMillisecs);
  7187. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7188. {
  7189. close();
  7190. return false;
  7191. }
  7192. return true;
  7193. }
  7194. void StreamingSocket::close()
  7195. {
  7196. #if JUCE_WINDOWS
  7197. if (handle != SOCKET_ERROR || connected)
  7198. closesocket (handle);
  7199. connected = false;
  7200. #else
  7201. if (connected)
  7202. {
  7203. connected = false;
  7204. if (isListener)
  7205. {
  7206. // need to do this to interrupt the accept() function..
  7207. StreamingSocket temp;
  7208. temp.connect ("localhost", portNumber, 1000);
  7209. }
  7210. }
  7211. if (handle != -1)
  7212. ::close (handle);
  7213. #endif
  7214. hostName = String::empty;
  7215. portNumber = 0;
  7216. handle = -1;
  7217. isListener = false;
  7218. }
  7219. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7220. {
  7221. if (connected)
  7222. close();
  7223. hostName = "listener";
  7224. portNumber = newPortNumber;
  7225. isListener = true;
  7226. struct sockaddr_in servTmpAddr;
  7227. zerostruct (servTmpAddr);
  7228. servTmpAddr.sin_family = PF_INET;
  7229. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7230. if (localHostName.isNotEmpty())
  7231. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7232. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7233. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7234. if (handle < 0)
  7235. return false;
  7236. const int reuse = 1;
  7237. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7238. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7239. || listen (handle, SOMAXCONN) < 0)
  7240. {
  7241. close();
  7242. return false;
  7243. }
  7244. connected = true;
  7245. return true;
  7246. }
  7247. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7248. {
  7249. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7250. // prepare this socket as a listener.
  7251. if (connected && isListener)
  7252. {
  7253. struct sockaddr address;
  7254. juce_socklen_t len = sizeof (sockaddr);
  7255. const int newSocket = (int) accept (handle, &address, &len);
  7256. if (newSocket >= 0 && connected)
  7257. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7258. portNumber, newSocket);
  7259. }
  7260. return 0;
  7261. }
  7262. bool StreamingSocket::isLocal() const throw()
  7263. {
  7264. return hostName == "127.0.0.1";
  7265. }
  7266. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7267. : portNumber (0),
  7268. handle (-1),
  7269. connected (true),
  7270. allowBroadcast (allowBroadcast_),
  7271. serverAddress (0)
  7272. {
  7273. #if JUCE_WINDOWS
  7274. SocketHelpers::initWin32Sockets();
  7275. #endif
  7276. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7277. bindToPort (localPortNumber);
  7278. }
  7279. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7280. const int handle_, const int localPortNumber)
  7281. : hostName (hostName_),
  7282. portNumber (portNumber_),
  7283. handle (handle_),
  7284. connected (true),
  7285. allowBroadcast (false),
  7286. serverAddress (0)
  7287. {
  7288. #if JUCE_WINDOWS
  7289. SocketHelpers::initWin32Sockets();
  7290. #endif
  7291. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7292. bindToPort (localPortNumber);
  7293. }
  7294. DatagramSocket::~DatagramSocket()
  7295. {
  7296. close();
  7297. delete static_cast <struct sockaddr_in*> (serverAddress);
  7298. serverAddress = 0;
  7299. }
  7300. void DatagramSocket::close()
  7301. {
  7302. #if JUCE_WINDOWS
  7303. closesocket (handle);
  7304. connected = false;
  7305. #else
  7306. connected = false;
  7307. ::close (handle);
  7308. #endif
  7309. hostName = String::empty;
  7310. portNumber = 0;
  7311. handle = -1;
  7312. }
  7313. bool DatagramSocket::bindToPort (const int port)
  7314. {
  7315. return SocketHelpers::bindSocketToPort (handle, port);
  7316. }
  7317. bool DatagramSocket::connect (const String& remoteHostName,
  7318. const int remotePortNumber,
  7319. const int timeOutMillisecs)
  7320. {
  7321. if (connected)
  7322. close();
  7323. hostName = remoteHostName;
  7324. portNumber = remotePortNumber;
  7325. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7326. remoteHostName, remotePortNumber,
  7327. timeOutMillisecs);
  7328. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7329. {
  7330. close();
  7331. return false;
  7332. }
  7333. return true;
  7334. }
  7335. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7336. {
  7337. struct sockaddr address;
  7338. juce_socklen_t len = sizeof (sockaddr);
  7339. while (waitUntilReady (true, -1) == 1)
  7340. {
  7341. char buf[1];
  7342. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7343. {
  7344. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7345. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7346. -1, -1);
  7347. }
  7348. }
  7349. return 0;
  7350. }
  7351. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7352. const int timeoutMsecs) const
  7353. {
  7354. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7355. : -1;
  7356. }
  7357. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7358. {
  7359. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7360. : -1;
  7361. }
  7362. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7363. {
  7364. // You need to call connect() first to set the server address..
  7365. jassert (serverAddress != 0 && connected);
  7366. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7367. numBytesToWrite, 0,
  7368. (const struct sockaddr*) serverAddress,
  7369. sizeof (struct sockaddr_in))
  7370. : -1;
  7371. }
  7372. bool DatagramSocket::isLocal() const throw()
  7373. {
  7374. return hostName == "127.0.0.1";
  7375. }
  7376. #if JUCE_MSVC
  7377. #pragma warning (pop)
  7378. #endif
  7379. END_JUCE_NAMESPACE
  7380. /*** End of inlined file: juce_Socket.cpp ***/
  7381. /*** Start of inlined file: juce_URL.cpp ***/
  7382. BEGIN_JUCE_NAMESPACE
  7383. URL::URL()
  7384. {
  7385. }
  7386. URL::URL (const String& url_)
  7387. : url (url_)
  7388. {
  7389. int i = url.indexOfChar ('?');
  7390. if (i >= 0)
  7391. {
  7392. do
  7393. {
  7394. const int nextAmp = url.indexOfChar (i + 1, '&');
  7395. const int equalsPos = url.indexOfChar (i + 1, '=');
  7396. if (equalsPos > i + 1)
  7397. {
  7398. if (nextAmp < 0)
  7399. {
  7400. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7401. removeEscapeChars (url.substring (equalsPos + 1)));
  7402. }
  7403. else if (nextAmp > 0 && equalsPos < nextAmp)
  7404. {
  7405. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7406. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7407. }
  7408. }
  7409. i = nextAmp;
  7410. }
  7411. while (i >= 0);
  7412. url = url.upToFirstOccurrenceOf ("?", false, false);
  7413. }
  7414. }
  7415. URL::URL (const URL& other)
  7416. : url (other.url),
  7417. postData (other.postData),
  7418. parameters (other.parameters),
  7419. filesToUpload (other.filesToUpload),
  7420. mimeTypes (other.mimeTypes)
  7421. {
  7422. }
  7423. URL& URL::operator= (const URL& other)
  7424. {
  7425. url = other.url;
  7426. postData = other.postData;
  7427. parameters = other.parameters;
  7428. filesToUpload = other.filesToUpload;
  7429. mimeTypes = other.mimeTypes;
  7430. return *this;
  7431. }
  7432. URL::~URL()
  7433. {
  7434. }
  7435. namespace URLHelpers
  7436. {
  7437. const String getMangledParameters (const StringPairArray& parameters)
  7438. {
  7439. String p;
  7440. for (int i = 0; i < parameters.size(); ++i)
  7441. {
  7442. if (i > 0)
  7443. p << '&';
  7444. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7445. << '='
  7446. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7447. }
  7448. return p;
  7449. }
  7450. int findStartOfDomain (const String& url)
  7451. {
  7452. int i = 0;
  7453. while (CharacterFunctions::isLetterOrDigit (url[i])
  7454. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7455. ++i;
  7456. return url[i] == ':' ? i + 1 : 0;
  7457. }
  7458. }
  7459. const String URL::toString (const bool includeGetParameters) const
  7460. {
  7461. if (includeGetParameters && parameters.size() > 0)
  7462. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7463. else
  7464. return url;
  7465. }
  7466. bool URL::isWellFormed() const
  7467. {
  7468. //xxx TODO
  7469. return url.isNotEmpty();
  7470. }
  7471. const String URL::getDomain() const
  7472. {
  7473. int start = URLHelpers::findStartOfDomain (url);
  7474. while (url[start] == '/')
  7475. ++start;
  7476. const int end1 = url.indexOfChar (start, '/');
  7477. const int end2 = url.indexOfChar (start, ':');
  7478. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7479. : jmin (end1, end2);
  7480. return url.substring (start, end);
  7481. }
  7482. const String URL::getSubPath() const
  7483. {
  7484. int start = URLHelpers::findStartOfDomain (url);
  7485. while (url[start] == '/')
  7486. ++start;
  7487. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7488. return startOfPath <= 0 ? String::empty
  7489. : url.substring (startOfPath);
  7490. }
  7491. const String URL::getScheme() const
  7492. {
  7493. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7494. }
  7495. const URL URL::withNewSubPath (const String& newPath) const
  7496. {
  7497. int start = URLHelpers::findStartOfDomain (url);
  7498. while (url[start] == '/')
  7499. ++start;
  7500. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7501. URL u (*this);
  7502. if (startOfPath > 0)
  7503. u.url = url.substring (0, startOfPath);
  7504. if (! u.url.endsWithChar ('/'))
  7505. u.url << '/';
  7506. if (newPath.startsWithChar ('/'))
  7507. u.url << newPath.substring (1);
  7508. else
  7509. u.url << newPath;
  7510. return u;
  7511. }
  7512. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7513. {
  7514. if (possibleURL.startsWithIgnoreCase ("http:")
  7515. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7516. return true;
  7517. if (possibleURL.startsWithIgnoreCase ("file:")
  7518. || possibleURL.containsChar ('@')
  7519. || possibleURL.endsWithChar ('.')
  7520. || (! possibleURL.containsChar ('.')))
  7521. return false;
  7522. if (possibleURL.startsWithIgnoreCase ("www.")
  7523. && possibleURL.substring (5).containsChar ('.'))
  7524. return true;
  7525. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7526. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7527. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7528. return true;
  7529. return false;
  7530. }
  7531. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7532. {
  7533. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7534. return atSign > 0
  7535. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7536. && (! possibleEmailAddress.endsWithChar ('.'));
  7537. }
  7538. void* juce_openInternetFile (const String& url,
  7539. const String& headers,
  7540. const MemoryBlock& optionalPostData,
  7541. const bool isPost,
  7542. URL::OpenStreamProgressCallback* callback,
  7543. void* callbackContext,
  7544. int timeOutMs);
  7545. void juce_closeInternetFile (void* handle);
  7546. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7547. int juce_seekInInternetFile (void* handle, int newPosition);
  7548. int64 juce_getInternetFileContentLength (void* handle);
  7549. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7550. class WebInputStream : public InputStream
  7551. {
  7552. public:
  7553. WebInputStream (const URL& url,
  7554. const bool isPost_,
  7555. URL::OpenStreamProgressCallback* const progressCallback_,
  7556. void* const progressCallbackContext_,
  7557. const String& extraHeaders,
  7558. const int timeOutMs_,
  7559. StringPairArray* const responseHeaders)
  7560. : position (0),
  7561. finished (false),
  7562. isPost (isPost_),
  7563. progressCallback (progressCallback_),
  7564. progressCallbackContext (progressCallbackContext_),
  7565. timeOutMs (timeOutMs_)
  7566. {
  7567. server = url.toString (! isPost);
  7568. if (isPost_)
  7569. createHeadersAndPostData (url);
  7570. headers += extraHeaders;
  7571. if (! headers.endsWithChar ('\n'))
  7572. headers << "\r\n";
  7573. handle = juce_openInternetFile (server, headers, postData, isPost,
  7574. progressCallback_, progressCallbackContext_,
  7575. timeOutMs);
  7576. if (responseHeaders != 0)
  7577. juce_getInternetFileHeaders (handle, *responseHeaders);
  7578. }
  7579. ~WebInputStream()
  7580. {
  7581. juce_closeInternetFile (handle);
  7582. }
  7583. bool isError() const { return handle == 0; }
  7584. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7585. bool isExhausted() { return finished; }
  7586. int64 getPosition() { return position; }
  7587. int read (void* dest, int bytes)
  7588. {
  7589. if (finished || isError())
  7590. {
  7591. return 0;
  7592. }
  7593. else
  7594. {
  7595. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7596. position += bytesRead;
  7597. if (bytesRead == 0)
  7598. finished = true;
  7599. return bytesRead;
  7600. }
  7601. }
  7602. bool setPosition (int64 wantedPos)
  7603. {
  7604. if (wantedPos != position)
  7605. {
  7606. finished = false;
  7607. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7608. if (actualPos == wantedPos)
  7609. {
  7610. position = wantedPos;
  7611. }
  7612. else
  7613. {
  7614. if (wantedPos < position)
  7615. {
  7616. juce_closeInternetFile (handle);
  7617. position = 0;
  7618. finished = false;
  7619. handle = juce_openInternetFile (server, headers, postData, isPost,
  7620. progressCallback, progressCallbackContext,
  7621. timeOutMs);
  7622. }
  7623. skipNextBytes (wantedPos - position);
  7624. }
  7625. }
  7626. return true;
  7627. }
  7628. private:
  7629. String server, headers;
  7630. MemoryBlock postData;
  7631. int64 position;
  7632. bool finished;
  7633. const bool isPost;
  7634. void* handle;
  7635. URL::OpenStreamProgressCallback* const progressCallback;
  7636. void* const progressCallbackContext;
  7637. const int timeOutMs;
  7638. void createHeadersAndPostData (const URL& url)
  7639. {
  7640. MemoryOutputStream data (postData, false);
  7641. if (url.getFilesToUpload().size() > 0)
  7642. {
  7643. // need to upload some files, so do it as multi-part...
  7644. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7645. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7646. data << "--" << boundary;
  7647. int i;
  7648. for (i = 0; i < url.getParameters().size(); ++i)
  7649. {
  7650. data << "\r\nContent-Disposition: form-data; name=\""
  7651. << url.getParameters().getAllKeys() [i]
  7652. << "\"\r\n\r\n"
  7653. << url.getParameters().getAllValues() [i]
  7654. << "\r\n--"
  7655. << boundary;
  7656. }
  7657. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7658. {
  7659. const File file (url.getFilesToUpload().getAllValues() [i]);
  7660. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7661. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7662. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7663. const String mimeType (url.getMimeTypesOfUploadFiles()
  7664. .getValue (paramName, String::empty));
  7665. if (mimeType.isNotEmpty())
  7666. data << "Content-Type: " << mimeType << "\r\n";
  7667. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7668. << file << "\r\n--" << boundary;
  7669. }
  7670. data << "--\r\n";
  7671. data.flush();
  7672. }
  7673. else
  7674. {
  7675. data << URLHelpers::getMangledParameters (url.getParameters())
  7676. << url.getPostData();
  7677. data.flush();
  7678. // just a short text attachment, so use simple url encoding..
  7679. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7680. + String ((unsigned int) postData.getSize())
  7681. + "\r\n";
  7682. }
  7683. }
  7684. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  7685. };
  7686. InputStream* URL::createInputStream (const bool usePostCommand,
  7687. OpenStreamProgressCallback* const progressCallback,
  7688. void* const progressCallbackContext,
  7689. const String& extraHeaders,
  7690. const int timeOutMs,
  7691. StringPairArray* const responseHeaders) const
  7692. {
  7693. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7694. progressCallback, progressCallbackContext,
  7695. extraHeaders, timeOutMs, responseHeaders));
  7696. return wi->isError() ? 0 : wi.release();
  7697. }
  7698. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7699. const bool usePostCommand) const
  7700. {
  7701. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7702. if (in != 0)
  7703. {
  7704. in->readIntoMemoryBlock (destData);
  7705. return true;
  7706. }
  7707. return false;
  7708. }
  7709. const String URL::readEntireTextStream (const bool usePostCommand) const
  7710. {
  7711. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7712. if (in != 0)
  7713. return in->readEntireStreamAsString();
  7714. return String::empty;
  7715. }
  7716. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7717. {
  7718. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7719. }
  7720. const URL URL::withParameter (const String& parameterName,
  7721. const String& parameterValue) const
  7722. {
  7723. URL u (*this);
  7724. u.parameters.set (parameterName, parameterValue);
  7725. return u;
  7726. }
  7727. const URL URL::withFileToUpload (const String& parameterName,
  7728. const File& fileToUpload,
  7729. const String& mimeType) const
  7730. {
  7731. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7732. URL u (*this);
  7733. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7734. u.mimeTypes.set (parameterName, mimeType);
  7735. return u;
  7736. }
  7737. const URL URL::withPOSTData (const String& postData_) const
  7738. {
  7739. URL u (*this);
  7740. u.postData = postData_;
  7741. return u;
  7742. }
  7743. const StringPairArray& URL::getParameters() const
  7744. {
  7745. return parameters;
  7746. }
  7747. const StringPairArray& URL::getFilesToUpload() const
  7748. {
  7749. return filesToUpload;
  7750. }
  7751. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7752. {
  7753. return mimeTypes;
  7754. }
  7755. const String URL::removeEscapeChars (const String& s)
  7756. {
  7757. String result (s.replaceCharacter ('+', ' '));
  7758. if (! result.containsChar ('%'))
  7759. return result;
  7760. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7761. // after all the replacements have been made, so that multi-byte chars are handled.
  7762. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7763. for (int i = 0; i < utf8.size(); ++i)
  7764. {
  7765. if (utf8.getUnchecked(i) == '%')
  7766. {
  7767. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7768. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7769. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7770. {
  7771. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7772. utf8.removeRange (i + 1, 2);
  7773. }
  7774. }
  7775. }
  7776. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7777. }
  7778. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7779. {
  7780. const char* const legalChars = isParameter ? "_-.*!'()"
  7781. : ",$_-.*!'()";
  7782. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7783. for (int i = 0; i < utf8.size(); ++i)
  7784. {
  7785. const char c = utf8.getUnchecked(i);
  7786. if (! (CharacterFunctions::isLetterOrDigit (c)
  7787. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7788. {
  7789. if (c == ' ')
  7790. {
  7791. utf8.set (i, '+');
  7792. }
  7793. else
  7794. {
  7795. static const char* const hexDigits = "0123456789abcdef";
  7796. utf8.set (i, '%');
  7797. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7798. utf8.insert (++i, hexDigits [c & 15]);
  7799. }
  7800. }
  7801. }
  7802. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7803. }
  7804. bool URL::launchInDefaultBrowser() const
  7805. {
  7806. String u (toString (true));
  7807. if (u.containsChar ('@') && ! u.containsChar (':'))
  7808. u = "mailto:" + u;
  7809. return PlatformUtilities::openDocument (u, String::empty);
  7810. }
  7811. END_JUCE_NAMESPACE
  7812. /*** End of inlined file: juce_URL.cpp ***/
  7813. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7814. BEGIN_JUCE_NAMESPACE
  7815. MACAddress::MACAddress()
  7816. : asInt64 (0)
  7817. {
  7818. }
  7819. MACAddress::MACAddress (const MACAddress& other)
  7820. : asInt64 (other.asInt64)
  7821. {
  7822. }
  7823. MACAddress& MACAddress::operator= (const MACAddress& other)
  7824. {
  7825. asInt64 = other.asInt64;
  7826. return *this;
  7827. }
  7828. MACAddress::MACAddress (const uint8 bytes[6])
  7829. : asInt64 (0)
  7830. {
  7831. memcpy (asBytes, bytes, sizeof (asBytes));
  7832. }
  7833. const String MACAddress::toString() const
  7834. {
  7835. String s;
  7836. s.preallocateStorage (18);
  7837. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7838. {
  7839. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  7840. if (i < numElementsInArray (asBytes) - 1)
  7841. s << '-';
  7842. }
  7843. return s;
  7844. }
  7845. int64 MACAddress::toInt64() const throw()
  7846. {
  7847. int64 n = 0;
  7848. for (int i = numElementsInArray (asBytes); --i >= 0;)
  7849. n = (n << 8) | asBytes[i];
  7850. return n;
  7851. }
  7852. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  7853. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  7854. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  7855. END_JUCE_NAMESPACE
  7856. /*** End of inlined file: juce_MACAddress.cpp ***/
  7857. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7858. BEGIN_JUCE_NAMESPACE
  7859. namespace
  7860. {
  7861. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7862. {
  7863. // You need to supply a real stream when creating a BufferedInputStream
  7864. jassert (source != 0);
  7865. requestedSize = jmax (256, requestedSize);
  7866. const int64 sourceSize = source->getTotalLength();
  7867. if (sourceSize >= 0 && sourceSize < requestedSize)
  7868. requestedSize = jmax (32, (int) sourceSize);
  7869. return requestedSize;
  7870. }
  7871. }
  7872. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  7873. const bool deleteSourceWhenDestroyed)
  7874. : source (sourceStream),
  7875. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  7876. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  7877. position (sourceStream->getPosition()),
  7878. lastReadPos (0),
  7879. bufferStart (position),
  7880. bufferOverlap (128)
  7881. {
  7882. buffer.malloc (bufferSize);
  7883. }
  7884. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  7885. : source (&sourceStream),
  7886. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  7887. position (sourceStream.getPosition()),
  7888. lastReadPos (0),
  7889. bufferStart (position),
  7890. bufferOverlap (128)
  7891. {
  7892. buffer.malloc (bufferSize);
  7893. }
  7894. BufferedInputStream::~BufferedInputStream()
  7895. {
  7896. }
  7897. int64 BufferedInputStream::getTotalLength()
  7898. {
  7899. return source->getTotalLength();
  7900. }
  7901. int64 BufferedInputStream::getPosition()
  7902. {
  7903. return position;
  7904. }
  7905. bool BufferedInputStream::setPosition (int64 newPosition)
  7906. {
  7907. position = jmax ((int64) 0, newPosition);
  7908. return true;
  7909. }
  7910. bool BufferedInputStream::isExhausted()
  7911. {
  7912. return (position >= lastReadPos)
  7913. && source->isExhausted();
  7914. }
  7915. void BufferedInputStream::ensureBuffered()
  7916. {
  7917. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7918. if (position < bufferStart || position >= bufferEndOverlap)
  7919. {
  7920. int bytesRead;
  7921. if (position < lastReadPos
  7922. && position >= bufferEndOverlap
  7923. && position >= bufferStart)
  7924. {
  7925. const int bytesToKeep = (int) (lastReadPos - position);
  7926. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7927. bufferStart = position;
  7928. bytesRead = source->read (buffer + bytesToKeep,
  7929. bufferSize - bytesToKeep);
  7930. lastReadPos += bytesRead;
  7931. bytesRead += bytesToKeep;
  7932. }
  7933. else
  7934. {
  7935. bufferStart = position;
  7936. source->setPosition (bufferStart);
  7937. bytesRead = source->read (buffer, bufferSize);
  7938. lastReadPos = bufferStart + bytesRead;
  7939. }
  7940. while (bytesRead < bufferSize)
  7941. buffer [bytesRead++] = 0;
  7942. }
  7943. }
  7944. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7945. {
  7946. if (position >= bufferStart
  7947. && position + maxBytesToRead <= lastReadPos)
  7948. {
  7949. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7950. position += maxBytesToRead;
  7951. return maxBytesToRead;
  7952. }
  7953. else
  7954. {
  7955. if (position < bufferStart || position >= lastReadPos)
  7956. ensureBuffered();
  7957. int bytesRead = 0;
  7958. while (maxBytesToRead > 0)
  7959. {
  7960. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7961. if (bytesAvailable > 0)
  7962. {
  7963. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7964. maxBytesToRead -= bytesAvailable;
  7965. bytesRead += bytesAvailable;
  7966. position += bytesAvailable;
  7967. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7968. }
  7969. const int64 oldLastReadPos = lastReadPos;
  7970. ensureBuffered();
  7971. if (oldLastReadPos == lastReadPos)
  7972. break; // if ensureBuffered() failed to read any more data, bail out
  7973. if (isExhausted())
  7974. break;
  7975. }
  7976. return bytesRead;
  7977. }
  7978. }
  7979. const String BufferedInputStream::readString()
  7980. {
  7981. if (position >= bufferStart
  7982. && position < lastReadPos)
  7983. {
  7984. const int maxChars = (int) (lastReadPos - position);
  7985. const char* const src = buffer + (int) (position - bufferStart);
  7986. for (int i = 0; i < maxChars; ++i)
  7987. {
  7988. if (src[i] == 0)
  7989. {
  7990. position += i + 1;
  7991. return String::fromUTF8 (src, i);
  7992. }
  7993. }
  7994. }
  7995. return InputStream::readString();
  7996. }
  7997. END_JUCE_NAMESPACE
  7998. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7999. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  8000. BEGIN_JUCE_NAMESPACE
  8001. FileInputSource::FileInputSource (const File& file_)
  8002. : file (file_)
  8003. {
  8004. }
  8005. FileInputSource::~FileInputSource()
  8006. {
  8007. }
  8008. InputStream* FileInputSource::createInputStream()
  8009. {
  8010. return file.createInputStream();
  8011. }
  8012. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  8013. {
  8014. return file.getSiblingFile (relatedItemPath).createInputStream();
  8015. }
  8016. int64 FileInputSource::hashCode() const
  8017. {
  8018. return file.hashCode();
  8019. }
  8020. END_JUCE_NAMESPACE
  8021. /*** End of inlined file: juce_FileInputSource.cpp ***/
  8022. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  8023. BEGIN_JUCE_NAMESPACE
  8024. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  8025. const size_t sourceDataSize,
  8026. const bool keepInternalCopy)
  8027. : data (static_cast <const char*> (sourceData)),
  8028. dataSize (sourceDataSize),
  8029. position (0)
  8030. {
  8031. if (keepInternalCopy)
  8032. {
  8033. internalCopy.append (data, sourceDataSize);
  8034. data = static_cast <const char*> (internalCopy.getData());
  8035. }
  8036. }
  8037. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  8038. const bool keepInternalCopy)
  8039. : data (static_cast <const char*> (sourceData.getData())),
  8040. dataSize (sourceData.getSize()),
  8041. position (0)
  8042. {
  8043. if (keepInternalCopy)
  8044. {
  8045. internalCopy = sourceData;
  8046. data = static_cast <const char*> (internalCopy.getData());
  8047. }
  8048. }
  8049. MemoryInputStream::~MemoryInputStream()
  8050. {
  8051. }
  8052. int64 MemoryInputStream::getTotalLength()
  8053. {
  8054. return dataSize;
  8055. }
  8056. int MemoryInputStream::read (void* const buffer, const int howMany)
  8057. {
  8058. jassert (howMany >= 0);
  8059. const int num = jmin (howMany, (int) (dataSize - position));
  8060. memcpy (buffer, data + position, num);
  8061. position += num;
  8062. return (int) num;
  8063. }
  8064. bool MemoryInputStream::isExhausted()
  8065. {
  8066. return (position >= dataSize);
  8067. }
  8068. bool MemoryInputStream::setPosition (const int64 pos)
  8069. {
  8070. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8071. return true;
  8072. }
  8073. int64 MemoryInputStream::getPosition()
  8074. {
  8075. return position;
  8076. }
  8077. #if JUCE_UNIT_TESTS
  8078. class MemoryStreamTests : public UnitTest
  8079. {
  8080. public:
  8081. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8082. void runTest()
  8083. {
  8084. beginTest ("Basics");
  8085. int randomInt = Random::getSystemRandom().nextInt();
  8086. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8087. double randomDouble = Random::getSystemRandom().nextDouble();
  8088. String randomString;
  8089. for (int i = 50; --i >= 0;)
  8090. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8091. MemoryOutputStream mo;
  8092. mo.writeInt (randomInt);
  8093. mo.writeIntBigEndian (randomInt);
  8094. mo.writeCompressedInt (randomInt);
  8095. mo.writeString (randomString);
  8096. mo.writeInt64 (randomInt64);
  8097. mo.writeInt64BigEndian (randomInt64);
  8098. mo.writeDouble (randomDouble);
  8099. mo.writeDoubleBigEndian (randomDouble);
  8100. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8101. expect (mi.readInt() == randomInt);
  8102. expect (mi.readIntBigEndian() == randomInt);
  8103. expect (mi.readCompressedInt() == randomInt);
  8104. expect (mi.readString() == randomString);
  8105. expect (mi.readInt64() == randomInt64);
  8106. expect (mi.readInt64BigEndian() == randomInt64);
  8107. expect (mi.readDouble() == randomDouble);
  8108. expect (mi.readDoubleBigEndian() == randomDouble);
  8109. }
  8110. };
  8111. static MemoryStreamTests memoryInputStreamUnitTests;
  8112. #endif
  8113. END_JUCE_NAMESPACE
  8114. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8115. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8116. BEGIN_JUCE_NAMESPACE
  8117. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8118. : data (internalBlock),
  8119. position (0),
  8120. size (0)
  8121. {
  8122. internalBlock.setSize (initialSize, false);
  8123. }
  8124. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8125. const bool appendToExistingBlockContent)
  8126. : data (memoryBlockToWriteTo),
  8127. position (0),
  8128. size (0)
  8129. {
  8130. if (appendToExistingBlockContent)
  8131. position = size = memoryBlockToWriteTo.getSize();
  8132. }
  8133. MemoryOutputStream::~MemoryOutputStream()
  8134. {
  8135. flush();
  8136. }
  8137. void MemoryOutputStream::flush()
  8138. {
  8139. if (&data != &internalBlock)
  8140. data.setSize (size, false);
  8141. }
  8142. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8143. {
  8144. data.ensureSize (bytesToPreallocate + 1);
  8145. }
  8146. void MemoryOutputStream::reset() throw()
  8147. {
  8148. position = 0;
  8149. size = 0;
  8150. }
  8151. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8152. {
  8153. if (howMany > 0)
  8154. {
  8155. const size_t storageNeeded = position + howMany;
  8156. if (storageNeeded >= data.getSize())
  8157. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  8158. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8159. position += howMany;
  8160. size = jmax (size, position);
  8161. }
  8162. return true;
  8163. }
  8164. const void* MemoryOutputStream::getData() const throw()
  8165. {
  8166. void* const d = data.getData();
  8167. if (data.getSize() > size)
  8168. static_cast <char*> (d) [size] = 0;
  8169. return d;
  8170. }
  8171. bool MemoryOutputStream::setPosition (int64 newPosition)
  8172. {
  8173. if (newPosition <= (int64) size)
  8174. {
  8175. // ok to seek backwards
  8176. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8177. return true;
  8178. }
  8179. else
  8180. {
  8181. // trying to make it bigger isn't a good thing to do..
  8182. return false;
  8183. }
  8184. }
  8185. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8186. {
  8187. // before writing from an input, see if we can preallocate to make it more efficient..
  8188. int64 availableData = source.getTotalLength() - source.getPosition();
  8189. if (availableData > 0)
  8190. {
  8191. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8192. availableData = maxNumBytesToWrite;
  8193. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8194. }
  8195. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8196. }
  8197. const String MemoryOutputStream::toUTF8() const
  8198. {
  8199. return String (static_cast <const char*> (getData()), getDataSize());
  8200. }
  8201. const String MemoryOutputStream::toString() const
  8202. {
  8203. return String::createStringFromData (getData(), getDataSize());
  8204. }
  8205. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8206. {
  8207. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8208. return stream;
  8209. }
  8210. END_JUCE_NAMESPACE
  8211. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8212. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8213. BEGIN_JUCE_NAMESPACE
  8214. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8215. const int64 startPositionInSourceStream_,
  8216. const int64 lengthOfSourceStream_,
  8217. const bool deleteSourceWhenDestroyed)
  8218. : source (sourceStream),
  8219. startPositionInSourceStream (startPositionInSourceStream_),
  8220. lengthOfSourceStream (lengthOfSourceStream_)
  8221. {
  8222. if (deleteSourceWhenDestroyed)
  8223. sourceToDelete = source;
  8224. setPosition (0);
  8225. }
  8226. SubregionStream::~SubregionStream()
  8227. {
  8228. }
  8229. int64 SubregionStream::getTotalLength()
  8230. {
  8231. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8232. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8233. : srcLen;
  8234. }
  8235. int64 SubregionStream::getPosition()
  8236. {
  8237. return source->getPosition() - startPositionInSourceStream;
  8238. }
  8239. bool SubregionStream::setPosition (int64 newPosition)
  8240. {
  8241. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8242. }
  8243. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8244. {
  8245. if (lengthOfSourceStream < 0)
  8246. {
  8247. return source->read (destBuffer, maxBytesToRead);
  8248. }
  8249. else
  8250. {
  8251. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8252. if (maxBytesToRead <= 0)
  8253. return 0;
  8254. return source->read (destBuffer, maxBytesToRead);
  8255. }
  8256. }
  8257. bool SubregionStream::isExhausted()
  8258. {
  8259. if (lengthOfSourceStream >= 0)
  8260. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8261. else
  8262. return source->isExhausted();
  8263. }
  8264. END_JUCE_NAMESPACE
  8265. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8266. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8267. BEGIN_JUCE_NAMESPACE
  8268. PerformanceCounter::PerformanceCounter (const String& name_,
  8269. int runsPerPrintout,
  8270. const File& loggingFile)
  8271. : name (name_),
  8272. numRuns (0),
  8273. runsPerPrint (runsPerPrintout),
  8274. totalTime (0),
  8275. outputFile (loggingFile)
  8276. {
  8277. if (outputFile != File::nonexistent)
  8278. {
  8279. String s ("**** Counter for \"");
  8280. s << name_ << "\" started at: "
  8281. << Time::getCurrentTime().toString (true, true)
  8282. << "\r\n";
  8283. outputFile.appendText (s, false, false);
  8284. }
  8285. }
  8286. PerformanceCounter::~PerformanceCounter()
  8287. {
  8288. printStatistics();
  8289. }
  8290. void PerformanceCounter::start()
  8291. {
  8292. started = Time::getHighResolutionTicks();
  8293. }
  8294. void PerformanceCounter::stop()
  8295. {
  8296. const int64 now = Time::getHighResolutionTicks();
  8297. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8298. if (++numRuns == runsPerPrint)
  8299. printStatistics();
  8300. }
  8301. void PerformanceCounter::printStatistics()
  8302. {
  8303. if (numRuns > 0)
  8304. {
  8305. String s ("Performance count for \"");
  8306. s << name << "\" - average over " << numRuns << " run(s) = ";
  8307. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8308. if (micros > 10000)
  8309. s << (micros/1000) << " millisecs";
  8310. else
  8311. s << micros << " microsecs";
  8312. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8313. Logger::outputDebugString (s);
  8314. s << "\r\n";
  8315. if (outputFile != File::nonexistent)
  8316. outputFile.appendText (s, false, false);
  8317. numRuns = 0;
  8318. totalTime = 0;
  8319. }
  8320. }
  8321. END_JUCE_NAMESPACE
  8322. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8323. /*** Start of inlined file: juce_Uuid.cpp ***/
  8324. BEGIN_JUCE_NAMESPACE
  8325. Uuid::Uuid()
  8326. {
  8327. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8328. // to make it very very unlikely that two UUIDs will ever be the same..
  8329. static int64 macAddresses[2];
  8330. static bool hasCheckedMacAddresses = false;
  8331. if (! hasCheckedMacAddresses)
  8332. {
  8333. hasCheckedMacAddresses = true;
  8334. Array<MACAddress> result;
  8335. MACAddress::findAllAddresses (result);
  8336. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8337. macAddresses[i] = result[i].toInt64();
  8338. }
  8339. value.asInt64[0] = macAddresses[0];
  8340. value.asInt64[1] = macAddresses[1];
  8341. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8342. // whose seed will carry over between calls to this method.
  8343. Random r (macAddresses[0] ^ macAddresses[1]
  8344. ^ Random::getSystemRandom().nextInt64());
  8345. for (int i = 4; --i >= 0;)
  8346. {
  8347. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8348. value.asInt[i] ^= r.nextInt();
  8349. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8350. }
  8351. }
  8352. Uuid::~Uuid() throw()
  8353. {
  8354. }
  8355. Uuid::Uuid (const Uuid& other)
  8356. : value (other.value)
  8357. {
  8358. }
  8359. Uuid& Uuid::operator= (const Uuid& other)
  8360. {
  8361. value = other.value;
  8362. return *this;
  8363. }
  8364. bool Uuid::operator== (const Uuid& other) const
  8365. {
  8366. return value.asInt64[0] == other.value.asInt64[0]
  8367. && value.asInt64[1] == other.value.asInt64[1];
  8368. }
  8369. bool Uuid::operator!= (const Uuid& other) const
  8370. {
  8371. return ! operator== (other);
  8372. }
  8373. bool Uuid::isNull() const throw()
  8374. {
  8375. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8376. }
  8377. const String Uuid::toString() const
  8378. {
  8379. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8380. }
  8381. Uuid::Uuid (const String& uuidString)
  8382. {
  8383. operator= (uuidString);
  8384. }
  8385. Uuid& Uuid::operator= (const String& uuidString)
  8386. {
  8387. MemoryBlock mb;
  8388. mb.loadFromHexString (uuidString);
  8389. mb.ensureSize (sizeof (value.asBytes), true);
  8390. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8391. return *this;
  8392. }
  8393. Uuid::Uuid (const uint8* const rawData)
  8394. {
  8395. operator= (rawData);
  8396. }
  8397. Uuid& Uuid::operator= (const uint8* const rawData)
  8398. {
  8399. if (rawData != 0)
  8400. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8401. else
  8402. zeromem (value.asBytes, sizeof (value.asBytes));
  8403. return *this;
  8404. }
  8405. END_JUCE_NAMESPACE
  8406. /*** End of inlined file: juce_Uuid.cpp ***/
  8407. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8408. BEGIN_JUCE_NAMESPACE
  8409. class ZipFile::ZipEntryInfo
  8410. {
  8411. public:
  8412. ZipFile::ZipEntry entry;
  8413. int streamOffset;
  8414. int compressedSize;
  8415. bool compressed;
  8416. };
  8417. class ZipFile::ZipInputStream : public InputStream
  8418. {
  8419. public:
  8420. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8421. : file (file_),
  8422. zipEntryInfo (zei),
  8423. pos (0),
  8424. headerSize (0),
  8425. inputStream (0)
  8426. {
  8427. inputStream = file_.inputStream;
  8428. if (file_.inputSource != 0)
  8429. {
  8430. inputStream = streamToDelete = file.inputSource->createInputStream();
  8431. }
  8432. else
  8433. {
  8434. #if JUCE_DEBUG
  8435. file_.numOpenStreams++;
  8436. #endif
  8437. }
  8438. char buffer [30];
  8439. if (inputStream != 0
  8440. && inputStream->setPosition (zei.streamOffset)
  8441. && inputStream->read (buffer, 30) == 30
  8442. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8443. {
  8444. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8445. + ByteOrder::littleEndianShort (buffer + 28);
  8446. }
  8447. }
  8448. ~ZipInputStream()
  8449. {
  8450. #if JUCE_DEBUG
  8451. if (inputStream != 0 && inputStream == file.inputStream)
  8452. file.numOpenStreams--;
  8453. #endif
  8454. }
  8455. int64 getTotalLength()
  8456. {
  8457. return zipEntryInfo.compressedSize;
  8458. }
  8459. int read (void* buffer, int howMany)
  8460. {
  8461. if (headerSize <= 0)
  8462. return 0;
  8463. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8464. if (inputStream == 0)
  8465. return 0;
  8466. int num;
  8467. if (inputStream == file.inputStream)
  8468. {
  8469. const ScopedLock sl (file.lock);
  8470. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8471. num = inputStream->read (buffer, howMany);
  8472. }
  8473. else
  8474. {
  8475. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8476. num = inputStream->read (buffer, howMany);
  8477. }
  8478. pos += num;
  8479. return num;
  8480. }
  8481. bool isExhausted()
  8482. {
  8483. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8484. }
  8485. int64 getPosition()
  8486. {
  8487. return pos;
  8488. }
  8489. bool setPosition (int64 newPos)
  8490. {
  8491. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8492. return true;
  8493. }
  8494. private:
  8495. ZipFile& file;
  8496. ZipEntryInfo zipEntryInfo;
  8497. int64 pos;
  8498. int headerSize;
  8499. InputStream* inputStream;
  8500. ScopedPointer<InputStream> streamToDelete;
  8501. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8502. };
  8503. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8504. : inputStream (source_)
  8505. #if JUCE_DEBUG
  8506. , numOpenStreams (0)
  8507. #endif
  8508. {
  8509. if (deleteStreamWhenDestroyed)
  8510. streamToDelete = inputStream;
  8511. init();
  8512. }
  8513. ZipFile::ZipFile (const File& file)
  8514. : inputStream (0)
  8515. #if JUCE_DEBUG
  8516. , numOpenStreams (0)
  8517. #endif
  8518. {
  8519. inputSource = new FileInputSource (file);
  8520. init();
  8521. }
  8522. ZipFile::ZipFile (InputSource* const inputSource_)
  8523. : inputStream (0),
  8524. inputSource (inputSource_)
  8525. #if JUCE_DEBUG
  8526. , numOpenStreams (0)
  8527. #endif
  8528. {
  8529. init();
  8530. }
  8531. ZipFile::~ZipFile()
  8532. {
  8533. #if JUCE_DEBUG
  8534. entries.clear();
  8535. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8536. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8537. Streams can't be kept open after the file is deleted because they need to share the input
  8538. stream that the file uses to read itself.
  8539. */
  8540. jassert (numOpenStreams == 0);
  8541. #endif
  8542. }
  8543. int ZipFile::getNumEntries() const throw()
  8544. {
  8545. return entries.size();
  8546. }
  8547. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8548. {
  8549. ZipEntryInfo* const zei = entries [index];
  8550. return zei != 0 ? &(zei->entry) : 0;
  8551. }
  8552. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8553. {
  8554. for (int i = 0; i < entries.size(); ++i)
  8555. if (entries.getUnchecked (i)->entry.filename == fileName)
  8556. return i;
  8557. return -1;
  8558. }
  8559. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8560. {
  8561. return getEntry (getIndexOfFileName (fileName));
  8562. }
  8563. InputStream* ZipFile::createStreamForEntry (const int index)
  8564. {
  8565. ZipEntryInfo* const zei = entries[index];
  8566. InputStream* stream = 0;
  8567. if (zei != 0)
  8568. {
  8569. stream = new ZipInputStream (*this, *zei);
  8570. if (zei->compressed)
  8571. {
  8572. stream = new GZIPDecompressorInputStream (stream, true, true,
  8573. zei->entry.uncompressedSize);
  8574. // (much faster to unzip in big blocks using a buffer..)
  8575. stream = new BufferedInputStream (stream, 32768, true);
  8576. }
  8577. }
  8578. return stream;
  8579. }
  8580. class ZipFile::ZipFilenameComparator
  8581. {
  8582. public:
  8583. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8584. {
  8585. return first->entry.filename.compare (second->entry.filename);
  8586. }
  8587. };
  8588. void ZipFile::sortEntriesByFilename()
  8589. {
  8590. ZipFilenameComparator sorter;
  8591. entries.sort (sorter);
  8592. }
  8593. void ZipFile::init()
  8594. {
  8595. ScopedPointer <InputStream> toDelete;
  8596. InputStream* in = inputStream;
  8597. if (inputSource != 0)
  8598. {
  8599. in = inputSource->createInputStream();
  8600. toDelete = in;
  8601. }
  8602. if (in != 0)
  8603. {
  8604. int numEntries = 0;
  8605. int pos = findEndOfZipEntryTable (*in, numEntries);
  8606. if (pos >= 0 && pos < in->getTotalLength())
  8607. {
  8608. const int size = (int) (in->getTotalLength() - pos);
  8609. in->setPosition (pos);
  8610. MemoryBlock headerData;
  8611. if (in->readIntoMemoryBlock (headerData, size) == size)
  8612. {
  8613. pos = 0;
  8614. for (int i = 0; i < numEntries; ++i)
  8615. {
  8616. if (pos + 46 > size)
  8617. break;
  8618. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8619. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8620. if (pos + 46 + fileNameLen > size)
  8621. break;
  8622. ZipEntryInfo* const zei = new ZipEntryInfo();
  8623. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8624. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8625. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8626. const int year = 1980 + (date >> 9);
  8627. const int month = ((date >> 5) & 15) - 1;
  8628. const int day = date & 31;
  8629. const int hours = time >> 11;
  8630. const int minutes = (time >> 5) & 63;
  8631. const int seconds = (time & 31) << 1;
  8632. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8633. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8634. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8635. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8636. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8637. entries.add (zei);
  8638. pos += 46 + fileNameLen
  8639. + ByteOrder::littleEndianShort (buffer + 30)
  8640. + ByteOrder::littleEndianShort (buffer + 32);
  8641. }
  8642. }
  8643. }
  8644. }
  8645. }
  8646. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8647. {
  8648. BufferedInputStream in (input, 8192);
  8649. in.setPosition (in.getTotalLength());
  8650. int64 pos = in.getPosition();
  8651. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8652. char buffer [32];
  8653. zeromem (buffer, sizeof (buffer));
  8654. while (pos > lowestPos)
  8655. {
  8656. in.setPosition (pos - 22);
  8657. pos = in.getPosition();
  8658. memcpy (buffer + 22, buffer, 4);
  8659. if (in.read (buffer, 22) != 22)
  8660. return 0;
  8661. for (int i = 0; i < 22; ++i)
  8662. {
  8663. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8664. {
  8665. in.setPosition (pos + i);
  8666. in.read (buffer, 22);
  8667. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8668. return ByteOrder::littleEndianInt (buffer + 16);
  8669. }
  8670. }
  8671. }
  8672. return 0;
  8673. }
  8674. bool ZipFile::uncompressTo (const File& targetDirectory,
  8675. const bool shouldOverwriteFiles)
  8676. {
  8677. for (int i = 0; i < entries.size(); ++i)
  8678. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8679. return false;
  8680. return true;
  8681. }
  8682. bool ZipFile::uncompressEntry (const int index,
  8683. const File& targetDirectory,
  8684. bool shouldOverwriteFiles)
  8685. {
  8686. const ZipEntryInfo* zei = entries [index];
  8687. if (zei != 0)
  8688. {
  8689. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8690. if (zei->entry.filename.endsWithChar ('/'))
  8691. {
  8692. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8693. }
  8694. else
  8695. {
  8696. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8697. if (in != 0)
  8698. {
  8699. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8700. return false;
  8701. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8702. {
  8703. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8704. if (out != 0)
  8705. {
  8706. out->writeFromInputStream (*in, -1);
  8707. out = 0;
  8708. targetFile.setCreationTime (zei->entry.fileTime);
  8709. targetFile.setLastModificationTime (zei->entry.fileTime);
  8710. targetFile.setLastAccessTime (zei->entry.fileTime);
  8711. return true;
  8712. }
  8713. }
  8714. }
  8715. }
  8716. }
  8717. return false;
  8718. }
  8719. END_JUCE_NAMESPACE
  8720. /*** End of inlined file: juce_ZipFile.cpp ***/
  8721. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8722. #if JUCE_MSVC
  8723. #pragma warning (push)
  8724. #pragma warning (disable: 4514 4996)
  8725. #endif
  8726. #include <cwctype>
  8727. #include <cctype>
  8728. #include <ctime>
  8729. BEGIN_JUCE_NAMESPACE
  8730. int CharacterFunctions::length (const char* const s) throw()
  8731. {
  8732. return (int) strlen (s);
  8733. }
  8734. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8735. {
  8736. return (int) wcslen (s);
  8737. }
  8738. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8739. {
  8740. strncpy (dest, src, maxChars);
  8741. }
  8742. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8743. {
  8744. wcsncpy (dest, src, maxChars);
  8745. }
  8746. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8747. {
  8748. mbstowcs (dest, src, maxChars);
  8749. }
  8750. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8751. {
  8752. wcstombs (dest, src, maxChars);
  8753. }
  8754. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8755. {
  8756. return (int) wcstombs (0, src, 0);
  8757. }
  8758. void CharacterFunctions::append (char* dest, const char* src) throw()
  8759. {
  8760. strcat (dest, src);
  8761. }
  8762. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8763. {
  8764. wcscat (dest, src);
  8765. }
  8766. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8767. {
  8768. return strcmp (s1, s2);
  8769. }
  8770. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8771. {
  8772. jassert (s1 != 0 && s2 != 0);
  8773. return wcscmp (s1, s2);
  8774. }
  8775. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8776. {
  8777. jassert (s1 != 0 && s2 != 0);
  8778. return strncmp (s1, s2, maxChars);
  8779. }
  8780. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8781. {
  8782. jassert (s1 != 0 && s2 != 0);
  8783. return wcsncmp (s1, s2, maxChars);
  8784. }
  8785. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8786. {
  8787. jassert (s1 != 0 && s2 != 0);
  8788. for (;;)
  8789. {
  8790. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8791. if (diff != 0)
  8792. return diff;
  8793. else if (*s1 == 0)
  8794. break;
  8795. ++s1;
  8796. ++s2;
  8797. }
  8798. return 0;
  8799. }
  8800. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8801. {
  8802. return -compare (s2, s1);
  8803. }
  8804. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8805. {
  8806. jassert (s1 != 0 && s2 != 0);
  8807. #if JUCE_WINDOWS
  8808. return stricmp (s1, s2);
  8809. #else
  8810. return strcasecmp (s1, s2);
  8811. #endif
  8812. }
  8813. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8814. {
  8815. jassert (s1 != 0 && s2 != 0);
  8816. #if JUCE_WINDOWS
  8817. return _wcsicmp (s1, s2);
  8818. #else
  8819. for (;;)
  8820. {
  8821. if (*s1 != *s2)
  8822. {
  8823. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8824. if (diff != 0)
  8825. return diff < 0 ? -1 : 1;
  8826. }
  8827. else if (*s1 == 0)
  8828. break;
  8829. ++s1;
  8830. ++s2;
  8831. }
  8832. return 0;
  8833. #endif
  8834. }
  8835. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8836. {
  8837. jassert (s1 != 0 && s2 != 0);
  8838. for (;;)
  8839. {
  8840. if (*s1 != *s2)
  8841. {
  8842. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8843. if (diff != 0)
  8844. return diff < 0 ? -1 : 1;
  8845. }
  8846. else if (*s1 == 0)
  8847. break;
  8848. ++s1;
  8849. ++s2;
  8850. }
  8851. return 0;
  8852. }
  8853. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8854. {
  8855. jassert (s1 != 0 && s2 != 0);
  8856. #if JUCE_WINDOWS
  8857. return strnicmp (s1, s2, maxChars);
  8858. #else
  8859. return strncasecmp (s1, s2, maxChars);
  8860. #endif
  8861. }
  8862. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8863. {
  8864. jassert (s1 != 0 && s2 != 0);
  8865. #if JUCE_WINDOWS
  8866. return _wcsnicmp (s1, s2, maxChars);
  8867. #else
  8868. while (--maxChars >= 0)
  8869. {
  8870. if (*s1 != *s2)
  8871. {
  8872. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8873. if (diff != 0)
  8874. return diff < 0 ? -1 : 1;
  8875. }
  8876. else if (*s1 == 0)
  8877. break;
  8878. ++s1;
  8879. ++s2;
  8880. }
  8881. return 0;
  8882. #endif
  8883. }
  8884. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8885. {
  8886. return strstr (haystack, needle);
  8887. }
  8888. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8889. {
  8890. return wcsstr (haystack, needle);
  8891. }
  8892. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8893. {
  8894. if (haystack != 0)
  8895. {
  8896. int i = 0;
  8897. if (ignoreCase)
  8898. {
  8899. const char n1 = toLowerCase (needle);
  8900. const char n2 = toUpperCase (needle);
  8901. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8902. {
  8903. while (haystack[i] != 0)
  8904. {
  8905. if (haystack[i] == n1 || haystack[i] == n2)
  8906. return i;
  8907. ++i;
  8908. }
  8909. return -1;
  8910. }
  8911. jassert (n1 == needle);
  8912. }
  8913. while (haystack[i] != 0)
  8914. {
  8915. if (haystack[i] == needle)
  8916. return i;
  8917. ++i;
  8918. }
  8919. }
  8920. return -1;
  8921. }
  8922. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8923. {
  8924. if (haystack != 0)
  8925. {
  8926. int i = 0;
  8927. if (ignoreCase)
  8928. {
  8929. const juce_wchar n1 = toLowerCase (needle);
  8930. const juce_wchar n2 = toUpperCase (needle);
  8931. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8932. {
  8933. while (haystack[i] != 0)
  8934. {
  8935. if (haystack[i] == n1 || haystack[i] == n2)
  8936. return i;
  8937. ++i;
  8938. }
  8939. return -1;
  8940. }
  8941. jassert (n1 == needle);
  8942. }
  8943. while (haystack[i] != 0)
  8944. {
  8945. if (haystack[i] == needle)
  8946. return i;
  8947. ++i;
  8948. }
  8949. }
  8950. return -1;
  8951. }
  8952. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8953. {
  8954. jassert (haystack != 0);
  8955. int i = 0;
  8956. while (haystack[i] != 0)
  8957. {
  8958. if (haystack[i] == needle)
  8959. return i;
  8960. ++i;
  8961. }
  8962. return -1;
  8963. }
  8964. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8965. {
  8966. jassert (haystack != 0);
  8967. int i = 0;
  8968. while (haystack[i] != 0)
  8969. {
  8970. if (haystack[i] == needle)
  8971. return i;
  8972. ++i;
  8973. }
  8974. return -1;
  8975. }
  8976. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8977. {
  8978. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8979. }
  8980. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8981. {
  8982. if (allowedChars == 0)
  8983. return 0;
  8984. int i = 0;
  8985. for (;;)
  8986. {
  8987. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8988. break;
  8989. ++i;
  8990. }
  8991. return i;
  8992. }
  8993. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8994. {
  8995. return (int) strftime (dest, maxChars, format, tm);
  8996. }
  8997. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8998. {
  8999. return (int) wcsftime (dest, maxChars, format, tm);
  9000. }
  9001. int CharacterFunctions::getIntValue (const char* const s) throw()
  9002. {
  9003. return atoi (s);
  9004. }
  9005. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  9006. {
  9007. #if JUCE_WINDOWS
  9008. return _wtoi (s);
  9009. #else
  9010. int v = 0;
  9011. while (isWhitespace (*s))
  9012. ++s;
  9013. const bool isNeg = *s == '-';
  9014. if (isNeg)
  9015. ++s;
  9016. for (;;)
  9017. {
  9018. const wchar_t c = *s++;
  9019. if (c >= '0' && c <= '9')
  9020. v = v * 10 + (int) (c - '0');
  9021. else
  9022. break;
  9023. }
  9024. return isNeg ? -v : v;
  9025. #endif
  9026. }
  9027. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  9028. {
  9029. #if JUCE_LINUX
  9030. return atoll (s);
  9031. #elif JUCE_WINDOWS
  9032. return _atoi64 (s);
  9033. #else
  9034. int64 v = 0;
  9035. while (isWhitespace (*s))
  9036. ++s;
  9037. const bool isNeg = *s == '-';
  9038. if (isNeg)
  9039. ++s;
  9040. for (;;)
  9041. {
  9042. const char c = *s++;
  9043. if (c >= '0' && c <= '9')
  9044. v = v * 10 + (int64) (c - '0');
  9045. else
  9046. break;
  9047. }
  9048. return isNeg ? -v : v;
  9049. #endif
  9050. }
  9051. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  9052. {
  9053. #if JUCE_WINDOWS
  9054. return _wtoi64 (s);
  9055. #else
  9056. int64 v = 0;
  9057. while (isWhitespace (*s))
  9058. ++s;
  9059. const bool isNeg = *s == '-';
  9060. if (isNeg)
  9061. ++s;
  9062. for (;;)
  9063. {
  9064. const juce_wchar c = *s++;
  9065. if (c >= '0' && c <= '9')
  9066. v = v * 10 + (int64) (c - '0');
  9067. else
  9068. break;
  9069. }
  9070. return isNeg ? -v : v;
  9071. #endif
  9072. }
  9073. namespace
  9074. {
  9075. double juce_mulexp10 (const double value, int exponent) throw()
  9076. {
  9077. if (exponent == 0)
  9078. return value;
  9079. if (value == 0)
  9080. return 0;
  9081. const bool negative = (exponent < 0);
  9082. if (negative)
  9083. exponent = -exponent;
  9084. double result = 1.0, power = 10.0;
  9085. for (int bit = 1; exponent != 0; bit <<= 1)
  9086. {
  9087. if ((exponent & bit) != 0)
  9088. {
  9089. exponent ^= bit;
  9090. result *= power;
  9091. if (exponent == 0)
  9092. break;
  9093. }
  9094. power *= power;
  9095. }
  9096. return negative ? (value / result) : (value * result);
  9097. }
  9098. template <class CharType>
  9099. double juce_atof (const CharType* const original) throw()
  9100. {
  9101. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9102. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9103. int exponent = 0, decPointIndex = 0, digit = 0;
  9104. int lastDigit = 0, numSignificantDigits = 0;
  9105. bool isNegative = false, digitsFound = false;
  9106. const int maxSignificantDigits = 15 + 2;
  9107. const CharType* s = original;
  9108. while (CharacterFunctions::isWhitespace (*s))
  9109. ++s;
  9110. switch (*s)
  9111. {
  9112. case '-': isNegative = true; // fall-through..
  9113. case '+': ++s;
  9114. }
  9115. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9116. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9117. for (;;)
  9118. {
  9119. if (CharacterFunctions::isDigit (*s))
  9120. {
  9121. lastDigit = digit;
  9122. digit = *s++ - '0';
  9123. digitsFound = true;
  9124. if (decPointIndex != 0)
  9125. exponentAdjustment[1]++;
  9126. if (numSignificantDigits == 0 && digit == 0)
  9127. continue;
  9128. if (++numSignificantDigits > maxSignificantDigits)
  9129. {
  9130. if (digit > 5)
  9131. ++accumulator [decPointIndex];
  9132. else if (digit == 5 && (lastDigit & 1) != 0)
  9133. ++accumulator [decPointIndex];
  9134. if (decPointIndex > 0)
  9135. exponentAdjustment[1]--;
  9136. else
  9137. exponentAdjustment[0]++;
  9138. while (CharacterFunctions::isDigit (*s))
  9139. {
  9140. ++s;
  9141. if (decPointIndex == 0)
  9142. exponentAdjustment[0]++;
  9143. }
  9144. }
  9145. else
  9146. {
  9147. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9148. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9149. {
  9150. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9151. + accumulator [decPointIndex];
  9152. accumulator [decPointIndex] = 0;
  9153. exponentAccumulator [decPointIndex] = 0;
  9154. }
  9155. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9156. exponentAccumulator [decPointIndex]++;
  9157. }
  9158. }
  9159. else if (decPointIndex == 0 && *s == '.')
  9160. {
  9161. ++s;
  9162. decPointIndex = 1;
  9163. if (numSignificantDigits > maxSignificantDigits)
  9164. {
  9165. while (CharacterFunctions::isDigit (*s))
  9166. ++s;
  9167. break;
  9168. }
  9169. }
  9170. else
  9171. {
  9172. break;
  9173. }
  9174. }
  9175. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9176. if (decPointIndex != 0)
  9177. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9178. if ((*s == 'e' || *s == 'E') && digitsFound)
  9179. {
  9180. bool negativeExponent = false;
  9181. switch (*++s)
  9182. {
  9183. case '-': negativeExponent = true; // fall-through..
  9184. case '+': ++s;
  9185. }
  9186. while (CharacterFunctions::isDigit (*s))
  9187. exponent = (exponent * 10) + (*s++ - '0');
  9188. if (negativeExponent)
  9189. exponent = -exponent;
  9190. }
  9191. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9192. if (decPointIndex != 0)
  9193. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9194. return isNegative ? -r : r;
  9195. }
  9196. }
  9197. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9198. {
  9199. return juce_atof <char> (s);
  9200. }
  9201. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9202. {
  9203. return juce_atof <juce_wchar> (s);
  9204. }
  9205. char CharacterFunctions::toUpperCase (const char character) throw()
  9206. {
  9207. return (char) toupper (character);
  9208. }
  9209. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9210. {
  9211. return towupper (character);
  9212. }
  9213. void CharacterFunctions::toUpperCase (char* s) throw()
  9214. {
  9215. #if JUCE_WINDOWS
  9216. strupr (s);
  9217. #else
  9218. while (*s != 0)
  9219. {
  9220. *s = toUpperCase (*s);
  9221. ++s;
  9222. }
  9223. #endif
  9224. }
  9225. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9226. {
  9227. #if JUCE_WINDOWS
  9228. _wcsupr (s);
  9229. #else
  9230. while (*s != 0)
  9231. {
  9232. *s = toUpperCase (*s);
  9233. ++s;
  9234. }
  9235. #endif
  9236. }
  9237. bool CharacterFunctions::isUpperCase (const char character) throw()
  9238. {
  9239. return isupper (character) != 0;
  9240. }
  9241. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9242. {
  9243. #if JUCE_WINDOWS
  9244. return iswupper (character) != 0;
  9245. #else
  9246. return toLowerCase (character) != character;
  9247. #endif
  9248. }
  9249. char CharacterFunctions::toLowerCase (const char character) throw()
  9250. {
  9251. return (char) tolower (character);
  9252. }
  9253. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9254. {
  9255. return towlower (character);
  9256. }
  9257. void CharacterFunctions::toLowerCase (char* s) throw()
  9258. {
  9259. #if JUCE_WINDOWS
  9260. strlwr (s);
  9261. #else
  9262. while (*s != 0)
  9263. {
  9264. *s = toLowerCase (*s);
  9265. ++s;
  9266. }
  9267. #endif
  9268. }
  9269. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9270. {
  9271. #if JUCE_WINDOWS
  9272. _wcslwr (s);
  9273. #else
  9274. while (*s != 0)
  9275. {
  9276. *s = toLowerCase (*s);
  9277. ++s;
  9278. }
  9279. #endif
  9280. }
  9281. bool CharacterFunctions::isLowerCase (const char character) throw()
  9282. {
  9283. return islower (character) != 0;
  9284. }
  9285. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9286. {
  9287. #if JUCE_WINDOWS
  9288. return iswlower (character) != 0;
  9289. #else
  9290. return toUpperCase (character) != character;
  9291. #endif
  9292. }
  9293. bool CharacterFunctions::isWhitespace (const char character) throw()
  9294. {
  9295. return character == ' ' || (character <= 13 && character >= 9);
  9296. }
  9297. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9298. {
  9299. return iswspace (character) != 0;
  9300. }
  9301. bool CharacterFunctions::isDigit (const char character) throw()
  9302. {
  9303. return (character >= '0' && character <= '9');
  9304. }
  9305. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9306. {
  9307. return iswdigit (character) != 0;
  9308. }
  9309. bool CharacterFunctions::isLetter (const char character) throw()
  9310. {
  9311. return (character >= 'a' && character <= 'z')
  9312. || (character >= 'A' && character <= 'Z');
  9313. }
  9314. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9315. {
  9316. return iswalpha (character) != 0;
  9317. }
  9318. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9319. {
  9320. return (character >= 'a' && character <= 'z')
  9321. || (character >= 'A' && character <= 'Z')
  9322. || (character >= '0' && character <= '9');
  9323. }
  9324. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9325. {
  9326. return iswalnum (character) != 0;
  9327. }
  9328. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9329. {
  9330. unsigned int d = digit - '0';
  9331. if (d < (unsigned int) 10)
  9332. return (int) d;
  9333. d += (unsigned int) ('0' - 'a');
  9334. if (d < (unsigned int) 6)
  9335. return (int) d + 10;
  9336. d += (unsigned int) ('a' - 'A');
  9337. if (d < (unsigned int) 6)
  9338. return (int) d + 10;
  9339. return -1;
  9340. }
  9341. #if JUCE_MSVC
  9342. #pragma warning (pop)
  9343. #endif
  9344. END_JUCE_NAMESPACE
  9345. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9346. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9347. BEGIN_JUCE_NAMESPACE
  9348. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9349. {
  9350. loadFromText (fileContents);
  9351. }
  9352. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9353. {
  9354. loadFromText (fileToLoad.loadFileAsString());
  9355. }
  9356. LocalisedStrings::~LocalisedStrings()
  9357. {
  9358. }
  9359. const String LocalisedStrings::translate (const String& text) const
  9360. {
  9361. return translations.getValue (text, text);
  9362. }
  9363. namespace
  9364. {
  9365. CriticalSection currentMappingsLock;
  9366. LocalisedStrings* currentMappings = 0;
  9367. int findCloseQuote (const String& text, int startPos)
  9368. {
  9369. juce_wchar lastChar = 0;
  9370. for (;;)
  9371. {
  9372. const juce_wchar c = text [startPos];
  9373. if (c == 0 || (c == '"' && lastChar != '\\'))
  9374. break;
  9375. lastChar = c;
  9376. ++startPos;
  9377. }
  9378. return startPos;
  9379. }
  9380. const String unescapeString (const String& s)
  9381. {
  9382. return s.replace ("\\\"", "\"")
  9383. .replace ("\\\'", "\'")
  9384. .replace ("\\t", "\t")
  9385. .replace ("\\r", "\r")
  9386. .replace ("\\n", "\n");
  9387. }
  9388. }
  9389. void LocalisedStrings::loadFromText (const String& fileContents)
  9390. {
  9391. StringArray lines;
  9392. lines.addLines (fileContents);
  9393. for (int i = 0; i < lines.size(); ++i)
  9394. {
  9395. String line (lines[i].trim());
  9396. if (line.startsWithChar ('"'))
  9397. {
  9398. int closeQuote = findCloseQuote (line, 1);
  9399. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9400. if (originalText.isNotEmpty())
  9401. {
  9402. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9403. closeQuote = findCloseQuote (line, openingQuote + 1);
  9404. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9405. if (newText.isNotEmpty())
  9406. translations.set (originalText, newText);
  9407. }
  9408. }
  9409. else if (line.startsWithIgnoreCase ("language:"))
  9410. {
  9411. languageName = line.substring (9).trim();
  9412. }
  9413. else if (line.startsWithIgnoreCase ("countries:"))
  9414. {
  9415. countryCodes.addTokens (line.substring (10).trim(), true);
  9416. countryCodes.trim();
  9417. countryCodes.removeEmptyStrings();
  9418. }
  9419. }
  9420. }
  9421. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9422. {
  9423. translations.setIgnoresCase (shouldIgnoreCase);
  9424. }
  9425. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9426. {
  9427. const ScopedLock sl (currentMappingsLock);
  9428. delete currentMappings;
  9429. currentMappings = newTranslations;
  9430. }
  9431. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9432. {
  9433. return currentMappings;
  9434. }
  9435. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9436. {
  9437. const ScopedLock sl (currentMappingsLock);
  9438. if (currentMappings != 0)
  9439. return currentMappings->translate (text);
  9440. return text;
  9441. }
  9442. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9443. {
  9444. return translateWithCurrentMappings (String (text));
  9445. }
  9446. END_JUCE_NAMESPACE
  9447. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9448. /*** Start of inlined file: juce_String.cpp ***/
  9449. #if JUCE_MSVC
  9450. #pragma warning (push)
  9451. #pragma warning (disable: 4514)
  9452. #endif
  9453. #include <locale>
  9454. BEGIN_JUCE_NAMESPACE
  9455. #if JUCE_MSVC
  9456. #pragma warning (pop)
  9457. #endif
  9458. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9459. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9460. #endif
  9461. class StringHolder
  9462. {
  9463. public:
  9464. StringHolder()
  9465. : refCount (0x3fffffff), allocatedNumChars (0)
  9466. {
  9467. text[0] = 0;
  9468. }
  9469. static juce_wchar* createUninitialised (const size_t numChars)
  9470. {
  9471. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9472. s->refCount.value = 0;
  9473. s->allocatedNumChars = numChars;
  9474. return &(s->text[0]);
  9475. }
  9476. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9477. {
  9478. juce_wchar* const dest = createUninitialised (numChars);
  9479. copyChars (dest, src, numChars);
  9480. return dest;
  9481. }
  9482. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9483. {
  9484. juce_wchar* const dest = createUninitialised (numChars);
  9485. CharacterFunctions::copy (dest, src, (int) numChars);
  9486. dest [numChars] = 0;
  9487. return dest;
  9488. }
  9489. static inline juce_wchar* getEmpty() throw()
  9490. {
  9491. return &(empty.text[0]);
  9492. }
  9493. static void retain (juce_wchar* const text) throw()
  9494. {
  9495. ++(bufferFromText (text)->refCount);
  9496. }
  9497. static inline void release (StringHolder* const b) throw()
  9498. {
  9499. if (--(b->refCount) == -1 && b != &empty)
  9500. delete[] reinterpret_cast <char*> (b);
  9501. }
  9502. static void release (juce_wchar* const text) throw()
  9503. {
  9504. release (bufferFromText (text));
  9505. }
  9506. static juce_wchar* makeUnique (juce_wchar* const text)
  9507. {
  9508. StringHolder* const b = bufferFromText (text);
  9509. if (b->refCount.get() <= 0)
  9510. return text;
  9511. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9512. release (b);
  9513. return newText;
  9514. }
  9515. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9516. {
  9517. StringHolder* const b = bufferFromText (text);
  9518. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9519. return text;
  9520. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9521. copyChars (newText, text, b->allocatedNumChars);
  9522. release (b);
  9523. return newText;
  9524. }
  9525. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9526. {
  9527. return bufferFromText (text)->allocatedNumChars;
  9528. }
  9529. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9530. {
  9531. jassert (src != 0 && dest != 0);
  9532. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9533. dest [numChars] = 0;
  9534. }
  9535. Atomic<int> refCount;
  9536. size_t allocatedNumChars;
  9537. juce_wchar text[1];
  9538. static StringHolder empty;
  9539. private:
  9540. static inline StringHolder* bufferFromText (void* const text) throw()
  9541. {
  9542. // (Can't use offsetof() here because of warnings about this not being a POD)
  9543. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9544. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9545. }
  9546. };
  9547. StringHolder StringHolder::empty;
  9548. const String String::empty;
  9549. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9550. {
  9551. jassert (t[numChars] == 0); // must have a null terminator
  9552. text = StringHolder::createCopy (t, numChars);
  9553. }
  9554. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9555. {
  9556. if (numExtraChars > 0)
  9557. {
  9558. const int oldLen = length();
  9559. const int newTotalLen = oldLen + numExtraChars;
  9560. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9561. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9562. }
  9563. }
  9564. void String::preallocateStorage (const size_t numChars)
  9565. {
  9566. text = StringHolder::makeUniqueWithSize (text, numChars);
  9567. }
  9568. String::String() throw()
  9569. : text (StringHolder::getEmpty())
  9570. {
  9571. }
  9572. String::~String() throw()
  9573. {
  9574. StringHolder::release (text);
  9575. }
  9576. String::String (const String& other) throw()
  9577. : text (other.text)
  9578. {
  9579. StringHolder::retain (text);
  9580. }
  9581. void String::swapWith (String& other) throw()
  9582. {
  9583. swapVariables (text, other.text);
  9584. }
  9585. String& String::operator= (const String& other) throw()
  9586. {
  9587. juce_wchar* const newText = other.text;
  9588. StringHolder::retain (newText);
  9589. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9590. return *this;
  9591. }
  9592. String::String (const size_t numChars, const int /*dummyVariable*/)
  9593. : text (StringHolder::createUninitialised (numChars))
  9594. {
  9595. }
  9596. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9597. {
  9598. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9599. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9600. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9601. }
  9602. String::String (const char* const t)
  9603. {
  9604. if (t != 0 && *t != 0)
  9605. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9606. else
  9607. text = StringHolder::getEmpty();
  9608. }
  9609. String::String (const juce_wchar* const t)
  9610. {
  9611. if (t != 0 && *t != 0)
  9612. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9613. else
  9614. text = StringHolder::getEmpty();
  9615. }
  9616. String::String (const char* const t, const size_t maxChars)
  9617. {
  9618. int i;
  9619. for (i = 0; (size_t) i < maxChars; ++i)
  9620. if (t[i] == 0)
  9621. break;
  9622. if (i > 0)
  9623. text = StringHolder::createCopy (t, i);
  9624. else
  9625. text = StringHolder::getEmpty();
  9626. }
  9627. String::String (const juce_wchar* const t, const size_t maxChars)
  9628. {
  9629. int i;
  9630. for (i = 0; (size_t) i < maxChars; ++i)
  9631. if (t[i] == 0)
  9632. break;
  9633. if (i > 0)
  9634. text = StringHolder::createCopy (t, i);
  9635. else
  9636. text = StringHolder::getEmpty();
  9637. }
  9638. const String String::charToString (const juce_wchar character)
  9639. {
  9640. String result ((size_t) 1, (int) 0);
  9641. result.text[0] = character;
  9642. result.text[1] = 0;
  9643. return result;
  9644. }
  9645. namespace NumberToStringConverters
  9646. {
  9647. // pass in a pointer to the END of a buffer..
  9648. juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9649. {
  9650. *--t = 0;
  9651. int64 v = (n >= 0) ? n : -n;
  9652. do
  9653. {
  9654. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9655. v /= 10;
  9656. } while (v > 0);
  9657. if (n < 0)
  9658. *--t = '-';
  9659. return t;
  9660. }
  9661. juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9662. {
  9663. *--t = 0;
  9664. do
  9665. {
  9666. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9667. v /= 10;
  9668. } while (v > 0);
  9669. return t;
  9670. }
  9671. juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9672. {
  9673. if (n == (int) 0x80000000) // (would cause an overflow)
  9674. return int64ToString (t, n);
  9675. *--t = 0;
  9676. int v = abs (n);
  9677. do
  9678. {
  9679. *--t = (juce_wchar) ('0' + (v % 10));
  9680. v /= 10;
  9681. } while (v > 0);
  9682. if (n < 0)
  9683. *--t = '-';
  9684. return t;
  9685. }
  9686. juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9687. {
  9688. *--t = 0;
  9689. do
  9690. {
  9691. *--t = (juce_wchar) ('0' + (v % 10));
  9692. v /= 10;
  9693. } while (v > 0);
  9694. return t;
  9695. }
  9696. juce_wchar getDecimalPoint()
  9697. {
  9698. #if JUCE_VC7_OR_EARLIER
  9699. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9700. #else
  9701. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9702. #endif
  9703. return dp;
  9704. }
  9705. juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9706. {
  9707. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9708. {
  9709. juce_wchar* const end = buffer + numChars;
  9710. juce_wchar* t = end;
  9711. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9712. *--t = (juce_wchar) 0;
  9713. while (numDecPlaces >= 0 || v > 0)
  9714. {
  9715. if (numDecPlaces == 0)
  9716. *--t = getDecimalPoint();
  9717. *--t = (juce_wchar) ('0' + (v % 10));
  9718. v /= 10;
  9719. --numDecPlaces;
  9720. }
  9721. if (n < 0)
  9722. *--t = '-';
  9723. len = end - t - 1;
  9724. return t;
  9725. }
  9726. else
  9727. {
  9728. #if JUCE_WINDOWS
  9729. #if JUCE_VC7_OR_EARLIER || JUCE_MINGW
  9730. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9731. #else
  9732. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9733. #endif
  9734. #else
  9735. len = swprintf (buffer, numChars, L"%.9g", n);
  9736. #endif
  9737. return buffer;
  9738. }
  9739. }
  9740. }
  9741. String::String (const int number)
  9742. {
  9743. juce_wchar buffer [16];
  9744. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9745. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9746. createInternal (start, end - start - 1);
  9747. }
  9748. String::String (const unsigned int number)
  9749. {
  9750. juce_wchar buffer [16];
  9751. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9752. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9753. createInternal (start, end - start - 1);
  9754. }
  9755. String::String (const short number)
  9756. {
  9757. juce_wchar buffer [16];
  9758. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9759. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9760. createInternal (start, end - start - 1);
  9761. }
  9762. String::String (const unsigned short number)
  9763. {
  9764. juce_wchar buffer [16];
  9765. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9766. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9767. createInternal (start, end - start - 1);
  9768. }
  9769. String::String (const int64 number)
  9770. {
  9771. juce_wchar buffer [32];
  9772. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9773. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9774. createInternal (start, end - start - 1);
  9775. }
  9776. String::String (const uint64 number)
  9777. {
  9778. juce_wchar buffer [32];
  9779. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9780. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9781. createInternal (start, end - start - 1);
  9782. }
  9783. String::String (const float number, const int numberOfDecimalPlaces)
  9784. {
  9785. juce_wchar buffer [48];
  9786. size_t len;
  9787. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9788. createInternal (start, len);
  9789. }
  9790. String::String (const double number, const int numberOfDecimalPlaces)
  9791. {
  9792. juce_wchar buffer [48];
  9793. size_t len;
  9794. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9795. createInternal (start, len);
  9796. }
  9797. int String::length() const throw()
  9798. {
  9799. return CharacterFunctions::length (text);
  9800. }
  9801. int String::hashCode() const throw()
  9802. {
  9803. const juce_wchar* t = text;
  9804. int result = 0;
  9805. while (*t != (juce_wchar) 0)
  9806. result = 31 * result + *t++;
  9807. return result;
  9808. }
  9809. int64 String::hashCode64() const throw()
  9810. {
  9811. const juce_wchar* t = text;
  9812. int64 result = 0;
  9813. while (*t != (juce_wchar) 0)
  9814. result = 101 * result + *t++;
  9815. return result;
  9816. }
  9817. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9818. {
  9819. return string1.compare (string2) == 0;
  9820. }
  9821. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9822. {
  9823. return string1.compare (string2) == 0;
  9824. }
  9825. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9826. {
  9827. return string1.compare (string2) == 0;
  9828. }
  9829. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9830. {
  9831. return string1.compare (string2) != 0;
  9832. }
  9833. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9834. {
  9835. return string1.compare (string2) != 0;
  9836. }
  9837. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9838. {
  9839. return string1.compare (string2) != 0;
  9840. }
  9841. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9842. {
  9843. return string1.compare (string2) > 0;
  9844. }
  9845. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9846. {
  9847. return string1.compare (string2) < 0;
  9848. }
  9849. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9850. {
  9851. return string1.compare (string2) >= 0;
  9852. }
  9853. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9854. {
  9855. return string1.compare (string2) <= 0;
  9856. }
  9857. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9858. {
  9859. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9860. : isEmpty();
  9861. }
  9862. bool String::equalsIgnoreCase (const char* t) const throw()
  9863. {
  9864. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9865. : isEmpty();
  9866. }
  9867. bool String::equalsIgnoreCase (const String& other) const throw()
  9868. {
  9869. return text == other.text
  9870. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9871. }
  9872. int String::compare (const String& other) const throw()
  9873. {
  9874. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9875. }
  9876. int String::compare (const char* other) const throw()
  9877. {
  9878. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9879. }
  9880. int String::compare (const juce_wchar* other) const throw()
  9881. {
  9882. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9883. }
  9884. int String::compareIgnoreCase (const String& other) const throw()
  9885. {
  9886. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9887. }
  9888. int String::compareLexicographically (const String& other) const throw()
  9889. {
  9890. const juce_wchar* s1 = text;
  9891. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9892. ++s1;
  9893. const juce_wchar* s2 = other.text;
  9894. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9895. ++s2;
  9896. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9897. }
  9898. String& String::operator+= (const juce_wchar* const t)
  9899. {
  9900. if (t != 0)
  9901. appendInternal (t, CharacterFunctions::length (t));
  9902. return *this;
  9903. }
  9904. String& String::operator+= (const String& other)
  9905. {
  9906. if (isEmpty())
  9907. operator= (other);
  9908. else
  9909. appendInternal (other.text, other.length());
  9910. return *this;
  9911. }
  9912. String& String::operator+= (const char ch)
  9913. {
  9914. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9915. return operator+= (static_cast <const juce_wchar*> (asString));
  9916. }
  9917. String& String::operator+= (const juce_wchar ch)
  9918. {
  9919. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9920. return operator+= (static_cast <const juce_wchar*> (asString));
  9921. }
  9922. String& String::operator+= (const int number)
  9923. {
  9924. juce_wchar buffer [16];
  9925. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9926. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9927. appendInternal (start, (int) (end - start));
  9928. return *this;
  9929. }
  9930. String& String::operator+= (const unsigned int number)
  9931. {
  9932. juce_wchar buffer [16];
  9933. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9934. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9935. appendInternal (start, (int) (end - start));
  9936. return *this;
  9937. }
  9938. void String::append (const juce_wchar* const other, const int howMany)
  9939. {
  9940. if (howMany > 0)
  9941. {
  9942. int i;
  9943. for (i = 0; i < howMany; ++i)
  9944. if (other[i] == 0)
  9945. break;
  9946. appendInternal (other, i);
  9947. }
  9948. }
  9949. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9950. {
  9951. String s (string1);
  9952. return s += string2;
  9953. }
  9954. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9955. {
  9956. String s (string1);
  9957. return s += string2;
  9958. }
  9959. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9960. {
  9961. return String::charToString (string1) + string2;
  9962. }
  9963. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9964. {
  9965. return String::charToString (string1) + string2;
  9966. }
  9967. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9968. {
  9969. return string1 += string2;
  9970. }
  9971. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9972. {
  9973. return string1 += string2;
  9974. }
  9975. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9976. {
  9977. return string1 += string2;
  9978. }
  9979. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9980. {
  9981. return string1 += string2;
  9982. }
  9983. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9984. {
  9985. return string1 += string2;
  9986. }
  9987. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9988. {
  9989. return string1 += characterToAppend;
  9990. }
  9991. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9992. {
  9993. return string1 += characterToAppend;
  9994. }
  9995. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9996. {
  9997. return string1 += string2;
  9998. }
  9999. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  10000. {
  10001. return string1 += string2;
  10002. }
  10003. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  10004. {
  10005. return string1 += string2;
  10006. }
  10007. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  10008. {
  10009. return string1 += (int) number;
  10010. }
  10011. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  10012. {
  10013. return string1 += number;
  10014. }
  10015. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  10016. {
  10017. return string1 += number;
  10018. }
  10019. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  10020. {
  10021. return string1 += (int) number;
  10022. }
  10023. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  10024. {
  10025. return string1 += (unsigned int) number;
  10026. }
  10027. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  10028. {
  10029. return string1 += String (number);
  10030. }
  10031. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  10032. {
  10033. return string1 += String (number);
  10034. }
  10035. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  10036. {
  10037. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  10038. // if lots of large, persistent strings were to be written to streams).
  10039. const int numBytes = text.getNumBytesAsUTF8();
  10040. HeapBlock<char> temp (numBytes + 1);
  10041. text.copyToUTF8 (temp, numBytes + 1);
  10042. stream.write (temp, numBytes);
  10043. return stream;
  10044. }
  10045. int String::indexOfChar (const juce_wchar character) const throw()
  10046. {
  10047. const juce_wchar* t = text;
  10048. for (;;)
  10049. {
  10050. if (*t == character)
  10051. return (int) (t - text);
  10052. if (*t++ == 0)
  10053. return -1;
  10054. }
  10055. }
  10056. int String::lastIndexOfChar (const juce_wchar character) const throw()
  10057. {
  10058. for (int i = length(); --i >= 0;)
  10059. if (text[i] == character)
  10060. return i;
  10061. return -1;
  10062. }
  10063. int String::indexOf (const String& t) const throw()
  10064. {
  10065. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  10066. return r == 0 ? -1 : (int) (r - text);
  10067. }
  10068. int String::indexOfChar (const int startIndex,
  10069. const juce_wchar character) const throw()
  10070. {
  10071. if (startIndex > 0 && startIndex >= length())
  10072. return -1;
  10073. const juce_wchar* t = text + jmax (0, startIndex);
  10074. for (;;)
  10075. {
  10076. if (*t == character)
  10077. return (int) (t - text);
  10078. if (*t == 0)
  10079. return -1;
  10080. ++t;
  10081. }
  10082. }
  10083. int String::indexOfAnyOf (const String& charactersToLookFor,
  10084. const int startIndex,
  10085. const bool ignoreCase) const throw()
  10086. {
  10087. if (startIndex > 0 && startIndex >= length())
  10088. return -1;
  10089. const juce_wchar* t = text + jmax (0, startIndex);
  10090. while (*t != 0)
  10091. {
  10092. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  10093. return (int) (t - text);
  10094. ++t;
  10095. }
  10096. return -1;
  10097. }
  10098. int String::indexOf (const int startIndex, const String& other) const throw()
  10099. {
  10100. if (startIndex > 0 && startIndex >= length())
  10101. return -1;
  10102. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  10103. return found == 0 ? -1 : (int) (found - text);
  10104. }
  10105. int String::indexOfIgnoreCase (const String& other) const throw()
  10106. {
  10107. if (other.isNotEmpty())
  10108. {
  10109. const int len = other.length();
  10110. const int end = length() - len;
  10111. for (int i = 0; i <= end; ++i)
  10112. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10113. return i;
  10114. }
  10115. return -1;
  10116. }
  10117. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10118. {
  10119. if (other.isNotEmpty())
  10120. {
  10121. const int len = other.length();
  10122. const int end = length() - len;
  10123. for (int i = jmax (0, startIndex); i <= end; ++i)
  10124. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10125. return i;
  10126. }
  10127. return -1;
  10128. }
  10129. int String::lastIndexOf (const String& other) const throw()
  10130. {
  10131. if (other.isNotEmpty())
  10132. {
  10133. const int len = other.length();
  10134. int i = length() - len;
  10135. if (i >= 0)
  10136. {
  10137. const juce_wchar* n = text + i;
  10138. while (i >= 0)
  10139. {
  10140. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10141. return i;
  10142. --i;
  10143. }
  10144. }
  10145. }
  10146. return -1;
  10147. }
  10148. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10149. {
  10150. if (other.isNotEmpty())
  10151. {
  10152. const int len = other.length();
  10153. int i = length() - len;
  10154. if (i >= 0)
  10155. {
  10156. const juce_wchar* n = text + i;
  10157. while (i >= 0)
  10158. {
  10159. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10160. return i;
  10161. --i;
  10162. }
  10163. }
  10164. }
  10165. return -1;
  10166. }
  10167. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10168. {
  10169. for (int i = length(); --i >= 0;)
  10170. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10171. return i;
  10172. return -1;
  10173. }
  10174. bool String::contains (const String& other) const throw()
  10175. {
  10176. return indexOf (other) >= 0;
  10177. }
  10178. bool String::containsChar (const juce_wchar character) const throw()
  10179. {
  10180. const juce_wchar* t = text;
  10181. for (;;)
  10182. {
  10183. if (*t == 0)
  10184. return false;
  10185. if (*t == character)
  10186. return true;
  10187. ++t;
  10188. }
  10189. }
  10190. bool String::containsIgnoreCase (const String& t) const throw()
  10191. {
  10192. return indexOfIgnoreCase (t) >= 0;
  10193. }
  10194. int String::indexOfWholeWord (const String& word) const throw()
  10195. {
  10196. if (word.isNotEmpty())
  10197. {
  10198. const int wordLen = word.length();
  10199. const int end = length() - wordLen;
  10200. const juce_wchar* t = text;
  10201. for (int i = 0; i <= end; ++i)
  10202. {
  10203. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10204. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10205. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10206. {
  10207. return i;
  10208. }
  10209. ++t;
  10210. }
  10211. }
  10212. return -1;
  10213. }
  10214. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10215. {
  10216. if (word.isNotEmpty())
  10217. {
  10218. const int wordLen = word.length();
  10219. const int end = length() - wordLen;
  10220. const juce_wchar* t = text;
  10221. for (int i = 0; i <= end; ++i)
  10222. {
  10223. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10224. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10225. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10226. {
  10227. return i;
  10228. }
  10229. ++t;
  10230. }
  10231. }
  10232. return -1;
  10233. }
  10234. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10235. {
  10236. return indexOfWholeWord (wordToLookFor) >= 0;
  10237. }
  10238. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10239. {
  10240. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10241. }
  10242. namespace WildCardHelpers
  10243. {
  10244. int indexOfMatch (const juce_wchar* const wildcard,
  10245. const juce_wchar* const test,
  10246. const bool ignoreCase) throw()
  10247. {
  10248. int start = 0;
  10249. while (test [start] != 0)
  10250. {
  10251. int i = 0;
  10252. for (;;)
  10253. {
  10254. const juce_wchar wc = wildcard [i];
  10255. const juce_wchar c = test [i + start];
  10256. if (wc == c
  10257. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10258. || (wc == '?' && c != 0))
  10259. {
  10260. if (wc == 0)
  10261. return start;
  10262. ++i;
  10263. }
  10264. else
  10265. {
  10266. if (wc == '*' && (wildcard [i + 1] == 0
  10267. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10268. {
  10269. return start;
  10270. }
  10271. break;
  10272. }
  10273. }
  10274. ++start;
  10275. }
  10276. return -1;
  10277. }
  10278. }
  10279. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10280. {
  10281. int i = 0;
  10282. for (;;)
  10283. {
  10284. const juce_wchar wc = wildcard.text [i];
  10285. const juce_wchar c = text [i];
  10286. if (wc == c
  10287. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10288. || (wc == '?' && c != 0))
  10289. {
  10290. if (wc == 0)
  10291. return true;
  10292. ++i;
  10293. }
  10294. else
  10295. {
  10296. return wc == '*' && (wildcard [i + 1] == 0
  10297. || WildCardHelpers::indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10298. }
  10299. }
  10300. }
  10301. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10302. {
  10303. const int len = stringToRepeat.length();
  10304. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10305. juce_wchar* n = result.text;
  10306. *n = 0;
  10307. while (--numberOfTimesToRepeat >= 0)
  10308. {
  10309. StringHolder::copyChars (n, stringToRepeat.text, len);
  10310. n += len;
  10311. }
  10312. return result;
  10313. }
  10314. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10315. {
  10316. jassert (padCharacter != 0);
  10317. const int len = length();
  10318. if (len >= minimumLength || padCharacter == 0)
  10319. return *this;
  10320. String result ((size_t) minimumLength + 1, (int) 0);
  10321. juce_wchar* n = result.text;
  10322. minimumLength -= len;
  10323. while (--minimumLength >= 0)
  10324. *n++ = padCharacter;
  10325. StringHolder::copyChars (n, text, len);
  10326. return result;
  10327. }
  10328. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10329. {
  10330. jassert (padCharacter != 0);
  10331. const int len = length();
  10332. if (len >= minimumLength || padCharacter == 0)
  10333. return *this;
  10334. String result (*this, (size_t) minimumLength);
  10335. juce_wchar* n = result.text + len;
  10336. minimumLength -= len;
  10337. while (--minimumLength >= 0)
  10338. *n++ = padCharacter;
  10339. *n = 0;
  10340. return result;
  10341. }
  10342. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10343. {
  10344. if (index < 0)
  10345. {
  10346. // a negative index to replace from?
  10347. jassertfalse;
  10348. index = 0;
  10349. }
  10350. if (numCharsToReplace < 0)
  10351. {
  10352. // replacing a negative number of characters?
  10353. numCharsToReplace = 0;
  10354. jassertfalse;
  10355. }
  10356. const int len = length();
  10357. if (index + numCharsToReplace > len)
  10358. {
  10359. if (index > len)
  10360. {
  10361. // replacing beyond the end of the string?
  10362. index = len;
  10363. jassertfalse;
  10364. }
  10365. numCharsToReplace = len - index;
  10366. }
  10367. const int newStringLen = stringToInsert.length();
  10368. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10369. if (newTotalLen <= 0)
  10370. return String::empty;
  10371. String result ((size_t) newTotalLen, (int) 0);
  10372. StringHolder::copyChars (result.text, text, index);
  10373. if (newStringLen > 0)
  10374. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10375. const int endStringLen = newTotalLen - (index + newStringLen);
  10376. if (endStringLen > 0)
  10377. StringHolder::copyChars (result.text + (index + newStringLen),
  10378. text + (index + numCharsToReplace),
  10379. endStringLen);
  10380. return result;
  10381. }
  10382. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10383. {
  10384. const int stringToReplaceLen = stringToReplace.length();
  10385. const int stringToInsertLen = stringToInsert.length();
  10386. int i = 0;
  10387. String result (*this);
  10388. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10389. : result.indexOf (i, stringToReplace))) >= 0)
  10390. {
  10391. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10392. i += stringToInsertLen;
  10393. }
  10394. return result;
  10395. }
  10396. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10397. {
  10398. const int index = indexOfChar (charToReplace);
  10399. if (index < 0)
  10400. return *this;
  10401. String result (*this, size_t());
  10402. juce_wchar* t = result.text + index;
  10403. while (*t != 0)
  10404. {
  10405. if (*t == charToReplace)
  10406. *t = charToInsert;
  10407. ++t;
  10408. }
  10409. return result;
  10410. }
  10411. const String String::replaceCharacters (const String& charactersToReplace,
  10412. const String& charactersToInsertInstead) const
  10413. {
  10414. String result (*this, size_t());
  10415. juce_wchar* t = result.text;
  10416. const int len2 = charactersToInsertInstead.length();
  10417. // the two strings passed in are supposed to be the same length!
  10418. jassert (len2 == charactersToReplace.length());
  10419. while (*t != 0)
  10420. {
  10421. const int index = charactersToReplace.indexOfChar (*t);
  10422. if (((unsigned int) index) < (unsigned int) len2)
  10423. *t = charactersToInsertInstead [index];
  10424. ++t;
  10425. }
  10426. return result;
  10427. }
  10428. bool String::startsWith (const String& other) const throw()
  10429. {
  10430. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10431. }
  10432. bool String::startsWithIgnoreCase (const String& other) const throw()
  10433. {
  10434. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10435. }
  10436. bool String::startsWithChar (const juce_wchar character) const throw()
  10437. {
  10438. jassert (character != 0); // strings can't contain a null character!
  10439. return text[0] == character;
  10440. }
  10441. bool String::endsWithChar (const juce_wchar character) const throw()
  10442. {
  10443. jassert (character != 0); // strings can't contain a null character!
  10444. return text[0] != 0
  10445. && text [length() - 1] == character;
  10446. }
  10447. bool String::endsWith (const String& other) const throw()
  10448. {
  10449. const int thisLen = length();
  10450. const int otherLen = other.length();
  10451. return thisLen >= otherLen
  10452. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10453. }
  10454. bool String::endsWithIgnoreCase (const String& other) const throw()
  10455. {
  10456. const int thisLen = length();
  10457. const int otherLen = other.length();
  10458. return thisLen >= otherLen
  10459. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10460. }
  10461. const String String::toUpperCase() const
  10462. {
  10463. String result (*this, size_t());
  10464. CharacterFunctions::toUpperCase (result.text);
  10465. return result;
  10466. }
  10467. const String String::toLowerCase() const
  10468. {
  10469. String result (*this, size_t());
  10470. CharacterFunctions::toLowerCase (result.text);
  10471. return result;
  10472. }
  10473. juce_wchar& String::operator[] (const int index)
  10474. {
  10475. jassert (((unsigned int) index) <= (unsigned int) length());
  10476. text = StringHolder::makeUnique (text);
  10477. return text [index];
  10478. }
  10479. juce_wchar String::getLastCharacter() const throw()
  10480. {
  10481. return isEmpty() ? juce_wchar() : text [length() - 1];
  10482. }
  10483. const String String::substring (int start, int end) const
  10484. {
  10485. if (start < 0)
  10486. start = 0;
  10487. else if (end <= start)
  10488. return empty;
  10489. int len = 0;
  10490. while (len <= end && text [len] != 0)
  10491. ++len;
  10492. if (end >= len)
  10493. {
  10494. if (start == 0)
  10495. return *this;
  10496. end = len;
  10497. }
  10498. return String (text + start, end - start);
  10499. }
  10500. const String String::substring (const int start) const
  10501. {
  10502. if (start <= 0)
  10503. return *this;
  10504. const int len = length();
  10505. if (start >= len)
  10506. return empty;
  10507. return String (text + start, len - start);
  10508. }
  10509. const String String::dropLastCharacters (const int numberToDrop) const
  10510. {
  10511. return String (text, jmax (0, length() - numberToDrop));
  10512. }
  10513. const String String::getLastCharacters (const int numCharacters) const
  10514. {
  10515. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10516. }
  10517. const String String::fromFirstOccurrenceOf (const String& sub,
  10518. const bool includeSubString,
  10519. const bool ignoreCase) const
  10520. {
  10521. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10522. : indexOf (sub);
  10523. if (i < 0)
  10524. return empty;
  10525. return substring (includeSubString ? i : i + sub.length());
  10526. }
  10527. const String String::fromLastOccurrenceOf (const String& sub,
  10528. const bool includeSubString,
  10529. const bool ignoreCase) const
  10530. {
  10531. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10532. : lastIndexOf (sub);
  10533. if (i < 0)
  10534. return *this;
  10535. return substring (includeSubString ? i : i + sub.length());
  10536. }
  10537. const String String::upToFirstOccurrenceOf (const String& sub,
  10538. const bool includeSubString,
  10539. const bool ignoreCase) const
  10540. {
  10541. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10542. : indexOf (sub);
  10543. if (i < 0)
  10544. return *this;
  10545. return substring (0, includeSubString ? i + sub.length() : i);
  10546. }
  10547. const String String::upToLastOccurrenceOf (const String& sub,
  10548. const bool includeSubString,
  10549. const bool ignoreCase) const
  10550. {
  10551. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10552. : lastIndexOf (sub);
  10553. if (i < 0)
  10554. return *this;
  10555. return substring (0, includeSubString ? i + sub.length() : i);
  10556. }
  10557. bool String::isQuotedString() const
  10558. {
  10559. const String trimmed (trimStart());
  10560. return trimmed[0] == '"'
  10561. || trimmed[0] == '\'';
  10562. }
  10563. const String String::unquoted() const
  10564. {
  10565. String s (*this);
  10566. if (s.text[0] == '"' || s.text[0] == '\'')
  10567. s = s.substring (1);
  10568. const int lastCharIndex = s.length() - 1;
  10569. if (lastCharIndex >= 0
  10570. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10571. s [lastCharIndex] = 0;
  10572. return s;
  10573. }
  10574. const String String::quoted (const juce_wchar quoteCharacter) const
  10575. {
  10576. if (isEmpty())
  10577. return charToString (quoteCharacter) + quoteCharacter;
  10578. String t (*this);
  10579. if (! t.startsWithChar (quoteCharacter))
  10580. t = charToString (quoteCharacter) + t;
  10581. if (! t.endsWithChar (quoteCharacter))
  10582. t += quoteCharacter;
  10583. return t;
  10584. }
  10585. const String String::trim() const
  10586. {
  10587. if (isEmpty())
  10588. return empty;
  10589. int start = 0;
  10590. while (CharacterFunctions::isWhitespace (text [start]))
  10591. ++start;
  10592. const int len = length();
  10593. int end = len - 1;
  10594. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10595. --end;
  10596. ++end;
  10597. if (end <= start)
  10598. return empty;
  10599. else if (start > 0 || end < len)
  10600. return String (text + start, end - start);
  10601. return *this;
  10602. }
  10603. const String String::trimStart() const
  10604. {
  10605. if (isEmpty())
  10606. return empty;
  10607. const juce_wchar* t = text;
  10608. while (CharacterFunctions::isWhitespace (*t))
  10609. ++t;
  10610. if (t == text)
  10611. return *this;
  10612. return String (t);
  10613. }
  10614. const String String::trimEnd() const
  10615. {
  10616. if (isEmpty())
  10617. return empty;
  10618. const juce_wchar* endT = text + (length() - 1);
  10619. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10620. --endT;
  10621. return String (text, (int) (++endT - text));
  10622. }
  10623. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10624. {
  10625. const juce_wchar* t = text;
  10626. while (charactersToTrim.containsChar (*t))
  10627. ++t;
  10628. return t == text ? *this : String (t);
  10629. }
  10630. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10631. {
  10632. if (isEmpty())
  10633. return empty;
  10634. const int len = length();
  10635. const juce_wchar* endT = text + (len - 1);
  10636. int numToRemove = 0;
  10637. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10638. {
  10639. ++numToRemove;
  10640. --endT;
  10641. }
  10642. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10643. }
  10644. const String String::retainCharacters (const String& charactersToRetain) const
  10645. {
  10646. if (isEmpty())
  10647. return empty;
  10648. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10649. juce_wchar* dst = result.text;
  10650. const juce_wchar* src = text;
  10651. while (*src != 0)
  10652. {
  10653. if (charactersToRetain.containsChar (*src))
  10654. *dst++ = *src;
  10655. ++src;
  10656. }
  10657. *dst = 0;
  10658. return result;
  10659. }
  10660. const String String::removeCharacters (const String& charactersToRemove) const
  10661. {
  10662. if (isEmpty())
  10663. return empty;
  10664. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10665. juce_wchar* dst = result.text;
  10666. const juce_wchar* src = text;
  10667. while (*src != 0)
  10668. {
  10669. if (! charactersToRemove.containsChar (*src))
  10670. *dst++ = *src;
  10671. ++src;
  10672. }
  10673. *dst = 0;
  10674. return result;
  10675. }
  10676. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10677. {
  10678. int i = 0;
  10679. for (;;)
  10680. {
  10681. if (! permittedCharacters.containsChar (text[i]))
  10682. break;
  10683. ++i;
  10684. }
  10685. return substring (0, i);
  10686. }
  10687. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10688. {
  10689. const juce_wchar* const t = text;
  10690. int i = 0;
  10691. while (t[i] != 0)
  10692. {
  10693. if (charactersToStopAt.containsChar (t[i]))
  10694. return String (text, i);
  10695. ++i;
  10696. }
  10697. return empty;
  10698. }
  10699. bool String::containsOnly (const String& chars) const throw()
  10700. {
  10701. const juce_wchar* t = text;
  10702. while (*t != 0)
  10703. if (! chars.containsChar (*t++))
  10704. return false;
  10705. return true;
  10706. }
  10707. bool String::containsAnyOf (const String& chars) const throw()
  10708. {
  10709. const juce_wchar* t = text;
  10710. while (*t != 0)
  10711. if (chars.containsChar (*t++))
  10712. return true;
  10713. return false;
  10714. }
  10715. bool String::containsNonWhitespaceChars() const throw()
  10716. {
  10717. const juce_wchar* t = text;
  10718. while (*t != 0)
  10719. if (! CharacterFunctions::isWhitespace (*t++))
  10720. return true;
  10721. return false;
  10722. }
  10723. const String String::formatted (const juce_wchar* const pf, ... )
  10724. {
  10725. jassert (pf != 0);
  10726. va_list args;
  10727. va_start (args, pf);
  10728. size_t bufferSize = 256;
  10729. String result (bufferSize, (int) 0);
  10730. result.text[0] = 0;
  10731. for (;;)
  10732. {
  10733. #if JUCE_LINUX && JUCE_64BIT
  10734. va_list tempArgs;
  10735. va_copy (tempArgs, args);
  10736. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10737. va_end (tempArgs);
  10738. #elif JUCE_WINDOWS
  10739. #if JUCE_MSVC
  10740. #pragma warning (push)
  10741. #pragma warning (disable: 4996)
  10742. #endif
  10743. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10744. #if JUCE_MSVC
  10745. #pragma warning (pop)
  10746. #endif
  10747. #else
  10748. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10749. #endif
  10750. if (num > 0)
  10751. return result;
  10752. bufferSize += 256;
  10753. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10754. break; // returns -1 because of an error rather than because it needs more space.
  10755. result.preallocateStorage (bufferSize);
  10756. }
  10757. return empty;
  10758. }
  10759. int String::getIntValue() const throw()
  10760. {
  10761. return CharacterFunctions::getIntValue (text);
  10762. }
  10763. int String::getTrailingIntValue() const throw()
  10764. {
  10765. int n = 0;
  10766. int mult = 1;
  10767. const juce_wchar* t = text + length();
  10768. while (--t >= text)
  10769. {
  10770. const juce_wchar c = *t;
  10771. if (! CharacterFunctions::isDigit (c))
  10772. {
  10773. if (c == '-')
  10774. n = -n;
  10775. break;
  10776. }
  10777. n += mult * (c - '0');
  10778. mult *= 10;
  10779. }
  10780. return n;
  10781. }
  10782. int64 String::getLargeIntValue() const throw()
  10783. {
  10784. return CharacterFunctions::getInt64Value (text);
  10785. }
  10786. float String::getFloatValue() const throw()
  10787. {
  10788. return (float) CharacterFunctions::getDoubleValue (text);
  10789. }
  10790. double String::getDoubleValue() const throw()
  10791. {
  10792. return CharacterFunctions::getDoubleValue (text);
  10793. }
  10794. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10795. const String String::toHexString (const int number)
  10796. {
  10797. juce_wchar buffer[32];
  10798. juce_wchar* const end = buffer + 32;
  10799. juce_wchar* t = end;
  10800. *--t = 0;
  10801. unsigned int v = (unsigned int) number;
  10802. do
  10803. {
  10804. *--t = hexDigits [v & 15];
  10805. v >>= 4;
  10806. } while (v != 0);
  10807. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10808. }
  10809. const String String::toHexString (const int64 number)
  10810. {
  10811. juce_wchar buffer[32];
  10812. juce_wchar* const end = buffer + 32;
  10813. juce_wchar* t = end;
  10814. *--t = 0;
  10815. uint64 v = (uint64) number;
  10816. do
  10817. {
  10818. *--t = hexDigits [(int) (v & 15)];
  10819. v >>= 4;
  10820. } while (v != 0);
  10821. return String (t, (int) (((char*) end) - (char*) t));
  10822. }
  10823. const String String::toHexString (const short number)
  10824. {
  10825. return toHexString ((int) (unsigned short) number);
  10826. }
  10827. const String String::toHexString (const unsigned char* data,
  10828. const int size,
  10829. const int groupSize)
  10830. {
  10831. if (size <= 0)
  10832. return empty;
  10833. int numChars = (size * 2) + 2;
  10834. if (groupSize > 0)
  10835. numChars += size / groupSize;
  10836. String s ((size_t) numChars, (int) 0);
  10837. juce_wchar* d = s.text;
  10838. for (int i = 0; i < size; ++i)
  10839. {
  10840. *d++ = hexDigits [(*data) >> 4];
  10841. *d++ = hexDigits [(*data) & 0xf];
  10842. ++data;
  10843. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10844. *d++ = ' ';
  10845. }
  10846. *d = 0;
  10847. return s;
  10848. }
  10849. int String::getHexValue32() const throw()
  10850. {
  10851. int result = 0;
  10852. const juce_wchar* c = text;
  10853. for (;;)
  10854. {
  10855. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10856. if (hexValue >= 0)
  10857. result = (result << 4) | hexValue;
  10858. else if (*c == 0)
  10859. break;
  10860. ++c;
  10861. }
  10862. return result;
  10863. }
  10864. int64 String::getHexValue64() const throw()
  10865. {
  10866. int64 result = 0;
  10867. const juce_wchar* c = text;
  10868. for (;;)
  10869. {
  10870. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10871. if (hexValue >= 0)
  10872. result = (result << 4) | hexValue;
  10873. else if (*c == 0)
  10874. break;
  10875. ++c;
  10876. }
  10877. return result;
  10878. }
  10879. const String String::createStringFromData (const void* const data_, const int size)
  10880. {
  10881. const char* const data = static_cast <const char*> (data_);
  10882. if (size <= 0 || data == 0)
  10883. {
  10884. return empty;
  10885. }
  10886. else if (size < 2)
  10887. {
  10888. return charToString (data[0]);
  10889. }
  10890. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10891. || (data[0] == (char)-1 && data[1] == (char)-2))
  10892. {
  10893. // assume it's 16-bit unicode
  10894. const bool bigEndian = (data[0] == (char)-2);
  10895. const int numChars = size / 2 - 1;
  10896. String result;
  10897. result.preallocateStorage (numChars + 2);
  10898. const uint16* const src = (const uint16*) (data + 2);
  10899. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10900. if (bigEndian)
  10901. {
  10902. for (int i = 0; i < numChars; ++i)
  10903. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10904. }
  10905. else
  10906. {
  10907. for (int i = 0; i < numChars; ++i)
  10908. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10909. }
  10910. dst [numChars] = 0;
  10911. return result;
  10912. }
  10913. else
  10914. {
  10915. return String::fromUTF8 (data, size);
  10916. }
  10917. }
  10918. const char* String::toUTF8() const
  10919. {
  10920. if (isEmpty())
  10921. {
  10922. return reinterpret_cast <const char*> (text);
  10923. }
  10924. else
  10925. {
  10926. const int currentLen = length() + 1;
  10927. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10928. String* const mutableThis = const_cast <String*> (this);
  10929. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10930. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10931. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10932. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10933. #endif
  10934. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10935. return otherCopy;
  10936. }
  10937. }
  10938. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10939. {
  10940. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10941. int num = 0, index = 0;
  10942. for (;;)
  10943. {
  10944. const uint32 c = (uint32) text [index++];
  10945. if (c >= 0x80)
  10946. {
  10947. int numExtraBytes = 1;
  10948. if (c >= 0x800)
  10949. {
  10950. ++numExtraBytes;
  10951. if (c >= 0x10000)
  10952. {
  10953. ++numExtraBytes;
  10954. if (c >= 0x200000)
  10955. {
  10956. ++numExtraBytes;
  10957. if (c >= 0x4000000)
  10958. ++numExtraBytes;
  10959. }
  10960. }
  10961. }
  10962. if (buffer != 0)
  10963. {
  10964. if (num + numExtraBytes >= maxBufferSizeBytes)
  10965. {
  10966. buffer [num++] = 0;
  10967. break;
  10968. }
  10969. else
  10970. {
  10971. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10972. while (--numExtraBytes >= 0)
  10973. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10974. }
  10975. }
  10976. else
  10977. {
  10978. num += numExtraBytes + 1;
  10979. }
  10980. }
  10981. else
  10982. {
  10983. if (buffer != 0)
  10984. {
  10985. if (num + 1 >= maxBufferSizeBytes)
  10986. {
  10987. buffer [num++] = 0;
  10988. break;
  10989. }
  10990. buffer [num] = (uint8) c;
  10991. }
  10992. ++num;
  10993. }
  10994. if (c == 0)
  10995. break;
  10996. }
  10997. return num;
  10998. }
  10999. int String::getNumBytesAsUTF8() const throw()
  11000. {
  11001. int num = 0;
  11002. const juce_wchar* t = text;
  11003. for (;;)
  11004. {
  11005. const uint32 c = (uint32) *t;
  11006. if (c >= 0x80)
  11007. {
  11008. ++num;
  11009. if (c >= 0x800)
  11010. {
  11011. ++num;
  11012. if (c >= 0x10000)
  11013. {
  11014. ++num;
  11015. if (c >= 0x200000)
  11016. {
  11017. ++num;
  11018. if (c >= 0x4000000)
  11019. ++num;
  11020. }
  11021. }
  11022. }
  11023. }
  11024. else if (c == 0)
  11025. break;
  11026. ++num;
  11027. ++t;
  11028. }
  11029. return num;
  11030. }
  11031. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  11032. {
  11033. if (buffer == 0)
  11034. return empty;
  11035. if (bufferSizeBytes < 0)
  11036. bufferSizeBytes = std::numeric_limits<int>::max();
  11037. size_t numBytes;
  11038. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  11039. if (buffer [numBytes] == 0)
  11040. break;
  11041. String result ((size_t) numBytes + 1, (int) 0);
  11042. juce_wchar* dest = result.text;
  11043. size_t i = 0;
  11044. while (i < numBytes)
  11045. {
  11046. const char c = buffer [i++];
  11047. if (c < 0)
  11048. {
  11049. unsigned int mask = 0x7f;
  11050. int bit = 0x40;
  11051. int numExtraValues = 0;
  11052. while (bit != 0 && (c & bit) != 0)
  11053. {
  11054. bit >>= 1;
  11055. mask >>= 1;
  11056. ++numExtraValues;
  11057. }
  11058. int n = (mask & (unsigned char) c);
  11059. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  11060. {
  11061. const char nextByte = buffer[i];
  11062. if ((nextByte & 0xc0) != 0x80)
  11063. break;
  11064. n <<= 6;
  11065. n |= (nextByte & 0x3f);
  11066. ++i;
  11067. }
  11068. *dest++ = (juce_wchar) n;
  11069. }
  11070. else
  11071. {
  11072. *dest++ = (juce_wchar) c;
  11073. }
  11074. }
  11075. *dest = 0;
  11076. return result;
  11077. }
  11078. const char* String::toCString() const
  11079. {
  11080. if (isEmpty())
  11081. {
  11082. return reinterpret_cast <const char*> (text);
  11083. }
  11084. else
  11085. {
  11086. const int len = length();
  11087. String* const mutableThis = const_cast <String*> (this);
  11088. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  11089. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  11090. CharacterFunctions::copy (otherCopy, text, len);
  11091. otherCopy [len] = 0;
  11092. return otherCopy;
  11093. }
  11094. }
  11095. #if JUCE_MSVC
  11096. #pragma warning (push)
  11097. #pragma warning (disable: 4514 4996)
  11098. #endif
  11099. int String::getNumBytesAsCString() const throw()
  11100. {
  11101. return (int) wcstombs (0, text, 0);
  11102. }
  11103. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  11104. {
  11105. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  11106. if (destBuffer != 0 && numBytes >= 0)
  11107. destBuffer [numBytes] = 0;
  11108. return numBytes;
  11109. }
  11110. #if JUCE_MSVC
  11111. #pragma warning (pop)
  11112. #endif
  11113. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11114. {
  11115. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11116. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11117. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11118. }
  11119. String::Concatenator::Concatenator (String& stringToAppendTo)
  11120. : result (stringToAppendTo),
  11121. nextIndex (stringToAppendTo.length())
  11122. {
  11123. }
  11124. String::Concatenator::~Concatenator()
  11125. {
  11126. }
  11127. void String::Concatenator::append (const String& s)
  11128. {
  11129. const int len = s.length();
  11130. if (len > 0)
  11131. {
  11132. result.preallocateStorage (nextIndex + len);
  11133. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11134. nextIndex += len;
  11135. }
  11136. }
  11137. #if JUCE_UNIT_TESTS
  11138. class StringTests : public UnitTest
  11139. {
  11140. public:
  11141. StringTests() : UnitTest ("String class") {}
  11142. void runTest()
  11143. {
  11144. {
  11145. beginTest ("Basics");
  11146. expect (String().length() == 0);
  11147. expect (String() == String::empty);
  11148. String s1, s2 ("abcd");
  11149. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11150. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11151. expect (s2.length() == 4);
  11152. s1 = "abcd";
  11153. expect (s2 == s1 && s1 == s2);
  11154. expect (s1 == "abcd" && s1 == L"abcd");
  11155. expect (String ("abcd") == String (L"abcd"));
  11156. expect (String ("abcdefg", 4) == L"abcd");
  11157. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11158. expect (String::charToString ('x') == "x");
  11159. expect (String::charToString (0) == String::empty);
  11160. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11161. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11162. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11163. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11164. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11165. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11166. expect (s1.indexOf (String::empty) == 0);
  11167. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11168. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11169. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11170. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11171. }
  11172. {
  11173. beginTest ("Operations");
  11174. String s ("012345678");
  11175. expect (s.hashCode() != 0);
  11176. expect (s.hashCode64() != 0);
  11177. expect (s.hashCode() != (s + s).hashCode());
  11178. expect (s.hashCode64() != (s + s).hashCode64());
  11179. expect (s.compare (String ("012345678")) == 0);
  11180. expect (s.compare (String ("012345679")) < 0);
  11181. expect (s.compare (String ("012345676")) > 0);
  11182. expect (s.substring (2, 3) == String::charToString (s[2]));
  11183. expect (s.substring (0, 1) == String::charToString (s[0]));
  11184. expect (s.getLastCharacter() == s [s.length() - 1]);
  11185. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11186. expect (s.substring (0, 3) == L"012");
  11187. expect (s.substring (0, 100) == s);
  11188. expect (s.substring (-1, 100) == s);
  11189. expect (s.substring (3) == "345678");
  11190. expect (s.indexOf (L"45") == 4);
  11191. expect (String ("444445").indexOf ("45") == 4);
  11192. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11193. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11194. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11195. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11196. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11197. expect (s.indexOfChar (L'4') == 4);
  11198. expect (s + s == "012345678012345678");
  11199. expect (s.startsWith (s));
  11200. expect (s.startsWith (s.substring (0, 4)));
  11201. expect (s.startsWith (s.dropLastCharacters (4)));
  11202. expect (s.endsWith (s.substring (5)));
  11203. expect (s.endsWith (s));
  11204. expect (s.contains (s.substring (3, 6)));
  11205. expect (s.contains (s.substring (3)));
  11206. expect (s.startsWithChar (s[0]));
  11207. expect (s.endsWithChar (s.getLastCharacter()));
  11208. expect (s [s.length()] == 0);
  11209. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11210. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11211. String s2 ("123");
  11212. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11213. s2 += "xyz";
  11214. expect (s2 == "1234567890xyz");
  11215. beginTest ("Numeric conversions");
  11216. expect (String::empty.getIntValue() == 0);
  11217. expect (String::empty.getDoubleValue() == 0.0);
  11218. expect (String::empty.getFloatValue() == 0.0f);
  11219. expect (s.getIntValue() == 12345678);
  11220. expect (s.getLargeIntValue() == (int64) 12345678);
  11221. expect (s.getDoubleValue() == 12345678.0);
  11222. expect (s.getFloatValue() == 12345678.0f);
  11223. expect (String (-1234).getIntValue() == -1234);
  11224. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11225. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11226. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11227. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11228. expect (s.getHexValue32() == 0x12345678);
  11229. expect (s.getHexValue64() == (int64) 0x12345678);
  11230. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11231. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11232. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11233. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11234. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11235. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11236. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11237. beginTest ("Subsections");
  11238. String s3;
  11239. s3 = "abcdeFGHIJ";
  11240. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11241. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11242. expect (s3.containsIgnoreCase (s3.substring (3)));
  11243. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11244. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11245. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11246. expect (s3.containsAnyOf (L"zzzFs"));
  11247. expect (s3.startsWith ("abcd"));
  11248. expect (s3.startsWithIgnoreCase (L"abCD"));
  11249. expect (s3.startsWith (String::empty));
  11250. expect (s3.startsWithChar ('a'));
  11251. expect (s3.endsWith (String ("HIJ")));
  11252. expect (s3.endsWithIgnoreCase (L"Hij"));
  11253. expect (s3.endsWith (String::empty));
  11254. expect (s3.endsWithChar (L'J'));
  11255. expect (s3.indexOf ("HIJ") == 7);
  11256. expect (s3.indexOf (L"HIJK") == -1);
  11257. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11258. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11259. String s4 (s3);
  11260. s4.append (String ("xyz123"), 3);
  11261. expect (s4 == s3 + "xyz");
  11262. expect (String (1234) < String (1235));
  11263. expect (String (1235) > String (1234));
  11264. expect (String (1234) >= String (1234));
  11265. expect (String (1234) <= String (1234));
  11266. expect (String (1235) >= String (1234));
  11267. expect (String (1234) <= String (1235));
  11268. String s5 ("word word2 word3");
  11269. expect (s5.containsWholeWord (String ("word2")));
  11270. expect (s5.indexOfWholeWord ("word2") == 5);
  11271. expect (s5.containsWholeWord (L"word"));
  11272. expect (s5.containsWholeWord ("word3"));
  11273. expect (s5.containsWholeWord (s5));
  11274. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11275. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11276. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11277. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11278. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11279. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11280. expect (s5.containsNonWhitespaceChars());
  11281. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11282. expect (s5.matchesWildcard (L"wor*", false));
  11283. expect (s5.matchesWildcard ("wOr*", true));
  11284. expect (s5.matchesWildcard (L"*word3", true));
  11285. expect (s5.matchesWildcard ("*word?", true));
  11286. expect (s5.matchesWildcard (L"Word*3", true));
  11287. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11288. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11289. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11290. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11291. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11292. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11293. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11294. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11295. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11296. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11297. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11298. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11299. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11300. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11301. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11302. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11303. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11304. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11305. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11306. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11307. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11308. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11309. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11310. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11311. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11312. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11313. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11314. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11315. expect (s5.replace ("Word", "", true) == " 2 3");
  11316. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11317. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11318. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11319. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11320. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11321. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11322. expect (s5.retainCharacters (String::empty).isEmpty());
  11323. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11324. expect (s5.removeCharacters (String::empty) == s5);
  11325. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11326. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11327. expect (! s5.isQuotedString());
  11328. expect (s5.quoted().isQuotedString());
  11329. expect (! s5.quoted().unquoted().isQuotedString());
  11330. expect (! String ("x'").isQuotedString());
  11331. expect (String ("'x").isQuotedString());
  11332. String s6 (" \t xyz \t\r\n");
  11333. expect (s6.trim() == String ("xyz"));
  11334. expect (s6.trim().trim() == "xyz");
  11335. expect (s5.trim() == s5);
  11336. expect (s6.trimStart().trimEnd() == s6.trim());
  11337. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11338. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11339. expect (s6.trimStart() != s6.trimEnd());
  11340. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11341. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11342. }
  11343. {
  11344. beginTest ("UTF8");
  11345. String s ("word word2 word3");
  11346. {
  11347. char buffer [100];
  11348. memset (buffer, 0xff, sizeof (buffer));
  11349. s.copyToUTF8 (buffer, 100);
  11350. expect (String::fromUTF8 (buffer, 100) == s);
  11351. juce_wchar bufferUnicode [100];
  11352. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11353. s.copyToUnicode (bufferUnicode, 100);
  11354. expect (String (bufferUnicode, 100) == s);
  11355. }
  11356. {
  11357. juce_wchar wideBuffer [50];
  11358. zerostruct (wideBuffer);
  11359. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11360. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11361. String wide (wideBuffer);
  11362. expect (wide == (const juce_wchar*) wideBuffer);
  11363. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11364. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11365. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11366. }
  11367. }
  11368. }
  11369. };
  11370. static StringTests stringUnitTests;
  11371. #endif
  11372. END_JUCE_NAMESPACE
  11373. /*** End of inlined file: juce_String.cpp ***/
  11374. /*** Start of inlined file: juce_StringArray.cpp ***/
  11375. BEGIN_JUCE_NAMESPACE
  11376. StringArray::StringArray() throw()
  11377. {
  11378. }
  11379. StringArray::StringArray (const StringArray& other)
  11380. : strings (other.strings)
  11381. {
  11382. }
  11383. StringArray::StringArray (const String& firstValue)
  11384. {
  11385. strings.add (firstValue);
  11386. }
  11387. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11388. const int numberOfStrings)
  11389. {
  11390. for (int i = 0; i < numberOfStrings; ++i)
  11391. strings.add (initialStrings [i]);
  11392. }
  11393. StringArray::StringArray (const char* const* const initialStrings,
  11394. const int numberOfStrings)
  11395. {
  11396. for (int i = 0; i < numberOfStrings; ++i)
  11397. strings.add (initialStrings [i]);
  11398. }
  11399. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11400. {
  11401. int i = 0;
  11402. while (initialStrings[i] != 0)
  11403. strings.add (initialStrings [i++]);
  11404. }
  11405. StringArray::StringArray (const char* const* const initialStrings)
  11406. {
  11407. int i = 0;
  11408. while (initialStrings[i] != 0)
  11409. strings.add (initialStrings [i++]);
  11410. }
  11411. StringArray& StringArray::operator= (const StringArray& other)
  11412. {
  11413. strings = other.strings;
  11414. return *this;
  11415. }
  11416. StringArray::~StringArray()
  11417. {
  11418. }
  11419. bool StringArray::operator== (const StringArray& other) const throw()
  11420. {
  11421. if (other.size() != size())
  11422. return false;
  11423. for (int i = size(); --i >= 0;)
  11424. if (other.strings.getReference(i) != strings.getReference(i))
  11425. return false;
  11426. return true;
  11427. }
  11428. bool StringArray::operator!= (const StringArray& other) const throw()
  11429. {
  11430. return ! operator== (other);
  11431. }
  11432. void StringArray::clear()
  11433. {
  11434. strings.clear();
  11435. }
  11436. const String& StringArray::operator[] (const int index) const throw()
  11437. {
  11438. if (((unsigned int) index) < (unsigned int) strings.size())
  11439. return strings.getReference (index);
  11440. return String::empty;
  11441. }
  11442. String& StringArray::getReference (const int index) throw()
  11443. {
  11444. jassert (((unsigned int) index) < (unsigned int) strings.size());
  11445. return strings.getReference (index);
  11446. }
  11447. void StringArray::add (const String& newString)
  11448. {
  11449. strings.add (newString);
  11450. }
  11451. void StringArray::insert (const int index, const String& newString)
  11452. {
  11453. strings.insert (index, newString);
  11454. }
  11455. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11456. {
  11457. if (! contains (newString, ignoreCase))
  11458. add (newString);
  11459. }
  11460. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11461. {
  11462. if (startIndex < 0)
  11463. {
  11464. jassertfalse;
  11465. startIndex = 0;
  11466. }
  11467. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11468. numElementsToAdd = otherArray.size() - startIndex;
  11469. while (--numElementsToAdd >= 0)
  11470. strings.add (otherArray.strings.getReference (startIndex++));
  11471. }
  11472. void StringArray::set (const int index, const String& newString)
  11473. {
  11474. strings.set (index, newString);
  11475. }
  11476. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11477. {
  11478. if (ignoreCase)
  11479. {
  11480. for (int i = size(); --i >= 0;)
  11481. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11482. return true;
  11483. }
  11484. else
  11485. {
  11486. for (int i = size(); --i >= 0;)
  11487. if (stringToLookFor == strings.getReference(i))
  11488. return true;
  11489. }
  11490. return false;
  11491. }
  11492. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11493. {
  11494. if (i < 0)
  11495. i = 0;
  11496. const int numElements = size();
  11497. if (ignoreCase)
  11498. {
  11499. while (i < numElements)
  11500. {
  11501. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11502. return i;
  11503. ++i;
  11504. }
  11505. }
  11506. else
  11507. {
  11508. while (i < numElements)
  11509. {
  11510. if (stringToLookFor == strings.getReference (i))
  11511. return i;
  11512. ++i;
  11513. }
  11514. }
  11515. return -1;
  11516. }
  11517. void StringArray::remove (const int index)
  11518. {
  11519. strings.remove (index);
  11520. }
  11521. void StringArray::removeString (const String& stringToRemove,
  11522. const bool ignoreCase)
  11523. {
  11524. if (ignoreCase)
  11525. {
  11526. for (int i = size(); --i >= 0;)
  11527. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11528. strings.remove (i);
  11529. }
  11530. else
  11531. {
  11532. for (int i = size(); --i >= 0;)
  11533. if (stringToRemove == strings.getReference (i))
  11534. strings.remove (i);
  11535. }
  11536. }
  11537. void StringArray::removeRange (int startIndex, int numberToRemove)
  11538. {
  11539. strings.removeRange (startIndex, numberToRemove);
  11540. }
  11541. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11542. {
  11543. if (removeWhitespaceStrings)
  11544. {
  11545. for (int i = size(); --i >= 0;)
  11546. if (! strings.getReference(i).containsNonWhitespaceChars())
  11547. strings.remove (i);
  11548. }
  11549. else
  11550. {
  11551. for (int i = size(); --i >= 0;)
  11552. if (strings.getReference(i).isEmpty())
  11553. strings.remove (i);
  11554. }
  11555. }
  11556. void StringArray::trim()
  11557. {
  11558. for (int i = size(); --i >= 0;)
  11559. {
  11560. String& s = strings.getReference(i);
  11561. s = s.trim();
  11562. }
  11563. }
  11564. class InternalStringArrayComparator_CaseSensitive
  11565. {
  11566. public:
  11567. static int compareElements (String& first, String& second) { return first.compare (second); }
  11568. };
  11569. class InternalStringArrayComparator_CaseInsensitive
  11570. {
  11571. public:
  11572. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11573. };
  11574. void StringArray::sort (const bool ignoreCase)
  11575. {
  11576. if (ignoreCase)
  11577. {
  11578. InternalStringArrayComparator_CaseInsensitive comp;
  11579. strings.sort (comp);
  11580. }
  11581. else
  11582. {
  11583. InternalStringArrayComparator_CaseSensitive comp;
  11584. strings.sort (comp);
  11585. }
  11586. }
  11587. void StringArray::move (const int currentIndex, int newIndex) throw()
  11588. {
  11589. strings.move (currentIndex, newIndex);
  11590. }
  11591. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11592. {
  11593. const int last = (numberToJoin < 0) ? size()
  11594. : jmin (size(), start + numberToJoin);
  11595. if (start < 0)
  11596. start = 0;
  11597. if (start >= last)
  11598. return String::empty;
  11599. if (start == last - 1)
  11600. return strings.getReference (start);
  11601. const int separatorLen = separator.length();
  11602. int charsNeeded = separatorLen * (last - start - 1);
  11603. for (int i = start; i < last; ++i)
  11604. charsNeeded += strings.getReference(i).length();
  11605. String result;
  11606. result.preallocateStorage (charsNeeded);
  11607. juce_wchar* dest = result;
  11608. while (start < last)
  11609. {
  11610. const String& s = strings.getReference (start);
  11611. const int len = s.length();
  11612. if (len > 0)
  11613. {
  11614. s.copyToUnicode (dest, len);
  11615. dest += len;
  11616. }
  11617. if (++start < last && separatorLen > 0)
  11618. {
  11619. separator.copyToUnicode (dest, separatorLen);
  11620. dest += separatorLen;
  11621. }
  11622. }
  11623. *dest = 0;
  11624. return result;
  11625. }
  11626. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11627. {
  11628. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11629. }
  11630. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11631. {
  11632. int num = 0;
  11633. if (text.isNotEmpty())
  11634. {
  11635. bool insideQuotes = false;
  11636. juce_wchar currentQuoteChar = 0;
  11637. int i = 0;
  11638. int tokenStart = 0;
  11639. for (;;)
  11640. {
  11641. const juce_wchar c = text[i];
  11642. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11643. if (! isBreak)
  11644. {
  11645. if (quoteCharacters.containsChar (c))
  11646. {
  11647. if (insideQuotes)
  11648. {
  11649. // only break out of quotes-mode if we find a matching quote to the
  11650. // one that we opened with..
  11651. if (currentQuoteChar == c)
  11652. insideQuotes = false;
  11653. }
  11654. else
  11655. {
  11656. insideQuotes = true;
  11657. currentQuoteChar = c;
  11658. }
  11659. }
  11660. }
  11661. else
  11662. {
  11663. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11664. ++num;
  11665. tokenStart = i + 1;
  11666. }
  11667. if (c == 0)
  11668. break;
  11669. ++i;
  11670. }
  11671. }
  11672. return num;
  11673. }
  11674. int StringArray::addLines (const String& sourceText)
  11675. {
  11676. int numLines = 0;
  11677. const juce_wchar* text = sourceText;
  11678. while (*text != 0)
  11679. {
  11680. const juce_wchar* const startOfLine = text;
  11681. while (*text != 0)
  11682. {
  11683. if (*text == '\r')
  11684. {
  11685. ++text;
  11686. if (*text == '\n')
  11687. ++text;
  11688. break;
  11689. }
  11690. if (*text == '\n')
  11691. {
  11692. ++text;
  11693. break;
  11694. }
  11695. ++text;
  11696. }
  11697. const juce_wchar* endOfLine = text;
  11698. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11699. --endOfLine;
  11700. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11701. --endOfLine;
  11702. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11703. ++numLines;
  11704. }
  11705. return numLines;
  11706. }
  11707. void StringArray::removeDuplicates (const bool ignoreCase)
  11708. {
  11709. for (int i = 0; i < size() - 1; ++i)
  11710. {
  11711. const String s (strings.getReference(i));
  11712. int nextIndex = i + 1;
  11713. for (;;)
  11714. {
  11715. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11716. if (nextIndex < 0)
  11717. break;
  11718. strings.remove (nextIndex);
  11719. }
  11720. }
  11721. }
  11722. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11723. const bool appendNumberToFirstInstance,
  11724. const juce_wchar* preNumberString,
  11725. const juce_wchar* postNumberString)
  11726. {
  11727. if (preNumberString == 0)
  11728. preNumberString = L" (";
  11729. if (postNumberString == 0)
  11730. postNumberString = L")";
  11731. for (int i = 0; i < size() - 1; ++i)
  11732. {
  11733. String& s = strings.getReference(i);
  11734. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11735. if (nextIndex >= 0)
  11736. {
  11737. const String original (s);
  11738. int number = 0;
  11739. if (appendNumberToFirstInstance)
  11740. s = original + preNumberString + String (++number) + postNumberString;
  11741. else
  11742. ++number;
  11743. while (nextIndex >= 0)
  11744. {
  11745. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11746. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11747. }
  11748. }
  11749. }
  11750. }
  11751. void StringArray::minimiseStorageOverheads()
  11752. {
  11753. strings.minimiseStorageOverheads();
  11754. }
  11755. END_JUCE_NAMESPACE
  11756. /*** End of inlined file: juce_StringArray.cpp ***/
  11757. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11758. BEGIN_JUCE_NAMESPACE
  11759. StringPairArray::StringPairArray (const bool ignoreCase_)
  11760. : ignoreCase (ignoreCase_)
  11761. {
  11762. }
  11763. StringPairArray::StringPairArray (const StringPairArray& other)
  11764. : keys (other.keys),
  11765. values (other.values),
  11766. ignoreCase (other.ignoreCase)
  11767. {
  11768. }
  11769. StringPairArray::~StringPairArray()
  11770. {
  11771. }
  11772. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11773. {
  11774. keys = other.keys;
  11775. values = other.values;
  11776. return *this;
  11777. }
  11778. bool StringPairArray::operator== (const StringPairArray& other) const
  11779. {
  11780. for (int i = keys.size(); --i >= 0;)
  11781. if (other [keys[i]] != values[i])
  11782. return false;
  11783. return true;
  11784. }
  11785. bool StringPairArray::operator!= (const StringPairArray& other) const
  11786. {
  11787. return ! operator== (other);
  11788. }
  11789. const String& StringPairArray::operator[] (const String& key) const
  11790. {
  11791. return values [keys.indexOf (key, ignoreCase)];
  11792. }
  11793. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11794. {
  11795. const int i = keys.indexOf (key, ignoreCase);
  11796. if (i >= 0)
  11797. return values[i];
  11798. return defaultReturnValue;
  11799. }
  11800. void StringPairArray::set (const String& key, const String& value)
  11801. {
  11802. const int i = keys.indexOf (key, ignoreCase);
  11803. if (i >= 0)
  11804. {
  11805. values.set (i, value);
  11806. }
  11807. else
  11808. {
  11809. keys.add (key);
  11810. values.add (value);
  11811. }
  11812. }
  11813. void StringPairArray::addArray (const StringPairArray& other)
  11814. {
  11815. for (int i = 0; i < other.size(); ++i)
  11816. set (other.keys[i], other.values[i]);
  11817. }
  11818. void StringPairArray::clear()
  11819. {
  11820. keys.clear();
  11821. values.clear();
  11822. }
  11823. void StringPairArray::remove (const String& key)
  11824. {
  11825. remove (keys.indexOf (key, ignoreCase));
  11826. }
  11827. void StringPairArray::remove (const int index)
  11828. {
  11829. keys.remove (index);
  11830. values.remove (index);
  11831. }
  11832. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11833. {
  11834. ignoreCase = shouldIgnoreCase;
  11835. }
  11836. const String StringPairArray::getDescription() const
  11837. {
  11838. String s;
  11839. for (int i = 0; i < keys.size(); ++i)
  11840. {
  11841. s << keys[i] << " = " << values[i];
  11842. if (i < keys.size())
  11843. s << ", ";
  11844. }
  11845. return s;
  11846. }
  11847. void StringPairArray::minimiseStorageOverheads()
  11848. {
  11849. keys.minimiseStorageOverheads();
  11850. values.minimiseStorageOverheads();
  11851. }
  11852. END_JUCE_NAMESPACE
  11853. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11854. /*** Start of inlined file: juce_StringPool.cpp ***/
  11855. BEGIN_JUCE_NAMESPACE
  11856. StringPool::StringPool() throw() {}
  11857. StringPool::~StringPool() {}
  11858. namespace StringPoolHelpers
  11859. {
  11860. template <class StringType>
  11861. const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11862. {
  11863. int start = 0;
  11864. int end = strings.size();
  11865. for (;;)
  11866. {
  11867. if (start >= end)
  11868. {
  11869. jassert (start <= end);
  11870. strings.insert (start, newString);
  11871. return strings.getReference (start);
  11872. }
  11873. else
  11874. {
  11875. const String& startString = strings.getReference (start);
  11876. if (startString == newString)
  11877. return startString;
  11878. const int halfway = (start + end) >> 1;
  11879. if (halfway == start)
  11880. {
  11881. if (startString.compare (newString) < 0)
  11882. ++start;
  11883. strings.insert (start, newString);
  11884. return strings.getReference (start);
  11885. }
  11886. const int comp = strings.getReference (halfway).compare (newString);
  11887. if (comp == 0)
  11888. return strings.getReference (halfway);
  11889. else if (comp < 0)
  11890. start = halfway;
  11891. else
  11892. end = halfway;
  11893. }
  11894. }
  11895. }
  11896. }
  11897. const juce_wchar* StringPool::getPooledString (const String& s)
  11898. {
  11899. if (s.isEmpty())
  11900. return String::empty;
  11901. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11902. }
  11903. const juce_wchar* StringPool::getPooledString (const char* const s)
  11904. {
  11905. if (s == 0 || *s == 0)
  11906. return String::empty;
  11907. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11908. }
  11909. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11910. {
  11911. if (s == 0 || *s == 0)
  11912. return String::empty;
  11913. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11914. }
  11915. int StringPool::size() const throw()
  11916. {
  11917. return strings.size();
  11918. }
  11919. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11920. {
  11921. return strings [index];
  11922. }
  11923. END_JUCE_NAMESPACE
  11924. /*** End of inlined file: juce_StringPool.cpp ***/
  11925. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11926. BEGIN_JUCE_NAMESPACE
  11927. XmlDocument::XmlDocument (const String& documentText)
  11928. : originalText (documentText),
  11929. ignoreEmptyTextElements (true)
  11930. {
  11931. }
  11932. XmlDocument::XmlDocument (const File& file)
  11933. : ignoreEmptyTextElements (true),
  11934. inputSource (new FileInputSource (file))
  11935. {
  11936. }
  11937. XmlDocument::~XmlDocument()
  11938. {
  11939. }
  11940. XmlElement* XmlDocument::parse (const File& file)
  11941. {
  11942. XmlDocument doc (file);
  11943. return doc.getDocumentElement();
  11944. }
  11945. XmlElement* XmlDocument::parse (const String& xmlData)
  11946. {
  11947. XmlDocument doc (xmlData);
  11948. return doc.getDocumentElement();
  11949. }
  11950. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11951. {
  11952. inputSource = newSource;
  11953. }
  11954. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11955. {
  11956. ignoreEmptyTextElements = shouldBeIgnored;
  11957. }
  11958. namespace XmlIdentifierChars
  11959. {
  11960. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11961. {
  11962. return CharacterFunctions::isLetterOrDigit (c)
  11963. || c == '_' || c == '-' || c == ':' || c == '.';
  11964. }
  11965. bool isIdentifierChar (const juce_wchar c) throw()
  11966. {
  11967. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11968. return (c < numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11969. : isIdentifierCharSlow (c);
  11970. }
  11971. /*static void generateIdentifierCharConstants()
  11972. {
  11973. uint32 n[8];
  11974. zerostruct (n);
  11975. for (int i = 0; i < 256; ++i)
  11976. if (isIdentifierCharSlow (i))
  11977. n[i >> 5] |= (1 << (i & 31));
  11978. String s;
  11979. for (int i = 0; i < 8; ++i)
  11980. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11981. DBG (s);
  11982. }*/
  11983. }
  11984. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11985. {
  11986. String textToParse (originalText);
  11987. if (textToParse.isEmpty() && inputSource != 0)
  11988. {
  11989. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11990. if (in != 0)
  11991. {
  11992. MemoryOutputStream data;
  11993. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11994. textToParse = data.toString();
  11995. if (! onlyReadOuterDocumentElement)
  11996. originalText = textToParse;
  11997. }
  11998. }
  11999. input = textToParse;
  12000. lastError = String::empty;
  12001. errorOccurred = false;
  12002. outOfData = false;
  12003. needToLoadDTD = true;
  12004. if (textToParse.isEmpty())
  12005. {
  12006. lastError = "not enough input";
  12007. }
  12008. else
  12009. {
  12010. skipHeader();
  12011. if (input != 0)
  12012. {
  12013. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  12014. if (! errorOccurred)
  12015. return result.release();
  12016. }
  12017. else
  12018. {
  12019. lastError = "incorrect xml header";
  12020. }
  12021. }
  12022. return 0;
  12023. }
  12024. const String& XmlDocument::getLastParseError() const throw()
  12025. {
  12026. return lastError;
  12027. }
  12028. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  12029. {
  12030. lastError = desc;
  12031. errorOccurred = ! carryOn;
  12032. }
  12033. const String XmlDocument::getFileContents (const String& filename) const
  12034. {
  12035. if (inputSource != 0)
  12036. {
  12037. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  12038. if (in != 0)
  12039. return in->readEntireStreamAsString();
  12040. }
  12041. return String::empty;
  12042. }
  12043. juce_wchar XmlDocument::readNextChar() throw()
  12044. {
  12045. if (*input != 0)
  12046. return *input++;
  12047. outOfData = true;
  12048. return 0;
  12049. }
  12050. int XmlDocument::findNextTokenLength() throw()
  12051. {
  12052. int len = 0;
  12053. juce_wchar c = *input;
  12054. while (XmlIdentifierChars::isIdentifierChar (c))
  12055. c = input [++len];
  12056. return len;
  12057. }
  12058. void XmlDocument::skipHeader()
  12059. {
  12060. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  12061. if (found != 0)
  12062. {
  12063. input = found;
  12064. input = CharacterFunctions::find (input, JUCE_T("?>"));
  12065. if (input == 0)
  12066. return;
  12067. #if JUCE_DEBUG
  12068. const String header (found, input - found);
  12069. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  12070. .fromFirstOccurrenceOf ("=", false, false)
  12071. .fromFirstOccurrenceOf ("\"", false, false)
  12072. .upToFirstOccurrenceOf ("\"", false, false).trim());
  12073. /* If you load an XML document with a non-UTF encoding type, it may have been
  12074. loaded wrongly.. Since all the files are read via the normal juce file streams,
  12075. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  12076. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  12077. read, use your own code to convert them to a unicode String, and pass that to the
  12078. XML parser.
  12079. */
  12080. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  12081. #endif
  12082. input += 2;
  12083. }
  12084. skipNextWhiteSpace();
  12085. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  12086. if (docType == 0)
  12087. return;
  12088. input = docType + 9;
  12089. int n = 1;
  12090. while (n > 0)
  12091. {
  12092. const juce_wchar c = readNextChar();
  12093. if (outOfData)
  12094. return;
  12095. if (c == '<')
  12096. ++n;
  12097. else if (c == '>')
  12098. --n;
  12099. }
  12100. docType += 9;
  12101. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  12102. }
  12103. void XmlDocument::skipNextWhiteSpace()
  12104. {
  12105. for (;;)
  12106. {
  12107. juce_wchar c = *input;
  12108. while (CharacterFunctions::isWhitespace (c))
  12109. c = *++input;
  12110. if (c == 0)
  12111. {
  12112. outOfData = true;
  12113. break;
  12114. }
  12115. else if (c == '<')
  12116. {
  12117. if (input[1] == '!'
  12118. && input[2] == '-'
  12119. && input[3] == '-')
  12120. {
  12121. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12122. if (closeComment == 0)
  12123. {
  12124. outOfData = true;
  12125. break;
  12126. }
  12127. input = closeComment + 3;
  12128. continue;
  12129. }
  12130. else if (input[1] == '?')
  12131. {
  12132. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12133. if (closeBracket == 0)
  12134. {
  12135. outOfData = true;
  12136. break;
  12137. }
  12138. input = closeBracket + 2;
  12139. continue;
  12140. }
  12141. }
  12142. break;
  12143. }
  12144. }
  12145. void XmlDocument::readQuotedString (String& result)
  12146. {
  12147. const juce_wchar quote = readNextChar();
  12148. while (! outOfData)
  12149. {
  12150. const juce_wchar c = readNextChar();
  12151. if (c == quote)
  12152. break;
  12153. if (c == '&')
  12154. {
  12155. --input;
  12156. readEntity (result);
  12157. }
  12158. else
  12159. {
  12160. --input;
  12161. const juce_wchar* const start = input;
  12162. for (;;)
  12163. {
  12164. const juce_wchar character = *input;
  12165. if (character == quote)
  12166. {
  12167. result.append (start, (int) (input - start));
  12168. ++input;
  12169. return;
  12170. }
  12171. else if (character == '&')
  12172. {
  12173. result.append (start, (int) (input - start));
  12174. break;
  12175. }
  12176. else if (character == 0)
  12177. {
  12178. outOfData = true;
  12179. setLastError ("unmatched quotes", false);
  12180. break;
  12181. }
  12182. ++input;
  12183. }
  12184. }
  12185. }
  12186. }
  12187. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12188. {
  12189. XmlElement* node = 0;
  12190. skipNextWhiteSpace();
  12191. if (outOfData)
  12192. return 0;
  12193. input = CharacterFunctions::find (input, JUCE_T("<"));
  12194. if (input != 0)
  12195. {
  12196. ++input;
  12197. int tagLen = findNextTokenLength();
  12198. if (tagLen == 0)
  12199. {
  12200. // no tag name - but allow for a gap after the '<' before giving an error
  12201. skipNextWhiteSpace();
  12202. tagLen = findNextTokenLength();
  12203. if (tagLen == 0)
  12204. {
  12205. setLastError ("tag name missing", false);
  12206. return node;
  12207. }
  12208. }
  12209. node = new XmlElement (String (input, tagLen));
  12210. input += tagLen;
  12211. XmlElement::XmlAttributeNode* lastAttribute = 0;
  12212. // look for attributes
  12213. for (;;)
  12214. {
  12215. skipNextWhiteSpace();
  12216. const juce_wchar c = *input;
  12217. // empty tag..
  12218. if (c == '/' && input[1] == '>')
  12219. {
  12220. input += 2;
  12221. break;
  12222. }
  12223. // parse the guts of the element..
  12224. if (c == '>')
  12225. {
  12226. ++input;
  12227. if (alsoParseSubElements)
  12228. readChildElements (node);
  12229. break;
  12230. }
  12231. // get an attribute..
  12232. if (XmlIdentifierChars::isIdentifierChar (c))
  12233. {
  12234. const int attNameLen = findNextTokenLength();
  12235. if (attNameLen > 0)
  12236. {
  12237. const juce_wchar* attNameStart = input;
  12238. input += attNameLen;
  12239. skipNextWhiteSpace();
  12240. if (readNextChar() == '=')
  12241. {
  12242. skipNextWhiteSpace();
  12243. const juce_wchar nextChar = *input;
  12244. if (nextChar == '"' || nextChar == '\'')
  12245. {
  12246. XmlElement::XmlAttributeNode* const newAtt
  12247. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12248. String::empty);
  12249. readQuotedString (newAtt->value);
  12250. if (lastAttribute == 0)
  12251. node->attributes = newAtt;
  12252. else
  12253. lastAttribute->next = newAtt;
  12254. lastAttribute = newAtt;
  12255. continue;
  12256. }
  12257. }
  12258. }
  12259. }
  12260. else
  12261. {
  12262. if (! outOfData)
  12263. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12264. }
  12265. break;
  12266. }
  12267. }
  12268. return node;
  12269. }
  12270. void XmlDocument::readChildElements (XmlElement* parent)
  12271. {
  12272. XmlElement* lastChildNode = 0;
  12273. for (;;)
  12274. {
  12275. const juce_wchar* const preWhitespaceInput = input;
  12276. skipNextWhiteSpace();
  12277. if (outOfData)
  12278. {
  12279. setLastError ("unmatched tags", false);
  12280. break;
  12281. }
  12282. if (*input == '<')
  12283. {
  12284. if (input[1] == '/')
  12285. {
  12286. // our close tag..
  12287. input = CharacterFunctions::find (input, JUCE_T(">"));
  12288. ++input;
  12289. break;
  12290. }
  12291. else if (input[1] == '!'
  12292. && input[2] == '['
  12293. && input[3] == 'C'
  12294. && input[4] == 'D'
  12295. && input[5] == 'A'
  12296. && input[6] == 'T'
  12297. && input[7] == 'A'
  12298. && input[8] == '[')
  12299. {
  12300. input += 9;
  12301. const juce_wchar* const inputStart = input;
  12302. int len = 0;
  12303. for (;;)
  12304. {
  12305. if (*input == 0)
  12306. {
  12307. setLastError ("unterminated CDATA section", false);
  12308. outOfData = true;
  12309. break;
  12310. }
  12311. else if (input[0] == ']'
  12312. && input[1] == ']'
  12313. && input[2] == '>')
  12314. {
  12315. input += 3;
  12316. break;
  12317. }
  12318. ++input;
  12319. ++len;
  12320. }
  12321. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  12322. if (lastChildNode != 0)
  12323. lastChildNode->nextElement = e;
  12324. else
  12325. parent->addChildElement (e);
  12326. lastChildNode = e;
  12327. }
  12328. else
  12329. {
  12330. // this is some other element, so parse and add it..
  12331. XmlElement* const n = readNextElement (true);
  12332. if (n != 0)
  12333. {
  12334. if (lastChildNode == 0)
  12335. parent->addChildElement (n);
  12336. else
  12337. lastChildNode->nextElement = n;
  12338. lastChildNode = n;
  12339. }
  12340. else
  12341. {
  12342. return;
  12343. }
  12344. }
  12345. }
  12346. else // must be a character block
  12347. {
  12348. input = preWhitespaceInput; // roll back to include the leading whitespace
  12349. String textElementContent;
  12350. for (;;)
  12351. {
  12352. const juce_wchar c = *input;
  12353. if (c == '<')
  12354. break;
  12355. if (c == 0)
  12356. {
  12357. setLastError ("unmatched tags", false);
  12358. outOfData = true;
  12359. return;
  12360. }
  12361. if (c == '&')
  12362. {
  12363. String entity;
  12364. readEntity (entity);
  12365. if (entity.startsWithChar ('<') && entity [1] != 0)
  12366. {
  12367. const juce_wchar* const oldInput = input;
  12368. const bool oldOutOfData = outOfData;
  12369. input = entity;
  12370. outOfData = false;
  12371. for (;;)
  12372. {
  12373. XmlElement* const n = readNextElement (true);
  12374. if (n == 0)
  12375. break;
  12376. if (lastChildNode == 0)
  12377. parent->addChildElement (n);
  12378. else
  12379. lastChildNode->nextElement = n;
  12380. lastChildNode = n;
  12381. }
  12382. input = oldInput;
  12383. outOfData = oldOutOfData;
  12384. }
  12385. else
  12386. {
  12387. textElementContent += entity;
  12388. }
  12389. }
  12390. else
  12391. {
  12392. const juce_wchar* start = input;
  12393. int len = 0;
  12394. for (;;)
  12395. {
  12396. const juce_wchar nextChar = *input;
  12397. if (nextChar == '<' || nextChar == '&')
  12398. {
  12399. break;
  12400. }
  12401. else if (nextChar == 0)
  12402. {
  12403. setLastError ("unmatched tags", false);
  12404. outOfData = true;
  12405. return;
  12406. }
  12407. ++input;
  12408. ++len;
  12409. }
  12410. textElementContent.append (start, len);
  12411. }
  12412. }
  12413. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12414. {
  12415. XmlElement* const textElement = XmlElement::createTextElement (textElementContent);
  12416. if (lastChildNode != 0)
  12417. lastChildNode->nextElement = textElement;
  12418. else
  12419. parent->addChildElement (textElement);
  12420. lastChildNode = textElement;
  12421. }
  12422. }
  12423. }
  12424. }
  12425. void XmlDocument::readEntity (String& result)
  12426. {
  12427. // skip over the ampersand
  12428. ++input;
  12429. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12430. {
  12431. input += 4;
  12432. result += '&';
  12433. }
  12434. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12435. {
  12436. input += 5;
  12437. result += '"';
  12438. }
  12439. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12440. {
  12441. input += 5;
  12442. result += '\'';
  12443. }
  12444. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12445. {
  12446. input += 3;
  12447. result += '<';
  12448. }
  12449. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12450. {
  12451. input += 3;
  12452. result += '>';
  12453. }
  12454. else if (*input == '#')
  12455. {
  12456. int charCode = 0;
  12457. ++input;
  12458. if (*input == 'x' || *input == 'X')
  12459. {
  12460. ++input;
  12461. int numChars = 0;
  12462. while (input[0] != ';')
  12463. {
  12464. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12465. if (hexValue < 0 || ++numChars > 8)
  12466. {
  12467. setLastError ("illegal escape sequence", true);
  12468. break;
  12469. }
  12470. charCode = (charCode << 4) | hexValue;
  12471. ++input;
  12472. }
  12473. ++input;
  12474. }
  12475. else if (input[0] >= '0' && input[0] <= '9')
  12476. {
  12477. int numChars = 0;
  12478. while (input[0] != ';')
  12479. {
  12480. if (++numChars > 12)
  12481. {
  12482. setLastError ("illegal escape sequence", true);
  12483. break;
  12484. }
  12485. charCode = charCode * 10 + (input[0] - '0');
  12486. ++input;
  12487. }
  12488. ++input;
  12489. }
  12490. else
  12491. {
  12492. setLastError ("illegal escape sequence", true);
  12493. result += '&';
  12494. return;
  12495. }
  12496. result << (juce_wchar) charCode;
  12497. }
  12498. else
  12499. {
  12500. const juce_wchar* const entityNameStart = input;
  12501. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12502. if (closingSemiColon == 0)
  12503. {
  12504. outOfData = true;
  12505. result += '&';
  12506. }
  12507. else
  12508. {
  12509. input = closingSemiColon + 1;
  12510. result += expandExternalEntity (String (entityNameStart,
  12511. (int) (closingSemiColon - entityNameStart)));
  12512. }
  12513. }
  12514. }
  12515. const String XmlDocument::expandEntity (const String& ent)
  12516. {
  12517. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12518. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12519. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12520. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12521. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12522. if (ent[0] == '#')
  12523. {
  12524. if (ent[1] == 'x' || ent[1] == 'X')
  12525. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12526. if (ent[1] >= '0' && ent[1] <= '9')
  12527. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12528. setLastError ("illegal escape sequence", false);
  12529. return String::charToString ('&');
  12530. }
  12531. return expandExternalEntity (ent);
  12532. }
  12533. const String XmlDocument::expandExternalEntity (const String& entity)
  12534. {
  12535. if (needToLoadDTD)
  12536. {
  12537. if (dtdText.isNotEmpty())
  12538. {
  12539. dtdText = dtdText.trimCharactersAtEnd (">");
  12540. tokenisedDTD.addTokens (dtdText, true);
  12541. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12542. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12543. {
  12544. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12545. tokenisedDTD.clear();
  12546. tokenisedDTD.addTokens (getFileContents (fn), true);
  12547. }
  12548. else
  12549. {
  12550. tokenisedDTD.clear();
  12551. const int openBracket = dtdText.indexOfChar ('[');
  12552. if (openBracket > 0)
  12553. {
  12554. const int closeBracket = dtdText.lastIndexOfChar (']');
  12555. if (closeBracket > openBracket)
  12556. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12557. closeBracket), true);
  12558. }
  12559. }
  12560. for (int i = tokenisedDTD.size(); --i >= 0;)
  12561. {
  12562. if (tokenisedDTD[i].startsWithChar ('%')
  12563. && tokenisedDTD[i].endsWithChar (';'))
  12564. {
  12565. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12566. StringArray newToks;
  12567. newToks.addTokens (parsed, true);
  12568. tokenisedDTD.remove (i);
  12569. for (int j = newToks.size(); --j >= 0;)
  12570. tokenisedDTD.insert (i, newToks[j]);
  12571. }
  12572. }
  12573. }
  12574. needToLoadDTD = false;
  12575. }
  12576. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12577. {
  12578. if (tokenisedDTD[i] == entity)
  12579. {
  12580. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12581. {
  12582. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12583. // check for sub-entities..
  12584. int ampersand = ent.indexOfChar ('&');
  12585. while (ampersand >= 0)
  12586. {
  12587. const int semiColon = ent.indexOf (i + 1, ";");
  12588. if (semiColon < 0)
  12589. {
  12590. setLastError ("entity without terminating semi-colon", false);
  12591. break;
  12592. }
  12593. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12594. ent = ent.substring (0, ampersand)
  12595. + resolved
  12596. + ent.substring (semiColon + 1);
  12597. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12598. }
  12599. return ent;
  12600. }
  12601. }
  12602. }
  12603. setLastError ("unknown entity", true);
  12604. return entity;
  12605. }
  12606. const String XmlDocument::getParameterEntity (const String& entity)
  12607. {
  12608. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12609. {
  12610. if (tokenisedDTD[i] == entity)
  12611. {
  12612. if (tokenisedDTD [i - 1] == "%"
  12613. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12614. {
  12615. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12616. if (ent.equalsIgnoreCase ("system"))
  12617. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12618. else
  12619. return ent.trim().unquoted();
  12620. }
  12621. }
  12622. }
  12623. return entity;
  12624. }
  12625. END_JUCE_NAMESPACE
  12626. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12627. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12628. BEGIN_JUCE_NAMESPACE
  12629. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12630. : name (other.name),
  12631. value (other.value),
  12632. next (0)
  12633. {
  12634. }
  12635. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12636. : name (name_),
  12637. value (value_),
  12638. next (0)
  12639. {
  12640. #if JUCE_DEBUG
  12641. // this checks whether the attribute name string contains any illegals characters..
  12642. for (const juce_wchar* t = name; *t != 0; ++t)
  12643. jassert (CharacterFunctions::isLetterOrDigit (*t) || *t == '_' || *t == '-' || *t == ':');
  12644. #endif
  12645. }
  12646. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12647. {
  12648. return name.equalsIgnoreCase (nameToMatch);
  12649. }
  12650. XmlElement::XmlElement (const String& tagName_) throw()
  12651. : tagName (tagName_),
  12652. firstChildElement (0),
  12653. nextElement (0),
  12654. attributes (0)
  12655. {
  12656. // the tag name mustn't be empty, or it'll look like a text element!
  12657. jassert (tagName_.containsNonWhitespaceChars())
  12658. // The tag can't contain spaces or other characters that would create invalid XML!
  12659. jassert (! tagName_.containsAnyOf (" <>/&"));
  12660. }
  12661. XmlElement::XmlElement (int /*dummy*/) throw()
  12662. : firstChildElement (0),
  12663. nextElement (0),
  12664. attributes (0)
  12665. {
  12666. }
  12667. XmlElement::XmlElement (const XmlElement& other)
  12668. : tagName (other.tagName),
  12669. firstChildElement (0),
  12670. nextElement (0),
  12671. attributes (0)
  12672. {
  12673. copyChildrenAndAttributesFrom (other);
  12674. }
  12675. XmlElement& XmlElement::operator= (const XmlElement& other)
  12676. {
  12677. if (this != &other)
  12678. {
  12679. removeAllAttributes();
  12680. deleteAllChildElements();
  12681. tagName = other.tagName;
  12682. copyChildrenAndAttributesFrom (other);
  12683. }
  12684. return *this;
  12685. }
  12686. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12687. {
  12688. XmlElement* child = other.firstChildElement;
  12689. XmlElement* lastChild = 0;
  12690. while (child != 0)
  12691. {
  12692. XmlElement* const copiedChild = new XmlElement (*child);
  12693. if (lastChild != 0)
  12694. lastChild->nextElement = copiedChild;
  12695. else
  12696. firstChildElement = copiedChild;
  12697. lastChild = copiedChild;
  12698. child = child->nextElement;
  12699. }
  12700. const XmlAttributeNode* att = other.attributes;
  12701. XmlAttributeNode* lastAtt = 0;
  12702. while (att != 0)
  12703. {
  12704. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12705. if (lastAtt != 0)
  12706. lastAtt->next = newAtt;
  12707. else
  12708. attributes = newAtt;
  12709. lastAtt = newAtt;
  12710. att = att->next;
  12711. }
  12712. }
  12713. XmlElement::~XmlElement() throw()
  12714. {
  12715. XmlElement* child = firstChildElement;
  12716. while (child != 0)
  12717. {
  12718. XmlElement* const nextChild = child->nextElement;
  12719. delete child;
  12720. child = nextChild;
  12721. }
  12722. XmlAttributeNode* att = attributes;
  12723. while (att != 0)
  12724. {
  12725. XmlAttributeNode* const nextAtt = att->next;
  12726. delete att;
  12727. att = nextAtt;
  12728. }
  12729. }
  12730. namespace XmlOutputFunctions
  12731. {
  12732. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12733. {
  12734. if ((character >= 'a' && character <= 'z')
  12735. || (character >= 'A' && character <= 'Z')
  12736. || (character >= '0' && character <= '9'))
  12737. return true;
  12738. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12739. do
  12740. {
  12741. if (((juce_wchar) (uint8) *t) == character)
  12742. return true;
  12743. }
  12744. while (*++t != 0);
  12745. return false;
  12746. }
  12747. void generateLegalCharConstants()
  12748. {
  12749. uint8 n[32];
  12750. zerostruct (n);
  12751. for (int i = 0; i < 256; ++i)
  12752. if (isLegalXmlCharSlow (i))
  12753. n[i >> 3] |= (1 << (i & 7));
  12754. String s;
  12755. for (int i = 0; i < 32; ++i)
  12756. s << (int) n[i] << ", ";
  12757. DBG (s);
  12758. }*/
  12759. bool isLegalXmlChar (const uint32 c) throw()
  12760. {
  12761. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12762. return c < sizeof (legalChars) * 8
  12763. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12764. }
  12765. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12766. {
  12767. const juce_wchar* t = text;
  12768. for (;;)
  12769. {
  12770. const juce_wchar character = *t++;
  12771. if (character == 0)
  12772. break;
  12773. if (isLegalXmlChar ((uint32) character))
  12774. {
  12775. outputStream << (char) character;
  12776. }
  12777. else
  12778. {
  12779. switch (character)
  12780. {
  12781. case '&': outputStream << "&amp;"; break;
  12782. case '"': outputStream << "&quot;"; break;
  12783. case '>': outputStream << "&gt;"; break;
  12784. case '<': outputStream << "&lt;"; break;
  12785. case '\n':
  12786. case '\r':
  12787. if (! changeNewLines)
  12788. {
  12789. outputStream << (char) character;
  12790. break;
  12791. }
  12792. // Note: deliberate fall-through here!
  12793. default:
  12794. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12795. break;
  12796. }
  12797. }
  12798. }
  12799. }
  12800. void writeSpaces (OutputStream& out, int numSpaces)
  12801. {
  12802. if (numSpaces > 0)
  12803. {
  12804. const char blanks[] = " ";
  12805. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12806. while (numSpaces > blankSize)
  12807. {
  12808. out.write (blanks, blankSize);
  12809. numSpaces -= blankSize;
  12810. }
  12811. out.write (blanks, numSpaces);
  12812. }
  12813. }
  12814. void writeNewLine (OutputStream& out)
  12815. {
  12816. out.write ("\r\n", 2);
  12817. }
  12818. }
  12819. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12820. const int indentationLevel,
  12821. const int lineWrapLength) const
  12822. {
  12823. using namespace XmlOutputFunctions;
  12824. writeSpaces (outputStream, indentationLevel);
  12825. if (! isTextElement())
  12826. {
  12827. outputStream.writeByte ('<');
  12828. outputStream << tagName;
  12829. {
  12830. const int attIndent = indentationLevel + tagName.length() + 1;
  12831. int lineLen = 0;
  12832. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12833. {
  12834. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12835. {
  12836. writeNewLine (outputStream);
  12837. writeSpaces (outputStream, attIndent);
  12838. lineLen = 0;
  12839. }
  12840. const int64 startPos = outputStream.getPosition();
  12841. outputStream.writeByte (' ');
  12842. outputStream << att->name;
  12843. outputStream.write ("=\"", 2);
  12844. escapeIllegalXmlChars (outputStream, att->value, true);
  12845. outputStream.writeByte ('"');
  12846. lineLen += (int) (outputStream.getPosition() - startPos);
  12847. }
  12848. }
  12849. if (firstChildElement != 0)
  12850. {
  12851. outputStream.writeByte ('>');
  12852. XmlElement* child = firstChildElement;
  12853. bool lastWasTextNode = false;
  12854. while (child != 0)
  12855. {
  12856. if (child->isTextElement())
  12857. {
  12858. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12859. lastWasTextNode = true;
  12860. }
  12861. else
  12862. {
  12863. if (indentationLevel >= 0 && ! lastWasTextNode)
  12864. writeNewLine (outputStream);
  12865. child->writeElementAsText (outputStream,
  12866. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12867. lastWasTextNode = false;
  12868. }
  12869. child = child->nextElement;
  12870. }
  12871. if (indentationLevel >= 0 && ! lastWasTextNode)
  12872. {
  12873. writeNewLine (outputStream);
  12874. writeSpaces (outputStream, indentationLevel);
  12875. }
  12876. outputStream.write ("</", 2);
  12877. outputStream << tagName;
  12878. outputStream.writeByte ('>');
  12879. }
  12880. else
  12881. {
  12882. outputStream.write ("/>", 2);
  12883. }
  12884. }
  12885. else
  12886. {
  12887. escapeIllegalXmlChars (outputStream, getText(), false);
  12888. }
  12889. }
  12890. const String XmlElement::createDocument (const String& dtdToUse,
  12891. const bool allOnOneLine,
  12892. const bool includeXmlHeader,
  12893. const String& encodingType,
  12894. const int lineWrapLength) const
  12895. {
  12896. MemoryOutputStream mem (2048);
  12897. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12898. return mem.toUTF8();
  12899. }
  12900. void XmlElement::writeToStream (OutputStream& output,
  12901. const String& dtdToUse,
  12902. const bool allOnOneLine,
  12903. const bool includeXmlHeader,
  12904. const String& encodingType,
  12905. const int lineWrapLength) const
  12906. {
  12907. using namespace XmlOutputFunctions;
  12908. if (includeXmlHeader)
  12909. {
  12910. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12911. if (allOnOneLine)
  12912. {
  12913. output.writeByte (' ');
  12914. }
  12915. else
  12916. {
  12917. writeNewLine (output);
  12918. writeNewLine (output);
  12919. }
  12920. }
  12921. if (dtdToUse.isNotEmpty())
  12922. {
  12923. output << dtdToUse;
  12924. if (allOnOneLine)
  12925. output.writeByte (' ');
  12926. else
  12927. writeNewLine (output);
  12928. }
  12929. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12930. if (! allOnOneLine)
  12931. writeNewLine (output);
  12932. }
  12933. bool XmlElement::writeToFile (const File& file,
  12934. const String& dtdToUse,
  12935. const String& encodingType,
  12936. const int lineWrapLength) const
  12937. {
  12938. if (file.hasWriteAccess())
  12939. {
  12940. TemporaryFile tempFile (file);
  12941. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12942. if (out != 0)
  12943. {
  12944. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12945. out = 0;
  12946. return tempFile.overwriteTargetFileWithTemporary();
  12947. }
  12948. }
  12949. return false;
  12950. }
  12951. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12952. {
  12953. #if JUCE_DEBUG
  12954. // if debugging, check that the case is actually the same, because
  12955. // valid xml is case-sensitive, and although this lets it pass, it's
  12956. // better not to..
  12957. if (tagName.equalsIgnoreCase (tagNameWanted))
  12958. {
  12959. jassert (tagName == tagNameWanted);
  12960. return true;
  12961. }
  12962. else
  12963. {
  12964. return false;
  12965. }
  12966. #else
  12967. return tagName.equalsIgnoreCase (tagNameWanted);
  12968. #endif
  12969. }
  12970. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12971. {
  12972. XmlElement* e = nextElement;
  12973. while (e != 0 && ! e->hasTagName (requiredTagName))
  12974. e = e->nextElement;
  12975. return e;
  12976. }
  12977. int XmlElement::getNumAttributes() const throw()
  12978. {
  12979. int count = 0;
  12980. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12981. ++count;
  12982. return count;
  12983. }
  12984. const String& XmlElement::getAttributeName (const int index) const throw()
  12985. {
  12986. int count = 0;
  12987. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12988. {
  12989. if (count == index)
  12990. return att->name;
  12991. ++count;
  12992. }
  12993. return String::empty;
  12994. }
  12995. const String& XmlElement::getAttributeValue (const int index) const throw()
  12996. {
  12997. int count = 0;
  12998. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12999. {
  13000. if (count == index)
  13001. return att->value;
  13002. ++count;
  13003. }
  13004. return String::empty;
  13005. }
  13006. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  13007. {
  13008. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13009. if (att->hasName (attributeName))
  13010. return true;
  13011. return false;
  13012. }
  13013. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  13014. {
  13015. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13016. if (att->hasName (attributeName))
  13017. return att->value;
  13018. return String::empty;
  13019. }
  13020. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  13021. {
  13022. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13023. if (att->hasName (attributeName))
  13024. return att->value;
  13025. return defaultReturnValue;
  13026. }
  13027. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  13028. {
  13029. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13030. if (att->hasName (attributeName))
  13031. return att->value.getIntValue();
  13032. return defaultReturnValue;
  13033. }
  13034. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  13035. {
  13036. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13037. if (att->hasName (attributeName))
  13038. return att->value.getDoubleValue();
  13039. return defaultReturnValue;
  13040. }
  13041. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  13042. {
  13043. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13044. {
  13045. if (att->hasName (attributeName))
  13046. {
  13047. juce_wchar firstChar = att->value[0];
  13048. if (CharacterFunctions::isWhitespace (firstChar))
  13049. firstChar = att->value.trimStart() [0];
  13050. return firstChar == '1'
  13051. || firstChar == 't'
  13052. || firstChar == 'y'
  13053. || firstChar == 'T'
  13054. || firstChar == 'Y';
  13055. }
  13056. }
  13057. return defaultReturnValue;
  13058. }
  13059. bool XmlElement::compareAttribute (const String& attributeName,
  13060. const String& stringToCompareAgainst,
  13061. const bool ignoreCase) const throw()
  13062. {
  13063. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13064. if (att->hasName (attributeName))
  13065. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  13066. : att->value == stringToCompareAgainst;
  13067. return false;
  13068. }
  13069. void XmlElement::setAttribute (const String& attributeName, const String& value)
  13070. {
  13071. if (attributes == 0)
  13072. {
  13073. attributes = new XmlAttributeNode (attributeName, value);
  13074. }
  13075. else
  13076. {
  13077. XmlAttributeNode* att = attributes;
  13078. for (;;)
  13079. {
  13080. if (att->hasName (attributeName))
  13081. {
  13082. att->value = value;
  13083. break;
  13084. }
  13085. else if (att->next == 0)
  13086. {
  13087. att->next = new XmlAttributeNode (attributeName, value);
  13088. break;
  13089. }
  13090. att = att->next;
  13091. }
  13092. }
  13093. }
  13094. void XmlElement::setAttribute (const String& attributeName, const int number)
  13095. {
  13096. setAttribute (attributeName, String (number));
  13097. }
  13098. void XmlElement::setAttribute (const String& attributeName, const double number)
  13099. {
  13100. setAttribute (attributeName, String (number));
  13101. }
  13102. void XmlElement::removeAttribute (const String& attributeName) throw()
  13103. {
  13104. XmlAttributeNode* lastAtt = 0;
  13105. for (XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13106. {
  13107. if (att->hasName (attributeName))
  13108. {
  13109. if (lastAtt == 0)
  13110. attributes = att->next;
  13111. else
  13112. lastAtt->next = att->next;
  13113. delete att;
  13114. break;
  13115. }
  13116. lastAtt = att;
  13117. }
  13118. }
  13119. void XmlElement::removeAllAttributes() throw()
  13120. {
  13121. while (attributes != 0)
  13122. {
  13123. XmlAttributeNode* const nextAtt = attributes->next;
  13124. delete attributes;
  13125. attributes = nextAtt;
  13126. }
  13127. }
  13128. int XmlElement::getNumChildElements() const throw()
  13129. {
  13130. int count = 0;
  13131. const XmlElement* child = firstChildElement;
  13132. while (child != 0)
  13133. {
  13134. ++count;
  13135. child = child->nextElement;
  13136. }
  13137. return count;
  13138. }
  13139. XmlElement* XmlElement::getChildElement (const int index) const throw()
  13140. {
  13141. int count = 0;
  13142. XmlElement* child = firstChildElement;
  13143. while (child != 0 && count < index)
  13144. {
  13145. child = child->nextElement;
  13146. ++count;
  13147. }
  13148. return child;
  13149. }
  13150. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  13151. {
  13152. XmlElement* child = firstChildElement;
  13153. while (child != 0)
  13154. {
  13155. if (child->hasTagName (childName))
  13156. break;
  13157. child = child->nextElement;
  13158. }
  13159. return child;
  13160. }
  13161. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  13162. {
  13163. if (newNode != 0)
  13164. {
  13165. if (firstChildElement == 0)
  13166. {
  13167. firstChildElement = newNode;
  13168. }
  13169. else
  13170. {
  13171. XmlElement* child = firstChildElement;
  13172. while (child->nextElement != 0)
  13173. child = child->nextElement;
  13174. child->nextElement = newNode;
  13175. // if this is non-zero, then something's probably
  13176. // gone wrong..
  13177. jassert (newNode->nextElement == 0);
  13178. }
  13179. }
  13180. }
  13181. void XmlElement::insertChildElement (XmlElement* const newNode,
  13182. int indexToInsertAt) throw()
  13183. {
  13184. if (newNode != 0)
  13185. {
  13186. removeChildElement (newNode, false);
  13187. if (indexToInsertAt == 0)
  13188. {
  13189. newNode->nextElement = firstChildElement;
  13190. firstChildElement = newNode;
  13191. }
  13192. else
  13193. {
  13194. if (firstChildElement == 0)
  13195. {
  13196. firstChildElement = newNode;
  13197. }
  13198. else
  13199. {
  13200. if (indexToInsertAt < 0)
  13201. indexToInsertAt = std::numeric_limits<int>::max();
  13202. XmlElement* child = firstChildElement;
  13203. while (child->nextElement != 0 && --indexToInsertAt > 0)
  13204. child = child->nextElement;
  13205. newNode->nextElement = child->nextElement;
  13206. child->nextElement = newNode;
  13207. }
  13208. }
  13209. }
  13210. }
  13211. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  13212. {
  13213. XmlElement* const newElement = new XmlElement (childTagName);
  13214. addChildElement (newElement);
  13215. return newElement;
  13216. }
  13217. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  13218. XmlElement* const newNode) throw()
  13219. {
  13220. if (newNode != 0)
  13221. {
  13222. XmlElement* child = firstChildElement;
  13223. XmlElement* previousNode = 0;
  13224. while (child != 0)
  13225. {
  13226. if (child == currentChildElement)
  13227. {
  13228. if (child != newNode)
  13229. {
  13230. if (previousNode == 0)
  13231. firstChildElement = newNode;
  13232. else
  13233. previousNode->nextElement = newNode;
  13234. newNode->nextElement = child->nextElement;
  13235. delete child;
  13236. }
  13237. return true;
  13238. }
  13239. previousNode = child;
  13240. child = child->nextElement;
  13241. }
  13242. }
  13243. return false;
  13244. }
  13245. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13246. const bool shouldDeleteTheChild) throw()
  13247. {
  13248. if (childToRemove != 0)
  13249. {
  13250. if (firstChildElement == childToRemove)
  13251. {
  13252. firstChildElement = childToRemove->nextElement;
  13253. childToRemove->nextElement = 0;
  13254. }
  13255. else
  13256. {
  13257. XmlElement* child = firstChildElement;
  13258. XmlElement* last = 0;
  13259. while (child != 0)
  13260. {
  13261. if (child == childToRemove)
  13262. {
  13263. if (last == 0)
  13264. firstChildElement = child->nextElement;
  13265. else
  13266. last->nextElement = child->nextElement;
  13267. childToRemove->nextElement = 0;
  13268. break;
  13269. }
  13270. last = child;
  13271. child = child->nextElement;
  13272. }
  13273. }
  13274. if (shouldDeleteTheChild)
  13275. delete childToRemove;
  13276. }
  13277. }
  13278. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13279. const bool ignoreOrderOfAttributes) const throw()
  13280. {
  13281. if (this != other)
  13282. {
  13283. if (other == 0 || tagName != other->tagName)
  13284. return false;
  13285. if (ignoreOrderOfAttributes)
  13286. {
  13287. int totalAtts = 0;
  13288. const XmlAttributeNode* att = attributes;
  13289. while (att != 0)
  13290. {
  13291. if (! other->compareAttribute (att->name, att->value))
  13292. return false;
  13293. att = att->next;
  13294. ++totalAtts;
  13295. }
  13296. if (totalAtts != other->getNumAttributes())
  13297. return false;
  13298. }
  13299. else
  13300. {
  13301. const XmlAttributeNode* thisAtt = attributes;
  13302. const XmlAttributeNode* otherAtt = other->attributes;
  13303. for (;;)
  13304. {
  13305. if (thisAtt == 0 || otherAtt == 0)
  13306. {
  13307. if (thisAtt == otherAtt) // both 0, so it's a match
  13308. break;
  13309. return false;
  13310. }
  13311. if (thisAtt->name != otherAtt->name
  13312. || thisAtt->value != otherAtt->value)
  13313. {
  13314. return false;
  13315. }
  13316. thisAtt = thisAtt->next;
  13317. otherAtt = otherAtt->next;
  13318. }
  13319. }
  13320. const XmlElement* thisChild = firstChildElement;
  13321. const XmlElement* otherChild = other->firstChildElement;
  13322. for (;;)
  13323. {
  13324. if (thisChild == 0 || otherChild == 0)
  13325. {
  13326. if (thisChild == otherChild) // both 0, so it's a match
  13327. break;
  13328. return false;
  13329. }
  13330. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13331. return false;
  13332. thisChild = thisChild->nextElement;
  13333. otherChild = otherChild->nextElement;
  13334. }
  13335. }
  13336. return true;
  13337. }
  13338. void XmlElement::deleteAllChildElements() throw()
  13339. {
  13340. while (firstChildElement != 0)
  13341. {
  13342. XmlElement* const nextChild = firstChildElement->nextElement;
  13343. delete firstChildElement;
  13344. firstChildElement = nextChild;
  13345. }
  13346. }
  13347. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13348. {
  13349. XmlElement* child = firstChildElement;
  13350. while (child != 0)
  13351. {
  13352. if (child->hasTagName (name))
  13353. {
  13354. XmlElement* const nextChild = child->nextElement;
  13355. removeChildElement (child, true);
  13356. child = nextChild;
  13357. }
  13358. else
  13359. {
  13360. child = child->nextElement;
  13361. }
  13362. }
  13363. }
  13364. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13365. {
  13366. const XmlElement* child = firstChildElement;
  13367. while (child != 0)
  13368. {
  13369. if (child == possibleChild)
  13370. return true;
  13371. child = child->nextElement;
  13372. }
  13373. return false;
  13374. }
  13375. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13376. {
  13377. if (this == elementToLookFor || elementToLookFor == 0)
  13378. return 0;
  13379. XmlElement* child = firstChildElement;
  13380. while (child != 0)
  13381. {
  13382. if (elementToLookFor == child)
  13383. return this;
  13384. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13385. if (found != 0)
  13386. return found;
  13387. child = child->nextElement;
  13388. }
  13389. return 0;
  13390. }
  13391. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13392. {
  13393. XmlElement* e = firstChildElement;
  13394. while (e != 0)
  13395. {
  13396. *elems++ = e;
  13397. e = e->nextElement;
  13398. }
  13399. }
  13400. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13401. {
  13402. XmlElement* e = firstChildElement = elems[0];
  13403. for (int i = 1; i < num; ++i)
  13404. {
  13405. e->nextElement = elems[i];
  13406. e = e->nextElement;
  13407. }
  13408. e->nextElement = 0;
  13409. }
  13410. bool XmlElement::isTextElement() const throw()
  13411. {
  13412. return tagName.isEmpty();
  13413. }
  13414. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13415. const String& XmlElement::getText() const throw()
  13416. {
  13417. jassert (isTextElement()); // you're trying to get the text from an element that
  13418. // isn't actually a text element.. If this contains text sub-nodes, you
  13419. // probably want to use getAllSubText instead.
  13420. return getStringAttribute (juce_xmltextContentAttributeName);
  13421. }
  13422. void XmlElement::setText (const String& newText)
  13423. {
  13424. if (isTextElement())
  13425. setAttribute (juce_xmltextContentAttributeName, newText);
  13426. else
  13427. jassertfalse; // you can only change the text in a text element, not a normal one.
  13428. }
  13429. const String XmlElement::getAllSubText() const
  13430. {
  13431. if (isTextElement())
  13432. return getText();
  13433. String result;
  13434. String::Concatenator concatenator (result);
  13435. const XmlElement* child = firstChildElement;
  13436. while (child != 0)
  13437. {
  13438. concatenator.append (child->getAllSubText());
  13439. child = child->nextElement;
  13440. }
  13441. return result;
  13442. }
  13443. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13444. const String& defaultReturnValue) const
  13445. {
  13446. const XmlElement* const child = getChildByName (childTagName);
  13447. if (child != 0)
  13448. return child->getAllSubText();
  13449. return defaultReturnValue;
  13450. }
  13451. XmlElement* XmlElement::createTextElement (const String& text)
  13452. {
  13453. XmlElement* const e = new XmlElement ((int) 0);
  13454. e->setAttribute (juce_xmltextContentAttributeName, text);
  13455. return e;
  13456. }
  13457. void XmlElement::addTextElement (const String& text)
  13458. {
  13459. addChildElement (createTextElement (text));
  13460. }
  13461. void XmlElement::deleteAllTextElements() throw()
  13462. {
  13463. XmlElement* child = firstChildElement;
  13464. while (child != 0)
  13465. {
  13466. XmlElement* const next = child->nextElement;
  13467. if (child->isTextElement())
  13468. removeChildElement (child, true);
  13469. child = next;
  13470. }
  13471. }
  13472. END_JUCE_NAMESPACE
  13473. /*** End of inlined file: juce_XmlElement.cpp ***/
  13474. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13475. BEGIN_JUCE_NAMESPACE
  13476. ReadWriteLock::ReadWriteLock() throw()
  13477. : numWaitingWriters (0),
  13478. numWriters (0),
  13479. writerThreadId (0)
  13480. {
  13481. }
  13482. ReadWriteLock::~ReadWriteLock() throw()
  13483. {
  13484. jassert (readerThreads.size() == 0);
  13485. jassert (numWriters == 0);
  13486. }
  13487. void ReadWriteLock::enterRead() const throw()
  13488. {
  13489. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13490. const ScopedLock sl (accessLock);
  13491. for (;;)
  13492. {
  13493. jassert (readerThreads.size() % 2 == 0);
  13494. int i;
  13495. for (i = 0; i < readerThreads.size(); i += 2)
  13496. if (readerThreads.getUnchecked(i) == threadId)
  13497. break;
  13498. if (i < readerThreads.size()
  13499. || numWriters + numWaitingWriters == 0
  13500. || (threadId == writerThreadId && numWriters > 0))
  13501. {
  13502. if (i < readerThreads.size())
  13503. {
  13504. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13505. }
  13506. else
  13507. {
  13508. readerThreads.add (threadId);
  13509. readerThreads.add ((Thread::ThreadID) 1);
  13510. }
  13511. return;
  13512. }
  13513. const ScopedUnlock ul (accessLock);
  13514. waitEvent.wait (100);
  13515. }
  13516. }
  13517. void ReadWriteLock::exitRead() const throw()
  13518. {
  13519. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13520. const ScopedLock sl (accessLock);
  13521. for (int i = 0; i < readerThreads.size(); i += 2)
  13522. {
  13523. if (readerThreads.getUnchecked(i) == threadId)
  13524. {
  13525. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13526. if (newCount == 0)
  13527. {
  13528. readerThreads.removeRange (i, 2);
  13529. waitEvent.signal();
  13530. }
  13531. else
  13532. {
  13533. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13534. }
  13535. return;
  13536. }
  13537. }
  13538. jassertfalse; // unlocking a lock that wasn't locked..
  13539. }
  13540. void ReadWriteLock::enterWrite() const throw()
  13541. {
  13542. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13543. const ScopedLock sl (accessLock);
  13544. for (;;)
  13545. {
  13546. if (readerThreads.size() + numWriters == 0
  13547. || threadId == writerThreadId
  13548. || (readerThreads.size() == 2
  13549. && readerThreads.getUnchecked(0) == threadId))
  13550. {
  13551. writerThreadId = threadId;
  13552. ++numWriters;
  13553. break;
  13554. }
  13555. ++numWaitingWriters;
  13556. accessLock.exit();
  13557. waitEvent.wait (100);
  13558. accessLock.enter();
  13559. --numWaitingWriters;
  13560. }
  13561. }
  13562. bool ReadWriteLock::tryEnterWrite() const throw()
  13563. {
  13564. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13565. const ScopedLock sl (accessLock);
  13566. if (readerThreads.size() + numWriters == 0
  13567. || threadId == writerThreadId
  13568. || (readerThreads.size() == 2
  13569. && readerThreads.getUnchecked(0) == threadId))
  13570. {
  13571. writerThreadId = threadId;
  13572. ++numWriters;
  13573. return true;
  13574. }
  13575. return false;
  13576. }
  13577. void ReadWriteLock::exitWrite() const throw()
  13578. {
  13579. const ScopedLock sl (accessLock);
  13580. // check this thread actually had the lock..
  13581. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13582. if (--numWriters == 0)
  13583. {
  13584. writerThreadId = 0;
  13585. waitEvent.signal();
  13586. }
  13587. }
  13588. END_JUCE_NAMESPACE
  13589. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13590. /*** Start of inlined file: juce_Thread.cpp ***/
  13591. BEGIN_JUCE_NAMESPACE
  13592. // these functions are implemented in the platform-specific code.
  13593. void* juce_createThread (void* userData);
  13594. void juce_killThread (void* handle);
  13595. bool juce_setThreadPriority (void* handle, int priority);
  13596. void juce_setCurrentThreadName (const String& name);
  13597. #if JUCE_WINDOWS
  13598. void juce_CloseThreadHandle (void* handle);
  13599. #endif
  13600. void Thread::threadEntryPoint (Thread* const thread)
  13601. {
  13602. {
  13603. const ScopedLock sl (runningThreadsLock);
  13604. runningThreads.add (thread);
  13605. }
  13606. JUCE_TRY
  13607. {
  13608. thread->threadId_ = Thread::getCurrentThreadId();
  13609. if (thread->threadName_.isNotEmpty())
  13610. juce_setCurrentThreadName (thread->threadName_);
  13611. if (thread->startSuspensionEvent_.wait (10000))
  13612. {
  13613. if (thread->affinityMask_ != 0)
  13614. setCurrentThreadAffinityMask (thread->affinityMask_);
  13615. thread->run();
  13616. }
  13617. }
  13618. JUCE_CATCH_ALL_ASSERT
  13619. {
  13620. const ScopedLock sl (runningThreadsLock);
  13621. jassert (runningThreads.contains (thread));
  13622. runningThreads.removeValue (thread);
  13623. }
  13624. #if JUCE_WINDOWS
  13625. juce_CloseThreadHandle (thread->threadHandle_);
  13626. #endif
  13627. thread->threadHandle_ = 0;
  13628. thread->threadId_ = 0;
  13629. }
  13630. // used to wrap the incoming call from the platform-specific code
  13631. void JUCE_API juce_threadEntryPoint (void* userData)
  13632. {
  13633. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13634. }
  13635. Thread::Thread (const String& threadName)
  13636. : threadName_ (threadName),
  13637. threadHandle_ (0),
  13638. threadPriority_ (5),
  13639. threadId_ (0),
  13640. affinityMask_ (0),
  13641. threadShouldExit_ (false)
  13642. {
  13643. }
  13644. Thread::~Thread()
  13645. {
  13646. /* If your thread class's destructor has been called without first stopping the thread, that
  13647. means that this partially destructed object is still performing some work - and that's not
  13648. unlikely to be a safe approach to take!
  13649. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13650. your subclass's destructor.
  13651. */
  13652. jassert (! isThreadRunning());
  13653. stopThread (100);
  13654. }
  13655. void Thread::startThread()
  13656. {
  13657. const ScopedLock sl (startStopLock);
  13658. threadShouldExit_ = false;
  13659. if (threadHandle_ == 0)
  13660. {
  13661. threadHandle_ = juce_createThread (this);
  13662. juce_setThreadPriority (threadHandle_, threadPriority_);
  13663. startSuspensionEvent_.signal();
  13664. }
  13665. }
  13666. void Thread::startThread (const int priority)
  13667. {
  13668. const ScopedLock sl (startStopLock);
  13669. if (threadHandle_ == 0)
  13670. {
  13671. threadPriority_ = priority;
  13672. startThread();
  13673. }
  13674. else
  13675. {
  13676. setPriority (priority);
  13677. }
  13678. }
  13679. bool Thread::isThreadRunning() const
  13680. {
  13681. return threadHandle_ != 0;
  13682. }
  13683. void Thread::signalThreadShouldExit()
  13684. {
  13685. threadShouldExit_ = true;
  13686. }
  13687. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13688. {
  13689. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13690. jassert (getThreadId() != getCurrentThreadId());
  13691. const int sleepMsPerIteration = 5;
  13692. int count = timeOutMilliseconds / sleepMsPerIteration;
  13693. while (isThreadRunning())
  13694. {
  13695. if (timeOutMilliseconds > 0 && --count < 0)
  13696. return false;
  13697. sleep (sleepMsPerIteration);
  13698. }
  13699. return true;
  13700. }
  13701. void Thread::stopThread (const int timeOutMilliseconds)
  13702. {
  13703. // agh! You can't stop the thread that's calling this method! How on earth
  13704. // would that work??
  13705. jassert (getCurrentThreadId() != getThreadId());
  13706. const ScopedLock sl (startStopLock);
  13707. if (isThreadRunning())
  13708. {
  13709. signalThreadShouldExit();
  13710. notify();
  13711. if (timeOutMilliseconds != 0)
  13712. waitForThreadToExit (timeOutMilliseconds);
  13713. if (isThreadRunning())
  13714. {
  13715. // very bad karma if this point is reached, as
  13716. // there are bound to be locks and events left in
  13717. // silly states when a thread is killed by force..
  13718. jassertfalse;
  13719. Logger::writeToLog ("!! killing thread by force !!");
  13720. juce_killThread (threadHandle_);
  13721. threadHandle_ = 0;
  13722. threadId_ = 0;
  13723. const ScopedLock sl2 (runningThreadsLock);
  13724. runningThreads.removeValue (this);
  13725. }
  13726. }
  13727. }
  13728. bool Thread::setPriority (const int priority)
  13729. {
  13730. const ScopedLock sl (startStopLock);
  13731. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13732. if (worked)
  13733. threadPriority_ = priority;
  13734. return worked;
  13735. }
  13736. bool Thread::setCurrentThreadPriority (const int priority)
  13737. {
  13738. return juce_setThreadPriority (0, priority);
  13739. }
  13740. void Thread::setAffinityMask (const uint32 affinityMask)
  13741. {
  13742. affinityMask_ = affinityMask;
  13743. }
  13744. bool Thread::wait (const int timeOutMilliseconds) const
  13745. {
  13746. return defaultEvent_.wait (timeOutMilliseconds);
  13747. }
  13748. void Thread::notify() const
  13749. {
  13750. defaultEvent_.signal();
  13751. }
  13752. int Thread::getNumRunningThreads()
  13753. {
  13754. return runningThreads.size();
  13755. }
  13756. Thread* Thread::getCurrentThread()
  13757. {
  13758. const ThreadID thisId = getCurrentThreadId();
  13759. const ScopedLock sl (runningThreadsLock);
  13760. for (int i = runningThreads.size(); --i >= 0;)
  13761. {
  13762. Thread* const t = runningThreads.getUnchecked(i);
  13763. if (t->threadId_ == thisId)
  13764. return t;
  13765. }
  13766. return 0;
  13767. }
  13768. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13769. {
  13770. {
  13771. const ScopedLock sl (runningThreadsLock);
  13772. for (int i = runningThreads.size(); --i >= 0;)
  13773. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13774. }
  13775. for (;;)
  13776. {
  13777. Thread* firstThread;
  13778. {
  13779. const ScopedLock sl (runningThreadsLock);
  13780. firstThread = runningThreads.getFirst();
  13781. }
  13782. if (firstThread == 0)
  13783. break;
  13784. firstThread->stopThread (timeOutMilliseconds);
  13785. }
  13786. }
  13787. Array<Thread*> Thread::runningThreads;
  13788. CriticalSection Thread::runningThreadsLock;
  13789. END_JUCE_NAMESPACE
  13790. /*** End of inlined file: juce_Thread.cpp ***/
  13791. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13792. BEGIN_JUCE_NAMESPACE
  13793. ThreadPoolJob::ThreadPoolJob (const String& name)
  13794. : jobName (name),
  13795. pool (0),
  13796. shouldStop (false),
  13797. isActive (false),
  13798. shouldBeDeleted (false)
  13799. {
  13800. }
  13801. ThreadPoolJob::~ThreadPoolJob()
  13802. {
  13803. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13804. // to remove it first!
  13805. jassert (pool == 0 || ! pool->contains (this));
  13806. }
  13807. const String ThreadPoolJob::getJobName() const
  13808. {
  13809. return jobName;
  13810. }
  13811. void ThreadPoolJob::setJobName (const String& newName)
  13812. {
  13813. jobName = newName;
  13814. }
  13815. void ThreadPoolJob::signalJobShouldExit()
  13816. {
  13817. shouldStop = true;
  13818. }
  13819. class ThreadPool::ThreadPoolThread : public Thread
  13820. {
  13821. public:
  13822. ThreadPoolThread (ThreadPool& pool_)
  13823. : Thread ("Pool"),
  13824. pool (pool_),
  13825. busy (false)
  13826. {
  13827. }
  13828. void run()
  13829. {
  13830. while (! threadShouldExit())
  13831. {
  13832. if (! pool.runNextJob())
  13833. wait (500);
  13834. }
  13835. }
  13836. private:
  13837. ThreadPool& pool;
  13838. bool volatile busy;
  13839. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13840. };
  13841. ThreadPool::ThreadPool (const int numThreads,
  13842. const bool startThreadsOnlyWhenNeeded,
  13843. const int stopThreadsWhenNotUsedTimeoutMs)
  13844. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13845. priority (5)
  13846. {
  13847. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13848. for (int i = jmax (1, numThreads); --i >= 0;)
  13849. threads.add (new ThreadPoolThread (*this));
  13850. if (! startThreadsOnlyWhenNeeded)
  13851. for (int i = threads.size(); --i >= 0;)
  13852. threads.getUnchecked(i)->startThread (priority);
  13853. }
  13854. ThreadPool::~ThreadPool()
  13855. {
  13856. removeAllJobs (true, 4000);
  13857. int i;
  13858. for (i = threads.size(); --i >= 0;)
  13859. threads.getUnchecked(i)->signalThreadShouldExit();
  13860. for (i = threads.size(); --i >= 0;)
  13861. threads.getUnchecked(i)->stopThread (500);
  13862. }
  13863. void ThreadPool::addJob (ThreadPoolJob* const job)
  13864. {
  13865. jassert (job != 0);
  13866. jassert (job->pool == 0);
  13867. if (job->pool == 0)
  13868. {
  13869. job->pool = this;
  13870. job->shouldStop = false;
  13871. job->isActive = false;
  13872. {
  13873. const ScopedLock sl (lock);
  13874. jobs.add (job);
  13875. int numRunning = 0;
  13876. for (int i = threads.size(); --i >= 0;)
  13877. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13878. ++numRunning;
  13879. if (numRunning < threads.size())
  13880. {
  13881. bool startedOne = false;
  13882. int n = 1000;
  13883. while (--n >= 0 && ! startedOne)
  13884. {
  13885. for (int i = threads.size(); --i >= 0;)
  13886. {
  13887. if (! threads.getUnchecked(i)->isThreadRunning())
  13888. {
  13889. threads.getUnchecked(i)->startThread (priority);
  13890. startedOne = true;
  13891. break;
  13892. }
  13893. }
  13894. if (! startedOne)
  13895. Thread::sleep (2);
  13896. }
  13897. }
  13898. }
  13899. for (int i = threads.size(); --i >= 0;)
  13900. threads.getUnchecked(i)->notify();
  13901. }
  13902. }
  13903. int ThreadPool::getNumJobs() const
  13904. {
  13905. return jobs.size();
  13906. }
  13907. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13908. {
  13909. const ScopedLock sl (lock);
  13910. return jobs [index];
  13911. }
  13912. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13913. {
  13914. const ScopedLock sl (lock);
  13915. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13916. }
  13917. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13918. {
  13919. const ScopedLock sl (lock);
  13920. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13921. }
  13922. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13923. const int timeOutMs) const
  13924. {
  13925. if (job != 0)
  13926. {
  13927. const uint32 start = Time::getMillisecondCounter();
  13928. while (contains (job))
  13929. {
  13930. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13931. return false;
  13932. jobFinishedSignal.wait (2);
  13933. }
  13934. }
  13935. return true;
  13936. }
  13937. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13938. const bool interruptIfRunning,
  13939. const int timeOutMs)
  13940. {
  13941. bool dontWait = true;
  13942. if (job != 0)
  13943. {
  13944. const ScopedLock sl (lock);
  13945. if (jobs.contains (job))
  13946. {
  13947. if (job->isActive)
  13948. {
  13949. if (interruptIfRunning)
  13950. job->signalJobShouldExit();
  13951. dontWait = false;
  13952. }
  13953. else
  13954. {
  13955. jobs.removeValue (job);
  13956. job->pool = 0;
  13957. }
  13958. }
  13959. }
  13960. return dontWait || waitForJobToFinish (job, timeOutMs);
  13961. }
  13962. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13963. const int timeOutMs,
  13964. const bool deleteInactiveJobs,
  13965. ThreadPool::JobSelector* selectedJobsToRemove)
  13966. {
  13967. Array <ThreadPoolJob*> jobsToWaitFor;
  13968. {
  13969. const ScopedLock sl (lock);
  13970. for (int i = jobs.size(); --i >= 0;)
  13971. {
  13972. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13973. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13974. {
  13975. if (job->isActive)
  13976. {
  13977. jobsToWaitFor.add (job);
  13978. if (interruptRunningJobs)
  13979. job->signalJobShouldExit();
  13980. }
  13981. else
  13982. {
  13983. jobs.remove (i);
  13984. if (deleteInactiveJobs)
  13985. delete job;
  13986. else
  13987. job->pool = 0;
  13988. }
  13989. }
  13990. }
  13991. }
  13992. const uint32 start = Time::getMillisecondCounter();
  13993. for (;;)
  13994. {
  13995. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13996. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13997. jobsToWaitFor.remove (i);
  13998. if (jobsToWaitFor.size() == 0)
  13999. break;
  14000. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  14001. return false;
  14002. jobFinishedSignal.wait (20);
  14003. }
  14004. return true;
  14005. }
  14006. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  14007. {
  14008. StringArray s;
  14009. const ScopedLock sl (lock);
  14010. for (int i = 0; i < jobs.size(); ++i)
  14011. {
  14012. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  14013. if (job->isActive || ! onlyReturnActiveJobs)
  14014. s.add (job->getJobName());
  14015. }
  14016. return s;
  14017. }
  14018. bool ThreadPool::setThreadPriorities (const int newPriority)
  14019. {
  14020. bool ok = true;
  14021. if (priority != newPriority)
  14022. {
  14023. priority = newPriority;
  14024. for (int i = threads.size(); --i >= 0;)
  14025. if (! threads.getUnchecked(i)->setPriority (newPriority))
  14026. ok = false;
  14027. }
  14028. return ok;
  14029. }
  14030. bool ThreadPool::runNextJob()
  14031. {
  14032. ThreadPoolJob* job = 0;
  14033. {
  14034. const ScopedLock sl (lock);
  14035. for (int i = 0; i < jobs.size(); ++i)
  14036. {
  14037. job = jobs[i];
  14038. if (job != 0 && ! (job->isActive || job->shouldStop))
  14039. break;
  14040. job = 0;
  14041. }
  14042. if (job != 0)
  14043. job->isActive = true;
  14044. }
  14045. if (job != 0)
  14046. {
  14047. JUCE_TRY
  14048. {
  14049. ThreadPoolJob::JobStatus result = job->runJob();
  14050. lastJobEndTime = Time::getApproximateMillisecondCounter();
  14051. const ScopedLock sl (lock);
  14052. if (jobs.contains (job))
  14053. {
  14054. job->isActive = false;
  14055. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  14056. {
  14057. job->pool = 0;
  14058. job->shouldStop = true;
  14059. jobs.removeValue (job);
  14060. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  14061. delete job;
  14062. jobFinishedSignal.signal();
  14063. }
  14064. else
  14065. {
  14066. // move the job to the end of the queue if it wants another go
  14067. jobs.move (jobs.indexOf (job), -1);
  14068. }
  14069. }
  14070. }
  14071. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  14072. catch (...)
  14073. {
  14074. const ScopedLock sl (lock);
  14075. jobs.removeValue (job);
  14076. }
  14077. #endif
  14078. }
  14079. else
  14080. {
  14081. if (threadStopTimeout > 0
  14082. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  14083. {
  14084. const ScopedLock sl (lock);
  14085. if (jobs.size() == 0)
  14086. for (int i = threads.size(); --i >= 0;)
  14087. threads.getUnchecked(i)->signalThreadShouldExit();
  14088. }
  14089. else
  14090. {
  14091. return false;
  14092. }
  14093. }
  14094. return true;
  14095. }
  14096. END_JUCE_NAMESPACE
  14097. /*** End of inlined file: juce_ThreadPool.cpp ***/
  14098. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  14099. BEGIN_JUCE_NAMESPACE
  14100. TimeSliceThread::TimeSliceThread (const String& threadName)
  14101. : Thread (threadName),
  14102. index (0),
  14103. clientBeingCalled (0),
  14104. clientsChanged (false)
  14105. {
  14106. }
  14107. TimeSliceThread::~TimeSliceThread()
  14108. {
  14109. stopThread (2000);
  14110. }
  14111. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  14112. {
  14113. const ScopedLock sl (listLock);
  14114. clients.addIfNotAlreadyThere (client);
  14115. clientsChanged = true;
  14116. notify();
  14117. }
  14118. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  14119. {
  14120. const ScopedLock sl1 (listLock);
  14121. clientsChanged = true;
  14122. // if there's a chance we're in the middle of calling this client, we need to
  14123. // also lock the outer lock..
  14124. if (clientBeingCalled == client)
  14125. {
  14126. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  14127. const ScopedLock sl2 (callbackLock);
  14128. const ScopedLock sl3 (listLock);
  14129. clients.removeValue (client);
  14130. }
  14131. else
  14132. {
  14133. clients.removeValue (client);
  14134. }
  14135. }
  14136. int TimeSliceThread::getNumClients() const
  14137. {
  14138. return clients.size();
  14139. }
  14140. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  14141. {
  14142. const ScopedLock sl (listLock);
  14143. return clients [i];
  14144. }
  14145. void TimeSliceThread::run()
  14146. {
  14147. int numCallsSinceBusy = 0;
  14148. while (! threadShouldExit())
  14149. {
  14150. int timeToWait = 500;
  14151. {
  14152. const ScopedLock sl (callbackLock);
  14153. {
  14154. const ScopedLock sl2 (listLock);
  14155. if (clients.size() > 0)
  14156. {
  14157. index = (index + 1) % clients.size();
  14158. clientBeingCalled = clients [index];
  14159. }
  14160. else
  14161. {
  14162. index = 0;
  14163. clientBeingCalled = 0;
  14164. }
  14165. if (clientsChanged)
  14166. {
  14167. clientsChanged = false;
  14168. numCallsSinceBusy = 0;
  14169. }
  14170. }
  14171. if (clientBeingCalled != 0)
  14172. {
  14173. if (clientBeingCalled->useTimeSlice())
  14174. numCallsSinceBusy = 0;
  14175. else
  14176. ++numCallsSinceBusy;
  14177. if (numCallsSinceBusy >= clients.size())
  14178. timeToWait = 500;
  14179. else if (index == 0)
  14180. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  14181. else
  14182. timeToWait = 0;
  14183. }
  14184. }
  14185. if (timeToWait > 0)
  14186. wait (timeToWait);
  14187. }
  14188. }
  14189. END_JUCE_NAMESPACE
  14190. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  14191. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14192. BEGIN_JUCE_NAMESPACE
  14193. DeletedAtShutdown::DeletedAtShutdown()
  14194. {
  14195. const ScopedLock sl (getLock());
  14196. getObjects().add (this);
  14197. }
  14198. DeletedAtShutdown::~DeletedAtShutdown()
  14199. {
  14200. const ScopedLock sl (getLock());
  14201. getObjects().removeValue (this);
  14202. }
  14203. void DeletedAtShutdown::deleteAll()
  14204. {
  14205. // make a local copy of the array, so it can't get into a loop if something
  14206. // creates another DeletedAtShutdown object during its destructor.
  14207. Array <DeletedAtShutdown*> localCopy;
  14208. {
  14209. const ScopedLock sl (getLock());
  14210. localCopy = getObjects();
  14211. }
  14212. for (int i = localCopy.size(); --i >= 0;)
  14213. {
  14214. JUCE_TRY
  14215. {
  14216. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  14217. // double-check that it's not already been deleted during another object's destructor.
  14218. {
  14219. const ScopedLock sl (getLock());
  14220. if (! getObjects().contains (deletee))
  14221. deletee = 0;
  14222. }
  14223. delete deletee;
  14224. }
  14225. JUCE_CATCH_EXCEPTION
  14226. }
  14227. // if no objects got re-created during shutdown, this should have been emptied by their
  14228. // destructors
  14229. jassert (getObjects().size() == 0);
  14230. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  14231. }
  14232. CriticalSection& DeletedAtShutdown::getLock()
  14233. {
  14234. static CriticalSection lock;
  14235. return lock;
  14236. }
  14237. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  14238. {
  14239. static Array <DeletedAtShutdown*> objects;
  14240. return objects;
  14241. }
  14242. END_JUCE_NAMESPACE
  14243. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14244. /*** Start of inlined file: juce_UnitTest.cpp ***/
  14245. BEGIN_JUCE_NAMESPACE
  14246. UnitTest::UnitTest (const String& name_)
  14247. : name (name_), runner (0)
  14248. {
  14249. getAllTests().add (this);
  14250. }
  14251. UnitTest::~UnitTest()
  14252. {
  14253. getAllTests().removeValue (this);
  14254. }
  14255. Array<UnitTest*>& UnitTest::getAllTests()
  14256. {
  14257. static Array<UnitTest*> tests;
  14258. return tests;
  14259. }
  14260. void UnitTest::initialise() {}
  14261. void UnitTest::shutdown() {}
  14262. void UnitTest::performTest (UnitTestRunner* const runner_)
  14263. {
  14264. jassert (runner_ != 0);
  14265. runner = runner_;
  14266. initialise();
  14267. runTest();
  14268. shutdown();
  14269. }
  14270. void UnitTest::logMessage (const String& message)
  14271. {
  14272. runner->logMessage (message);
  14273. }
  14274. void UnitTest::beginTest (const String& testName)
  14275. {
  14276. runner->beginNewTest (this, testName);
  14277. }
  14278. void UnitTest::expect (const bool result, const String& failureMessage)
  14279. {
  14280. if (result)
  14281. runner->addPass();
  14282. else
  14283. runner->addFail (failureMessage);
  14284. }
  14285. UnitTestRunner::UnitTestRunner()
  14286. : currentTest (0), assertOnFailure (false)
  14287. {
  14288. }
  14289. UnitTestRunner::~UnitTestRunner()
  14290. {
  14291. }
  14292. int UnitTestRunner::getNumResults() const throw()
  14293. {
  14294. return results.size();
  14295. }
  14296. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  14297. {
  14298. return results [index];
  14299. }
  14300. void UnitTestRunner::resultsUpdated()
  14301. {
  14302. }
  14303. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14304. {
  14305. results.clear();
  14306. assertOnFailure = assertOnFailure_;
  14307. resultsUpdated();
  14308. for (int i = 0; i < tests.size(); ++i)
  14309. {
  14310. try
  14311. {
  14312. tests.getUnchecked(i)->performTest (this);
  14313. }
  14314. catch (...)
  14315. {
  14316. addFail ("An unhandled exception was thrown!");
  14317. }
  14318. }
  14319. endTest();
  14320. }
  14321. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14322. {
  14323. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14324. }
  14325. void UnitTestRunner::logMessage (const String& message)
  14326. {
  14327. Logger::writeToLog (message);
  14328. }
  14329. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14330. {
  14331. endTest();
  14332. currentTest = test;
  14333. TestResult* const r = new TestResult();
  14334. r->unitTestName = test->getName();
  14335. r->subcategoryName = subCategory;
  14336. r->passes = 0;
  14337. r->failures = 0;
  14338. results.add (r);
  14339. logMessage ("-----------------------------------------------------------------");
  14340. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14341. resultsUpdated();
  14342. }
  14343. void UnitTestRunner::endTest()
  14344. {
  14345. if (results.size() > 0)
  14346. {
  14347. TestResult* const r = results.getLast();
  14348. if (r->failures > 0)
  14349. {
  14350. String m ("FAILED!!");
  14351. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14352. << " failed, out of a total of " << (r->passes + r->failures);
  14353. logMessage (String::empty);
  14354. logMessage (m);
  14355. logMessage (String::empty);
  14356. }
  14357. else
  14358. {
  14359. logMessage ("All tests completed successfully");
  14360. }
  14361. }
  14362. }
  14363. void UnitTestRunner::addPass()
  14364. {
  14365. {
  14366. const ScopedLock sl (results.getLock());
  14367. TestResult* const r = results.getLast();
  14368. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14369. r->passes++;
  14370. String message ("Test ");
  14371. message << (r->failures + r->passes) << " passed";
  14372. logMessage (message);
  14373. }
  14374. resultsUpdated();
  14375. }
  14376. void UnitTestRunner::addFail (const String& failureMessage)
  14377. {
  14378. {
  14379. const ScopedLock sl (results.getLock());
  14380. TestResult* const r = results.getLast();
  14381. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14382. r->failures++;
  14383. String message ("!!! Test ");
  14384. message << (r->failures + r->passes) << " failed";
  14385. if (failureMessage.isNotEmpty())
  14386. message << ": " << failureMessage;
  14387. r->messages.add (message);
  14388. logMessage (message);
  14389. }
  14390. resultsUpdated();
  14391. if (assertOnFailure) { jassertfalse }
  14392. }
  14393. END_JUCE_NAMESPACE
  14394. /*** End of inlined file: juce_UnitTest.cpp ***/
  14395. #endif
  14396. #if JUCE_BUILD_MISC
  14397. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14398. BEGIN_JUCE_NAMESPACE
  14399. class ValueTree::SetPropertyAction : public UndoableAction
  14400. {
  14401. public:
  14402. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14403. const var& newValue_, const var& oldValue_,
  14404. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14405. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14406. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14407. {
  14408. }
  14409. ~SetPropertyAction() {}
  14410. bool perform()
  14411. {
  14412. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14413. if (isDeletingProperty)
  14414. target->removeProperty (name, 0);
  14415. else
  14416. target->setProperty (name, newValue, 0);
  14417. return true;
  14418. }
  14419. bool undo()
  14420. {
  14421. if (isAddingNewProperty)
  14422. target->removeProperty (name, 0);
  14423. else
  14424. target->setProperty (name, oldValue, 0);
  14425. return true;
  14426. }
  14427. int getSizeInUnits()
  14428. {
  14429. return (int) sizeof (*this); //xxx should be more accurate
  14430. }
  14431. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14432. {
  14433. if (! (isAddingNewProperty || isDeletingProperty))
  14434. {
  14435. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14436. if (next != 0 && next->target == target && next->name == name
  14437. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14438. {
  14439. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14440. }
  14441. }
  14442. return 0;
  14443. }
  14444. private:
  14445. const SharedObjectPtr target;
  14446. const Identifier name;
  14447. const var newValue;
  14448. var oldValue;
  14449. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14450. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  14451. };
  14452. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14453. {
  14454. public:
  14455. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14456. const SharedObjectPtr& newChild_)
  14457. : target (target_),
  14458. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14459. childIndex (childIndex_),
  14460. isDeleting (newChild_ == 0)
  14461. {
  14462. jassert (child != 0);
  14463. }
  14464. ~AddOrRemoveChildAction() {}
  14465. bool perform()
  14466. {
  14467. if (isDeleting)
  14468. target->removeChild (childIndex, 0);
  14469. else
  14470. target->addChild (child, childIndex, 0);
  14471. return true;
  14472. }
  14473. bool undo()
  14474. {
  14475. if (isDeleting)
  14476. {
  14477. target->addChild (child, childIndex, 0);
  14478. }
  14479. else
  14480. {
  14481. // If you hit this, it seems that your object's state is getting confused - probably
  14482. // because you've interleaved some undoable and non-undoable operations?
  14483. jassert (childIndex < target->children.size());
  14484. target->removeChild (childIndex, 0);
  14485. }
  14486. return true;
  14487. }
  14488. int getSizeInUnits()
  14489. {
  14490. return (int) sizeof (*this); //xxx should be more accurate
  14491. }
  14492. private:
  14493. const SharedObjectPtr target, child;
  14494. const int childIndex;
  14495. const bool isDeleting;
  14496. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  14497. };
  14498. class ValueTree::MoveChildAction : public UndoableAction
  14499. {
  14500. public:
  14501. MoveChildAction (const SharedObjectPtr& parent_,
  14502. const int startIndex_, const int endIndex_)
  14503. : parent (parent_),
  14504. startIndex (startIndex_),
  14505. endIndex (endIndex_)
  14506. {
  14507. }
  14508. ~MoveChildAction() {}
  14509. bool perform()
  14510. {
  14511. parent->moveChild (startIndex, endIndex, 0);
  14512. return true;
  14513. }
  14514. bool undo()
  14515. {
  14516. parent->moveChild (endIndex, startIndex, 0);
  14517. return true;
  14518. }
  14519. int getSizeInUnits()
  14520. {
  14521. return (int) sizeof (*this); //xxx should be more accurate
  14522. }
  14523. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14524. {
  14525. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14526. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14527. return new MoveChildAction (parent, startIndex, next->endIndex);
  14528. return 0;
  14529. }
  14530. private:
  14531. const SharedObjectPtr parent;
  14532. const int startIndex, endIndex;
  14533. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  14534. };
  14535. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14536. : type (type_), parent (0)
  14537. {
  14538. }
  14539. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14540. : type (other.type), properties (other.properties), parent (0)
  14541. {
  14542. for (int i = 0; i < other.children.size(); ++i)
  14543. {
  14544. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14545. child->parent = this;
  14546. children.add (child);
  14547. }
  14548. }
  14549. ValueTree::SharedObject::~SharedObject()
  14550. {
  14551. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14552. for (int i = children.size(); --i >= 0;)
  14553. {
  14554. const SharedObjectPtr c (children.getUnchecked(i));
  14555. c->parent = 0;
  14556. children.remove (i);
  14557. c->sendParentChangeMessage();
  14558. }
  14559. }
  14560. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14561. {
  14562. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14563. {
  14564. ValueTree* const v = valueTreesWithListeners[i];
  14565. if (v != 0)
  14566. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14567. }
  14568. }
  14569. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14570. {
  14571. ValueTree tree (this);
  14572. ValueTree::SharedObject* t = this;
  14573. while (t != 0)
  14574. {
  14575. t->sendPropertyChangeMessage (tree, property);
  14576. t = t->parent;
  14577. }
  14578. }
  14579. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14580. {
  14581. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14582. {
  14583. ValueTree* const v = valueTreesWithListeners[i];
  14584. if (v != 0)
  14585. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14586. }
  14587. }
  14588. void ValueTree::SharedObject::sendChildChangeMessage()
  14589. {
  14590. ValueTree tree (this);
  14591. ValueTree::SharedObject* t = this;
  14592. while (t != 0)
  14593. {
  14594. t->sendChildChangeMessage (tree);
  14595. t = t->parent;
  14596. }
  14597. }
  14598. void ValueTree::SharedObject::sendParentChangeMessage()
  14599. {
  14600. ValueTree tree (this);
  14601. int i;
  14602. for (i = children.size(); --i >= 0;)
  14603. {
  14604. SharedObject* const t = children[i];
  14605. if (t != 0)
  14606. t->sendParentChangeMessage();
  14607. }
  14608. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14609. {
  14610. ValueTree* const v = valueTreesWithListeners[i];
  14611. if (v != 0)
  14612. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14613. }
  14614. }
  14615. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14616. {
  14617. return properties [name];
  14618. }
  14619. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14620. {
  14621. return properties.getWithDefault (name, defaultReturnValue);
  14622. }
  14623. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14624. {
  14625. if (undoManager == 0)
  14626. {
  14627. if (properties.set (name, newValue))
  14628. sendPropertyChangeMessage (name);
  14629. }
  14630. else
  14631. {
  14632. var* const existingValue = properties.getVarPointer (name);
  14633. if (existingValue != 0)
  14634. {
  14635. if (*existingValue != newValue)
  14636. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14637. }
  14638. else
  14639. {
  14640. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14641. }
  14642. }
  14643. }
  14644. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14645. {
  14646. return properties.contains (name);
  14647. }
  14648. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14649. {
  14650. if (undoManager == 0)
  14651. {
  14652. if (properties.remove (name))
  14653. sendPropertyChangeMessage (name);
  14654. }
  14655. else
  14656. {
  14657. if (properties.contains (name))
  14658. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14659. }
  14660. }
  14661. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14662. {
  14663. if (undoManager == 0)
  14664. {
  14665. while (properties.size() > 0)
  14666. {
  14667. const Identifier name (properties.getName (properties.size() - 1));
  14668. properties.remove (name);
  14669. sendPropertyChangeMessage (name);
  14670. }
  14671. }
  14672. else
  14673. {
  14674. for (int i = properties.size(); --i >= 0;)
  14675. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14676. }
  14677. }
  14678. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14679. {
  14680. for (int i = 0; i < children.size(); ++i)
  14681. if (children.getUnchecked(i)->type == typeToMatch)
  14682. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14683. return ValueTree::invalid;
  14684. }
  14685. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14686. {
  14687. for (int i = 0; i < children.size(); ++i)
  14688. if (children.getUnchecked(i)->type == typeToMatch)
  14689. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14690. SharedObject* const newObject = new SharedObject (typeToMatch);
  14691. addChild (newObject, -1, undoManager);
  14692. return ValueTree (newObject);
  14693. }
  14694. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14695. {
  14696. for (int i = 0; i < children.size(); ++i)
  14697. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14698. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14699. return ValueTree::invalid;
  14700. }
  14701. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14702. {
  14703. const SharedObject* p = parent;
  14704. while (p != 0)
  14705. {
  14706. if (p == possibleParent)
  14707. return true;
  14708. p = p->parent;
  14709. }
  14710. return false;
  14711. }
  14712. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14713. {
  14714. return children.indexOf (child.object);
  14715. }
  14716. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14717. {
  14718. if (child != 0 && child->parent != this)
  14719. {
  14720. if (child != this && ! isAChildOf (child))
  14721. {
  14722. // You should always make sure that a child is removed from its previous parent before
  14723. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14724. // undomanager should be used when removing it from its current parent..
  14725. jassert (child->parent == 0);
  14726. if (child->parent != 0)
  14727. {
  14728. jassert (child->parent->children.indexOf (child) >= 0);
  14729. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14730. }
  14731. if (undoManager == 0)
  14732. {
  14733. children.insert (index, child);
  14734. child->parent = this;
  14735. sendChildChangeMessage();
  14736. child->sendParentChangeMessage();
  14737. }
  14738. else
  14739. {
  14740. if (index < 0)
  14741. index = children.size();
  14742. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14743. }
  14744. }
  14745. else
  14746. {
  14747. // You're attempting to create a recursive loop! A node
  14748. // can't be a child of one of its own children!
  14749. jassertfalse;
  14750. }
  14751. }
  14752. }
  14753. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14754. {
  14755. const SharedObjectPtr child (children [childIndex]);
  14756. if (child != 0)
  14757. {
  14758. if (undoManager == 0)
  14759. {
  14760. children.remove (childIndex);
  14761. child->parent = 0;
  14762. sendChildChangeMessage();
  14763. child->sendParentChangeMessage();
  14764. }
  14765. else
  14766. {
  14767. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14768. }
  14769. }
  14770. }
  14771. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14772. {
  14773. while (children.size() > 0)
  14774. removeChild (children.size() - 1, undoManager);
  14775. }
  14776. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14777. {
  14778. // The source index must be a valid index!
  14779. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14780. if (currentIndex != newIndex
  14781. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14782. {
  14783. if (undoManager == 0)
  14784. {
  14785. children.move (currentIndex, newIndex);
  14786. sendChildChangeMessage();
  14787. }
  14788. else
  14789. {
  14790. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14791. newIndex = children.size() - 1;
  14792. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14793. }
  14794. }
  14795. }
  14796. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14797. {
  14798. jassert (newOrder.size() == children.size());
  14799. if (undoManager == 0)
  14800. {
  14801. children = newOrder;
  14802. sendChildChangeMessage();
  14803. }
  14804. else
  14805. {
  14806. for (int i = 0; i < children.size(); ++i)
  14807. {
  14808. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14809. {
  14810. jassert (children.contains (newOrder.getUnchecked(i)));
  14811. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14812. }
  14813. }
  14814. }
  14815. }
  14816. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14817. {
  14818. if (type != other.type
  14819. || properties.size() != other.properties.size()
  14820. || children.size() != other.children.size()
  14821. || properties != other.properties)
  14822. return false;
  14823. for (int i = 0; i < children.size(); ++i)
  14824. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14825. return false;
  14826. return true;
  14827. }
  14828. ValueTree::ValueTree() throw()
  14829. : object (0)
  14830. {
  14831. }
  14832. const ValueTree ValueTree::invalid;
  14833. ValueTree::ValueTree (const Identifier& type_)
  14834. : object (new ValueTree::SharedObject (type_))
  14835. {
  14836. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14837. }
  14838. ValueTree::ValueTree (SharedObject* const object_)
  14839. : object (object_)
  14840. {
  14841. }
  14842. ValueTree::ValueTree (const ValueTree& other)
  14843. : object (other.object)
  14844. {
  14845. }
  14846. ValueTree& ValueTree::operator= (const ValueTree& other)
  14847. {
  14848. if (listeners.size() > 0)
  14849. {
  14850. if (object != 0)
  14851. object->valueTreesWithListeners.removeValue (this);
  14852. if (other.object != 0)
  14853. other.object->valueTreesWithListeners.add (this);
  14854. }
  14855. object = other.object;
  14856. return *this;
  14857. }
  14858. ValueTree::~ValueTree()
  14859. {
  14860. if (listeners.size() > 0 && object != 0)
  14861. object->valueTreesWithListeners.removeValue (this);
  14862. }
  14863. bool ValueTree::operator== (const ValueTree& other) const throw()
  14864. {
  14865. return object == other.object;
  14866. }
  14867. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14868. {
  14869. return object != other.object;
  14870. }
  14871. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14872. {
  14873. return object == other.object
  14874. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14875. }
  14876. ValueTree ValueTree::createCopy() const
  14877. {
  14878. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14879. }
  14880. bool ValueTree::hasType (const Identifier& typeName) const
  14881. {
  14882. return object != 0 && object->type == typeName;
  14883. }
  14884. const Identifier ValueTree::getType() const
  14885. {
  14886. return object != 0 ? object->type : Identifier();
  14887. }
  14888. ValueTree ValueTree::getParent() const
  14889. {
  14890. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14891. }
  14892. ValueTree ValueTree::getSibling (const int delta) const
  14893. {
  14894. if (object == 0 || object->parent == 0)
  14895. return invalid;
  14896. const int index = object->parent->indexOf (*this) + delta;
  14897. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14898. }
  14899. const var& ValueTree::operator[] (const Identifier& name) const
  14900. {
  14901. return object == 0 ? var::null : object->getProperty (name);
  14902. }
  14903. const var& ValueTree::getProperty (const Identifier& name) const
  14904. {
  14905. return object == 0 ? var::null : object->getProperty (name);
  14906. }
  14907. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14908. {
  14909. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14910. }
  14911. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14912. {
  14913. jassert (name.toString().isNotEmpty());
  14914. if (object != 0 && name.toString().isNotEmpty())
  14915. object->setProperty (name, newValue, undoManager);
  14916. }
  14917. bool ValueTree::hasProperty (const Identifier& name) const
  14918. {
  14919. return object != 0 && object->hasProperty (name);
  14920. }
  14921. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14922. {
  14923. if (object != 0)
  14924. object->removeProperty (name, undoManager);
  14925. }
  14926. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14927. {
  14928. if (object != 0)
  14929. object->removeAllProperties (undoManager);
  14930. }
  14931. int ValueTree::getNumProperties() const
  14932. {
  14933. return object == 0 ? 0 : object->properties.size();
  14934. }
  14935. const Identifier ValueTree::getPropertyName (const int index) const
  14936. {
  14937. return object == 0 ? Identifier()
  14938. : object->properties.getName (index);
  14939. }
  14940. class ValueTreePropertyValueSource : public Value::ValueSource,
  14941. public ValueTree::Listener
  14942. {
  14943. public:
  14944. ValueTreePropertyValueSource (const ValueTree& tree_,
  14945. const Identifier& property_,
  14946. UndoManager* const undoManager_)
  14947. : tree (tree_),
  14948. property (property_),
  14949. undoManager (undoManager_)
  14950. {
  14951. tree.addListener (this);
  14952. }
  14953. ~ValueTreePropertyValueSource()
  14954. {
  14955. tree.removeListener (this);
  14956. }
  14957. const var getValue() const
  14958. {
  14959. return tree [property];
  14960. }
  14961. void setValue (const var& newValue)
  14962. {
  14963. tree.setProperty (property, newValue, undoManager);
  14964. }
  14965. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14966. {
  14967. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14968. sendChangeMessage (false);
  14969. }
  14970. void valueTreeChildrenChanged (ValueTree&) {}
  14971. void valueTreeParentChanged (ValueTree&) {}
  14972. private:
  14973. ValueTree tree;
  14974. const Identifier property;
  14975. UndoManager* const undoManager;
  14976. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14977. };
  14978. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14979. {
  14980. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14981. }
  14982. int ValueTree::getNumChildren() const
  14983. {
  14984. return object == 0 ? 0 : object->children.size();
  14985. }
  14986. ValueTree ValueTree::getChild (int index) const
  14987. {
  14988. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14989. }
  14990. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14991. {
  14992. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14993. }
  14994. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14995. {
  14996. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14997. }
  14998. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14999. {
  15000. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  15001. }
  15002. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  15003. {
  15004. return object != 0 && object->isAChildOf (possibleParent.object);
  15005. }
  15006. int ValueTree::indexOf (const ValueTree& child) const
  15007. {
  15008. return object != 0 ? object->indexOf (child) : -1;
  15009. }
  15010. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  15011. {
  15012. if (object != 0)
  15013. object->addChild (child.object, index, undoManager);
  15014. }
  15015. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  15016. {
  15017. if (object != 0)
  15018. object->removeChild (childIndex, undoManager);
  15019. }
  15020. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  15021. {
  15022. if (object != 0)
  15023. object->removeChild (object->children.indexOf (child.object), undoManager);
  15024. }
  15025. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  15026. {
  15027. if (object != 0)
  15028. object->removeAllChildren (undoManager);
  15029. }
  15030. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  15031. {
  15032. if (object != 0)
  15033. object->moveChild (currentIndex, newIndex, undoManager);
  15034. }
  15035. void ValueTree::addListener (Listener* listener)
  15036. {
  15037. if (listener != 0)
  15038. {
  15039. if (listeners.size() == 0 && object != 0)
  15040. object->valueTreesWithListeners.add (this);
  15041. listeners.add (listener);
  15042. }
  15043. }
  15044. void ValueTree::removeListener (Listener* listener)
  15045. {
  15046. listeners.remove (listener);
  15047. if (listeners.size() == 0 && object != 0)
  15048. object->valueTreesWithListeners.removeValue (this);
  15049. }
  15050. XmlElement* ValueTree::SharedObject::createXml() const
  15051. {
  15052. XmlElement* xml = new XmlElement (type.toString());
  15053. int i;
  15054. for (i = 0; i < properties.size(); ++i)
  15055. {
  15056. Identifier name (properties.getName(i));
  15057. const var& v = properties [name];
  15058. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  15059. xml->setAttribute (name.toString(), v.toString());
  15060. }
  15061. for (i = 0; i < children.size(); ++i)
  15062. xml->addChildElement (children.getUnchecked(i)->createXml());
  15063. return xml;
  15064. }
  15065. XmlElement* ValueTree::createXml() const
  15066. {
  15067. return object != 0 ? object->createXml() : 0;
  15068. }
  15069. ValueTree ValueTree::fromXml (const XmlElement& xml)
  15070. {
  15071. ValueTree v (xml.getTagName());
  15072. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  15073. for (int i = 0; i < numAtts; ++i)
  15074. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  15075. forEachXmlChildElement (xml, e)
  15076. {
  15077. v.addChild (fromXml (*e), -1, 0);
  15078. }
  15079. return v;
  15080. }
  15081. void ValueTree::writeToStream (OutputStream& output)
  15082. {
  15083. output.writeString (getType().toString());
  15084. const int numProps = getNumProperties();
  15085. output.writeCompressedInt (numProps);
  15086. int i;
  15087. for (i = 0; i < numProps; ++i)
  15088. {
  15089. const Identifier name (getPropertyName(i));
  15090. output.writeString (name.toString());
  15091. getProperty(name).writeToStream (output);
  15092. }
  15093. const int numChildren = getNumChildren();
  15094. output.writeCompressedInt (numChildren);
  15095. for (i = 0; i < numChildren; ++i)
  15096. getChild (i).writeToStream (output);
  15097. }
  15098. ValueTree ValueTree::readFromStream (InputStream& input)
  15099. {
  15100. const String type (input.readString());
  15101. if (type.isEmpty())
  15102. return ValueTree::invalid;
  15103. ValueTree v (type);
  15104. const int numProps = input.readCompressedInt();
  15105. if (numProps < 0)
  15106. {
  15107. jassertfalse; // trying to read corrupted data!
  15108. return v;
  15109. }
  15110. int i;
  15111. for (i = 0; i < numProps; ++i)
  15112. {
  15113. const String name (input.readString());
  15114. jassert (name.isNotEmpty());
  15115. const var value (var::readFromStream (input));
  15116. v.setProperty (name, value, 0);
  15117. }
  15118. const int numChildren = input.readCompressedInt();
  15119. for (i = 0; i < numChildren; ++i)
  15120. v.addChild (readFromStream (input), -1, 0);
  15121. return v;
  15122. }
  15123. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  15124. {
  15125. MemoryInputStream in (data, numBytes, false);
  15126. return readFromStream (in);
  15127. }
  15128. END_JUCE_NAMESPACE
  15129. /*** End of inlined file: juce_ValueTree.cpp ***/
  15130. /*** Start of inlined file: juce_Value.cpp ***/
  15131. BEGIN_JUCE_NAMESPACE
  15132. Value::ValueSource::ValueSource()
  15133. {
  15134. }
  15135. Value::ValueSource::~ValueSource()
  15136. {
  15137. }
  15138. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  15139. {
  15140. if (synchronous)
  15141. {
  15142. for (int i = valuesWithListeners.size(); --i >= 0;)
  15143. {
  15144. Value* const v = valuesWithListeners[i];
  15145. if (v != 0)
  15146. v->callListeners();
  15147. }
  15148. }
  15149. else
  15150. {
  15151. triggerAsyncUpdate();
  15152. }
  15153. }
  15154. void Value::ValueSource::handleAsyncUpdate()
  15155. {
  15156. sendChangeMessage (true);
  15157. }
  15158. class SimpleValueSource : public Value::ValueSource
  15159. {
  15160. public:
  15161. SimpleValueSource()
  15162. {
  15163. }
  15164. SimpleValueSource (const var& initialValue)
  15165. : value (initialValue)
  15166. {
  15167. }
  15168. ~SimpleValueSource()
  15169. {
  15170. }
  15171. const var getValue() const
  15172. {
  15173. return value;
  15174. }
  15175. void setValue (const var& newValue)
  15176. {
  15177. if (newValue != value)
  15178. {
  15179. value = newValue;
  15180. sendChangeMessage (false);
  15181. }
  15182. }
  15183. private:
  15184. var value;
  15185. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  15186. };
  15187. Value::Value()
  15188. : value (new SimpleValueSource())
  15189. {
  15190. }
  15191. Value::Value (ValueSource* const value_)
  15192. : value (value_)
  15193. {
  15194. jassert (value_ != 0);
  15195. }
  15196. Value::Value (const var& initialValue)
  15197. : value (new SimpleValueSource (initialValue))
  15198. {
  15199. }
  15200. Value::Value (const Value& other)
  15201. : value (other.value)
  15202. {
  15203. }
  15204. Value& Value::operator= (const Value& other)
  15205. {
  15206. value = other.value;
  15207. return *this;
  15208. }
  15209. Value::~Value()
  15210. {
  15211. if (listeners.size() > 0)
  15212. value->valuesWithListeners.removeValue (this);
  15213. }
  15214. const var Value::getValue() const
  15215. {
  15216. return value->getValue();
  15217. }
  15218. Value::operator const var() const
  15219. {
  15220. return getValue();
  15221. }
  15222. void Value::setValue (const var& newValue)
  15223. {
  15224. value->setValue (newValue);
  15225. }
  15226. const String Value::toString() const
  15227. {
  15228. return value->getValue().toString();
  15229. }
  15230. Value& Value::operator= (const var& newValue)
  15231. {
  15232. value->setValue (newValue);
  15233. return *this;
  15234. }
  15235. void Value::referTo (const Value& valueToReferTo)
  15236. {
  15237. if (valueToReferTo.value != value)
  15238. {
  15239. if (listeners.size() > 0)
  15240. {
  15241. value->valuesWithListeners.removeValue (this);
  15242. valueToReferTo.value->valuesWithListeners.add (this);
  15243. }
  15244. value = valueToReferTo.value;
  15245. callListeners();
  15246. }
  15247. }
  15248. bool Value::refersToSameSourceAs (const Value& other) const
  15249. {
  15250. return value == other.value;
  15251. }
  15252. bool Value::operator== (const Value& other) const
  15253. {
  15254. return value == other.value || value->getValue() == other.getValue();
  15255. }
  15256. bool Value::operator!= (const Value& other) const
  15257. {
  15258. return value != other.value && value->getValue() != other.getValue();
  15259. }
  15260. void Value::addListener (ValueListener* const listener)
  15261. {
  15262. if (listener != 0)
  15263. {
  15264. if (listeners.size() == 0)
  15265. value->valuesWithListeners.add (this);
  15266. listeners.add (listener);
  15267. }
  15268. }
  15269. void Value::removeListener (ValueListener* const listener)
  15270. {
  15271. listeners.remove (listener);
  15272. if (listeners.size() == 0)
  15273. value->valuesWithListeners.removeValue (this);
  15274. }
  15275. void Value::callListeners()
  15276. {
  15277. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15278. listeners.call (&ValueListener::valueChanged, v);
  15279. }
  15280. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15281. {
  15282. return stream << value.toString();
  15283. }
  15284. END_JUCE_NAMESPACE
  15285. /*** End of inlined file: juce_Value.cpp ***/
  15286. /*** Start of inlined file: juce_Application.cpp ***/
  15287. BEGIN_JUCE_NAMESPACE
  15288. #if JUCE_MAC
  15289. extern void juce_initialiseMacMainMenu();
  15290. #endif
  15291. JUCEApplication::JUCEApplication()
  15292. : appReturnValue (0),
  15293. stillInitialising (true)
  15294. {
  15295. jassert (isStandaloneApp() && appInstance == 0);
  15296. appInstance = this;
  15297. }
  15298. JUCEApplication::~JUCEApplication()
  15299. {
  15300. if (appLock != 0)
  15301. {
  15302. appLock->exit();
  15303. appLock = 0;
  15304. }
  15305. jassert (appInstance == this);
  15306. appInstance = 0;
  15307. }
  15308. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15309. JUCEApplication* JUCEApplication::appInstance = 0;
  15310. bool JUCEApplication::moreThanOneInstanceAllowed()
  15311. {
  15312. return true;
  15313. }
  15314. void JUCEApplication::anotherInstanceStarted (const String&)
  15315. {
  15316. }
  15317. void JUCEApplication::systemRequestedQuit()
  15318. {
  15319. quit();
  15320. }
  15321. void JUCEApplication::quit()
  15322. {
  15323. MessageManager::getInstance()->stopDispatchLoop();
  15324. }
  15325. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15326. {
  15327. appReturnValue = newReturnValue;
  15328. }
  15329. void JUCEApplication::actionListenerCallback (const String& message)
  15330. {
  15331. if (message.startsWith (getApplicationName() + "/"))
  15332. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15333. }
  15334. void JUCEApplication::unhandledException (const std::exception*,
  15335. const String&,
  15336. const int)
  15337. {
  15338. jassertfalse;
  15339. }
  15340. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15341. const char* const sourceFile,
  15342. const int lineNumber)
  15343. {
  15344. if (appInstance != 0)
  15345. appInstance->unhandledException (e, sourceFile, lineNumber);
  15346. }
  15347. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15348. {
  15349. return 0;
  15350. }
  15351. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15352. {
  15353. commands.add (StandardApplicationCommandIDs::quit);
  15354. }
  15355. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15356. {
  15357. if (commandID == StandardApplicationCommandIDs::quit)
  15358. {
  15359. result.setInfo (TRANS("Quit"),
  15360. TRANS("Quits the application"),
  15361. "Application",
  15362. 0);
  15363. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15364. }
  15365. }
  15366. bool JUCEApplication::perform (const InvocationInfo& info)
  15367. {
  15368. if (info.commandID == StandardApplicationCommandIDs::quit)
  15369. {
  15370. systemRequestedQuit();
  15371. return true;
  15372. }
  15373. return false;
  15374. }
  15375. bool JUCEApplication::initialiseApp (const String& commandLine)
  15376. {
  15377. commandLineParameters = commandLine.trim();
  15378. #if ! JUCE_IOS
  15379. jassert (appLock == 0); // initialiseApp must only be called once!
  15380. if (! moreThanOneInstanceAllowed())
  15381. {
  15382. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15383. if (! appLock->enter(0))
  15384. {
  15385. appLock = 0;
  15386. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15387. DBG ("Another instance is running - quitting...");
  15388. return false;
  15389. }
  15390. }
  15391. #endif
  15392. // let the app do its setting-up..
  15393. initialise (commandLineParameters);
  15394. #if JUCE_MAC
  15395. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15396. #endif
  15397. // register for broadcast new app messages
  15398. MessageManager::getInstance()->registerBroadcastListener (this);
  15399. stillInitialising = false;
  15400. return true;
  15401. }
  15402. int JUCEApplication::shutdownApp()
  15403. {
  15404. jassert (appInstance == this);
  15405. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15406. JUCE_TRY
  15407. {
  15408. // give the app a chance to clean up..
  15409. shutdown();
  15410. }
  15411. JUCE_CATCH_EXCEPTION
  15412. return getApplicationReturnValue();
  15413. }
  15414. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15415. void JUCEApplication::appWillTerminateByForce()
  15416. {
  15417. {
  15418. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15419. if (app != 0)
  15420. app->shutdownApp();
  15421. }
  15422. shutdownJuce_GUI();
  15423. }
  15424. int JUCEApplication::main (const String& commandLine)
  15425. {
  15426. ScopedJuceInitialiser_GUI libraryInitialiser;
  15427. jassert (createInstance != 0);
  15428. int returnCode = 0;
  15429. {
  15430. const ScopedPointer<JUCEApplication> app (createInstance());
  15431. if (! app->initialiseApp (commandLine))
  15432. return 0;
  15433. JUCE_TRY
  15434. {
  15435. // loop until a quit message is received..
  15436. MessageManager::getInstance()->runDispatchLoop();
  15437. }
  15438. JUCE_CATCH_EXCEPTION
  15439. returnCode = app->shutdownApp();
  15440. }
  15441. return returnCode;
  15442. }
  15443. #if JUCE_IOS
  15444. extern int juce_iOSMain (int argc, const char* argv[]);
  15445. #endif
  15446. #if ! JUCE_WINDOWS
  15447. extern const char* juce_Argv0;
  15448. #endif
  15449. int JUCEApplication::main (int argc, const char* argv[])
  15450. {
  15451. JUCE_AUTORELEASEPOOL
  15452. #if ! JUCE_WINDOWS
  15453. jassert (createInstance != 0);
  15454. juce_Argv0 = argv[0];
  15455. #endif
  15456. #if JUCE_IOS
  15457. return juce_iOSMain (argc, argv);
  15458. #else
  15459. String cmd;
  15460. for (int i = 1; i < argc; ++i)
  15461. cmd << argv[i] << ' ';
  15462. return JUCEApplication::main (cmd);
  15463. #endif
  15464. }
  15465. END_JUCE_NAMESPACE
  15466. /*** End of inlined file: juce_Application.cpp ***/
  15467. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15468. BEGIN_JUCE_NAMESPACE
  15469. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15470. : commandID (commandID_),
  15471. flags (0)
  15472. {
  15473. }
  15474. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15475. const String& description_,
  15476. const String& categoryName_,
  15477. const int flags_) throw()
  15478. {
  15479. shortName = shortName_;
  15480. description = description_;
  15481. categoryName = categoryName_;
  15482. flags = flags_;
  15483. }
  15484. void ApplicationCommandInfo::setActive (const bool b) throw()
  15485. {
  15486. if (b)
  15487. flags &= ~isDisabled;
  15488. else
  15489. flags |= isDisabled;
  15490. }
  15491. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15492. {
  15493. if (b)
  15494. flags |= isTicked;
  15495. else
  15496. flags &= ~isTicked;
  15497. }
  15498. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15499. {
  15500. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15501. }
  15502. END_JUCE_NAMESPACE
  15503. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15504. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15505. BEGIN_JUCE_NAMESPACE
  15506. ApplicationCommandManager::ApplicationCommandManager()
  15507. : firstTarget (0)
  15508. {
  15509. keyMappings = new KeyPressMappingSet (this);
  15510. Desktop::getInstance().addFocusChangeListener (this);
  15511. }
  15512. ApplicationCommandManager::~ApplicationCommandManager()
  15513. {
  15514. Desktop::getInstance().removeFocusChangeListener (this);
  15515. keyMappings = 0;
  15516. }
  15517. void ApplicationCommandManager::clearCommands()
  15518. {
  15519. commands.clear();
  15520. keyMappings->clearAllKeyPresses();
  15521. triggerAsyncUpdate();
  15522. }
  15523. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15524. {
  15525. // zero isn't a valid command ID!
  15526. jassert (newCommand.commandID != 0);
  15527. // the name isn't optional!
  15528. jassert (newCommand.shortName.isNotEmpty());
  15529. if (getCommandForID (newCommand.commandID) == 0)
  15530. {
  15531. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15532. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15533. commands.add (newInfo);
  15534. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15535. triggerAsyncUpdate();
  15536. }
  15537. else
  15538. {
  15539. // trying to re-register the same command with different parameters?
  15540. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15541. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15542. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15543. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15544. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15545. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15546. }
  15547. }
  15548. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15549. {
  15550. if (target != 0)
  15551. {
  15552. Array <CommandID> commandIDs;
  15553. target->getAllCommands (commandIDs);
  15554. for (int i = 0; i < commandIDs.size(); ++i)
  15555. {
  15556. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15557. target->getCommandInfo (info.commandID, info);
  15558. registerCommand (info);
  15559. }
  15560. }
  15561. }
  15562. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15563. {
  15564. for (int i = commands.size(); --i >= 0;)
  15565. {
  15566. if (commands.getUnchecked (i)->commandID == commandID)
  15567. {
  15568. commands.remove (i);
  15569. triggerAsyncUpdate();
  15570. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15571. for (int j = keys.size(); --j >= 0;)
  15572. keyMappings->removeKeyPress (keys.getReference (j));
  15573. }
  15574. }
  15575. }
  15576. void ApplicationCommandManager::commandStatusChanged()
  15577. {
  15578. triggerAsyncUpdate();
  15579. }
  15580. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15581. {
  15582. for (int i = commands.size(); --i >= 0;)
  15583. if (commands.getUnchecked(i)->commandID == commandID)
  15584. return commands.getUnchecked(i);
  15585. return 0;
  15586. }
  15587. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15588. {
  15589. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15590. return (ci != 0) ? ci->shortName : String::empty;
  15591. }
  15592. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15593. {
  15594. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15595. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15596. : String::empty;
  15597. }
  15598. const StringArray ApplicationCommandManager::getCommandCategories() const
  15599. {
  15600. StringArray s;
  15601. for (int i = 0; i < commands.size(); ++i)
  15602. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15603. return s;
  15604. }
  15605. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15606. {
  15607. Array <CommandID> results;
  15608. for (int i = 0; i < commands.size(); ++i)
  15609. if (commands.getUnchecked(i)->categoryName == categoryName)
  15610. results.add (commands.getUnchecked(i)->commandID);
  15611. return results;
  15612. }
  15613. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15614. {
  15615. ApplicationCommandTarget::InvocationInfo info (commandID);
  15616. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15617. return invoke (info, asynchronously);
  15618. }
  15619. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15620. {
  15621. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15622. // manager first..
  15623. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15624. ApplicationCommandInfo commandInfo (0);
  15625. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15626. if (target == 0)
  15627. return false;
  15628. ApplicationCommandTarget::InvocationInfo info (info_);
  15629. info.commandFlags = commandInfo.flags;
  15630. sendListenerInvokeCallback (info);
  15631. const bool ok = target->invoke (info, asynchronously);
  15632. commandStatusChanged();
  15633. return ok;
  15634. }
  15635. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15636. {
  15637. return firstTarget != 0 ? firstTarget
  15638. : findDefaultComponentTarget();
  15639. }
  15640. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15641. {
  15642. firstTarget = newTarget;
  15643. }
  15644. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15645. ApplicationCommandInfo& upToDateInfo)
  15646. {
  15647. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15648. if (target == 0)
  15649. target = JUCEApplication::getInstance();
  15650. if (target != 0)
  15651. target = target->getTargetForCommand (commandID);
  15652. if (target != 0)
  15653. target->getCommandInfo (commandID, upToDateInfo);
  15654. return target;
  15655. }
  15656. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15657. {
  15658. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15659. if (target == 0 && c != 0)
  15660. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15661. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15662. return target;
  15663. }
  15664. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15665. {
  15666. Component* c = Component::getCurrentlyFocusedComponent();
  15667. if (c == 0)
  15668. {
  15669. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15670. if (activeWindow != 0)
  15671. {
  15672. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15673. if (c == 0)
  15674. c = activeWindow;
  15675. }
  15676. }
  15677. if (c == 0 && Process::isForegroundProcess())
  15678. {
  15679. // getting a bit desperate now - try all desktop comps..
  15680. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15681. {
  15682. ApplicationCommandTarget* const target
  15683. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15684. ->getPeer()->getLastFocusedSubcomponent());
  15685. if (target != 0)
  15686. return target;
  15687. }
  15688. }
  15689. if (c != 0)
  15690. {
  15691. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15692. // if we're focused on a ResizableWindow, chances are that it's the content
  15693. // component that really should get the event. And if not, the event will
  15694. // still be passed up to the top level window anyway, so let's send it to the
  15695. // content comp.
  15696. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15697. c = resizableWindow->getContentComponent();
  15698. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15699. if (target != 0)
  15700. return target;
  15701. }
  15702. return JUCEApplication::getInstance();
  15703. }
  15704. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15705. {
  15706. listeners.add (listener);
  15707. }
  15708. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15709. {
  15710. listeners.remove (listener);
  15711. }
  15712. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15713. {
  15714. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15715. }
  15716. void ApplicationCommandManager::handleAsyncUpdate()
  15717. {
  15718. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15719. }
  15720. void ApplicationCommandManager::globalFocusChanged (Component*)
  15721. {
  15722. commandStatusChanged();
  15723. }
  15724. END_JUCE_NAMESPACE
  15725. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15726. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15727. BEGIN_JUCE_NAMESPACE
  15728. ApplicationCommandTarget::ApplicationCommandTarget()
  15729. {
  15730. }
  15731. ApplicationCommandTarget::~ApplicationCommandTarget()
  15732. {
  15733. messageInvoker = 0;
  15734. }
  15735. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15736. {
  15737. if (isCommandActive (info.commandID))
  15738. {
  15739. if (async)
  15740. {
  15741. if (messageInvoker == 0)
  15742. messageInvoker = new CommandTargetMessageInvoker (this);
  15743. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15744. return true;
  15745. }
  15746. else
  15747. {
  15748. const bool success = perform (info);
  15749. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15750. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15751. // returns the command's info.
  15752. return success;
  15753. }
  15754. }
  15755. return false;
  15756. }
  15757. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15758. {
  15759. Component* c = dynamic_cast <Component*> (this);
  15760. if (c != 0)
  15761. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15762. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15763. return 0;
  15764. }
  15765. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15766. {
  15767. ApplicationCommandTarget* target = this;
  15768. int depth = 0;
  15769. while (target != 0)
  15770. {
  15771. Array <CommandID> commandIDs;
  15772. target->getAllCommands (commandIDs);
  15773. if (commandIDs.contains (commandID))
  15774. return target;
  15775. target = target->getNextCommandTarget();
  15776. ++depth;
  15777. jassert (depth < 100); // could be a recursive command chain??
  15778. jassert (target != this); // definitely a recursive command chain!
  15779. if (depth > 100 || target == this)
  15780. break;
  15781. }
  15782. if (target == 0)
  15783. {
  15784. target = JUCEApplication::getInstance();
  15785. if (target != 0)
  15786. {
  15787. Array <CommandID> commandIDs;
  15788. target->getAllCommands (commandIDs);
  15789. if (commandIDs.contains (commandID))
  15790. return target;
  15791. }
  15792. }
  15793. return 0;
  15794. }
  15795. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15796. {
  15797. ApplicationCommandInfo info (commandID);
  15798. info.flags = ApplicationCommandInfo::isDisabled;
  15799. getCommandInfo (commandID, info);
  15800. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15801. }
  15802. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15803. {
  15804. ApplicationCommandTarget* target = this;
  15805. int depth = 0;
  15806. while (target != 0)
  15807. {
  15808. if (target->tryToInvoke (info, async))
  15809. return true;
  15810. target = target->getNextCommandTarget();
  15811. ++depth;
  15812. jassert (depth < 100); // could be a recursive command chain??
  15813. jassert (target != this); // definitely a recursive command chain!
  15814. if (depth > 100 || target == this)
  15815. break;
  15816. }
  15817. if (target == 0)
  15818. {
  15819. target = JUCEApplication::getInstance();
  15820. if (target != 0)
  15821. return target->tryToInvoke (info, async);
  15822. }
  15823. return false;
  15824. }
  15825. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15826. {
  15827. ApplicationCommandTarget::InvocationInfo info (commandID);
  15828. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15829. return invoke (info, asynchronously);
  15830. }
  15831. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15832. : commandID (commandID_),
  15833. commandFlags (0),
  15834. invocationMethod (direct),
  15835. originatingComponent (0),
  15836. isKeyDown (false),
  15837. millisecsSinceKeyPressed (0)
  15838. {
  15839. }
  15840. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15841. : owner (owner_)
  15842. {
  15843. }
  15844. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15845. {
  15846. }
  15847. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15848. {
  15849. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15850. owner->tryToInvoke (*info, false);
  15851. }
  15852. END_JUCE_NAMESPACE
  15853. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15854. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15855. BEGIN_JUCE_NAMESPACE
  15856. juce_ImplementSingleton (ApplicationProperties)
  15857. ApplicationProperties::ApplicationProperties()
  15858. : msBeforeSaving (3000),
  15859. options (PropertiesFile::storeAsBinary),
  15860. commonSettingsAreReadOnly (0),
  15861. processLock (0)
  15862. {
  15863. }
  15864. ApplicationProperties::~ApplicationProperties()
  15865. {
  15866. closeFiles();
  15867. clearSingletonInstance();
  15868. }
  15869. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15870. const String& fileNameSuffix,
  15871. const String& folderName_,
  15872. const int millisecondsBeforeSaving,
  15873. const int propertiesFileOptions,
  15874. InterProcessLock* processLock_)
  15875. {
  15876. appName = applicationName;
  15877. fileSuffix = fileNameSuffix;
  15878. folderName = folderName_;
  15879. msBeforeSaving = millisecondsBeforeSaving;
  15880. options = propertiesFileOptions;
  15881. processLock = processLock_;
  15882. }
  15883. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15884. const bool testCommonSettings,
  15885. const bool showWarningDialogOnFailure)
  15886. {
  15887. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15888. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15889. if (! (userOk && commonOk))
  15890. {
  15891. if (showWarningDialogOnFailure)
  15892. {
  15893. String filenames;
  15894. if (userProps != 0 && ! userOk)
  15895. filenames << '\n' << userProps->getFile().getFullPathName();
  15896. if (commonProps != 0 && ! commonOk)
  15897. filenames << '\n' << commonProps->getFile().getFullPathName();
  15898. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15899. appName + TRANS(" - Unable to save settings"),
  15900. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15901. + appName + TRANS(" needs to be able to write to the following files:\n")
  15902. + filenames
  15903. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15904. }
  15905. return false;
  15906. }
  15907. return true;
  15908. }
  15909. void ApplicationProperties::openFiles()
  15910. {
  15911. // You need to call setStorageParameters() before trying to get hold of the
  15912. // properties!
  15913. jassert (appName.isNotEmpty());
  15914. if (appName.isNotEmpty())
  15915. {
  15916. if (userProps == 0)
  15917. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15918. false, msBeforeSaving, options, processLock);
  15919. if (commonProps == 0)
  15920. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15921. true, msBeforeSaving, options, processLock);
  15922. userProps->setFallbackPropertySet (commonProps);
  15923. }
  15924. }
  15925. PropertiesFile* ApplicationProperties::getUserSettings()
  15926. {
  15927. if (userProps == 0)
  15928. openFiles();
  15929. return userProps;
  15930. }
  15931. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15932. {
  15933. if (commonProps == 0)
  15934. openFiles();
  15935. if (returnUserPropsIfReadOnly)
  15936. {
  15937. if (commonSettingsAreReadOnly == 0)
  15938. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15939. if (commonSettingsAreReadOnly > 0)
  15940. return userProps;
  15941. }
  15942. return commonProps;
  15943. }
  15944. bool ApplicationProperties::saveIfNeeded()
  15945. {
  15946. return (userProps == 0 || userProps->saveIfNeeded())
  15947. && (commonProps == 0 || commonProps->saveIfNeeded());
  15948. }
  15949. void ApplicationProperties::closeFiles()
  15950. {
  15951. userProps = 0;
  15952. commonProps = 0;
  15953. }
  15954. END_JUCE_NAMESPACE
  15955. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15956. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15957. BEGIN_JUCE_NAMESPACE
  15958. namespace PropertyFileConstants
  15959. {
  15960. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15961. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15962. static const char* const fileTag = "PROPERTIES";
  15963. static const char* const valueTag = "VALUE";
  15964. static const char* const nameAttribute = "name";
  15965. static const char* const valueAttribute = "val";
  15966. }
  15967. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15968. const int options_, InterProcessLock* const processLock_)
  15969. : PropertySet (ignoreCaseOfKeyNames),
  15970. file (f),
  15971. timerInterval (millisecondsBeforeSaving),
  15972. options (options_),
  15973. loadedOk (false),
  15974. needsWriting (false),
  15975. processLock (processLock_)
  15976. {
  15977. // You need to correctly specify just one storage format for the file
  15978. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15979. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15980. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15981. ProcessScopedLock pl (createProcessLock());
  15982. if (pl != 0 && ! pl->isLocked())
  15983. return; // locking failure..
  15984. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15985. if (fileStream != 0)
  15986. {
  15987. int magicNumber = fileStream->readInt();
  15988. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15989. {
  15990. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15991. magicNumber = PropertyFileConstants::magicNumber;
  15992. }
  15993. if (magicNumber == PropertyFileConstants::magicNumber)
  15994. {
  15995. loadedOk = true;
  15996. BufferedInputStream in (fileStream.release(), 2048, true);
  15997. int numValues = in.readInt();
  15998. while (--numValues >= 0 && ! in.isExhausted())
  15999. {
  16000. const String key (in.readString());
  16001. const String value (in.readString());
  16002. jassert (key.isNotEmpty());
  16003. if (key.isNotEmpty())
  16004. getAllProperties().set (key, value);
  16005. }
  16006. }
  16007. else
  16008. {
  16009. // Not a binary props file - let's see if it's XML..
  16010. fileStream = 0;
  16011. XmlDocument parser (f);
  16012. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  16013. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  16014. {
  16015. doc = parser.getDocumentElement();
  16016. if (doc != 0)
  16017. {
  16018. loadedOk = true;
  16019. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  16020. {
  16021. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  16022. if (name.isNotEmpty())
  16023. {
  16024. getAllProperties().set (name,
  16025. e->getFirstChildElement() != 0
  16026. ? e->getFirstChildElement()->createDocument (String::empty, true)
  16027. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  16028. }
  16029. }
  16030. }
  16031. else
  16032. {
  16033. // must be a pretty broken XML file we're trying to parse here,
  16034. // or a sign that this object needs an InterProcessLock,
  16035. // or just a failure reading the file. This last reason is why
  16036. // we don't jassertfalse here.
  16037. }
  16038. }
  16039. }
  16040. }
  16041. else
  16042. {
  16043. loadedOk = ! f.exists();
  16044. }
  16045. }
  16046. PropertiesFile::~PropertiesFile()
  16047. {
  16048. if (! saveIfNeeded())
  16049. jassertfalse;
  16050. }
  16051. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  16052. {
  16053. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  16054. }
  16055. bool PropertiesFile::saveIfNeeded()
  16056. {
  16057. const ScopedLock sl (getLock());
  16058. return (! needsWriting) || save();
  16059. }
  16060. bool PropertiesFile::needsToBeSaved() const
  16061. {
  16062. const ScopedLock sl (getLock());
  16063. return needsWriting;
  16064. }
  16065. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  16066. {
  16067. const ScopedLock sl (getLock());
  16068. needsWriting = needsToBeSaved_;
  16069. }
  16070. bool PropertiesFile::save()
  16071. {
  16072. const ScopedLock sl (getLock());
  16073. stopTimer();
  16074. if (file == File::nonexistent
  16075. || file.isDirectory()
  16076. || ! file.getParentDirectory().createDirectory())
  16077. return false;
  16078. if ((options & storeAsXML) != 0)
  16079. {
  16080. XmlElement doc (PropertyFileConstants::fileTag);
  16081. for (int i = 0; i < getAllProperties().size(); ++i)
  16082. {
  16083. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  16084. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  16085. // if the value seems to contain xml, store it as such..
  16086. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  16087. if (childElement != 0)
  16088. e->addChildElement (childElement);
  16089. else
  16090. e->setAttribute (PropertyFileConstants::valueAttribute,
  16091. getAllProperties().getAllValues() [i]);
  16092. }
  16093. ProcessScopedLock pl (createProcessLock());
  16094. if (pl != 0 && ! pl->isLocked())
  16095. return false; // locking failure..
  16096. if (doc.writeToFile (file, String::empty))
  16097. {
  16098. needsWriting = false;
  16099. return true;
  16100. }
  16101. }
  16102. else
  16103. {
  16104. ProcessScopedLock pl (createProcessLock());
  16105. if (pl != 0 && ! pl->isLocked())
  16106. return false; // locking failure..
  16107. TemporaryFile tempFile (file);
  16108. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  16109. if (out != 0)
  16110. {
  16111. if ((options & storeAsCompressedBinary) != 0)
  16112. {
  16113. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  16114. out->flush();
  16115. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  16116. }
  16117. else
  16118. {
  16119. // have you set up the storage option flags correctly?
  16120. jassert ((options & storeAsBinary) != 0);
  16121. out->writeInt (PropertyFileConstants::magicNumber);
  16122. }
  16123. const int numProperties = getAllProperties().size();
  16124. out->writeInt (numProperties);
  16125. for (int i = 0; i < numProperties; ++i)
  16126. {
  16127. out->writeString (getAllProperties().getAllKeys() [i]);
  16128. out->writeString (getAllProperties().getAllValues() [i]);
  16129. }
  16130. out = 0;
  16131. if (tempFile.overwriteTargetFileWithTemporary())
  16132. {
  16133. needsWriting = false;
  16134. return true;
  16135. }
  16136. }
  16137. }
  16138. return false;
  16139. }
  16140. void PropertiesFile::timerCallback()
  16141. {
  16142. saveIfNeeded();
  16143. }
  16144. void PropertiesFile::propertyChanged()
  16145. {
  16146. sendChangeMessage();
  16147. needsWriting = true;
  16148. if (timerInterval > 0)
  16149. startTimer (timerInterval);
  16150. else if (timerInterval == 0)
  16151. saveIfNeeded();
  16152. }
  16153. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  16154. const String& fileNameSuffix,
  16155. const String& folderName,
  16156. const bool commonToAllUsers)
  16157. {
  16158. // mustn't have illegal characters in this name..
  16159. jassert (applicationName == File::createLegalFileName (applicationName));
  16160. #if JUCE_MAC || JUCE_IOS
  16161. File dir (commonToAllUsers ? "/Library/Preferences"
  16162. : "~/Library/Preferences");
  16163. if (folderName.isNotEmpty())
  16164. dir = dir.getChildFile (folderName);
  16165. #endif
  16166. #ifdef JUCE_LINUX
  16167. const File dir ((commonToAllUsers ? "/var/" : "~/")
  16168. + (folderName.isNotEmpty() ? folderName
  16169. : ("." + applicationName)));
  16170. #endif
  16171. #if JUCE_WINDOWS
  16172. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  16173. : File::userApplicationDataDirectory));
  16174. if (dir == File::nonexistent)
  16175. return File::nonexistent;
  16176. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  16177. : applicationName);
  16178. #endif
  16179. return dir.getChildFile (applicationName)
  16180. .withFileExtension (fileNameSuffix);
  16181. }
  16182. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  16183. const String& fileNameSuffix,
  16184. const String& folderName,
  16185. const bool commonToAllUsers,
  16186. const int millisecondsBeforeSaving,
  16187. const int propertiesFileOptions,
  16188. InterProcessLock* processLock_)
  16189. {
  16190. const File file (getDefaultAppSettingsFile (applicationName,
  16191. fileNameSuffix,
  16192. folderName,
  16193. commonToAllUsers));
  16194. jassert (file != File::nonexistent);
  16195. if (file == File::nonexistent)
  16196. return 0;
  16197. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  16198. }
  16199. END_JUCE_NAMESPACE
  16200. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  16201. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  16202. BEGIN_JUCE_NAMESPACE
  16203. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  16204. const String& fileWildcard_,
  16205. const String& openFileDialogTitle_,
  16206. const String& saveFileDialogTitle_)
  16207. : changedSinceSave (false),
  16208. fileExtension (fileExtension_),
  16209. fileWildcard (fileWildcard_),
  16210. openFileDialogTitle (openFileDialogTitle_),
  16211. saveFileDialogTitle (saveFileDialogTitle_)
  16212. {
  16213. }
  16214. FileBasedDocument::~FileBasedDocument()
  16215. {
  16216. }
  16217. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  16218. {
  16219. if (changedSinceSave != hasChanged)
  16220. {
  16221. changedSinceSave = hasChanged;
  16222. sendChangeMessage();
  16223. }
  16224. }
  16225. void FileBasedDocument::changed()
  16226. {
  16227. changedSinceSave = true;
  16228. sendChangeMessage();
  16229. }
  16230. void FileBasedDocument::setFile (const File& newFile)
  16231. {
  16232. if (documentFile != newFile)
  16233. {
  16234. documentFile = newFile;
  16235. changed();
  16236. }
  16237. }
  16238. bool FileBasedDocument::loadFrom (const File& newFile,
  16239. const bool showMessageOnFailure)
  16240. {
  16241. MouseCursor::showWaitCursor();
  16242. const File oldFile (documentFile);
  16243. documentFile = newFile;
  16244. String error;
  16245. if (newFile.existsAsFile())
  16246. {
  16247. error = loadDocument (newFile);
  16248. if (error.isEmpty())
  16249. {
  16250. setChangedFlag (false);
  16251. MouseCursor::hideWaitCursor();
  16252. setLastDocumentOpened (newFile);
  16253. return true;
  16254. }
  16255. }
  16256. else
  16257. {
  16258. error = "The file doesn't exist";
  16259. }
  16260. documentFile = oldFile;
  16261. MouseCursor::hideWaitCursor();
  16262. if (showMessageOnFailure)
  16263. {
  16264. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16265. TRANS("Failed to open file..."),
  16266. TRANS("There was an error while trying to load the file:\n\n")
  16267. + newFile.getFullPathName()
  16268. + "\n\n"
  16269. + error);
  16270. }
  16271. return false;
  16272. }
  16273. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16274. {
  16275. FileChooser fc (openFileDialogTitle,
  16276. getLastDocumentOpened(),
  16277. fileWildcard);
  16278. if (fc.browseForFileToOpen())
  16279. return loadFrom (fc.getResult(), showMessageOnFailure);
  16280. return false;
  16281. }
  16282. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16283. const bool showMessageOnFailure)
  16284. {
  16285. return saveAs (documentFile,
  16286. false,
  16287. askUserForFileIfNotSpecified,
  16288. showMessageOnFailure);
  16289. }
  16290. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16291. const bool warnAboutOverwritingExistingFiles,
  16292. const bool askUserForFileIfNotSpecified,
  16293. const bool showMessageOnFailure)
  16294. {
  16295. if (newFile == File::nonexistent)
  16296. {
  16297. if (askUserForFileIfNotSpecified)
  16298. {
  16299. return saveAsInteractive (true);
  16300. }
  16301. else
  16302. {
  16303. // can't save to an unspecified file
  16304. jassertfalse;
  16305. return failedToWriteToFile;
  16306. }
  16307. }
  16308. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16309. {
  16310. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16311. TRANS("File already exists"),
  16312. TRANS("There's already a file called:\n\n")
  16313. + newFile.getFullPathName()
  16314. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16315. TRANS("overwrite"),
  16316. TRANS("cancel")))
  16317. {
  16318. return userCancelledSave;
  16319. }
  16320. }
  16321. MouseCursor::showWaitCursor();
  16322. const File oldFile (documentFile);
  16323. documentFile = newFile;
  16324. String error (saveDocument (newFile));
  16325. if (error.isEmpty())
  16326. {
  16327. setChangedFlag (false);
  16328. MouseCursor::hideWaitCursor();
  16329. return savedOk;
  16330. }
  16331. documentFile = oldFile;
  16332. MouseCursor::hideWaitCursor();
  16333. if (showMessageOnFailure)
  16334. {
  16335. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16336. TRANS("Error writing to file..."),
  16337. TRANS("An error occurred while trying to save \"")
  16338. + getDocumentTitle()
  16339. + TRANS("\" to the file:\n\n")
  16340. + newFile.getFullPathName()
  16341. + "\n\n"
  16342. + error);
  16343. }
  16344. return failedToWriteToFile;
  16345. }
  16346. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16347. {
  16348. if (! hasChangedSinceSaved())
  16349. return savedOk;
  16350. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16351. TRANS("Closing document..."),
  16352. TRANS("Do you want to save the changes to \"")
  16353. + getDocumentTitle() + "\"?",
  16354. TRANS("save"),
  16355. TRANS("discard changes"),
  16356. TRANS("cancel"));
  16357. if (r == 1)
  16358. {
  16359. // save changes
  16360. return save (true, true);
  16361. }
  16362. else if (r == 2)
  16363. {
  16364. // discard changes
  16365. return savedOk;
  16366. }
  16367. return userCancelledSave;
  16368. }
  16369. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16370. {
  16371. File f;
  16372. if (documentFile.existsAsFile())
  16373. f = documentFile;
  16374. else
  16375. f = getLastDocumentOpened();
  16376. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16377. if (legalFilename.isEmpty())
  16378. legalFilename = "unnamed";
  16379. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16380. f = f.getSiblingFile (legalFilename);
  16381. else
  16382. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16383. f = f.withFileExtension (fileExtension)
  16384. .getNonexistentSibling (true);
  16385. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16386. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16387. {
  16388. File chosen (fc.getResult());
  16389. if (chosen.getFileExtension().isEmpty())
  16390. {
  16391. chosen = chosen.withFileExtension (fileExtension);
  16392. if (chosen.exists())
  16393. {
  16394. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16395. TRANS("File already exists"),
  16396. TRANS("There's already a file called:")
  16397. + "\n\n" + chosen.getFullPathName()
  16398. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16399. TRANS("overwrite"),
  16400. TRANS("cancel")))
  16401. {
  16402. return userCancelledSave;
  16403. }
  16404. }
  16405. }
  16406. setLastDocumentOpened (chosen);
  16407. return saveAs (chosen, false, false, true);
  16408. }
  16409. return userCancelledSave;
  16410. }
  16411. END_JUCE_NAMESPACE
  16412. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16413. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16414. BEGIN_JUCE_NAMESPACE
  16415. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16416. : maxNumberOfItems (10)
  16417. {
  16418. }
  16419. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16420. {
  16421. }
  16422. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16423. {
  16424. maxNumberOfItems = jmax (1, newMaxNumber);
  16425. while (getNumFiles() > maxNumberOfItems)
  16426. files.remove (getNumFiles() - 1);
  16427. }
  16428. int RecentlyOpenedFilesList::getNumFiles() const
  16429. {
  16430. return files.size();
  16431. }
  16432. const File RecentlyOpenedFilesList::getFile (const int index) const
  16433. {
  16434. return File (files [index]);
  16435. }
  16436. void RecentlyOpenedFilesList::clear()
  16437. {
  16438. files.clear();
  16439. }
  16440. void RecentlyOpenedFilesList::addFile (const File& file)
  16441. {
  16442. const String path (file.getFullPathName());
  16443. files.removeString (path, true);
  16444. files.insert (0, path);
  16445. setMaxNumberOfItems (maxNumberOfItems);
  16446. }
  16447. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16448. {
  16449. for (int i = getNumFiles(); --i >= 0;)
  16450. if (! getFile(i).exists())
  16451. files.remove (i);
  16452. }
  16453. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16454. const int baseItemId,
  16455. const bool showFullPaths,
  16456. const bool dontAddNonExistentFiles,
  16457. const File** filesToAvoid)
  16458. {
  16459. int num = 0;
  16460. for (int i = 0; i < getNumFiles(); ++i)
  16461. {
  16462. const File f (getFile(i));
  16463. if ((! dontAddNonExistentFiles) || f.exists())
  16464. {
  16465. bool needsAvoiding = false;
  16466. if (filesToAvoid != 0)
  16467. {
  16468. const File** avoid = filesToAvoid;
  16469. while (*avoid != 0)
  16470. {
  16471. if (f == **avoid)
  16472. {
  16473. needsAvoiding = true;
  16474. break;
  16475. }
  16476. ++avoid;
  16477. }
  16478. }
  16479. if (! needsAvoiding)
  16480. {
  16481. menuToAddTo.addItem (baseItemId + i,
  16482. showFullPaths ? f.getFullPathName()
  16483. : f.getFileName());
  16484. ++num;
  16485. }
  16486. }
  16487. }
  16488. return num;
  16489. }
  16490. const String RecentlyOpenedFilesList::toString() const
  16491. {
  16492. return files.joinIntoString ("\n");
  16493. }
  16494. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16495. {
  16496. clear();
  16497. files.addLines (stringifiedVersion);
  16498. setMaxNumberOfItems (maxNumberOfItems);
  16499. }
  16500. END_JUCE_NAMESPACE
  16501. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16502. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16503. BEGIN_JUCE_NAMESPACE
  16504. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16505. const int minimumTransactions)
  16506. : totalUnitsStored (0),
  16507. nextIndex (0),
  16508. newTransaction (true),
  16509. reentrancyCheck (false)
  16510. {
  16511. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16512. minimumTransactions);
  16513. }
  16514. UndoManager::~UndoManager()
  16515. {
  16516. clearUndoHistory();
  16517. }
  16518. void UndoManager::clearUndoHistory()
  16519. {
  16520. transactions.clear();
  16521. transactionNames.clear();
  16522. totalUnitsStored = 0;
  16523. nextIndex = 0;
  16524. sendChangeMessage();
  16525. }
  16526. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16527. {
  16528. return totalUnitsStored;
  16529. }
  16530. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16531. const int minimumTransactions)
  16532. {
  16533. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16534. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16535. }
  16536. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16537. {
  16538. if (command_ != 0)
  16539. {
  16540. ScopedPointer<UndoableAction> command (command_);
  16541. if (actionName.isNotEmpty())
  16542. currentTransactionName = actionName;
  16543. if (reentrancyCheck)
  16544. {
  16545. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16546. // undo() methods, or else these actions won't actually get done.
  16547. return false;
  16548. }
  16549. else if (command->perform())
  16550. {
  16551. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16552. if (commandSet != 0 && ! newTransaction)
  16553. {
  16554. UndoableAction* lastAction = commandSet->getLast();
  16555. if (lastAction != 0)
  16556. {
  16557. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16558. if (coalescedAction != 0)
  16559. {
  16560. command = coalescedAction;
  16561. totalUnitsStored -= lastAction->getSizeInUnits();
  16562. commandSet->removeLast();
  16563. }
  16564. }
  16565. }
  16566. else
  16567. {
  16568. commandSet = new OwnedArray<UndoableAction>();
  16569. transactions.insert (nextIndex, commandSet);
  16570. transactionNames.insert (nextIndex, currentTransactionName);
  16571. ++nextIndex;
  16572. }
  16573. totalUnitsStored += command->getSizeInUnits();
  16574. commandSet->add (command.release());
  16575. newTransaction = false;
  16576. while (nextIndex < transactions.size())
  16577. {
  16578. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16579. for (int i = lastSet->size(); --i >= 0;)
  16580. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16581. transactions.removeLast();
  16582. transactionNames.remove (transactionNames.size() - 1);
  16583. }
  16584. while (nextIndex > 0
  16585. && totalUnitsStored > maxNumUnitsToKeep
  16586. && transactions.size() > minimumTransactionsToKeep)
  16587. {
  16588. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16589. for (int i = firstSet->size(); --i >= 0;)
  16590. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16591. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16592. transactions.remove (0);
  16593. transactionNames.remove (0);
  16594. --nextIndex;
  16595. }
  16596. sendChangeMessage();
  16597. return true;
  16598. }
  16599. }
  16600. return false;
  16601. }
  16602. void UndoManager::beginNewTransaction (const String& actionName)
  16603. {
  16604. newTransaction = true;
  16605. currentTransactionName = actionName;
  16606. }
  16607. void UndoManager::setCurrentTransactionName (const String& newName)
  16608. {
  16609. currentTransactionName = newName;
  16610. }
  16611. bool UndoManager::canUndo() const
  16612. {
  16613. return nextIndex > 0;
  16614. }
  16615. bool UndoManager::canRedo() const
  16616. {
  16617. return nextIndex < transactions.size();
  16618. }
  16619. const String UndoManager::getUndoDescription() const
  16620. {
  16621. return transactionNames [nextIndex - 1];
  16622. }
  16623. const String UndoManager::getRedoDescription() const
  16624. {
  16625. return transactionNames [nextIndex];
  16626. }
  16627. bool UndoManager::undo()
  16628. {
  16629. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16630. if (commandSet == 0)
  16631. return false;
  16632. reentrancyCheck = true;
  16633. bool failed = false;
  16634. for (int i = commandSet->size(); --i >= 0;)
  16635. {
  16636. if (! commandSet->getUnchecked(i)->undo())
  16637. {
  16638. jassertfalse;
  16639. failed = true;
  16640. break;
  16641. }
  16642. }
  16643. reentrancyCheck = false;
  16644. if (failed)
  16645. clearUndoHistory();
  16646. else
  16647. --nextIndex;
  16648. beginNewTransaction();
  16649. sendChangeMessage();
  16650. return true;
  16651. }
  16652. bool UndoManager::redo()
  16653. {
  16654. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16655. if (commandSet == 0)
  16656. return false;
  16657. reentrancyCheck = true;
  16658. bool failed = false;
  16659. for (int i = 0; i < commandSet->size(); ++i)
  16660. {
  16661. if (! commandSet->getUnchecked(i)->perform())
  16662. {
  16663. jassertfalse;
  16664. failed = true;
  16665. break;
  16666. }
  16667. }
  16668. reentrancyCheck = false;
  16669. if (failed)
  16670. clearUndoHistory();
  16671. else
  16672. ++nextIndex;
  16673. beginNewTransaction();
  16674. sendChangeMessage();
  16675. return true;
  16676. }
  16677. bool UndoManager::undoCurrentTransactionOnly()
  16678. {
  16679. return newTransaction ? false : undo();
  16680. }
  16681. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16682. {
  16683. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16684. if (commandSet != 0 && ! newTransaction)
  16685. {
  16686. for (int i = 0; i < commandSet->size(); ++i)
  16687. actionsFound.add (commandSet->getUnchecked(i));
  16688. }
  16689. }
  16690. int UndoManager::getNumActionsInCurrentTransaction() const
  16691. {
  16692. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16693. if (commandSet != 0 && ! newTransaction)
  16694. return commandSet->size();
  16695. return 0;
  16696. }
  16697. END_JUCE_NAMESPACE
  16698. /*** End of inlined file: juce_UndoManager.cpp ***/
  16699. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16700. BEGIN_JUCE_NAMESPACE
  16701. static const char* const aiffFormatName = "AIFF file";
  16702. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16703. class AiffAudioFormatReader : public AudioFormatReader
  16704. {
  16705. public:
  16706. int bytesPerFrame;
  16707. int64 dataChunkStart;
  16708. bool littleEndian;
  16709. AiffAudioFormatReader (InputStream* in)
  16710. : AudioFormatReader (in, TRANS (aiffFormatName))
  16711. {
  16712. if (input->readInt() == chunkName ("FORM"))
  16713. {
  16714. const int len = input->readIntBigEndian();
  16715. const int64 end = input->getPosition() + len;
  16716. const int nextType = input->readInt();
  16717. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16718. {
  16719. bool hasGotVer = false;
  16720. bool hasGotData = false;
  16721. bool hasGotType = false;
  16722. while (input->getPosition() < end)
  16723. {
  16724. const int type = input->readInt();
  16725. const uint32 length = (uint32) input->readIntBigEndian();
  16726. const int64 chunkEnd = input->getPosition() + length;
  16727. if (type == chunkName ("FVER"))
  16728. {
  16729. hasGotVer = true;
  16730. const int ver = input->readIntBigEndian();
  16731. if (ver != 0 && ver != (int) 0xa2805140)
  16732. break;
  16733. }
  16734. else if (type == chunkName ("COMM"))
  16735. {
  16736. hasGotType = true;
  16737. numChannels = (unsigned int) input->readShortBigEndian();
  16738. lengthInSamples = input->readIntBigEndian();
  16739. bitsPerSample = input->readShortBigEndian();
  16740. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16741. unsigned char sampleRateBytes[10];
  16742. input->read (sampleRateBytes, 10);
  16743. const int byte0 = sampleRateBytes[0];
  16744. if ((byte0 & 0x80) != 0
  16745. || byte0 <= 0x3F || byte0 > 0x40
  16746. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16747. break;
  16748. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16749. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16750. sampleRate = (int) sampRate;
  16751. if (length <= 18)
  16752. {
  16753. // some types don't have a chunk large enough to include a compression
  16754. // type, so assume it's just big-endian pcm
  16755. littleEndian = false;
  16756. }
  16757. else
  16758. {
  16759. const int compType = input->readInt();
  16760. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16761. {
  16762. littleEndian = false;
  16763. }
  16764. else if (compType == chunkName ("sowt"))
  16765. {
  16766. littleEndian = true;
  16767. }
  16768. else
  16769. {
  16770. sampleRate = 0;
  16771. break;
  16772. }
  16773. }
  16774. }
  16775. else if (type == chunkName ("SSND"))
  16776. {
  16777. hasGotData = true;
  16778. const int offset = input->readIntBigEndian();
  16779. dataChunkStart = input->getPosition() + 4 + offset;
  16780. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16781. }
  16782. else if ((hasGotVer && hasGotData && hasGotType)
  16783. || chunkEnd < input->getPosition()
  16784. || input->isExhausted())
  16785. {
  16786. break;
  16787. }
  16788. input->setPosition (chunkEnd);
  16789. }
  16790. }
  16791. }
  16792. }
  16793. ~AiffAudioFormatReader()
  16794. {
  16795. }
  16796. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16797. int64 startSampleInFile, int numSamples)
  16798. {
  16799. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16800. if (samplesAvailable < numSamples)
  16801. {
  16802. for (int i = numDestChannels; --i >= 0;)
  16803. if (destSamples[i] != 0)
  16804. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16805. numSamples = (int) samplesAvailable;
  16806. }
  16807. if (numSamples <= 0)
  16808. return true;
  16809. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16810. while (numSamples > 0)
  16811. {
  16812. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16813. char tempBuffer [tempBufSize];
  16814. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16815. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16816. if (bytesRead < numThisTime * bytesPerFrame)
  16817. {
  16818. jassert (bytesRead >= 0);
  16819. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16820. }
  16821. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16822. if (littleEndian)
  16823. {
  16824. switch (bitsPerSample)
  16825. {
  16826. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16827. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16828. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16829. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16830. default: jassertfalse; break;
  16831. }
  16832. }
  16833. else
  16834. {
  16835. switch (bitsPerSample)
  16836. {
  16837. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16838. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16839. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16840. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16841. default: jassertfalse; break;
  16842. }
  16843. }
  16844. startOffsetInDestBuffer += numThisTime;
  16845. numSamples -= numThisTime;
  16846. }
  16847. return true;
  16848. }
  16849. private:
  16850. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16851. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16852. };
  16853. class AiffAudioFormatWriter : public AudioFormatWriter
  16854. {
  16855. public:
  16856. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16857. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16858. lengthInSamples (0),
  16859. bytesWritten (0),
  16860. writeFailed (false)
  16861. {
  16862. headerPosition = out->getPosition();
  16863. writeHeader();
  16864. }
  16865. ~AiffAudioFormatWriter()
  16866. {
  16867. if ((bytesWritten & 1) != 0)
  16868. output->writeByte (0);
  16869. writeHeader();
  16870. }
  16871. bool write (const int** data, int numSamples)
  16872. {
  16873. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16874. if (writeFailed)
  16875. return false;
  16876. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16877. tempBlock.ensureSize (bytes, false);
  16878. switch (bitsPerSample)
  16879. {
  16880. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16881. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16882. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16883. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16884. default: jassertfalse; break;
  16885. }
  16886. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16887. || ! output->write (tempBlock.getData(), bytes))
  16888. {
  16889. // failed to write to disk, so let's try writing the header.
  16890. // If it's just run out of disk space, then if it does manage
  16891. // to write the header, we'll still have a useable file..
  16892. writeHeader();
  16893. writeFailed = true;
  16894. return false;
  16895. }
  16896. else
  16897. {
  16898. bytesWritten += bytes;
  16899. lengthInSamples += numSamples;
  16900. return true;
  16901. }
  16902. }
  16903. private:
  16904. MemoryBlock tempBlock;
  16905. uint32 lengthInSamples, bytesWritten;
  16906. int64 headerPosition;
  16907. bool writeFailed;
  16908. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16909. void writeHeader()
  16910. {
  16911. const bool couldSeekOk = output->setPosition (headerPosition);
  16912. (void) couldSeekOk;
  16913. // if this fails, you've given it an output stream that can't seek! It needs
  16914. // to be able to seek back to write the header
  16915. jassert (couldSeekOk);
  16916. const int headerLen = 54;
  16917. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16918. audioBytes += (audioBytes & 1);
  16919. output->writeInt (chunkName ("FORM"));
  16920. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16921. output->writeInt (chunkName ("AIFF"));
  16922. output->writeInt (chunkName ("COMM"));
  16923. output->writeIntBigEndian (18);
  16924. output->writeShortBigEndian ((short) numChannels);
  16925. output->writeIntBigEndian (lengthInSamples);
  16926. output->writeShortBigEndian ((short) bitsPerSample);
  16927. uint8 sampleRateBytes[10];
  16928. zeromem (sampleRateBytes, 10);
  16929. if (sampleRate <= 1)
  16930. {
  16931. sampleRateBytes[0] = 0x3f;
  16932. sampleRateBytes[1] = 0xff;
  16933. sampleRateBytes[2] = 0x80;
  16934. }
  16935. else
  16936. {
  16937. int mask = 0x40000000;
  16938. sampleRateBytes[0] = 0x40;
  16939. if (sampleRate >= mask)
  16940. {
  16941. jassertfalse;
  16942. sampleRateBytes[1] = 0x1d;
  16943. }
  16944. else
  16945. {
  16946. int n = (int) sampleRate;
  16947. int i;
  16948. for (i = 0; i <= 32 ; ++i)
  16949. {
  16950. if ((n & mask) != 0)
  16951. break;
  16952. mask >>= 1;
  16953. }
  16954. n = n << (i + 1);
  16955. sampleRateBytes[1] = (uint8) (29 - i);
  16956. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16957. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16958. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16959. sampleRateBytes[5] = (uint8) (n & 0xff);
  16960. }
  16961. }
  16962. output->write (sampleRateBytes, 10);
  16963. output->writeInt (chunkName ("SSND"));
  16964. output->writeIntBigEndian (audioBytes + 8);
  16965. output->writeInt (0);
  16966. output->writeInt (0);
  16967. jassert (output->getPosition() == headerLen);
  16968. }
  16969. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16970. };
  16971. AiffAudioFormat::AiffAudioFormat()
  16972. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16973. {
  16974. }
  16975. AiffAudioFormat::~AiffAudioFormat()
  16976. {
  16977. }
  16978. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16979. {
  16980. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16981. return Array <int> (rates);
  16982. }
  16983. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16984. {
  16985. const int depths[] = { 8, 16, 24, 0 };
  16986. return Array <int> (depths);
  16987. }
  16988. bool AiffAudioFormat::canDoStereo() { return true; }
  16989. bool AiffAudioFormat::canDoMono() { return true; }
  16990. #if JUCE_MAC
  16991. bool AiffAudioFormat::canHandleFile (const File& f)
  16992. {
  16993. if (AudioFormat::canHandleFile (f))
  16994. return true;
  16995. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16996. return type == 'AIFF' || type == 'AIFC'
  16997. || type == 'aiff' || type == 'aifc';
  16998. }
  16999. #endif
  17000. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  17001. {
  17002. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  17003. if (w->sampleRate != 0)
  17004. return w.release();
  17005. if (! deleteStreamIfOpeningFails)
  17006. w->input = 0;
  17007. return 0;
  17008. }
  17009. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  17010. double sampleRate,
  17011. unsigned int numberOfChannels,
  17012. int bitsPerSample,
  17013. const StringPairArray& /*metadataValues*/,
  17014. int /*qualityOptionIndex*/)
  17015. {
  17016. if (getPossibleBitDepths().contains (bitsPerSample))
  17017. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  17018. return 0;
  17019. }
  17020. END_JUCE_NAMESPACE
  17021. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  17022. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  17023. BEGIN_JUCE_NAMESPACE
  17024. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  17025. : formatName (name),
  17026. fileExtensions (extensions)
  17027. {
  17028. }
  17029. AudioFormat::~AudioFormat()
  17030. {
  17031. }
  17032. bool AudioFormat::canHandleFile (const File& f)
  17033. {
  17034. for (int i = 0; i < fileExtensions.size(); ++i)
  17035. if (f.hasFileExtension (fileExtensions[i]))
  17036. return true;
  17037. return false;
  17038. }
  17039. const String& AudioFormat::getFormatName() const { return formatName; }
  17040. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  17041. bool AudioFormat::isCompressed() { return false; }
  17042. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  17043. END_JUCE_NAMESPACE
  17044. /*** End of inlined file: juce_AudioFormat.cpp ***/
  17045. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  17046. BEGIN_JUCE_NAMESPACE
  17047. AudioFormatReader::AudioFormatReader (InputStream* const in,
  17048. const String& formatName_)
  17049. : sampleRate (0),
  17050. bitsPerSample (0),
  17051. lengthInSamples (0),
  17052. numChannels (0),
  17053. usesFloatingPointData (false),
  17054. input (in),
  17055. formatName (formatName_)
  17056. {
  17057. }
  17058. AudioFormatReader::~AudioFormatReader()
  17059. {
  17060. delete input;
  17061. }
  17062. bool AudioFormatReader::read (int* const* destSamples,
  17063. int numDestChannels,
  17064. int64 startSampleInSource,
  17065. int numSamplesToRead,
  17066. const bool fillLeftoverChannelsWithCopies)
  17067. {
  17068. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  17069. int startOffsetInDestBuffer = 0;
  17070. if (startSampleInSource < 0)
  17071. {
  17072. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  17073. for (int i = numDestChannels; --i >= 0;)
  17074. if (destSamples[i] != 0)
  17075. zeromem (destSamples[i], sizeof (int) * silence);
  17076. startOffsetInDestBuffer += silence;
  17077. numSamplesToRead -= silence;
  17078. startSampleInSource = 0;
  17079. }
  17080. if (numSamplesToRead <= 0)
  17081. return true;
  17082. if (! readSamples (const_cast<int**> (destSamples),
  17083. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  17084. startSampleInSource, numSamplesToRead))
  17085. return false;
  17086. if (numDestChannels > (int) numChannels)
  17087. {
  17088. if (fillLeftoverChannelsWithCopies)
  17089. {
  17090. int* lastFullChannel = destSamples[0];
  17091. for (int i = (int) numChannels; --i > 0;)
  17092. {
  17093. if (destSamples[i] != 0)
  17094. {
  17095. lastFullChannel = destSamples[i];
  17096. break;
  17097. }
  17098. }
  17099. if (lastFullChannel != 0)
  17100. for (int i = numChannels; i < numDestChannels; ++i)
  17101. if (destSamples[i] != 0)
  17102. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17103. }
  17104. else
  17105. {
  17106. for (int i = numChannels; i < numDestChannels; ++i)
  17107. if (destSamples[i] != 0)
  17108. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17109. }
  17110. }
  17111. return true;
  17112. }
  17113. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  17114. {
  17115. float mn = buffer[0];
  17116. float mx = mn;
  17117. for (int i = 1; i < num; ++i)
  17118. {
  17119. const float s = buffer[i];
  17120. if (s > mx) mx = s;
  17121. if (s < mn) mn = s;
  17122. }
  17123. maxVal = mx;
  17124. minVal = mn;
  17125. }
  17126. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17127. int64 numSamples,
  17128. float& lowestLeft, float& highestLeft,
  17129. float& lowestRight, float& highestRight)
  17130. {
  17131. if (numSamples <= 0)
  17132. {
  17133. lowestLeft = 0;
  17134. lowestRight = 0;
  17135. highestLeft = 0;
  17136. highestRight = 0;
  17137. return;
  17138. }
  17139. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17140. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17141. int* tempBuffer[3];
  17142. tempBuffer[0] = tempSpace.getData();
  17143. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17144. tempBuffer[2] = 0;
  17145. if (usesFloatingPointData)
  17146. {
  17147. float lmin = 1.0e6f;
  17148. float lmax = -lmin;
  17149. float rmin = lmin;
  17150. float rmax = lmax;
  17151. while (numSamples > 0)
  17152. {
  17153. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17154. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17155. numSamples -= numToDo;
  17156. startSampleInFile += numToDo;
  17157. float bufmin, bufmax;
  17158. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufmax, bufmin);
  17159. lmin = jmin (lmin, bufmin);
  17160. lmax = jmax (lmax, bufmax);
  17161. if (numChannels > 1)
  17162. {
  17163. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufmax, bufmin);
  17164. rmin = jmin (rmin, bufmin);
  17165. rmax = jmax (rmax, bufmax);
  17166. }
  17167. }
  17168. if (numChannels <= 1)
  17169. {
  17170. rmax = lmax;
  17171. rmin = lmin;
  17172. }
  17173. lowestLeft = lmin;
  17174. highestLeft = lmax;
  17175. lowestRight = rmin;
  17176. highestRight = rmax;
  17177. }
  17178. else
  17179. {
  17180. int lmax = std::numeric_limits<int>::min();
  17181. int lmin = std::numeric_limits<int>::max();
  17182. int rmax = std::numeric_limits<int>::min();
  17183. int rmin = std::numeric_limits<int>::max();
  17184. while (numSamples > 0)
  17185. {
  17186. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17187. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17188. numSamples -= numToDo;
  17189. startSampleInFile += numToDo;
  17190. for (int j = numChannels; --j >= 0;)
  17191. {
  17192. int bufMax = std::numeric_limits<int>::min();
  17193. int bufMin = std::numeric_limits<int>::max();
  17194. const int* const b = tempBuffer[j];
  17195. for (int i = 0; i < numToDo; ++i)
  17196. {
  17197. const int samp = b[i];
  17198. if (samp < bufMin)
  17199. bufMin = samp;
  17200. if (samp > bufMax)
  17201. bufMax = samp;
  17202. }
  17203. if (j == 0)
  17204. {
  17205. lmax = jmax (lmax, bufMax);
  17206. lmin = jmin (lmin, bufMin);
  17207. }
  17208. else
  17209. {
  17210. rmax = jmax (rmax, bufMax);
  17211. rmin = jmin (rmin, bufMin);
  17212. }
  17213. }
  17214. }
  17215. if (numChannels <= 1)
  17216. {
  17217. rmax = lmax;
  17218. rmin = lmin;
  17219. }
  17220. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17221. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17222. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17223. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17224. }
  17225. }
  17226. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17227. int64 numSamplesToSearch,
  17228. const double magnitudeRangeMinimum,
  17229. const double magnitudeRangeMaximum,
  17230. const int minimumConsecutiveSamples)
  17231. {
  17232. if (numSamplesToSearch == 0)
  17233. return -1;
  17234. const int bufferSize = 4096;
  17235. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17236. int* tempBuffer[3];
  17237. tempBuffer[0] = tempSpace.getData();
  17238. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17239. tempBuffer[2] = 0;
  17240. int consecutive = 0;
  17241. int64 firstMatchPos = -1;
  17242. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17243. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17244. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17245. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17246. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17247. while (numSamplesToSearch != 0)
  17248. {
  17249. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17250. int64 bufferStart = startSample;
  17251. if (numSamplesToSearch < 0)
  17252. bufferStart -= numThisTime;
  17253. if (bufferStart >= (int) lengthInSamples)
  17254. break;
  17255. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17256. int num = numThisTime;
  17257. while (--num >= 0)
  17258. {
  17259. if (numSamplesToSearch < 0)
  17260. --startSample;
  17261. bool matches = false;
  17262. const int index = (int) (startSample - bufferStart);
  17263. if (usesFloatingPointData)
  17264. {
  17265. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17266. if (sample1 >= magnitudeRangeMinimum
  17267. && sample1 <= magnitudeRangeMaximum)
  17268. {
  17269. matches = true;
  17270. }
  17271. else if (numChannels > 1)
  17272. {
  17273. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17274. matches = (sample2 >= magnitudeRangeMinimum
  17275. && sample2 <= magnitudeRangeMaximum);
  17276. }
  17277. }
  17278. else
  17279. {
  17280. const int sample1 = abs (tempBuffer[0] [index]);
  17281. if (sample1 >= intMagnitudeRangeMinimum
  17282. && sample1 <= intMagnitudeRangeMaximum)
  17283. {
  17284. matches = true;
  17285. }
  17286. else if (numChannels > 1)
  17287. {
  17288. const int sample2 = abs (tempBuffer[1][index]);
  17289. matches = (sample2 >= intMagnitudeRangeMinimum
  17290. && sample2 <= intMagnitudeRangeMaximum);
  17291. }
  17292. }
  17293. if (matches)
  17294. {
  17295. if (firstMatchPos < 0)
  17296. firstMatchPos = startSample;
  17297. if (++consecutive >= minimumConsecutiveSamples)
  17298. {
  17299. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17300. return -1;
  17301. return firstMatchPos;
  17302. }
  17303. }
  17304. else
  17305. {
  17306. consecutive = 0;
  17307. firstMatchPos = -1;
  17308. }
  17309. if (numSamplesToSearch > 0)
  17310. ++startSample;
  17311. }
  17312. if (numSamplesToSearch > 0)
  17313. numSamplesToSearch -= numThisTime;
  17314. else
  17315. numSamplesToSearch += numThisTime;
  17316. }
  17317. return -1;
  17318. }
  17319. END_JUCE_NAMESPACE
  17320. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17321. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17322. BEGIN_JUCE_NAMESPACE
  17323. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17324. const String& formatName_,
  17325. const double rate,
  17326. const unsigned int numChannels_,
  17327. const unsigned int bitsPerSample_)
  17328. : sampleRate (rate),
  17329. numChannels (numChannels_),
  17330. bitsPerSample (bitsPerSample_),
  17331. usesFloatingPointData (false),
  17332. output (out),
  17333. formatName (formatName_)
  17334. {
  17335. }
  17336. AudioFormatWriter::~AudioFormatWriter()
  17337. {
  17338. delete output;
  17339. }
  17340. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17341. int64 startSample,
  17342. int64 numSamplesToRead)
  17343. {
  17344. const int bufferSize = 16384;
  17345. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17346. int* buffers [128];
  17347. zerostruct (buffers);
  17348. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17349. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17350. if (numSamplesToRead < 0)
  17351. numSamplesToRead = reader.lengthInSamples;
  17352. while (numSamplesToRead > 0)
  17353. {
  17354. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17355. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17356. return false;
  17357. if (reader.usesFloatingPointData != isFloatingPoint())
  17358. {
  17359. int** bufferChan = buffers;
  17360. while (*bufferChan != 0)
  17361. {
  17362. int* b = *bufferChan++;
  17363. if (isFloatingPoint())
  17364. {
  17365. // int -> float
  17366. const double factor = 1.0 / std::numeric_limits<int>::max();
  17367. for (int i = 0; i < numToDo; ++i)
  17368. ((float*) b)[i] = (float) (factor * b[i]);
  17369. }
  17370. else
  17371. {
  17372. // float -> int
  17373. for (int i = 0; i < numToDo; ++i)
  17374. {
  17375. const double samp = *(const float*) b;
  17376. if (samp <= -1.0)
  17377. *b++ = std::numeric_limits<int>::min();
  17378. else if (samp >= 1.0)
  17379. *b++ = std::numeric_limits<int>::max();
  17380. else
  17381. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17382. }
  17383. }
  17384. }
  17385. }
  17386. if (! write (const_cast<const int**> (buffers), numToDo))
  17387. return false;
  17388. numSamplesToRead -= numToDo;
  17389. startSample += numToDo;
  17390. }
  17391. return true;
  17392. }
  17393. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17394. {
  17395. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17396. while (numSamplesToRead > 0)
  17397. {
  17398. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17399. AudioSourceChannelInfo info;
  17400. info.buffer = &tempBuffer;
  17401. info.startSample = 0;
  17402. info.numSamples = numToDo;
  17403. info.clearActiveBufferRegion();
  17404. source.getNextAudioBlock (info);
  17405. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17406. return false;
  17407. numSamplesToRead -= numToDo;
  17408. }
  17409. return true;
  17410. }
  17411. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17412. {
  17413. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17414. if (numSamples <= 0)
  17415. return true;
  17416. HeapBlock<int> tempBuffer;
  17417. HeapBlock<int*> chans (numChannels + 1);
  17418. chans [numChannels] = 0;
  17419. if (isFloatingPoint())
  17420. {
  17421. for (int i = numChannels; --i >= 0;)
  17422. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17423. }
  17424. else
  17425. {
  17426. tempBuffer.malloc (numSamples * numChannels);
  17427. for (unsigned int i = 0; i < numChannels; ++i)
  17428. {
  17429. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17430. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17431. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17432. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17433. destData.convertSamples (sourceData, numSamples);
  17434. }
  17435. }
  17436. return write ((const int**) chans.getData(), numSamples);
  17437. }
  17438. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17439. public AbstractFifo
  17440. {
  17441. public:
  17442. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize)
  17443. : AbstractFifo (bufferSize),
  17444. buffer (numChannels, bufferSize),
  17445. timeSliceThread (timeSliceThread_),
  17446. writer (writer_), isRunning (true)
  17447. {
  17448. timeSliceThread.addTimeSliceClient (this);
  17449. }
  17450. ~Buffer()
  17451. {
  17452. isRunning = false;
  17453. timeSliceThread.removeTimeSliceClient (this);
  17454. while (useTimeSlice())
  17455. {}
  17456. }
  17457. bool write (const float** data, int numSamples)
  17458. {
  17459. if (numSamples <= 0 || ! isRunning)
  17460. return true;
  17461. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17462. int start1, size1, start2, size2;
  17463. prepareToWrite (numSamples, start1, size1, start2, size2);
  17464. if (size1 + size2 < numSamples)
  17465. return false;
  17466. for (int i = buffer.getNumChannels(); --i >= 0;)
  17467. {
  17468. buffer.copyFrom (i, start1, data[i], size1);
  17469. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17470. }
  17471. finishedWrite (size1 + size2);
  17472. timeSliceThread.notify();
  17473. return true;
  17474. }
  17475. bool useTimeSlice()
  17476. {
  17477. const int numToDo = getTotalSize() / 4;
  17478. int start1, size1, start2, size2;
  17479. prepareToRead (numToDo, start1, size1, start2, size2);
  17480. if (size1 <= 0)
  17481. return false;
  17482. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17483. if (size2 > 0)
  17484. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17485. finishedRead (size1 + size2);
  17486. return true;
  17487. }
  17488. private:
  17489. AudioSampleBuffer buffer;
  17490. TimeSliceThread& timeSliceThread;
  17491. ScopedPointer<AudioFormatWriter> writer;
  17492. volatile bool isRunning;
  17493. JUCE_DECLARE_NON_COPYABLE (Buffer);
  17494. };
  17495. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17496. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17497. {
  17498. }
  17499. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17500. {
  17501. }
  17502. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17503. {
  17504. return buffer->write (data, numSamples);
  17505. }
  17506. END_JUCE_NAMESPACE
  17507. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17508. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17509. BEGIN_JUCE_NAMESPACE
  17510. AudioFormatManager::AudioFormatManager()
  17511. : defaultFormatIndex (0)
  17512. {
  17513. }
  17514. AudioFormatManager::~AudioFormatManager()
  17515. {
  17516. clearFormats();
  17517. clearSingletonInstance();
  17518. }
  17519. juce_ImplementSingleton (AudioFormatManager);
  17520. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17521. const bool makeThisTheDefaultFormat)
  17522. {
  17523. jassert (newFormat != 0);
  17524. if (newFormat != 0)
  17525. {
  17526. #if JUCE_DEBUG
  17527. for (int i = getNumKnownFormats(); --i >= 0;)
  17528. {
  17529. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17530. {
  17531. jassertfalse; // trying to add the same format twice!
  17532. }
  17533. }
  17534. #endif
  17535. if (makeThisTheDefaultFormat)
  17536. defaultFormatIndex = getNumKnownFormats();
  17537. knownFormats.add (newFormat);
  17538. }
  17539. }
  17540. void AudioFormatManager::registerBasicFormats()
  17541. {
  17542. #if JUCE_MAC
  17543. registerFormat (new AiffAudioFormat(), true);
  17544. registerFormat (new WavAudioFormat(), false);
  17545. #else
  17546. registerFormat (new WavAudioFormat(), true);
  17547. registerFormat (new AiffAudioFormat(), false);
  17548. #endif
  17549. #if JUCE_USE_FLAC
  17550. registerFormat (new FlacAudioFormat(), false);
  17551. #endif
  17552. #if JUCE_USE_OGGVORBIS
  17553. registerFormat (new OggVorbisAudioFormat(), false);
  17554. #endif
  17555. }
  17556. void AudioFormatManager::clearFormats()
  17557. {
  17558. knownFormats.clear();
  17559. defaultFormatIndex = 0;
  17560. }
  17561. int AudioFormatManager::getNumKnownFormats() const
  17562. {
  17563. return knownFormats.size();
  17564. }
  17565. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17566. {
  17567. return knownFormats [index];
  17568. }
  17569. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17570. {
  17571. return getKnownFormat (defaultFormatIndex);
  17572. }
  17573. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17574. {
  17575. String e (fileExtension);
  17576. if (! e.startsWithChar ('.'))
  17577. e = "." + e;
  17578. for (int i = 0; i < getNumKnownFormats(); ++i)
  17579. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17580. return getKnownFormat(i);
  17581. return 0;
  17582. }
  17583. const String AudioFormatManager::getWildcardForAllFormats() const
  17584. {
  17585. StringArray allExtensions;
  17586. int i;
  17587. for (i = 0; i < getNumKnownFormats(); ++i)
  17588. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17589. allExtensions.trim();
  17590. allExtensions.removeEmptyStrings();
  17591. String s;
  17592. for (i = 0; i < allExtensions.size(); ++i)
  17593. {
  17594. s << '*';
  17595. if (! allExtensions[i].startsWithChar ('.'))
  17596. s << '.';
  17597. s << allExtensions[i];
  17598. if (i < allExtensions.size() - 1)
  17599. s << ';';
  17600. }
  17601. return s;
  17602. }
  17603. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17604. {
  17605. // you need to actually register some formats before the manager can
  17606. // use them to open a file!
  17607. jassert (getNumKnownFormats() > 0);
  17608. for (int i = 0; i < getNumKnownFormats(); ++i)
  17609. {
  17610. AudioFormat* const af = getKnownFormat(i);
  17611. if (af->canHandleFile (file))
  17612. {
  17613. InputStream* const in = file.createInputStream();
  17614. if (in != 0)
  17615. {
  17616. AudioFormatReader* const r = af->createReaderFor (in, true);
  17617. if (r != 0)
  17618. return r;
  17619. }
  17620. }
  17621. }
  17622. return 0;
  17623. }
  17624. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17625. {
  17626. // you need to actually register some formats before the manager can
  17627. // use them to open a file!
  17628. jassert (getNumKnownFormats() > 0);
  17629. ScopedPointer <InputStream> in (audioFileStream);
  17630. if (in != 0)
  17631. {
  17632. const int64 originalStreamPos = in->getPosition();
  17633. for (int i = 0; i < getNumKnownFormats(); ++i)
  17634. {
  17635. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17636. if (r != 0)
  17637. {
  17638. in.release();
  17639. return r;
  17640. }
  17641. in->setPosition (originalStreamPos);
  17642. // the stream that is passed-in must be capable of being repositioned so
  17643. // that all the formats can have a go at opening it.
  17644. jassert (in->getPosition() == originalStreamPos);
  17645. }
  17646. }
  17647. return 0;
  17648. }
  17649. END_JUCE_NAMESPACE
  17650. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17651. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17652. BEGIN_JUCE_NAMESPACE
  17653. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17654. const int64 startSample_,
  17655. const int64 length_,
  17656. const bool deleteSourceWhenDeleted_)
  17657. : AudioFormatReader (0, source_->getFormatName()),
  17658. source (source_),
  17659. startSample (startSample_),
  17660. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17661. {
  17662. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17663. sampleRate = source->sampleRate;
  17664. bitsPerSample = source->bitsPerSample;
  17665. lengthInSamples = length;
  17666. numChannels = source->numChannels;
  17667. usesFloatingPointData = source->usesFloatingPointData;
  17668. }
  17669. AudioSubsectionReader::~AudioSubsectionReader()
  17670. {
  17671. if (deleteSourceWhenDeleted)
  17672. delete source;
  17673. }
  17674. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17675. int64 startSampleInFile, int numSamples)
  17676. {
  17677. if (startSampleInFile + numSamples > length)
  17678. {
  17679. for (int i = numDestChannels; --i >= 0;)
  17680. if (destSamples[i] != 0)
  17681. zeromem (destSamples[i], sizeof (int) * numSamples);
  17682. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17683. if (numSamples <= 0)
  17684. return true;
  17685. }
  17686. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17687. startSampleInFile + startSample, numSamples);
  17688. }
  17689. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17690. int64 numSamples,
  17691. float& lowestLeft,
  17692. float& highestLeft,
  17693. float& lowestRight,
  17694. float& highestRight)
  17695. {
  17696. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17697. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17698. source->readMaxLevels (startSampleInFile + startSample,
  17699. numSamples,
  17700. lowestLeft,
  17701. highestLeft,
  17702. lowestRight,
  17703. highestRight);
  17704. }
  17705. END_JUCE_NAMESPACE
  17706. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17707. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17708. BEGIN_JUCE_NAMESPACE
  17709. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17710. AudioFormatManager& formatManagerToUse_,
  17711. AudioThumbnailCache& cacheToUse)
  17712. : formatManagerToUse (formatManagerToUse_),
  17713. cache (cacheToUse),
  17714. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17715. timeBeforeDeletingReader (2000)
  17716. {
  17717. clear();
  17718. }
  17719. AudioThumbnail::~AudioThumbnail()
  17720. {
  17721. cache.removeThumbnail (this);
  17722. const ScopedLock sl (readerLock);
  17723. reader = 0;
  17724. }
  17725. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17726. {
  17727. jassert (data.getData() != 0);
  17728. return static_cast <DataFormat*> (data.getData());
  17729. }
  17730. void AudioThumbnail::setSource (InputSource* const newSource)
  17731. {
  17732. cache.removeThumbnail (this);
  17733. timerCallback(); // stops the timer and deletes the reader
  17734. source = newSource;
  17735. clear();
  17736. if (newSource != 0
  17737. && ! (cache.loadThumb (*this, newSource->hashCode())
  17738. && isFullyLoaded()))
  17739. {
  17740. {
  17741. const ScopedLock sl (readerLock);
  17742. reader = createReader();
  17743. }
  17744. if (reader != 0)
  17745. {
  17746. initialiseFromAudioFile (*reader);
  17747. cache.addThumbnail (this);
  17748. }
  17749. }
  17750. sendChangeMessage();
  17751. }
  17752. bool AudioThumbnail::useTimeSlice()
  17753. {
  17754. const ScopedLock sl (readerLock);
  17755. if (isFullyLoaded())
  17756. {
  17757. if (reader != 0)
  17758. startTimer (timeBeforeDeletingReader);
  17759. cache.removeThumbnail (this);
  17760. return false;
  17761. }
  17762. if (reader == 0)
  17763. reader = createReader();
  17764. if (reader != 0)
  17765. {
  17766. readNextBlockFromAudioFile (*reader);
  17767. stopTimer();
  17768. sendChangeMessage();
  17769. const bool justFinished = isFullyLoaded();
  17770. if (justFinished)
  17771. cache.storeThumb (*this, source->hashCode());
  17772. return ! justFinished;
  17773. }
  17774. return false;
  17775. }
  17776. AudioFormatReader* AudioThumbnail::createReader() const
  17777. {
  17778. if (source != 0)
  17779. {
  17780. InputStream* const audioFileStream = source->createInputStream();
  17781. if (audioFileStream != 0)
  17782. return formatManagerToUse.createReaderFor (audioFileStream);
  17783. }
  17784. return 0;
  17785. }
  17786. void AudioThumbnail::timerCallback()
  17787. {
  17788. stopTimer();
  17789. const ScopedLock sl (readerLock);
  17790. reader = 0;
  17791. }
  17792. void AudioThumbnail::clear()
  17793. {
  17794. data.setSize (sizeof (DataFormat) + 3);
  17795. DataFormat* const d = getData();
  17796. d->thumbnailMagic[0] = 'j';
  17797. d->thumbnailMagic[1] = 'a';
  17798. d->thumbnailMagic[2] = 't';
  17799. d->thumbnailMagic[3] = 'm';
  17800. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17801. d->totalSamples = 0;
  17802. d->numFinishedSamples = 0;
  17803. d->numThumbnailSamples = 0;
  17804. d->numChannels = 0;
  17805. d->sampleRate = 0;
  17806. numSamplesCached = 0;
  17807. cacheNeedsRefilling = true;
  17808. }
  17809. void AudioThumbnail::loadFrom (InputStream& input)
  17810. {
  17811. const ScopedLock sl (readerLock);
  17812. data.setSize (0);
  17813. input.readIntoMemoryBlock (data);
  17814. DataFormat* const d = getData();
  17815. d->flipEndiannessIfBigEndian();
  17816. if (! (d->thumbnailMagic[0] == 'j'
  17817. && d->thumbnailMagic[1] == 'a'
  17818. && d->thumbnailMagic[2] == 't'
  17819. && d->thumbnailMagic[3] == 'm'))
  17820. {
  17821. clear();
  17822. }
  17823. numSamplesCached = 0;
  17824. cacheNeedsRefilling = true;
  17825. }
  17826. void AudioThumbnail::saveTo (OutputStream& output) const
  17827. {
  17828. const ScopedLock sl (readerLock);
  17829. DataFormat* const d = getData();
  17830. d->flipEndiannessIfBigEndian();
  17831. output.write (d, (int) data.getSize());
  17832. d->flipEndiannessIfBigEndian();
  17833. }
  17834. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17835. {
  17836. DataFormat* d = getData();
  17837. d->totalSamples = fileReader.lengthInSamples;
  17838. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17839. d->numFinishedSamples = 0;
  17840. d->sampleRate = roundToInt (fileReader.sampleRate);
  17841. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17842. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17843. d = getData();
  17844. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17845. return d->totalSamples > 0;
  17846. }
  17847. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17848. {
  17849. DataFormat* const d = getData();
  17850. if (d->numFinishedSamples < d->totalSamples)
  17851. {
  17852. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17853. generateSection (fileReader,
  17854. d->numFinishedSamples,
  17855. numToDo);
  17856. d->numFinishedSamples += numToDo;
  17857. }
  17858. cacheNeedsRefilling = true;
  17859. return d->numFinishedSamples < d->totalSamples;
  17860. }
  17861. int AudioThumbnail::getNumChannels() const throw()
  17862. {
  17863. return getData()->numChannels;
  17864. }
  17865. double AudioThumbnail::getTotalLength() const throw()
  17866. {
  17867. const DataFormat* const d = getData();
  17868. if (d->sampleRate > 0)
  17869. return d->totalSamples / (double) d->sampleRate;
  17870. else
  17871. return 0.0;
  17872. }
  17873. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17874. int64 startSample,
  17875. int numSamples)
  17876. {
  17877. DataFormat* const d = getData();
  17878. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17879. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17880. char* const l = getChannelData (0);
  17881. char* const r = getChannelData (1);
  17882. for (int i = firstDataPos; i < lastDataPos; ++i)
  17883. {
  17884. const int sourceStart = i * d->samplesPerThumbSample;
  17885. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17886. float lowestLeft, highestLeft, lowestRight, highestRight;
  17887. fileReader.readMaxLevels (sourceStart,
  17888. sourceEnd - sourceStart,
  17889. lowestLeft,
  17890. highestLeft,
  17891. lowestRight,
  17892. highestRight);
  17893. int n = i * 2;
  17894. if (r != 0)
  17895. {
  17896. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17897. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17898. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17899. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17900. }
  17901. else
  17902. {
  17903. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17904. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17905. }
  17906. }
  17907. }
  17908. char* AudioThumbnail::getChannelData (int channel) const
  17909. {
  17910. DataFormat* const d = getData();
  17911. if (channel >= 0 && channel < d->numChannels)
  17912. return d->data + (channel * 2 * d->numThumbnailSamples);
  17913. return 0;
  17914. }
  17915. bool AudioThumbnail::isFullyLoaded() const throw()
  17916. {
  17917. const DataFormat* const d = getData();
  17918. return d->numFinishedSamples >= d->totalSamples;
  17919. }
  17920. void AudioThumbnail::refillCache (const int numSamples,
  17921. double startTime,
  17922. const double timePerPixel)
  17923. {
  17924. const DataFormat* const d = getData();
  17925. if (numSamples <= 0
  17926. || timePerPixel <= 0.0
  17927. || d->sampleRate <= 0)
  17928. {
  17929. numSamplesCached = 0;
  17930. cacheNeedsRefilling = true;
  17931. return;
  17932. }
  17933. if (numSamples == numSamplesCached
  17934. && numChannelsCached == d->numChannels
  17935. && startTime == cachedStart
  17936. && timePerPixel == cachedTimePerPixel
  17937. && ! cacheNeedsRefilling)
  17938. {
  17939. return;
  17940. }
  17941. numSamplesCached = numSamples;
  17942. numChannelsCached = d->numChannels;
  17943. cachedStart = startTime;
  17944. cachedTimePerPixel = timePerPixel;
  17945. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17946. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17947. const ScopedLock sl (readerLock);
  17948. cacheNeedsRefilling = false;
  17949. if (needExtraDetail && reader == 0)
  17950. reader = createReader();
  17951. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17952. {
  17953. startTimer (timeBeforeDeletingReader);
  17954. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17955. int sample = roundToInt (startTime * d->sampleRate);
  17956. for (int i = numSamples; --i >= 0;)
  17957. {
  17958. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17959. if (sample >= 0)
  17960. {
  17961. if (sample >= reader->lengthInSamples)
  17962. break;
  17963. float lmin, lmax, rmin, rmax;
  17964. reader->readMaxLevels (sample,
  17965. jmax (1, nextSample - sample),
  17966. lmin, lmax, rmin, rmax);
  17967. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17968. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17969. if (numChannelsCached > 1)
  17970. {
  17971. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  17972. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  17973. }
  17974. cacheData += 2 * numChannelsCached;
  17975. }
  17976. startTime += timePerPixel;
  17977. sample = nextSample;
  17978. }
  17979. }
  17980. else
  17981. {
  17982. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17983. {
  17984. char* const channelData = getChannelData (channelNum);
  17985. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  17986. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  17987. startTime = cachedStart;
  17988. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17989. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  17990. for (int i = numSamples; --i >= 0;)
  17991. {
  17992. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17993. if (sample >= 0 && channelData != 0)
  17994. {
  17995. char mx = -128;
  17996. char mn = 127;
  17997. while (sample <= nextSample)
  17998. {
  17999. if (sample >= numFinished)
  18000. break;
  18001. const int n = sample << 1;
  18002. const char sampMin = channelData [n];
  18003. const char sampMax = channelData [n + 1];
  18004. if (sampMin < mn)
  18005. mn = sampMin;
  18006. if (sampMax > mx)
  18007. mx = sampMax;
  18008. ++sample;
  18009. }
  18010. if (mn <= mx)
  18011. {
  18012. cacheData[0] = mn;
  18013. cacheData[1] = mx;
  18014. }
  18015. else
  18016. {
  18017. cacheData[0] = 1;
  18018. cacheData[1] = 0;
  18019. }
  18020. }
  18021. else
  18022. {
  18023. cacheData[0] = 1;
  18024. cacheData[1] = 0;
  18025. }
  18026. cacheData += numChannelsCached * 2;
  18027. startTime += timePerPixel;
  18028. sample = nextSample;
  18029. }
  18030. }
  18031. }
  18032. }
  18033. void AudioThumbnail::drawChannel (Graphics& g,
  18034. int x, int y, int w, int h,
  18035. double startTime,
  18036. double endTime,
  18037. int channelNum,
  18038. const float verticalZoomFactor)
  18039. {
  18040. refillCache (w, startTime, (endTime - startTime) / w);
  18041. if (numSamplesCached >= w
  18042. && channelNum >= 0
  18043. && channelNum < numChannelsCached)
  18044. {
  18045. const float topY = (float) y;
  18046. const float bottomY = topY + h;
  18047. const float midY = topY + h * 0.5f;
  18048. const float vscale = verticalZoomFactor * h / 256.0f;
  18049. const Rectangle<int> clip (g.getClipBounds());
  18050. const int skipLeft = jlimit (0, w, clip.getX() - x);
  18051. w -= skipLeft;
  18052. x += skipLeft;
  18053. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  18054. + (channelNum << 1)
  18055. + skipLeft * (numChannelsCached << 1);
  18056. while (--w >= 0)
  18057. {
  18058. const char mn = cacheData[0];
  18059. const char mx = cacheData[1];
  18060. cacheData += numChannelsCached << 1;
  18061. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  18062. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  18063. jmin (midY - mn * vscale + 0.3f, bottomY));
  18064. if (++x >= clip.getRight())
  18065. break;
  18066. }
  18067. }
  18068. }
  18069. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  18070. {
  18071. #if JUCE_BIG_ENDIAN
  18072. struct Flipper
  18073. {
  18074. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  18075. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  18076. };
  18077. Flipper::flip (samplesPerThumbSample);
  18078. Flipper::flip (totalSamples);
  18079. Flipper::flip (numFinishedSamples);
  18080. Flipper::flip (numThumbnailSamples);
  18081. Flipper::flip (numChannels);
  18082. Flipper::flip (sampleRate);
  18083. #endif
  18084. }
  18085. END_JUCE_NAMESPACE
  18086. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18087. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18088. BEGIN_JUCE_NAMESPACE
  18089. struct ThumbnailCacheEntry
  18090. {
  18091. int64 hash;
  18092. uint32 lastUsed;
  18093. MemoryBlock data;
  18094. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  18095. };
  18096. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18097. : TimeSliceThread ("thumb cache"),
  18098. maxNumThumbsToStore (maxNumThumbsToStore_)
  18099. {
  18100. startThread (2);
  18101. }
  18102. AudioThumbnailCache::~AudioThumbnailCache()
  18103. {
  18104. }
  18105. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18106. {
  18107. for (int i = thumbs.size(); --i >= 0;)
  18108. {
  18109. if (thumbs[i]->hash == hashCode)
  18110. {
  18111. MemoryInputStream in (thumbs[i]->data, false);
  18112. thumb.loadFrom (in);
  18113. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  18114. return true;
  18115. }
  18116. }
  18117. return false;
  18118. }
  18119. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18120. const int64 hashCode)
  18121. {
  18122. MemoryOutputStream out;
  18123. thumb.saveTo (out);
  18124. ThumbnailCacheEntry* te = 0;
  18125. for (int i = thumbs.size(); --i >= 0;)
  18126. {
  18127. if (thumbs[i]->hash == hashCode)
  18128. {
  18129. te = thumbs[i];
  18130. break;
  18131. }
  18132. }
  18133. if (te == 0)
  18134. {
  18135. te = new ThumbnailCacheEntry();
  18136. te->hash = hashCode;
  18137. if (thumbs.size() < maxNumThumbsToStore)
  18138. {
  18139. thumbs.add (te);
  18140. }
  18141. else
  18142. {
  18143. int oldest = 0;
  18144. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  18145. int i;
  18146. for (i = thumbs.size(); --i >= 0;)
  18147. if (thumbs[i]->lastUsed < oldestTime)
  18148. oldest = i;
  18149. thumbs.set (i, te);
  18150. }
  18151. }
  18152. te->lastUsed = Time::getMillisecondCounter();
  18153. te->data.setSize (0);
  18154. te->data.append (out.getData(), out.getDataSize());
  18155. }
  18156. void AudioThumbnailCache::clear()
  18157. {
  18158. thumbs.clear();
  18159. }
  18160. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  18161. {
  18162. addTimeSliceClient (thumb);
  18163. }
  18164. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  18165. {
  18166. removeTimeSliceClient (thumb);
  18167. }
  18168. END_JUCE_NAMESPACE
  18169. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18170. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18171. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18172. #if ! JUCE_WINDOWS
  18173. #include <QuickTime/Movies.h>
  18174. #include <QuickTime/QTML.h>
  18175. #include <QuickTime/QuickTimeComponents.h>
  18176. #include <QuickTime/MediaHandlers.h>
  18177. #include <QuickTime/ImageCodec.h>
  18178. #else
  18179. #if JUCE_MSVC
  18180. #pragma warning (push)
  18181. #pragma warning (disable : 4100)
  18182. #endif
  18183. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18184. add its header directory to your include path.
  18185. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18186. flag in juce_Config.h
  18187. */
  18188. #include <Movies.h>
  18189. #include <QTML.h>
  18190. #include <QuickTimeComponents.h>
  18191. #include <MediaHandlers.h>
  18192. #include <ImageCodec.h>
  18193. #if JUCE_MSVC
  18194. #pragma warning (pop)
  18195. #endif
  18196. #endif
  18197. BEGIN_JUCE_NAMESPACE
  18198. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18199. static const char* const quickTimeFormatName = "QuickTime file";
  18200. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18201. class QTAudioReader : public AudioFormatReader
  18202. {
  18203. public:
  18204. QTAudioReader (InputStream* const input_, const int trackNum_)
  18205. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18206. ok (false),
  18207. movie (0),
  18208. trackNum (trackNum_),
  18209. lastSampleRead (0),
  18210. lastThreadId (0),
  18211. extractor (0),
  18212. dataHandle (0)
  18213. {
  18214. JUCE_AUTORELEASEPOOL
  18215. bufferList.calloc (256, 1);
  18216. #if JUCE_WINDOWS
  18217. if (InitializeQTML (0) != noErr)
  18218. return;
  18219. #endif
  18220. if (EnterMovies() != noErr)
  18221. return;
  18222. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18223. if (! opened)
  18224. return;
  18225. {
  18226. const int numTracks = GetMovieTrackCount (movie);
  18227. int trackCount = 0;
  18228. for (int i = 1; i <= numTracks; ++i)
  18229. {
  18230. track = GetMovieIndTrack (movie, i);
  18231. media = GetTrackMedia (track);
  18232. OSType mediaType;
  18233. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18234. if (mediaType == SoundMediaType
  18235. && trackCount++ == trackNum_)
  18236. {
  18237. ok = true;
  18238. break;
  18239. }
  18240. }
  18241. }
  18242. if (! ok)
  18243. return;
  18244. ok = false;
  18245. lengthInSamples = GetMediaDecodeDuration (media);
  18246. usesFloatingPointData = false;
  18247. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18248. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18249. / GetMediaTimeScale (media);
  18250. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18251. unsigned long output_layout_size;
  18252. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18253. kQTPropertyClass_MovieAudioExtraction_Audio,
  18254. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18255. 0, &output_layout_size, 0);
  18256. if (err != noErr)
  18257. return;
  18258. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18259. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18260. err = MovieAudioExtractionGetProperty (extractor,
  18261. kQTPropertyClass_MovieAudioExtraction_Audio,
  18262. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18263. output_layout_size, qt_audio_channel_layout, 0);
  18264. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18265. err = MovieAudioExtractionSetProperty (extractor,
  18266. kQTPropertyClass_MovieAudioExtraction_Audio,
  18267. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18268. output_layout_size,
  18269. qt_audio_channel_layout);
  18270. err = MovieAudioExtractionGetProperty (extractor,
  18271. kQTPropertyClass_MovieAudioExtraction_Audio,
  18272. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18273. sizeof (inputStreamDesc),
  18274. &inputStreamDesc, 0);
  18275. if (err != noErr)
  18276. return;
  18277. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18278. | kAudioFormatFlagIsPacked
  18279. | kAudioFormatFlagsNativeEndian;
  18280. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18281. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18282. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18283. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18284. err = MovieAudioExtractionSetProperty (extractor,
  18285. kQTPropertyClass_MovieAudioExtraction_Audio,
  18286. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18287. sizeof (inputStreamDesc),
  18288. &inputStreamDesc);
  18289. if (err != noErr)
  18290. return;
  18291. Boolean allChannelsDiscrete = false;
  18292. err = MovieAudioExtractionSetProperty (extractor,
  18293. kQTPropertyClass_MovieAudioExtraction_Movie,
  18294. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18295. sizeof (allChannelsDiscrete),
  18296. &allChannelsDiscrete);
  18297. if (err != noErr)
  18298. return;
  18299. bufferList->mNumberBuffers = 1;
  18300. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18301. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18302. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18303. bufferList->mBuffers[0].mData = dataBuffer;
  18304. sampleRate = inputStreamDesc.mSampleRate;
  18305. bitsPerSample = 16;
  18306. numChannels = inputStreamDesc.mChannelsPerFrame;
  18307. detachThread();
  18308. ok = true;
  18309. }
  18310. ~QTAudioReader()
  18311. {
  18312. JUCE_AUTORELEASEPOOL
  18313. checkThreadIsAttached();
  18314. if (dataHandle != 0)
  18315. DisposeHandle (dataHandle);
  18316. if (extractor != 0)
  18317. {
  18318. MovieAudioExtractionEnd (extractor);
  18319. extractor = 0;
  18320. }
  18321. DisposeMovie (movie);
  18322. #if JUCE_MAC
  18323. ExitMoviesOnThread ();
  18324. #endif
  18325. }
  18326. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18327. int64 startSampleInFile, int numSamples)
  18328. {
  18329. JUCE_AUTORELEASEPOOL
  18330. checkThreadIsAttached();
  18331. bool ok = true;
  18332. while (numSamples > 0)
  18333. {
  18334. if (lastSampleRead != startSampleInFile)
  18335. {
  18336. TimeRecord time;
  18337. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18338. time.base = 0;
  18339. time.value.hi = 0;
  18340. time.value.lo = (UInt32) startSampleInFile;
  18341. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18342. kQTPropertyClass_MovieAudioExtraction_Movie,
  18343. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18344. sizeof (time), &time);
  18345. if (err != noErr)
  18346. {
  18347. ok = false;
  18348. break;
  18349. }
  18350. }
  18351. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18352. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18353. UInt32 outFlags = 0;
  18354. UInt32 actualNumFrames = framesToDo;
  18355. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18356. if (err != noErr)
  18357. {
  18358. ok = false;
  18359. break;
  18360. }
  18361. lastSampleRead = startSampleInFile + actualNumFrames;
  18362. const int samplesReceived = actualNumFrames;
  18363. for (int j = numDestChannels; --j >= 0;)
  18364. {
  18365. if (destSamples[j] != 0)
  18366. {
  18367. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18368. for (int i = 0; i < samplesReceived; ++i)
  18369. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18370. }
  18371. }
  18372. startOffsetInDestBuffer += samplesReceived;
  18373. startSampleInFile += samplesReceived;
  18374. numSamples -= samplesReceived;
  18375. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18376. {
  18377. for (int j = numDestChannels; --j >= 0;)
  18378. if (destSamples[j] != 0)
  18379. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18380. break;
  18381. }
  18382. }
  18383. detachThread();
  18384. return ok;
  18385. }
  18386. bool ok;
  18387. private:
  18388. Movie movie;
  18389. Media media;
  18390. Track track;
  18391. const int trackNum;
  18392. double trackUnitsPerFrame;
  18393. int samplesPerFrame;
  18394. int64 lastSampleRead;
  18395. Thread::ThreadID lastThreadId;
  18396. MovieAudioExtractionRef extractor;
  18397. AudioStreamBasicDescription inputStreamDesc;
  18398. HeapBlock <AudioBufferList> bufferList;
  18399. HeapBlock <char> dataBuffer;
  18400. Handle dataHandle;
  18401. void checkThreadIsAttached()
  18402. {
  18403. #if JUCE_MAC
  18404. if (Thread::getCurrentThreadId() != lastThreadId)
  18405. EnterMoviesOnThread (0);
  18406. AttachMovieToCurrentThread (movie);
  18407. #endif
  18408. }
  18409. void detachThread()
  18410. {
  18411. #if JUCE_MAC
  18412. DetachMovieFromCurrentThread (movie);
  18413. #endif
  18414. }
  18415. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18416. };
  18417. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18418. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18419. {
  18420. }
  18421. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18422. {
  18423. }
  18424. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18425. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18426. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18427. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18428. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18429. const bool deleteStreamIfOpeningFails)
  18430. {
  18431. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18432. if (r->ok)
  18433. return r.release();
  18434. if (! deleteStreamIfOpeningFails)
  18435. r->input = 0;
  18436. return 0;
  18437. }
  18438. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18439. double /*sampleRateToUse*/,
  18440. unsigned int /*numberOfChannels*/,
  18441. int /*bitsPerSample*/,
  18442. const StringPairArray& /*metadataValues*/,
  18443. int /*qualityOptionIndex*/)
  18444. {
  18445. jassertfalse; // not yet implemented!
  18446. return 0;
  18447. }
  18448. END_JUCE_NAMESPACE
  18449. #endif
  18450. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18451. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18452. BEGIN_JUCE_NAMESPACE
  18453. static const char* const wavFormatName = "WAV file";
  18454. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18455. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18456. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18457. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18458. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18459. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18460. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18461. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18462. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18463. const String& originator,
  18464. const String& originatorRef,
  18465. const Time& date,
  18466. const int64 timeReferenceSamples,
  18467. const String& codingHistory)
  18468. {
  18469. StringPairArray m;
  18470. m.set (bwavDescription, description);
  18471. m.set (bwavOriginator, originator);
  18472. m.set (bwavOriginatorRef, originatorRef);
  18473. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18474. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18475. m.set (bwavTimeReference, String (timeReferenceSamples));
  18476. m.set (bwavCodingHistory, codingHistory);
  18477. return m;
  18478. }
  18479. #if JUCE_MSVC
  18480. #pragma pack (push, 1)
  18481. #define PACKED
  18482. #elif JUCE_GCC
  18483. #define PACKED __attribute__((packed))
  18484. #else
  18485. #define PACKED
  18486. #endif
  18487. struct BWAVChunk
  18488. {
  18489. char description [256];
  18490. char originator [32];
  18491. char originatorRef [32];
  18492. char originationDate [10];
  18493. char originationTime [8];
  18494. uint32 timeRefLow;
  18495. uint32 timeRefHigh;
  18496. uint16 version;
  18497. uint8 umid[64];
  18498. uint8 reserved[190];
  18499. char codingHistory[1];
  18500. void copyTo (StringPairArray& values) const
  18501. {
  18502. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18503. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18504. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18505. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18506. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18507. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18508. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18509. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18510. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18511. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18512. }
  18513. static MemoryBlock createFrom (const StringPairArray& values)
  18514. {
  18515. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18516. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18517. data.fillWith (0);
  18518. BWAVChunk* b = (BWAVChunk*) data.getData();
  18519. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18520. // as they get called in the right order..
  18521. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18522. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18523. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18524. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18525. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18526. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18527. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18528. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18529. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18530. if (b->description[0] != 0
  18531. || b->originator[0] != 0
  18532. || b->originationDate[0] != 0
  18533. || b->originationTime[0] != 0
  18534. || b->codingHistory[0] != 0
  18535. || time != 0)
  18536. {
  18537. return data;
  18538. }
  18539. return MemoryBlock();
  18540. }
  18541. } PACKED;
  18542. struct SMPLChunk
  18543. {
  18544. struct SampleLoop
  18545. {
  18546. uint32 identifier;
  18547. uint32 type;
  18548. uint32 start;
  18549. uint32 end;
  18550. uint32 fraction;
  18551. uint32 playCount;
  18552. } PACKED;
  18553. uint32 manufacturer;
  18554. uint32 product;
  18555. uint32 samplePeriod;
  18556. uint32 midiUnityNote;
  18557. uint32 midiPitchFraction;
  18558. uint32 smpteFormat;
  18559. uint32 smpteOffset;
  18560. uint32 numSampleLoops;
  18561. uint32 samplerData;
  18562. SampleLoop loops[1];
  18563. void copyTo (StringPairArray& values, const int totalSize) const
  18564. {
  18565. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18566. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18567. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18568. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18569. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18570. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18571. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18572. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18573. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18574. for (uint32 i = 0; i < numSampleLoops; ++i)
  18575. {
  18576. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18577. break;
  18578. const String prefix ("Loop" + String(i));
  18579. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18580. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18581. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18582. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18583. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18584. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18585. }
  18586. }
  18587. static MemoryBlock createFrom (const StringPairArray& values)
  18588. {
  18589. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18590. if (numLoops <= 0)
  18591. return MemoryBlock();
  18592. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18593. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18594. data.fillWith (0);
  18595. SMPLChunk* s = (SMPLChunk*) data.getData();
  18596. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18597. // as they get called in the right order..
  18598. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18599. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18600. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18601. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18602. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18603. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18604. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18605. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18606. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18607. for (int i = 0; i < numLoops; ++i)
  18608. {
  18609. const String prefix ("Loop" + String(i));
  18610. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18611. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18612. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18613. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18614. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18615. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18616. }
  18617. return data;
  18618. }
  18619. } PACKED;
  18620. struct ExtensibleWavSubFormat
  18621. {
  18622. uint32 data1;
  18623. uint16 data2;
  18624. uint16 data3;
  18625. uint8 data4[8];
  18626. } PACKED;
  18627. #if JUCE_MSVC
  18628. #pragma pack (pop)
  18629. #endif
  18630. #undef PACKED
  18631. class WavAudioFormatReader : public AudioFormatReader
  18632. {
  18633. public:
  18634. WavAudioFormatReader (InputStream* const in)
  18635. : AudioFormatReader (in, TRANS (wavFormatName)),
  18636. bwavChunkStart (0),
  18637. bwavSize (0),
  18638. dataLength (0)
  18639. {
  18640. if (input->readInt() == chunkName ("RIFF"))
  18641. {
  18642. const uint32 len = (uint32) input->readInt();
  18643. const int64 end = input->getPosition() + len;
  18644. bool hasGotType = false;
  18645. bool hasGotData = false;
  18646. if (input->readInt() == chunkName ("WAVE"))
  18647. {
  18648. while (input->getPosition() < end
  18649. && ! input->isExhausted())
  18650. {
  18651. const int chunkType = input->readInt();
  18652. uint32 length = (uint32) input->readInt();
  18653. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18654. if (chunkType == chunkName ("fmt "))
  18655. {
  18656. // read the format chunk
  18657. const unsigned short format = input->readShort();
  18658. const short numChans = input->readShort();
  18659. sampleRate = input->readInt();
  18660. const int bytesPerSec = input->readInt();
  18661. numChannels = numChans;
  18662. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18663. bitsPerSample = 8 * bytesPerFrame / numChans;
  18664. if (format == 3)
  18665. {
  18666. usesFloatingPointData = true;
  18667. }
  18668. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18669. {
  18670. if (length < 40) // too short
  18671. {
  18672. bytesPerFrame = 0;
  18673. }
  18674. else
  18675. {
  18676. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18677. ExtensibleWavSubFormat subFormat;
  18678. subFormat.data1 = input->readInt();
  18679. subFormat.data2 = input->readShort();
  18680. subFormat.data3 = input->readShort();
  18681. input->read (subFormat.data4, sizeof (subFormat.data4));
  18682. const ExtensibleWavSubFormat pcmFormat
  18683. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18684. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18685. {
  18686. const ExtensibleWavSubFormat ambisonicFormat
  18687. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18688. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18689. bytesPerFrame = 0;
  18690. }
  18691. }
  18692. }
  18693. else if (format != 1)
  18694. {
  18695. bytesPerFrame = 0;
  18696. }
  18697. hasGotType = true;
  18698. }
  18699. else if (chunkType == chunkName ("data"))
  18700. {
  18701. // get the data chunk's position
  18702. dataLength = length;
  18703. dataChunkStart = input->getPosition();
  18704. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18705. hasGotData = true;
  18706. }
  18707. else if (chunkType == chunkName ("bext"))
  18708. {
  18709. bwavChunkStart = input->getPosition();
  18710. bwavSize = length;
  18711. // Broadcast-wav extension chunk..
  18712. HeapBlock <BWAVChunk> bwav;
  18713. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18714. input->read (bwav, length);
  18715. bwav->copyTo (metadataValues);
  18716. }
  18717. else if (chunkType == chunkName ("smpl"))
  18718. {
  18719. HeapBlock <SMPLChunk> smpl;
  18720. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18721. input->read (smpl, length);
  18722. smpl->copyTo (metadataValues, length);
  18723. }
  18724. else if (chunkEnd <= input->getPosition())
  18725. {
  18726. break;
  18727. }
  18728. input->setPosition (chunkEnd);
  18729. }
  18730. }
  18731. }
  18732. }
  18733. ~WavAudioFormatReader()
  18734. {
  18735. }
  18736. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18737. int64 startSampleInFile, int numSamples)
  18738. {
  18739. jassert (destSamples != 0);
  18740. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18741. if (samplesAvailable < numSamples)
  18742. {
  18743. for (int i = numDestChannels; --i >= 0;)
  18744. if (destSamples[i] != 0)
  18745. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18746. numSamples = (int) samplesAvailable;
  18747. }
  18748. if (numSamples <= 0)
  18749. return true;
  18750. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18751. while (numSamples > 0)
  18752. {
  18753. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18754. char tempBuffer [tempBufSize];
  18755. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18756. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18757. if (bytesRead < numThisTime * bytesPerFrame)
  18758. {
  18759. jassert (bytesRead >= 0);
  18760. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18761. }
  18762. switch (bitsPerSample)
  18763. {
  18764. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18765. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18766. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18767. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18768. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18769. default: jassertfalse; break;
  18770. }
  18771. startOffsetInDestBuffer += numThisTime;
  18772. numSamples -= numThisTime;
  18773. }
  18774. return true;
  18775. }
  18776. int64 bwavChunkStart, bwavSize;
  18777. private:
  18778. ScopedPointer<AudioData::Converter> converter;
  18779. int bytesPerFrame;
  18780. int64 dataChunkStart, dataLength;
  18781. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18782. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18783. };
  18784. class WavAudioFormatWriter : public AudioFormatWriter
  18785. {
  18786. public:
  18787. WavAudioFormatWriter (OutputStream* const out,
  18788. const double sampleRate_,
  18789. const unsigned int numChannels_,
  18790. const int bits,
  18791. const StringPairArray& metadataValues)
  18792. : AudioFormatWriter (out,
  18793. TRANS (wavFormatName),
  18794. sampleRate_,
  18795. numChannels_,
  18796. bits),
  18797. lengthInSamples (0),
  18798. bytesWritten (0),
  18799. writeFailed (false)
  18800. {
  18801. if (metadataValues.size() > 0)
  18802. {
  18803. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18804. smplChunk = SMPLChunk::createFrom (metadataValues);
  18805. }
  18806. headerPosition = out->getPosition();
  18807. writeHeader();
  18808. }
  18809. ~WavAudioFormatWriter()
  18810. {
  18811. writeHeader();
  18812. }
  18813. bool write (const int** data, int numSamples)
  18814. {
  18815. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18816. if (writeFailed)
  18817. return false;
  18818. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18819. tempBlock.ensureSize (bytes, false);
  18820. switch (bitsPerSample)
  18821. {
  18822. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18823. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18824. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18825. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18826. default: jassertfalse; break;
  18827. }
  18828. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18829. || ! output->write (tempBlock.getData(), bytes))
  18830. {
  18831. // failed to write to disk, so let's try writing the header.
  18832. // If it's just run out of disk space, then if it does manage
  18833. // to write the header, we'll still have a useable file..
  18834. writeHeader();
  18835. writeFailed = true;
  18836. return false;
  18837. }
  18838. else
  18839. {
  18840. bytesWritten += bytes;
  18841. lengthInSamples += numSamples;
  18842. return true;
  18843. }
  18844. }
  18845. private:
  18846. ScopedPointer<AudioData::Converter> converter;
  18847. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18848. uint32 lengthInSamples, bytesWritten;
  18849. int64 headerPosition;
  18850. bool writeFailed;
  18851. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18852. void writeHeader()
  18853. {
  18854. const bool seekedOk = output->setPosition (headerPosition);
  18855. (void) seekedOk;
  18856. // if this fails, you've given it an output stream that can't seek! It needs
  18857. // to be able to seek back to write the header
  18858. jassert (seekedOk);
  18859. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18860. output->writeInt (chunkName ("RIFF"));
  18861. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18862. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18863. output->writeInt (chunkName ("WAVE"));
  18864. output->writeInt (chunkName ("fmt "));
  18865. output->writeInt (16);
  18866. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18867. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18868. output->writeShort ((short) numChannels);
  18869. output->writeInt ((int) sampleRate);
  18870. output->writeInt (bytesPerFrame * (int) sampleRate);
  18871. output->writeShort ((short) bytesPerFrame);
  18872. output->writeShort ((short) bitsPerSample);
  18873. if (bwavChunk.getSize() > 0)
  18874. {
  18875. output->writeInt (chunkName ("bext"));
  18876. output->writeInt ((int) bwavChunk.getSize());
  18877. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18878. }
  18879. if (smplChunk.getSize() > 0)
  18880. {
  18881. output->writeInt (chunkName ("smpl"));
  18882. output->writeInt ((int) smplChunk.getSize());
  18883. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18884. }
  18885. output->writeInt (chunkName ("data"));
  18886. output->writeInt (lengthInSamples * bytesPerFrame);
  18887. usesFloatingPointData = (bitsPerSample == 32);
  18888. }
  18889. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18890. };
  18891. WavAudioFormat::WavAudioFormat()
  18892. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18893. {
  18894. }
  18895. WavAudioFormat::~WavAudioFormat()
  18896. {
  18897. }
  18898. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18899. {
  18900. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18901. return Array <int> (rates);
  18902. }
  18903. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18904. {
  18905. const int depths[] = { 8, 16, 24, 32, 0 };
  18906. return Array <int> (depths);
  18907. }
  18908. bool WavAudioFormat::canDoStereo() { return true; }
  18909. bool WavAudioFormat::canDoMono() { return true; }
  18910. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18911. const bool deleteStreamIfOpeningFails)
  18912. {
  18913. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18914. if (r->sampleRate != 0)
  18915. return r.release();
  18916. if (! deleteStreamIfOpeningFails)
  18917. r->input = 0;
  18918. return 0;
  18919. }
  18920. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18921. double sampleRate,
  18922. unsigned int numChannels,
  18923. int bitsPerSample,
  18924. const StringPairArray& metadataValues,
  18925. int /*qualityOptionIndex*/)
  18926. {
  18927. if (getPossibleBitDepths().contains (bitsPerSample))
  18928. {
  18929. return new WavAudioFormatWriter (out,
  18930. sampleRate,
  18931. numChannels,
  18932. bitsPerSample,
  18933. metadataValues);
  18934. }
  18935. return 0;
  18936. }
  18937. namespace
  18938. {
  18939. bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18940. {
  18941. TemporaryFile tempFile (file);
  18942. WavAudioFormat wav;
  18943. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18944. if (reader != 0)
  18945. {
  18946. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18947. if (outStream != 0)
  18948. {
  18949. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18950. reader->numChannels, reader->bitsPerSample,
  18951. metadata, 0));
  18952. if (writer != 0)
  18953. {
  18954. outStream.release();
  18955. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18956. writer = 0;
  18957. reader = 0;
  18958. return ok && tempFile.overwriteTargetFileWithTemporary();
  18959. }
  18960. }
  18961. }
  18962. return false;
  18963. }
  18964. }
  18965. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18966. {
  18967. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18968. if (reader != 0)
  18969. {
  18970. const int64 bwavPos = reader->bwavChunkStart;
  18971. const int64 bwavSize = reader->bwavSize;
  18972. reader = 0;
  18973. if (bwavSize > 0)
  18974. {
  18975. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18976. if (chunk.getSize() <= (size_t) bwavSize)
  18977. {
  18978. // the new one will fit in the space available, so write it directly..
  18979. const int64 oldSize = wavFile.getSize();
  18980. {
  18981. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18982. out->setPosition (bwavPos);
  18983. out->write (chunk.getData(), (int) chunk.getSize());
  18984. out->setPosition (oldSize);
  18985. }
  18986. jassert (wavFile.getSize() == oldSize);
  18987. return true;
  18988. }
  18989. }
  18990. }
  18991. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18992. }
  18993. END_JUCE_NAMESPACE
  18994. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18995. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18996. #if JUCE_USE_CDREADER
  18997. BEGIN_JUCE_NAMESPACE
  18998. int AudioCDReader::getNumTracks() const
  18999. {
  19000. return trackStartSamples.size() - 1;
  19001. }
  19002. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  19003. {
  19004. return trackStartSamples [trackNum];
  19005. }
  19006. const Array<int>& AudioCDReader::getTrackOffsets() const
  19007. {
  19008. return trackStartSamples;
  19009. }
  19010. int AudioCDReader::getCDDBId()
  19011. {
  19012. int checksum = 0;
  19013. const int numTracks = getNumTracks();
  19014. for (int i = 0; i < numTracks; ++i)
  19015. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  19016. checksum += offset % 10;
  19017. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  19018. // CCLLLLTT: checksum, length, tracks
  19019. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  19020. }
  19021. END_JUCE_NAMESPACE
  19022. #endif
  19023. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  19024. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19025. BEGIN_JUCE_NAMESPACE
  19026. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  19027. const bool deleteReaderWhenThisIsDeleted)
  19028. : reader (reader_),
  19029. deleteReader (deleteReaderWhenThisIsDeleted),
  19030. nextPlayPos (0),
  19031. looping (false)
  19032. {
  19033. jassert (reader != 0);
  19034. }
  19035. AudioFormatReaderSource::~AudioFormatReaderSource()
  19036. {
  19037. releaseResources();
  19038. if (deleteReader)
  19039. delete reader;
  19040. }
  19041. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  19042. {
  19043. nextPlayPos = newPosition;
  19044. }
  19045. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  19046. {
  19047. looping = shouldLoop;
  19048. }
  19049. int AudioFormatReaderSource::getNextReadPosition() const
  19050. {
  19051. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  19052. : nextPlayPos;
  19053. }
  19054. int AudioFormatReaderSource::getTotalLength() const
  19055. {
  19056. return (int) reader->lengthInSamples;
  19057. }
  19058. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19059. double /*sampleRate*/)
  19060. {
  19061. }
  19062. void AudioFormatReaderSource::releaseResources()
  19063. {
  19064. }
  19065. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19066. {
  19067. if (info.numSamples > 0)
  19068. {
  19069. const int start = nextPlayPos;
  19070. if (looping)
  19071. {
  19072. const int newStart = start % (int) reader->lengthInSamples;
  19073. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  19074. if (newEnd > newStart)
  19075. {
  19076. info.buffer->readFromAudioReader (reader,
  19077. info.startSample,
  19078. newEnd - newStart,
  19079. newStart,
  19080. true, true);
  19081. }
  19082. else
  19083. {
  19084. const int endSamps = (int) reader->lengthInSamples - newStart;
  19085. info.buffer->readFromAudioReader (reader,
  19086. info.startSample,
  19087. endSamps,
  19088. newStart,
  19089. true, true);
  19090. info.buffer->readFromAudioReader (reader,
  19091. info.startSample + endSamps,
  19092. newEnd,
  19093. 0,
  19094. true, true);
  19095. }
  19096. nextPlayPos = newEnd;
  19097. }
  19098. else
  19099. {
  19100. info.buffer->readFromAudioReader (reader,
  19101. info.startSample,
  19102. info.numSamples,
  19103. start,
  19104. true, true);
  19105. nextPlayPos += info.numSamples;
  19106. }
  19107. }
  19108. }
  19109. END_JUCE_NAMESPACE
  19110. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19111. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19112. BEGIN_JUCE_NAMESPACE
  19113. AudioSourcePlayer::AudioSourcePlayer()
  19114. : source (0),
  19115. sampleRate (0),
  19116. bufferSize (0),
  19117. tempBuffer (2, 8),
  19118. lastGain (1.0f),
  19119. gain (1.0f)
  19120. {
  19121. }
  19122. AudioSourcePlayer::~AudioSourcePlayer()
  19123. {
  19124. setSource (0);
  19125. }
  19126. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19127. {
  19128. if (source != newSource)
  19129. {
  19130. AudioSource* const oldSource = source;
  19131. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19132. newSource->prepareToPlay (bufferSize, sampleRate);
  19133. {
  19134. const ScopedLock sl (readLock);
  19135. source = newSource;
  19136. }
  19137. if (oldSource != 0)
  19138. oldSource->releaseResources();
  19139. }
  19140. }
  19141. void AudioSourcePlayer::setGain (const float newGain) throw()
  19142. {
  19143. gain = newGain;
  19144. }
  19145. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19146. int totalNumInputChannels,
  19147. float** outputChannelData,
  19148. int totalNumOutputChannels,
  19149. int numSamples)
  19150. {
  19151. // these should have been prepared by audioDeviceAboutToStart()...
  19152. jassert (sampleRate > 0 && bufferSize > 0);
  19153. const ScopedLock sl (readLock);
  19154. if (source != 0)
  19155. {
  19156. AudioSourceChannelInfo info;
  19157. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19158. // messy stuff needed to compact the channels down into an array
  19159. // of non-zero pointers..
  19160. for (i = 0; i < totalNumInputChannels; ++i)
  19161. {
  19162. if (inputChannelData[i] != 0)
  19163. {
  19164. inputChans [numInputs++] = inputChannelData[i];
  19165. if (numInputs >= numElementsInArray (inputChans))
  19166. break;
  19167. }
  19168. }
  19169. for (i = 0; i < totalNumOutputChannels; ++i)
  19170. {
  19171. if (outputChannelData[i] != 0)
  19172. {
  19173. outputChans [numOutputs++] = outputChannelData[i];
  19174. if (numOutputs >= numElementsInArray (outputChans))
  19175. break;
  19176. }
  19177. }
  19178. if (numInputs > numOutputs)
  19179. {
  19180. // if there aren't enough output channels for the number of
  19181. // inputs, we need to create some temporary extra ones (can't
  19182. // use the input data in case it gets written to)
  19183. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19184. false, false, true);
  19185. for (i = 0; i < numOutputs; ++i)
  19186. {
  19187. channels[numActiveChans] = outputChans[i];
  19188. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19189. ++numActiveChans;
  19190. }
  19191. for (i = numOutputs; i < numInputs; ++i)
  19192. {
  19193. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19194. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19195. ++numActiveChans;
  19196. }
  19197. }
  19198. else
  19199. {
  19200. for (i = 0; i < numInputs; ++i)
  19201. {
  19202. channels[numActiveChans] = outputChans[i];
  19203. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19204. ++numActiveChans;
  19205. }
  19206. for (i = numInputs; i < numOutputs; ++i)
  19207. {
  19208. channels[numActiveChans] = outputChans[i];
  19209. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19210. ++numActiveChans;
  19211. }
  19212. }
  19213. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19214. info.buffer = &buffer;
  19215. info.startSample = 0;
  19216. info.numSamples = numSamples;
  19217. source->getNextAudioBlock (info);
  19218. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19219. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19220. lastGain = gain;
  19221. }
  19222. else
  19223. {
  19224. for (int i = 0; i < totalNumOutputChannels; ++i)
  19225. if (outputChannelData[i] != 0)
  19226. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19227. }
  19228. }
  19229. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19230. {
  19231. sampleRate = device->getCurrentSampleRate();
  19232. bufferSize = device->getCurrentBufferSizeSamples();
  19233. zeromem (channels, sizeof (channels));
  19234. if (source != 0)
  19235. source->prepareToPlay (bufferSize, sampleRate);
  19236. }
  19237. void AudioSourcePlayer::audioDeviceStopped()
  19238. {
  19239. if (source != 0)
  19240. source->releaseResources();
  19241. sampleRate = 0.0;
  19242. bufferSize = 0;
  19243. tempBuffer.setSize (2, 8);
  19244. }
  19245. END_JUCE_NAMESPACE
  19246. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19247. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19248. BEGIN_JUCE_NAMESPACE
  19249. AudioTransportSource::AudioTransportSource()
  19250. : source (0),
  19251. resamplerSource (0),
  19252. bufferingSource (0),
  19253. positionableSource (0),
  19254. masterSource (0),
  19255. gain (1.0f),
  19256. lastGain (1.0f),
  19257. playing (false),
  19258. stopped (true),
  19259. sampleRate (44100.0),
  19260. sourceSampleRate (0.0),
  19261. blockSize (128),
  19262. readAheadBufferSize (0),
  19263. isPrepared (false),
  19264. inputStreamEOF (false)
  19265. {
  19266. }
  19267. AudioTransportSource::~AudioTransportSource()
  19268. {
  19269. setSource (0);
  19270. releaseResources();
  19271. }
  19272. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19273. int readAheadBufferSize_,
  19274. double sourceSampleRateToCorrectFor)
  19275. {
  19276. if (source == newSource)
  19277. {
  19278. if (source == 0)
  19279. return;
  19280. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19281. }
  19282. readAheadBufferSize = readAheadBufferSize_;
  19283. sourceSampleRate = sourceSampleRateToCorrectFor;
  19284. ResamplingAudioSource* newResamplerSource = 0;
  19285. BufferingAudioSource* newBufferingSource = 0;
  19286. PositionableAudioSource* newPositionableSource = 0;
  19287. AudioSource* newMasterSource = 0;
  19288. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19289. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19290. AudioSource* oldMasterSource = masterSource;
  19291. if (newSource != 0)
  19292. {
  19293. newPositionableSource = newSource;
  19294. if (readAheadBufferSize_ > 0)
  19295. newPositionableSource = newBufferingSource
  19296. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19297. newPositionableSource->setNextReadPosition (0);
  19298. if (sourceSampleRateToCorrectFor != 0)
  19299. newMasterSource = newResamplerSource
  19300. = new ResamplingAudioSource (newPositionableSource, false);
  19301. else
  19302. newMasterSource = newPositionableSource;
  19303. if (isPrepared)
  19304. {
  19305. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19306. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19307. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19308. }
  19309. }
  19310. {
  19311. const ScopedLock sl (callbackLock);
  19312. source = newSource;
  19313. resamplerSource = newResamplerSource;
  19314. bufferingSource = newBufferingSource;
  19315. masterSource = newMasterSource;
  19316. positionableSource = newPositionableSource;
  19317. playing = false;
  19318. }
  19319. if (oldMasterSource != 0)
  19320. oldMasterSource->releaseResources();
  19321. }
  19322. void AudioTransportSource::start()
  19323. {
  19324. if ((! playing) && masterSource != 0)
  19325. {
  19326. {
  19327. const ScopedLock sl (callbackLock);
  19328. playing = true;
  19329. stopped = false;
  19330. inputStreamEOF = false;
  19331. }
  19332. sendChangeMessage();
  19333. }
  19334. }
  19335. void AudioTransportSource::stop()
  19336. {
  19337. if (playing)
  19338. {
  19339. {
  19340. const ScopedLock sl (callbackLock);
  19341. playing = false;
  19342. }
  19343. int n = 500;
  19344. while (--n >= 0 && ! stopped)
  19345. Thread::sleep (2);
  19346. sendChangeMessage();
  19347. }
  19348. }
  19349. void AudioTransportSource::setPosition (double newPosition)
  19350. {
  19351. if (sampleRate > 0.0)
  19352. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19353. }
  19354. double AudioTransportSource::getCurrentPosition() const
  19355. {
  19356. if (sampleRate > 0.0)
  19357. return getNextReadPosition() / sampleRate;
  19358. else
  19359. return 0.0;
  19360. }
  19361. void AudioTransportSource::setNextReadPosition (int newPosition)
  19362. {
  19363. if (positionableSource != 0)
  19364. {
  19365. if (sampleRate > 0 && sourceSampleRate > 0)
  19366. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19367. positionableSource->setNextReadPosition (newPosition);
  19368. }
  19369. }
  19370. int AudioTransportSource::getNextReadPosition() const
  19371. {
  19372. if (positionableSource != 0)
  19373. {
  19374. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19375. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19376. }
  19377. return 0;
  19378. }
  19379. int AudioTransportSource::getTotalLength() const
  19380. {
  19381. const ScopedLock sl (callbackLock);
  19382. if (positionableSource != 0)
  19383. {
  19384. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19385. return roundToInt (positionableSource->getTotalLength() * ratio);
  19386. }
  19387. return 0;
  19388. }
  19389. bool AudioTransportSource::isLooping() const
  19390. {
  19391. const ScopedLock sl (callbackLock);
  19392. return positionableSource != 0
  19393. && positionableSource->isLooping();
  19394. }
  19395. void AudioTransportSource::setGain (const float newGain) throw()
  19396. {
  19397. gain = newGain;
  19398. }
  19399. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19400. double sampleRate_)
  19401. {
  19402. const ScopedLock sl (callbackLock);
  19403. sampleRate = sampleRate_;
  19404. blockSize = samplesPerBlockExpected;
  19405. if (masterSource != 0)
  19406. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19407. if (resamplerSource != 0 && sourceSampleRate != 0)
  19408. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19409. isPrepared = true;
  19410. }
  19411. void AudioTransportSource::releaseResources()
  19412. {
  19413. const ScopedLock sl (callbackLock);
  19414. if (masterSource != 0)
  19415. masterSource->releaseResources();
  19416. isPrepared = false;
  19417. }
  19418. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19419. {
  19420. const ScopedLock sl (callbackLock);
  19421. inputStreamEOF = false;
  19422. if (masterSource != 0 && ! stopped)
  19423. {
  19424. masterSource->getNextAudioBlock (info);
  19425. if (! playing)
  19426. {
  19427. // just stopped playing, so fade out the last block..
  19428. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19429. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19430. if (info.numSamples > 256)
  19431. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19432. }
  19433. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19434. && ! positionableSource->isLooping())
  19435. {
  19436. playing = false;
  19437. inputStreamEOF = true;
  19438. sendChangeMessage();
  19439. }
  19440. stopped = ! playing;
  19441. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19442. {
  19443. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19444. lastGain, gain);
  19445. }
  19446. }
  19447. else
  19448. {
  19449. info.clearActiveBufferRegion();
  19450. stopped = true;
  19451. }
  19452. lastGain = gain;
  19453. }
  19454. END_JUCE_NAMESPACE
  19455. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19456. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19457. BEGIN_JUCE_NAMESPACE
  19458. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19459. public Thread,
  19460. private Timer
  19461. {
  19462. public:
  19463. SharedBufferingAudioSourceThread()
  19464. : Thread ("Audio Buffer")
  19465. {
  19466. }
  19467. ~SharedBufferingAudioSourceThread()
  19468. {
  19469. stopThread (10000);
  19470. clearSingletonInstance();
  19471. }
  19472. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19473. void addSource (BufferingAudioSource* source)
  19474. {
  19475. const ScopedLock sl (lock);
  19476. if (! sources.contains (source))
  19477. {
  19478. sources.add (source);
  19479. startThread();
  19480. stopTimer();
  19481. }
  19482. notify();
  19483. }
  19484. void removeSource (BufferingAudioSource* source)
  19485. {
  19486. const ScopedLock sl (lock);
  19487. sources.removeValue (source);
  19488. if (sources.size() == 0)
  19489. startTimer (5000);
  19490. }
  19491. private:
  19492. Array <BufferingAudioSource*> sources;
  19493. CriticalSection lock;
  19494. void run()
  19495. {
  19496. while (! threadShouldExit())
  19497. {
  19498. bool busy = false;
  19499. for (int i = sources.size(); --i >= 0;)
  19500. {
  19501. if (threadShouldExit())
  19502. return;
  19503. const ScopedLock sl (lock);
  19504. BufferingAudioSource* const b = sources[i];
  19505. if (b != 0 && b->readNextBufferChunk())
  19506. busy = true;
  19507. }
  19508. if (! busy)
  19509. wait (500);
  19510. }
  19511. }
  19512. void timerCallback()
  19513. {
  19514. stopTimer();
  19515. if (sources.size() == 0)
  19516. deleteInstance();
  19517. }
  19518. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19519. };
  19520. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19521. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19522. const bool deleteSourceWhenDeleted_,
  19523. int numberOfSamplesToBuffer_)
  19524. : source (source_),
  19525. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19526. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19527. buffer (2, 0),
  19528. bufferValidStart (0),
  19529. bufferValidEnd (0),
  19530. nextPlayPos (0),
  19531. wasSourceLooping (false)
  19532. {
  19533. jassert (source_ != 0);
  19534. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19535. // not using a larger buffer..
  19536. }
  19537. BufferingAudioSource::~BufferingAudioSource()
  19538. {
  19539. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19540. if (thread != 0)
  19541. thread->removeSource (this);
  19542. if (deleteSourceWhenDeleted)
  19543. delete source;
  19544. }
  19545. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19546. {
  19547. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19548. sampleRate = sampleRate_;
  19549. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19550. buffer.clear();
  19551. bufferValidStart = 0;
  19552. bufferValidEnd = 0;
  19553. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19554. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19555. buffer.getNumSamples() / 2))
  19556. {
  19557. SharedBufferingAudioSourceThread::getInstance()->notify();
  19558. Thread::sleep (5);
  19559. }
  19560. }
  19561. void BufferingAudioSource::releaseResources()
  19562. {
  19563. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19564. if (thread != 0)
  19565. thread->removeSource (this);
  19566. buffer.setSize (2, 0);
  19567. source->releaseResources();
  19568. }
  19569. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19570. {
  19571. const ScopedLock sl (bufferStartPosLock);
  19572. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19573. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19574. if (validStart == validEnd)
  19575. {
  19576. // total cache miss
  19577. info.clearActiveBufferRegion();
  19578. }
  19579. else
  19580. {
  19581. if (validStart > 0)
  19582. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19583. if (validEnd < info.numSamples)
  19584. info.buffer->clear (info.startSample + validEnd,
  19585. info.numSamples - validEnd); // partial cache miss at end
  19586. if (validStart < validEnd)
  19587. {
  19588. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19589. {
  19590. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19591. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19592. if (startBufferIndex < endBufferIndex)
  19593. {
  19594. info.buffer->copyFrom (chan, info.startSample + validStart,
  19595. buffer,
  19596. chan, startBufferIndex,
  19597. validEnd - validStart);
  19598. }
  19599. else
  19600. {
  19601. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19602. info.buffer->copyFrom (chan, info.startSample + validStart,
  19603. buffer,
  19604. chan, startBufferIndex,
  19605. initialSize);
  19606. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19607. buffer,
  19608. chan, 0,
  19609. (validEnd - validStart) - initialSize);
  19610. }
  19611. }
  19612. }
  19613. nextPlayPos += info.numSamples;
  19614. if (source->isLooping() && nextPlayPos > 0)
  19615. nextPlayPos %= source->getTotalLength();
  19616. }
  19617. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19618. if (thread != 0)
  19619. thread->notify();
  19620. }
  19621. int BufferingAudioSource::getNextReadPosition() const
  19622. {
  19623. return (source->isLooping() && nextPlayPos > 0)
  19624. ? nextPlayPos % source->getTotalLength()
  19625. : nextPlayPos;
  19626. }
  19627. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19628. {
  19629. const ScopedLock sl (bufferStartPosLock);
  19630. nextPlayPos = newPosition;
  19631. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19632. if (thread != 0)
  19633. thread->notify();
  19634. }
  19635. bool BufferingAudioSource::readNextBufferChunk()
  19636. {
  19637. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19638. {
  19639. const ScopedLock sl (bufferStartPosLock);
  19640. if (wasSourceLooping != isLooping())
  19641. {
  19642. wasSourceLooping = isLooping();
  19643. bufferValidStart = 0;
  19644. bufferValidEnd = 0;
  19645. }
  19646. newBVS = jmax (0, nextPlayPos);
  19647. newBVE = newBVS + buffer.getNumSamples() - 4;
  19648. sectionToReadStart = 0;
  19649. sectionToReadEnd = 0;
  19650. const int maxChunkSize = 2048;
  19651. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19652. {
  19653. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19654. sectionToReadStart = newBVS;
  19655. sectionToReadEnd = newBVE;
  19656. bufferValidStart = 0;
  19657. bufferValidEnd = 0;
  19658. }
  19659. else if (abs (newBVS - bufferValidStart) > 512
  19660. || abs (newBVE - bufferValidEnd) > 512)
  19661. {
  19662. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19663. sectionToReadStart = bufferValidEnd;
  19664. sectionToReadEnd = newBVE;
  19665. bufferValidStart = newBVS;
  19666. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19667. }
  19668. }
  19669. if (sectionToReadStart != sectionToReadEnd)
  19670. {
  19671. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19672. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19673. if (bufferIndexStart < bufferIndexEnd)
  19674. {
  19675. readBufferSection (sectionToReadStart,
  19676. sectionToReadEnd - sectionToReadStart,
  19677. bufferIndexStart);
  19678. }
  19679. else
  19680. {
  19681. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19682. readBufferSection (sectionToReadStart,
  19683. initialSize,
  19684. bufferIndexStart);
  19685. readBufferSection (sectionToReadStart + initialSize,
  19686. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19687. 0);
  19688. }
  19689. const ScopedLock sl2 (bufferStartPosLock);
  19690. bufferValidStart = newBVS;
  19691. bufferValidEnd = newBVE;
  19692. return true;
  19693. }
  19694. else
  19695. {
  19696. return false;
  19697. }
  19698. }
  19699. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19700. {
  19701. if (source->getNextReadPosition() != start)
  19702. source->setNextReadPosition (start);
  19703. AudioSourceChannelInfo info;
  19704. info.buffer = &buffer;
  19705. info.startSample = bufferOffset;
  19706. info.numSamples = length;
  19707. source->getNextAudioBlock (info);
  19708. }
  19709. END_JUCE_NAMESPACE
  19710. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19711. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19712. BEGIN_JUCE_NAMESPACE
  19713. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19714. const bool deleteSourceWhenDeleted_)
  19715. : requiredNumberOfChannels (2),
  19716. source (source_),
  19717. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19718. buffer (2, 16)
  19719. {
  19720. remappedInfo.buffer = &buffer;
  19721. remappedInfo.startSample = 0;
  19722. }
  19723. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19724. {
  19725. if (deleteSourceWhenDeleted)
  19726. delete source;
  19727. }
  19728. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19729. {
  19730. const ScopedLock sl (lock);
  19731. requiredNumberOfChannels = requiredNumberOfChannels_;
  19732. }
  19733. void ChannelRemappingAudioSource::clearAllMappings()
  19734. {
  19735. const ScopedLock sl (lock);
  19736. remappedInputs.clear();
  19737. remappedOutputs.clear();
  19738. }
  19739. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19740. {
  19741. const ScopedLock sl (lock);
  19742. while (remappedInputs.size() < destIndex)
  19743. remappedInputs.add (-1);
  19744. remappedInputs.set (destIndex, sourceIndex);
  19745. }
  19746. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19747. {
  19748. const ScopedLock sl (lock);
  19749. while (remappedOutputs.size() < sourceIndex)
  19750. remappedOutputs.add (-1);
  19751. remappedOutputs.set (sourceIndex, destIndex);
  19752. }
  19753. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19754. {
  19755. const ScopedLock sl (lock);
  19756. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19757. return remappedInputs.getUnchecked (inputChannelIndex);
  19758. return -1;
  19759. }
  19760. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19761. {
  19762. const ScopedLock sl (lock);
  19763. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19764. return remappedOutputs .getUnchecked (outputChannelIndex);
  19765. return -1;
  19766. }
  19767. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19768. {
  19769. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19770. }
  19771. void ChannelRemappingAudioSource::releaseResources()
  19772. {
  19773. source->releaseResources();
  19774. }
  19775. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19776. {
  19777. const ScopedLock sl (lock);
  19778. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19779. const int numChans = bufferToFill.buffer->getNumChannels();
  19780. int i;
  19781. for (i = 0; i < buffer.getNumChannels(); ++i)
  19782. {
  19783. const int remappedChan = getRemappedInputChannel (i);
  19784. if (remappedChan >= 0 && remappedChan < numChans)
  19785. {
  19786. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19787. remappedChan,
  19788. bufferToFill.startSample,
  19789. bufferToFill.numSamples);
  19790. }
  19791. else
  19792. {
  19793. buffer.clear (i, 0, bufferToFill.numSamples);
  19794. }
  19795. }
  19796. remappedInfo.numSamples = bufferToFill.numSamples;
  19797. source->getNextAudioBlock (remappedInfo);
  19798. bufferToFill.clearActiveBufferRegion();
  19799. for (i = 0; i < requiredNumberOfChannels; ++i)
  19800. {
  19801. const int remappedChan = getRemappedOutputChannel (i);
  19802. if (remappedChan >= 0 && remappedChan < numChans)
  19803. {
  19804. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19805. buffer, i, 0, bufferToFill.numSamples);
  19806. }
  19807. }
  19808. }
  19809. XmlElement* ChannelRemappingAudioSource::createXml() const
  19810. {
  19811. XmlElement* e = new XmlElement ("MAPPINGS");
  19812. String ins, outs;
  19813. int i;
  19814. const ScopedLock sl (lock);
  19815. for (i = 0; i < remappedInputs.size(); ++i)
  19816. ins << remappedInputs.getUnchecked(i) << ' ';
  19817. for (i = 0; i < remappedOutputs.size(); ++i)
  19818. outs << remappedOutputs.getUnchecked(i) << ' ';
  19819. e->setAttribute ("inputs", ins.trimEnd());
  19820. e->setAttribute ("outputs", outs.trimEnd());
  19821. return e;
  19822. }
  19823. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19824. {
  19825. if (e.hasTagName ("MAPPINGS"))
  19826. {
  19827. const ScopedLock sl (lock);
  19828. clearAllMappings();
  19829. StringArray ins, outs;
  19830. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19831. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19832. int i;
  19833. for (i = 0; i < ins.size(); ++i)
  19834. remappedInputs.add (ins[i].getIntValue());
  19835. for (i = 0; i < outs.size(); ++i)
  19836. remappedOutputs.add (outs[i].getIntValue());
  19837. }
  19838. }
  19839. END_JUCE_NAMESPACE
  19840. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19841. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19842. BEGIN_JUCE_NAMESPACE
  19843. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19844. const bool deleteInputWhenDeleted_)
  19845. : input (inputSource),
  19846. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19847. {
  19848. jassert (inputSource != 0);
  19849. for (int i = 2; --i >= 0;)
  19850. iirFilters.add (new IIRFilter());
  19851. }
  19852. IIRFilterAudioSource::~IIRFilterAudioSource()
  19853. {
  19854. if (deleteInputWhenDeleted)
  19855. delete input;
  19856. }
  19857. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19858. {
  19859. for (int i = iirFilters.size(); --i >= 0;)
  19860. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19861. }
  19862. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19863. {
  19864. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19865. for (int i = iirFilters.size(); --i >= 0;)
  19866. iirFilters.getUnchecked(i)->reset();
  19867. }
  19868. void IIRFilterAudioSource::releaseResources()
  19869. {
  19870. input->releaseResources();
  19871. }
  19872. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19873. {
  19874. input->getNextAudioBlock (bufferToFill);
  19875. const int numChannels = bufferToFill.buffer->getNumChannels();
  19876. while (numChannels > iirFilters.size())
  19877. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19878. for (int i = 0; i < numChannels; ++i)
  19879. iirFilters.getUnchecked(i)
  19880. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19881. bufferToFill.numSamples);
  19882. }
  19883. END_JUCE_NAMESPACE
  19884. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19885. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19886. BEGIN_JUCE_NAMESPACE
  19887. MixerAudioSource::MixerAudioSource()
  19888. : tempBuffer (2, 0),
  19889. currentSampleRate (0.0),
  19890. bufferSizeExpected (0)
  19891. {
  19892. }
  19893. MixerAudioSource::~MixerAudioSource()
  19894. {
  19895. removeAllInputs();
  19896. }
  19897. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19898. {
  19899. if (input != 0 && ! inputs.contains (input))
  19900. {
  19901. double localRate;
  19902. int localBufferSize;
  19903. {
  19904. const ScopedLock sl (lock);
  19905. localRate = currentSampleRate;
  19906. localBufferSize = bufferSizeExpected;
  19907. }
  19908. if (localRate != 0.0)
  19909. input->prepareToPlay (localBufferSize, localRate);
  19910. const ScopedLock sl (lock);
  19911. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19912. inputs.add (input);
  19913. }
  19914. }
  19915. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19916. {
  19917. if (input != 0)
  19918. {
  19919. int index;
  19920. {
  19921. const ScopedLock sl (lock);
  19922. index = inputs.indexOf (input);
  19923. if (index >= 0)
  19924. {
  19925. inputsToDelete.shiftBits (index, 1);
  19926. inputs.remove (index);
  19927. }
  19928. }
  19929. if (index >= 0)
  19930. {
  19931. input->releaseResources();
  19932. if (deleteInput)
  19933. delete input;
  19934. }
  19935. }
  19936. }
  19937. void MixerAudioSource::removeAllInputs()
  19938. {
  19939. OwnedArray<AudioSource> toDelete;
  19940. {
  19941. const ScopedLock sl (lock);
  19942. for (int i = inputs.size(); --i >= 0;)
  19943. if (inputsToDelete[i])
  19944. toDelete.add (inputs.getUnchecked(i));
  19945. }
  19946. }
  19947. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19948. {
  19949. tempBuffer.setSize (2, samplesPerBlockExpected);
  19950. const ScopedLock sl (lock);
  19951. currentSampleRate = sampleRate;
  19952. bufferSizeExpected = samplesPerBlockExpected;
  19953. for (int i = inputs.size(); --i >= 0;)
  19954. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19955. }
  19956. void MixerAudioSource::releaseResources()
  19957. {
  19958. const ScopedLock sl (lock);
  19959. for (int i = inputs.size(); --i >= 0;)
  19960. inputs.getUnchecked(i)->releaseResources();
  19961. tempBuffer.setSize (2, 0);
  19962. currentSampleRate = 0;
  19963. bufferSizeExpected = 0;
  19964. }
  19965. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19966. {
  19967. const ScopedLock sl (lock);
  19968. if (inputs.size() > 0)
  19969. {
  19970. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19971. if (inputs.size() > 1)
  19972. {
  19973. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19974. info.buffer->getNumSamples());
  19975. AudioSourceChannelInfo info2;
  19976. info2.buffer = &tempBuffer;
  19977. info2.numSamples = info.numSamples;
  19978. info2.startSample = 0;
  19979. for (int i = 1; i < inputs.size(); ++i)
  19980. {
  19981. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19982. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19983. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19984. }
  19985. }
  19986. }
  19987. else
  19988. {
  19989. info.clearActiveBufferRegion();
  19990. }
  19991. }
  19992. END_JUCE_NAMESPACE
  19993. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19994. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19995. BEGIN_JUCE_NAMESPACE
  19996. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19997. const bool deleteInputWhenDeleted_,
  19998. const int numChannels_)
  19999. : input (inputSource),
  20000. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  20001. ratio (1.0),
  20002. lastRatio (1.0),
  20003. buffer (numChannels_, 0),
  20004. sampsInBuffer (0),
  20005. numChannels (numChannels_)
  20006. {
  20007. jassert (input != 0);
  20008. }
  20009. ResamplingAudioSource::~ResamplingAudioSource()
  20010. {
  20011. if (deleteInputWhenDeleted)
  20012. delete input;
  20013. }
  20014. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  20015. {
  20016. jassert (samplesInPerOutputSample > 0);
  20017. const ScopedLock sl (ratioLock);
  20018. ratio = jmax (0.0, samplesInPerOutputSample);
  20019. }
  20020. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  20021. double sampleRate)
  20022. {
  20023. const ScopedLock sl (ratioLock);
  20024. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20025. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  20026. buffer.clear();
  20027. sampsInBuffer = 0;
  20028. bufferPos = 0;
  20029. subSampleOffset = 0.0;
  20030. filterStates.calloc (numChannels);
  20031. srcBuffers.calloc (numChannels);
  20032. destBuffers.calloc (numChannels);
  20033. createLowPass (ratio);
  20034. resetFilters();
  20035. }
  20036. void ResamplingAudioSource::releaseResources()
  20037. {
  20038. input->releaseResources();
  20039. buffer.setSize (numChannels, 0);
  20040. }
  20041. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20042. {
  20043. const ScopedLock sl (ratioLock);
  20044. if (lastRatio != ratio)
  20045. {
  20046. createLowPass (ratio);
  20047. lastRatio = ratio;
  20048. }
  20049. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  20050. int bufferSize = buffer.getNumSamples();
  20051. if (bufferSize < sampsNeeded + 8)
  20052. {
  20053. bufferPos %= bufferSize;
  20054. bufferSize = sampsNeeded + 32;
  20055. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  20056. }
  20057. bufferPos %= bufferSize;
  20058. int endOfBufferPos = bufferPos + sampsInBuffer;
  20059. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  20060. while (sampsNeeded > sampsInBuffer)
  20061. {
  20062. endOfBufferPos %= bufferSize;
  20063. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  20064. bufferSize - endOfBufferPos);
  20065. AudioSourceChannelInfo readInfo;
  20066. readInfo.buffer = &buffer;
  20067. readInfo.numSamples = numToDo;
  20068. readInfo.startSample = endOfBufferPos;
  20069. input->getNextAudioBlock (readInfo);
  20070. if (ratio > 1.0001)
  20071. {
  20072. // for down-sampling, pre-apply the filter..
  20073. for (int i = channelsToProcess; --i >= 0;)
  20074. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20075. }
  20076. sampsInBuffer += numToDo;
  20077. endOfBufferPos += numToDo;
  20078. }
  20079. for (int channel = 0; channel < channelsToProcess; ++channel)
  20080. {
  20081. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20082. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20083. }
  20084. int nextPos = (bufferPos + 1) % bufferSize;
  20085. for (int m = info.numSamples; --m >= 0;)
  20086. {
  20087. const float alpha = (float) subSampleOffset;
  20088. const float invAlpha = 1.0f - alpha;
  20089. for (int channel = 0; channel < channelsToProcess; ++channel)
  20090. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20091. subSampleOffset += ratio;
  20092. jassert (sampsInBuffer > 0);
  20093. while (subSampleOffset >= 1.0)
  20094. {
  20095. if (++bufferPos >= bufferSize)
  20096. bufferPos = 0;
  20097. --sampsInBuffer;
  20098. nextPos = (bufferPos + 1) % bufferSize;
  20099. subSampleOffset -= 1.0;
  20100. }
  20101. }
  20102. if (ratio < 0.9999)
  20103. {
  20104. // for up-sampling, apply the filter after transposing..
  20105. for (int i = channelsToProcess; --i >= 0;)
  20106. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20107. }
  20108. else if (ratio <= 1.0001)
  20109. {
  20110. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20111. for (int i = channelsToProcess; --i >= 0;)
  20112. {
  20113. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20114. FilterState& fs = filterStates[i];
  20115. if (info.numSamples > 1)
  20116. {
  20117. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20118. }
  20119. else
  20120. {
  20121. fs.y2 = fs.y1;
  20122. fs.x2 = fs.x1;
  20123. }
  20124. fs.y1 = fs.x1 = *endOfBuffer;
  20125. }
  20126. }
  20127. jassert (sampsInBuffer >= 0);
  20128. }
  20129. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20130. {
  20131. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20132. : 0.5 * frequencyRatio;
  20133. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  20134. const double nSquared = n * n;
  20135. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20136. setFilterCoefficients (c1,
  20137. c1 * 2.0f,
  20138. c1,
  20139. 1.0,
  20140. c1 * 2.0 * (1.0 - nSquared),
  20141. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20142. }
  20143. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20144. {
  20145. const double a = 1.0 / c4;
  20146. c1 *= a;
  20147. c2 *= a;
  20148. c3 *= a;
  20149. c5 *= a;
  20150. c6 *= a;
  20151. coefficients[0] = c1;
  20152. coefficients[1] = c2;
  20153. coefficients[2] = c3;
  20154. coefficients[3] = c4;
  20155. coefficients[4] = c5;
  20156. coefficients[5] = c6;
  20157. }
  20158. void ResamplingAudioSource::resetFilters()
  20159. {
  20160. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20161. }
  20162. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20163. {
  20164. while (--num >= 0)
  20165. {
  20166. const double in = *samples;
  20167. double out = coefficients[0] * in
  20168. + coefficients[1] * fs.x1
  20169. + coefficients[2] * fs.x2
  20170. - coefficients[4] * fs.y1
  20171. - coefficients[5] * fs.y2;
  20172. #if JUCE_INTEL
  20173. if (! (out < -1.0e-8 || out > 1.0e-8))
  20174. out = 0;
  20175. #endif
  20176. fs.x2 = fs.x1;
  20177. fs.x1 = in;
  20178. fs.y2 = fs.y1;
  20179. fs.y1 = out;
  20180. *samples++ = (float) out;
  20181. }
  20182. }
  20183. END_JUCE_NAMESPACE
  20184. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20185. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20186. BEGIN_JUCE_NAMESPACE
  20187. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20188. : frequency (1000.0),
  20189. sampleRate (44100.0),
  20190. currentPhase (0.0),
  20191. phasePerSample (0.0),
  20192. amplitude (0.5f)
  20193. {
  20194. }
  20195. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20196. {
  20197. }
  20198. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20199. {
  20200. amplitude = newAmplitude;
  20201. }
  20202. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20203. {
  20204. frequency = newFrequencyHz;
  20205. phasePerSample = 0.0;
  20206. }
  20207. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20208. double sampleRate_)
  20209. {
  20210. currentPhase = 0.0;
  20211. phasePerSample = 0.0;
  20212. sampleRate = sampleRate_;
  20213. }
  20214. void ToneGeneratorAudioSource::releaseResources()
  20215. {
  20216. }
  20217. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20218. {
  20219. if (phasePerSample == 0.0)
  20220. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20221. for (int i = 0; i < info.numSamples; ++i)
  20222. {
  20223. const float sample = amplitude * (float) std::sin (currentPhase);
  20224. currentPhase += phasePerSample;
  20225. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20226. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20227. }
  20228. }
  20229. END_JUCE_NAMESPACE
  20230. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20231. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20232. BEGIN_JUCE_NAMESPACE
  20233. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20234. : sampleRate (0),
  20235. bufferSize (0),
  20236. useDefaultInputChannels (true),
  20237. useDefaultOutputChannels (true)
  20238. {
  20239. }
  20240. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20241. {
  20242. return outputDeviceName == other.outputDeviceName
  20243. && inputDeviceName == other.inputDeviceName
  20244. && sampleRate == other.sampleRate
  20245. && bufferSize == other.bufferSize
  20246. && inputChannels == other.inputChannels
  20247. && useDefaultInputChannels == other.useDefaultInputChannels
  20248. && outputChannels == other.outputChannels
  20249. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20250. }
  20251. AudioDeviceManager::AudioDeviceManager()
  20252. : currentAudioDevice (0),
  20253. numInputChansNeeded (0),
  20254. numOutputChansNeeded (2),
  20255. listNeedsScanning (true),
  20256. useInputNames (false),
  20257. inputLevelMeasurementEnabledCount (0),
  20258. inputLevel (0),
  20259. tempBuffer (2, 2),
  20260. defaultMidiOutput (0),
  20261. cpuUsageMs (0),
  20262. timeToCpuScale (0)
  20263. {
  20264. callbackHandler.owner = this;
  20265. }
  20266. AudioDeviceManager::~AudioDeviceManager()
  20267. {
  20268. currentAudioDevice = 0;
  20269. defaultMidiOutput = 0;
  20270. }
  20271. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20272. {
  20273. if (availableDeviceTypes.size() == 0)
  20274. {
  20275. createAudioDeviceTypes (availableDeviceTypes);
  20276. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20277. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20278. if (availableDeviceTypes.size() > 0)
  20279. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20280. }
  20281. }
  20282. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20283. {
  20284. scanDevicesIfNeeded();
  20285. return availableDeviceTypes;
  20286. }
  20287. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20288. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20289. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20290. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20291. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20292. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20293. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20294. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20295. {
  20296. (void) list; // (to avoid 'unused param' warnings)
  20297. #if JUCE_WINDOWS
  20298. #if JUCE_WASAPI
  20299. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20300. list.add (juce_createAudioIODeviceType_WASAPI());
  20301. #endif
  20302. #if JUCE_DIRECTSOUND
  20303. list.add (juce_createAudioIODeviceType_DirectSound());
  20304. #endif
  20305. #if JUCE_ASIO
  20306. list.add (juce_createAudioIODeviceType_ASIO());
  20307. #endif
  20308. #endif
  20309. #if JUCE_MAC
  20310. list.add (juce_createAudioIODeviceType_CoreAudio());
  20311. #endif
  20312. #if JUCE_IOS
  20313. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20314. #endif
  20315. #if JUCE_LINUX && JUCE_ALSA
  20316. list.add (juce_createAudioIODeviceType_ALSA());
  20317. #endif
  20318. #if JUCE_LINUX && JUCE_JACK
  20319. list.add (juce_createAudioIODeviceType_JACK());
  20320. #endif
  20321. }
  20322. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20323. const int numOutputChannelsNeeded,
  20324. const XmlElement* const e,
  20325. const bool selectDefaultDeviceOnFailure,
  20326. const String& preferredDefaultDeviceName,
  20327. const AudioDeviceSetup* preferredSetupOptions)
  20328. {
  20329. scanDevicesIfNeeded();
  20330. numInputChansNeeded = numInputChannelsNeeded;
  20331. numOutputChansNeeded = numOutputChannelsNeeded;
  20332. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20333. {
  20334. lastExplicitSettings = new XmlElement (*e);
  20335. String error;
  20336. AudioDeviceSetup setup;
  20337. if (preferredSetupOptions != 0)
  20338. setup = *preferredSetupOptions;
  20339. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20340. {
  20341. setup.inputDeviceName = setup.outputDeviceName
  20342. = e->getStringAttribute ("audioDeviceName");
  20343. }
  20344. else
  20345. {
  20346. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20347. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20348. }
  20349. currentDeviceType = e->getStringAttribute ("deviceType");
  20350. if (currentDeviceType.isEmpty())
  20351. {
  20352. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20353. if (type != 0)
  20354. currentDeviceType = type->getTypeName();
  20355. else if (availableDeviceTypes.size() > 0)
  20356. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20357. }
  20358. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20359. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20360. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20361. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20362. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20363. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20364. error = setAudioDeviceSetup (setup, true);
  20365. midiInsFromXml.clear();
  20366. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20367. midiInsFromXml.add (c->getStringAttribute ("name"));
  20368. const StringArray allMidiIns (MidiInput::getDevices());
  20369. for (int i = allMidiIns.size(); --i >= 0;)
  20370. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20371. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20372. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20373. false, preferredDefaultDeviceName);
  20374. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20375. return error;
  20376. }
  20377. else
  20378. {
  20379. AudioDeviceSetup setup;
  20380. if (preferredSetupOptions != 0)
  20381. {
  20382. setup = *preferredSetupOptions;
  20383. }
  20384. else if (preferredDefaultDeviceName.isNotEmpty())
  20385. {
  20386. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20387. {
  20388. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20389. StringArray outs (type->getDeviceNames (false));
  20390. int i;
  20391. for (i = 0; i < outs.size(); ++i)
  20392. {
  20393. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20394. {
  20395. setup.outputDeviceName = outs[i];
  20396. break;
  20397. }
  20398. }
  20399. StringArray ins (type->getDeviceNames (true));
  20400. for (i = 0; i < ins.size(); ++i)
  20401. {
  20402. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20403. {
  20404. setup.inputDeviceName = ins[i];
  20405. break;
  20406. }
  20407. }
  20408. }
  20409. }
  20410. insertDefaultDeviceNames (setup);
  20411. return setAudioDeviceSetup (setup, false);
  20412. }
  20413. }
  20414. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20415. {
  20416. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20417. if (type != 0)
  20418. {
  20419. if (setup.outputDeviceName.isEmpty())
  20420. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20421. if (setup.inputDeviceName.isEmpty())
  20422. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20423. }
  20424. }
  20425. XmlElement* AudioDeviceManager::createStateXml() const
  20426. {
  20427. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20428. }
  20429. void AudioDeviceManager::scanDevicesIfNeeded()
  20430. {
  20431. if (listNeedsScanning)
  20432. {
  20433. listNeedsScanning = false;
  20434. createDeviceTypesIfNeeded();
  20435. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20436. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20437. }
  20438. }
  20439. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20440. {
  20441. scanDevicesIfNeeded();
  20442. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20443. {
  20444. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20445. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20446. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20447. {
  20448. return type;
  20449. }
  20450. }
  20451. return 0;
  20452. }
  20453. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20454. {
  20455. setup = currentSetup;
  20456. }
  20457. void AudioDeviceManager::deleteCurrentDevice()
  20458. {
  20459. currentAudioDevice = 0;
  20460. currentSetup.inputDeviceName = String::empty;
  20461. currentSetup.outputDeviceName = String::empty;
  20462. }
  20463. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20464. const bool treatAsChosenDevice)
  20465. {
  20466. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20467. {
  20468. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20469. && currentDeviceType != type)
  20470. {
  20471. currentDeviceType = type;
  20472. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20473. insertDefaultDeviceNames (s);
  20474. setAudioDeviceSetup (s, treatAsChosenDevice);
  20475. sendChangeMessage();
  20476. break;
  20477. }
  20478. }
  20479. }
  20480. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20481. {
  20482. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20483. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20484. return availableDeviceTypes[i];
  20485. return availableDeviceTypes[0];
  20486. }
  20487. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20488. const bool treatAsChosenDevice)
  20489. {
  20490. jassert (&newSetup != &currentSetup); // this will have no effect
  20491. if (newSetup == currentSetup && currentAudioDevice != 0)
  20492. return String::empty;
  20493. if (! (newSetup == currentSetup))
  20494. sendChangeMessage();
  20495. stopDevice();
  20496. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20497. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20498. String error;
  20499. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20500. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20501. {
  20502. deleteCurrentDevice();
  20503. if (treatAsChosenDevice)
  20504. updateXml();
  20505. return String::empty;
  20506. }
  20507. if (currentSetup.inputDeviceName != newInputDeviceName
  20508. || currentSetup.outputDeviceName != newOutputDeviceName
  20509. || currentAudioDevice == 0)
  20510. {
  20511. deleteCurrentDevice();
  20512. scanDevicesIfNeeded();
  20513. if (newOutputDeviceName.isNotEmpty()
  20514. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20515. {
  20516. return "No such device: " + newOutputDeviceName;
  20517. }
  20518. if (newInputDeviceName.isNotEmpty()
  20519. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20520. {
  20521. return "No such device: " + newInputDeviceName;
  20522. }
  20523. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20524. if (currentAudioDevice == 0)
  20525. 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!";
  20526. else
  20527. error = currentAudioDevice->getLastError();
  20528. if (error.isNotEmpty())
  20529. {
  20530. deleteCurrentDevice();
  20531. return error;
  20532. }
  20533. if (newSetup.useDefaultInputChannels)
  20534. {
  20535. inputChannels.clear();
  20536. inputChannels.setRange (0, numInputChansNeeded, true);
  20537. }
  20538. if (newSetup.useDefaultOutputChannels)
  20539. {
  20540. outputChannels.clear();
  20541. outputChannels.setRange (0, numOutputChansNeeded, true);
  20542. }
  20543. if (newInputDeviceName.isEmpty())
  20544. inputChannels.clear();
  20545. if (newOutputDeviceName.isEmpty())
  20546. outputChannels.clear();
  20547. }
  20548. if (! newSetup.useDefaultInputChannels)
  20549. inputChannels = newSetup.inputChannels;
  20550. if (! newSetup.useDefaultOutputChannels)
  20551. outputChannels = newSetup.outputChannels;
  20552. currentSetup = newSetup;
  20553. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20554. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20555. error = currentAudioDevice->open (inputChannels,
  20556. outputChannels,
  20557. currentSetup.sampleRate,
  20558. currentSetup.bufferSize);
  20559. if (error.isEmpty())
  20560. {
  20561. currentDeviceType = currentAudioDevice->getTypeName();
  20562. currentAudioDevice->start (&callbackHandler);
  20563. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20564. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20565. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20566. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20567. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20568. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20569. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20570. if (treatAsChosenDevice)
  20571. updateXml();
  20572. }
  20573. else
  20574. {
  20575. deleteCurrentDevice();
  20576. }
  20577. return error;
  20578. }
  20579. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20580. {
  20581. jassert (currentAudioDevice != 0);
  20582. if (rate > 0)
  20583. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20584. if (currentAudioDevice->getSampleRate (i) == rate)
  20585. return rate;
  20586. double lowestAbove44 = 0.0;
  20587. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20588. {
  20589. const double sr = currentAudioDevice->getSampleRate (i);
  20590. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20591. lowestAbove44 = sr;
  20592. }
  20593. if (lowestAbove44 > 0.0)
  20594. return lowestAbove44;
  20595. return currentAudioDevice->getSampleRate (0);
  20596. }
  20597. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20598. {
  20599. jassert (currentAudioDevice != 0);
  20600. if (bufferSize > 0)
  20601. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20602. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20603. return bufferSize;
  20604. return currentAudioDevice->getDefaultBufferSize();
  20605. }
  20606. void AudioDeviceManager::stopDevice()
  20607. {
  20608. if (currentAudioDevice != 0)
  20609. currentAudioDevice->stop();
  20610. testSound = 0;
  20611. }
  20612. void AudioDeviceManager::closeAudioDevice()
  20613. {
  20614. stopDevice();
  20615. currentAudioDevice = 0;
  20616. }
  20617. void AudioDeviceManager::restartLastAudioDevice()
  20618. {
  20619. if (currentAudioDevice == 0)
  20620. {
  20621. if (currentSetup.inputDeviceName.isEmpty()
  20622. && currentSetup.outputDeviceName.isEmpty())
  20623. {
  20624. // This method will only reload the last device that was running
  20625. // before closeAudioDevice() was called - you need to actually open
  20626. // one first, with setAudioDevice().
  20627. jassertfalse;
  20628. return;
  20629. }
  20630. AudioDeviceSetup s (currentSetup);
  20631. setAudioDeviceSetup (s, false);
  20632. }
  20633. }
  20634. void AudioDeviceManager::updateXml()
  20635. {
  20636. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20637. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20638. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20639. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20640. if (currentAudioDevice != 0)
  20641. {
  20642. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20643. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20644. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20645. if (! currentSetup.useDefaultInputChannels)
  20646. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20647. if (! currentSetup.useDefaultOutputChannels)
  20648. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20649. }
  20650. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20651. {
  20652. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20653. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20654. }
  20655. if (midiInsFromXml.size() > 0)
  20656. {
  20657. // Add any midi devices that have been enabled before, but which aren't currently
  20658. // open because the device has been disconnected.
  20659. const StringArray availableMidiDevices (MidiInput::getDevices());
  20660. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20661. {
  20662. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20663. {
  20664. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20665. m->setAttribute ("name", midiInsFromXml[i]);
  20666. }
  20667. }
  20668. }
  20669. if (defaultMidiOutputName.isNotEmpty())
  20670. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20671. }
  20672. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20673. {
  20674. {
  20675. const ScopedLock sl (audioCallbackLock);
  20676. if (callbacks.contains (newCallback))
  20677. return;
  20678. }
  20679. if (currentAudioDevice != 0 && newCallback != 0)
  20680. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20681. const ScopedLock sl (audioCallbackLock);
  20682. callbacks.add (newCallback);
  20683. }
  20684. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20685. {
  20686. if (callback != 0)
  20687. {
  20688. bool needsDeinitialising = currentAudioDevice != 0;
  20689. {
  20690. const ScopedLock sl (audioCallbackLock);
  20691. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20692. callbacks.removeValue (callback);
  20693. }
  20694. if (needsDeinitialising)
  20695. callback->audioDeviceStopped();
  20696. }
  20697. }
  20698. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20699. int numInputChannels,
  20700. float** outputChannelData,
  20701. int numOutputChannels,
  20702. int numSamples)
  20703. {
  20704. const ScopedLock sl (audioCallbackLock);
  20705. if (inputLevelMeasurementEnabledCount > 0)
  20706. {
  20707. for (int j = 0; j < numSamples; ++j)
  20708. {
  20709. float s = 0;
  20710. for (int i = 0; i < numInputChannels; ++i)
  20711. s += std::abs (inputChannelData[i][j]);
  20712. s /= numInputChannels;
  20713. const double decayFactor = 0.99992;
  20714. if (s > inputLevel)
  20715. inputLevel = s;
  20716. else if (inputLevel > 0.001f)
  20717. inputLevel *= decayFactor;
  20718. else
  20719. inputLevel = 0;
  20720. }
  20721. }
  20722. if (callbacks.size() > 0)
  20723. {
  20724. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20725. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20726. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20727. outputChannelData, numOutputChannels, numSamples);
  20728. float** const tempChans = tempBuffer.getArrayOfChannels();
  20729. for (int i = callbacks.size(); --i > 0;)
  20730. {
  20731. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20732. tempChans, numOutputChannels, numSamples);
  20733. for (int chan = 0; chan < numOutputChannels; ++chan)
  20734. {
  20735. const float* const src = tempChans [chan];
  20736. float* const dst = outputChannelData [chan];
  20737. if (src != 0 && dst != 0)
  20738. for (int j = 0; j < numSamples; ++j)
  20739. dst[j] += src[j];
  20740. }
  20741. }
  20742. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20743. const double filterAmount = 0.2;
  20744. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20745. }
  20746. else
  20747. {
  20748. for (int i = 0; i < numOutputChannels; ++i)
  20749. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20750. }
  20751. if (testSound != 0)
  20752. {
  20753. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20754. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20755. for (int i = 0; i < numOutputChannels; ++i)
  20756. for (int j = 0; j < numSamps; ++j)
  20757. outputChannelData [i][j] += src[j];
  20758. testSoundPosition += numSamps;
  20759. if (testSoundPosition >= testSound->getNumSamples())
  20760. testSound = 0;
  20761. }
  20762. }
  20763. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20764. {
  20765. cpuUsageMs = 0;
  20766. const double sampleRate = device->getCurrentSampleRate();
  20767. const int blockSize = device->getCurrentBufferSizeSamples();
  20768. if (sampleRate > 0.0 && blockSize > 0)
  20769. {
  20770. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20771. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20772. }
  20773. {
  20774. const ScopedLock sl (audioCallbackLock);
  20775. for (int i = callbacks.size(); --i >= 0;)
  20776. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20777. }
  20778. sendChangeMessage();
  20779. }
  20780. void AudioDeviceManager::audioDeviceStoppedInt()
  20781. {
  20782. cpuUsageMs = 0;
  20783. timeToCpuScale = 0;
  20784. sendChangeMessage();
  20785. const ScopedLock sl (audioCallbackLock);
  20786. for (int i = callbacks.size(); --i >= 0;)
  20787. callbacks.getUnchecked(i)->audioDeviceStopped();
  20788. }
  20789. double AudioDeviceManager::getCpuUsage() const
  20790. {
  20791. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20792. }
  20793. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20794. const bool enabled)
  20795. {
  20796. if (enabled != isMidiInputEnabled (name))
  20797. {
  20798. if (enabled)
  20799. {
  20800. const int index = MidiInput::getDevices().indexOf (name);
  20801. if (index >= 0)
  20802. {
  20803. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20804. if (min != 0)
  20805. {
  20806. enabledMidiInputs.add (min);
  20807. min->start();
  20808. }
  20809. }
  20810. }
  20811. else
  20812. {
  20813. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20814. if (enabledMidiInputs[i]->getName() == name)
  20815. enabledMidiInputs.remove (i);
  20816. }
  20817. updateXml();
  20818. sendChangeMessage();
  20819. }
  20820. }
  20821. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20822. {
  20823. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20824. if (enabledMidiInputs[i]->getName() == name)
  20825. return true;
  20826. return false;
  20827. }
  20828. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20829. MidiInputCallback* callback)
  20830. {
  20831. removeMidiInputCallback (name, callback);
  20832. if (name.isEmpty())
  20833. {
  20834. midiCallbacks.add (callback);
  20835. midiCallbackDevices.add (0);
  20836. }
  20837. else
  20838. {
  20839. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20840. {
  20841. if (enabledMidiInputs[i]->getName() == name)
  20842. {
  20843. const ScopedLock sl (midiCallbackLock);
  20844. midiCallbacks.add (callback);
  20845. midiCallbackDevices.add (enabledMidiInputs[i]);
  20846. break;
  20847. }
  20848. }
  20849. }
  20850. }
  20851. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20852. MidiInputCallback* /*callback*/)
  20853. {
  20854. const ScopedLock sl (midiCallbackLock);
  20855. for (int i = midiCallbacks.size(); --i >= 0;)
  20856. {
  20857. String devName;
  20858. if (midiCallbackDevices.getUnchecked(i) != 0)
  20859. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20860. if (devName == name)
  20861. {
  20862. midiCallbacks.remove (i);
  20863. midiCallbackDevices.remove (i);
  20864. }
  20865. }
  20866. }
  20867. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20868. const MidiMessage& message)
  20869. {
  20870. if (! message.isActiveSense())
  20871. {
  20872. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20873. const ScopedLock sl (midiCallbackLock);
  20874. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20875. {
  20876. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20877. if (md == source || (md == 0 && isDefaultSource))
  20878. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20879. }
  20880. }
  20881. }
  20882. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20883. {
  20884. if (defaultMidiOutputName != deviceName)
  20885. {
  20886. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20887. {
  20888. const ScopedLock sl (audioCallbackLock);
  20889. oldCallbacks = callbacks;
  20890. callbacks.clear();
  20891. }
  20892. if (currentAudioDevice != 0)
  20893. for (int i = oldCallbacks.size(); --i >= 0;)
  20894. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20895. defaultMidiOutput = 0;
  20896. defaultMidiOutputName = deviceName;
  20897. if (deviceName.isNotEmpty())
  20898. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20899. if (currentAudioDevice != 0)
  20900. for (int i = oldCallbacks.size(); --i >= 0;)
  20901. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20902. {
  20903. const ScopedLock sl (audioCallbackLock);
  20904. callbacks = oldCallbacks;
  20905. }
  20906. updateXml();
  20907. sendChangeMessage();
  20908. }
  20909. }
  20910. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20911. int numInputChannels,
  20912. float** outputChannelData,
  20913. int numOutputChannels,
  20914. int numSamples)
  20915. {
  20916. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20917. }
  20918. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20919. {
  20920. owner->audioDeviceAboutToStartInt (device);
  20921. }
  20922. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20923. {
  20924. owner->audioDeviceStoppedInt();
  20925. }
  20926. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20927. {
  20928. owner->handleIncomingMidiMessageInt (source, message);
  20929. }
  20930. void AudioDeviceManager::playTestSound()
  20931. {
  20932. { // cunningly nested to swap, unlock and delete in that order.
  20933. ScopedPointer <AudioSampleBuffer> oldSound;
  20934. {
  20935. const ScopedLock sl (audioCallbackLock);
  20936. oldSound = testSound;
  20937. }
  20938. }
  20939. testSoundPosition = 0;
  20940. if (currentAudioDevice != 0)
  20941. {
  20942. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20943. const int soundLength = (int) sampleRate;
  20944. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20945. float* samples = newSound->getSampleData (0);
  20946. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20947. const float amplitude = 0.5f;
  20948. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20949. for (int i = 0; i < soundLength; ++i)
  20950. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20951. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20952. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20953. const ScopedLock sl (audioCallbackLock);
  20954. testSound = newSound;
  20955. }
  20956. }
  20957. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20958. {
  20959. const ScopedLock sl (audioCallbackLock);
  20960. if (enableMeasurement)
  20961. ++inputLevelMeasurementEnabledCount;
  20962. else
  20963. --inputLevelMeasurementEnabledCount;
  20964. inputLevel = 0;
  20965. }
  20966. double AudioDeviceManager::getCurrentInputLevel() const
  20967. {
  20968. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20969. return inputLevel;
  20970. }
  20971. END_JUCE_NAMESPACE
  20972. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20973. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20974. BEGIN_JUCE_NAMESPACE
  20975. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20976. : name (deviceName),
  20977. typeName (typeName_)
  20978. {
  20979. }
  20980. AudioIODevice::~AudioIODevice()
  20981. {
  20982. }
  20983. bool AudioIODevice::hasControlPanel() const
  20984. {
  20985. return false;
  20986. }
  20987. bool AudioIODevice::showControlPanel()
  20988. {
  20989. jassertfalse; // this should only be called for devices which return true from
  20990. // their hasControlPanel() method.
  20991. return false;
  20992. }
  20993. END_JUCE_NAMESPACE
  20994. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20995. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20996. BEGIN_JUCE_NAMESPACE
  20997. AudioIODeviceType::AudioIODeviceType (const String& name)
  20998. : typeName (name)
  20999. {
  21000. }
  21001. AudioIODeviceType::~AudioIODeviceType()
  21002. {
  21003. }
  21004. END_JUCE_NAMESPACE
  21005. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  21006. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  21007. BEGIN_JUCE_NAMESPACE
  21008. MidiOutput::MidiOutput()
  21009. : Thread ("midi out"),
  21010. internal (0),
  21011. firstMessage (0)
  21012. {
  21013. }
  21014. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  21015. const double sampleNumber)
  21016. : message (data, len, sampleNumber)
  21017. {
  21018. }
  21019. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  21020. const double millisecondCounterToStartAt,
  21021. double samplesPerSecondForBuffer)
  21022. {
  21023. // You've got to call startBackgroundThread() for this to actually work..
  21024. jassert (isThreadRunning());
  21025. // this needs to be a value in the future - RTFM for this method!
  21026. jassert (millisecondCounterToStartAt > 0);
  21027. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  21028. MidiBuffer::Iterator i (buffer);
  21029. const uint8* data;
  21030. int len, time;
  21031. while (i.getNextEvent (data, len, time))
  21032. {
  21033. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  21034. PendingMessage* const m
  21035. = new PendingMessage (data, len, eventTime);
  21036. const ScopedLock sl (lock);
  21037. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  21038. {
  21039. m->next = firstMessage;
  21040. firstMessage = m;
  21041. }
  21042. else
  21043. {
  21044. PendingMessage* mm = firstMessage;
  21045. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  21046. mm = mm->next;
  21047. m->next = mm->next;
  21048. mm->next = m;
  21049. }
  21050. }
  21051. notify();
  21052. }
  21053. void MidiOutput::clearAllPendingMessages()
  21054. {
  21055. const ScopedLock sl (lock);
  21056. while (firstMessage != 0)
  21057. {
  21058. PendingMessage* const m = firstMessage;
  21059. firstMessage = firstMessage->next;
  21060. delete m;
  21061. }
  21062. }
  21063. void MidiOutput::startBackgroundThread()
  21064. {
  21065. startThread (9);
  21066. }
  21067. void MidiOutput::stopBackgroundThread()
  21068. {
  21069. stopThread (5000);
  21070. }
  21071. void MidiOutput::run()
  21072. {
  21073. while (! threadShouldExit())
  21074. {
  21075. uint32 now = Time::getMillisecondCounter();
  21076. uint32 eventTime = 0;
  21077. uint32 timeToWait = 500;
  21078. PendingMessage* message;
  21079. {
  21080. const ScopedLock sl (lock);
  21081. message = firstMessage;
  21082. if (message != 0)
  21083. {
  21084. eventTime = roundToInt (message->message.getTimeStamp());
  21085. if (eventTime > now + 20)
  21086. {
  21087. timeToWait = eventTime - (now + 20);
  21088. message = 0;
  21089. }
  21090. else
  21091. {
  21092. firstMessage = message->next;
  21093. }
  21094. }
  21095. }
  21096. if (message != 0)
  21097. {
  21098. if (eventTime > now)
  21099. {
  21100. Time::waitForMillisecondCounter (eventTime);
  21101. if (threadShouldExit())
  21102. break;
  21103. }
  21104. if (eventTime > now - 200)
  21105. sendMessageNow (message->message);
  21106. delete message;
  21107. }
  21108. else
  21109. {
  21110. jassert (timeToWait < 1000 * 30);
  21111. wait (timeToWait);
  21112. }
  21113. }
  21114. clearAllPendingMessages();
  21115. }
  21116. END_JUCE_NAMESPACE
  21117. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21118. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21119. BEGIN_JUCE_NAMESPACE
  21120. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21121. {
  21122. const double maxVal = (double) 0x7fff;
  21123. char* intData = static_cast <char*> (dest);
  21124. if (dest != (void*) source || destBytesPerSample <= 4)
  21125. {
  21126. for (int i = 0; i < numSamples; ++i)
  21127. {
  21128. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21129. intData += destBytesPerSample;
  21130. }
  21131. }
  21132. else
  21133. {
  21134. intData += destBytesPerSample * numSamples;
  21135. for (int i = numSamples; --i >= 0;)
  21136. {
  21137. intData -= destBytesPerSample;
  21138. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21139. }
  21140. }
  21141. }
  21142. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21143. {
  21144. const double maxVal = (double) 0x7fff;
  21145. char* intData = static_cast <char*> (dest);
  21146. if (dest != (void*) source || destBytesPerSample <= 4)
  21147. {
  21148. for (int i = 0; i < numSamples; ++i)
  21149. {
  21150. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21151. intData += destBytesPerSample;
  21152. }
  21153. }
  21154. else
  21155. {
  21156. intData += destBytesPerSample * numSamples;
  21157. for (int i = numSamples; --i >= 0;)
  21158. {
  21159. intData -= destBytesPerSample;
  21160. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21161. }
  21162. }
  21163. }
  21164. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21165. {
  21166. const double maxVal = (double) 0x7fffff;
  21167. char* intData = static_cast <char*> (dest);
  21168. if (dest != (void*) source || destBytesPerSample <= 4)
  21169. {
  21170. for (int i = 0; i < numSamples; ++i)
  21171. {
  21172. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21173. intData += destBytesPerSample;
  21174. }
  21175. }
  21176. else
  21177. {
  21178. intData += destBytesPerSample * numSamples;
  21179. for (int i = numSamples; --i >= 0;)
  21180. {
  21181. intData -= destBytesPerSample;
  21182. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21183. }
  21184. }
  21185. }
  21186. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21187. {
  21188. const double maxVal = (double) 0x7fffff;
  21189. char* intData = static_cast <char*> (dest);
  21190. if (dest != (void*) source || destBytesPerSample <= 4)
  21191. {
  21192. for (int i = 0; i < numSamples; ++i)
  21193. {
  21194. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21195. intData += destBytesPerSample;
  21196. }
  21197. }
  21198. else
  21199. {
  21200. intData += destBytesPerSample * numSamples;
  21201. for (int i = numSamples; --i >= 0;)
  21202. {
  21203. intData -= destBytesPerSample;
  21204. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21205. }
  21206. }
  21207. }
  21208. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21209. {
  21210. const double maxVal = (double) 0x7fffffff;
  21211. char* intData = static_cast <char*> (dest);
  21212. if (dest != (void*) source || destBytesPerSample <= 4)
  21213. {
  21214. for (int i = 0; i < numSamples; ++i)
  21215. {
  21216. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21217. intData += destBytesPerSample;
  21218. }
  21219. }
  21220. else
  21221. {
  21222. intData += destBytesPerSample * numSamples;
  21223. for (int i = numSamples; --i >= 0;)
  21224. {
  21225. intData -= destBytesPerSample;
  21226. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21227. }
  21228. }
  21229. }
  21230. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21231. {
  21232. const double maxVal = (double) 0x7fffffff;
  21233. char* intData = static_cast <char*> (dest);
  21234. if (dest != (void*) source || destBytesPerSample <= 4)
  21235. {
  21236. for (int i = 0; i < numSamples; ++i)
  21237. {
  21238. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21239. intData += destBytesPerSample;
  21240. }
  21241. }
  21242. else
  21243. {
  21244. intData += destBytesPerSample * numSamples;
  21245. for (int i = numSamples; --i >= 0;)
  21246. {
  21247. intData -= destBytesPerSample;
  21248. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21249. }
  21250. }
  21251. }
  21252. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21253. {
  21254. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21255. char* d = static_cast <char*> (dest);
  21256. for (int i = 0; i < numSamples; ++i)
  21257. {
  21258. *(float*) d = source[i];
  21259. #if JUCE_BIG_ENDIAN
  21260. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21261. #endif
  21262. d += destBytesPerSample;
  21263. }
  21264. }
  21265. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21266. {
  21267. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21268. char* d = static_cast <char*> (dest);
  21269. for (int i = 0; i < numSamples; ++i)
  21270. {
  21271. *(float*) d = source[i];
  21272. #if JUCE_LITTLE_ENDIAN
  21273. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21274. #endif
  21275. d += destBytesPerSample;
  21276. }
  21277. }
  21278. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21279. {
  21280. const float scale = 1.0f / 0x7fff;
  21281. const char* intData = static_cast <const char*> (source);
  21282. if (source != (void*) dest || srcBytesPerSample >= 4)
  21283. {
  21284. for (int i = 0; i < numSamples; ++i)
  21285. {
  21286. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21287. intData += srcBytesPerSample;
  21288. }
  21289. }
  21290. else
  21291. {
  21292. intData += srcBytesPerSample * numSamples;
  21293. for (int i = numSamples; --i >= 0;)
  21294. {
  21295. intData -= srcBytesPerSample;
  21296. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21297. }
  21298. }
  21299. }
  21300. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21301. {
  21302. const float scale = 1.0f / 0x7fff;
  21303. const char* intData = static_cast <const char*> (source);
  21304. if (source != (void*) dest || srcBytesPerSample >= 4)
  21305. {
  21306. for (int i = 0; i < numSamples; ++i)
  21307. {
  21308. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21309. intData += srcBytesPerSample;
  21310. }
  21311. }
  21312. else
  21313. {
  21314. intData += srcBytesPerSample * numSamples;
  21315. for (int i = numSamples; --i >= 0;)
  21316. {
  21317. intData -= srcBytesPerSample;
  21318. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21319. }
  21320. }
  21321. }
  21322. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21323. {
  21324. const float scale = 1.0f / 0x7fffff;
  21325. const char* intData = static_cast <const char*> (source);
  21326. if (source != (void*) dest || srcBytesPerSample >= 4)
  21327. {
  21328. for (int i = 0; i < numSamples; ++i)
  21329. {
  21330. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21331. intData += srcBytesPerSample;
  21332. }
  21333. }
  21334. else
  21335. {
  21336. intData += srcBytesPerSample * numSamples;
  21337. for (int i = numSamples; --i >= 0;)
  21338. {
  21339. intData -= srcBytesPerSample;
  21340. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21341. }
  21342. }
  21343. }
  21344. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21345. {
  21346. const float scale = 1.0f / 0x7fffff;
  21347. const char* intData = static_cast <const char*> (source);
  21348. if (source != (void*) dest || srcBytesPerSample >= 4)
  21349. {
  21350. for (int i = 0; i < numSamples; ++i)
  21351. {
  21352. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21353. intData += srcBytesPerSample;
  21354. }
  21355. }
  21356. else
  21357. {
  21358. intData += srcBytesPerSample * numSamples;
  21359. for (int i = numSamples; --i >= 0;)
  21360. {
  21361. intData -= srcBytesPerSample;
  21362. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21363. }
  21364. }
  21365. }
  21366. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21367. {
  21368. const float scale = 1.0f / 0x7fffffff;
  21369. const char* intData = static_cast <const char*> (source);
  21370. if (source != (void*) dest || srcBytesPerSample >= 4)
  21371. {
  21372. for (int i = 0; i < numSamples; ++i)
  21373. {
  21374. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21375. intData += srcBytesPerSample;
  21376. }
  21377. }
  21378. else
  21379. {
  21380. intData += srcBytesPerSample * numSamples;
  21381. for (int i = numSamples; --i >= 0;)
  21382. {
  21383. intData -= srcBytesPerSample;
  21384. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21385. }
  21386. }
  21387. }
  21388. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21389. {
  21390. const float scale = 1.0f / 0x7fffffff;
  21391. const char* intData = static_cast <const char*> (source);
  21392. if (source != (void*) dest || srcBytesPerSample >= 4)
  21393. {
  21394. for (int i = 0; i < numSamples; ++i)
  21395. {
  21396. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21397. intData += srcBytesPerSample;
  21398. }
  21399. }
  21400. else
  21401. {
  21402. intData += srcBytesPerSample * numSamples;
  21403. for (int i = numSamples; --i >= 0;)
  21404. {
  21405. intData -= srcBytesPerSample;
  21406. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21407. }
  21408. }
  21409. }
  21410. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21411. {
  21412. const char* s = static_cast <const char*> (source);
  21413. for (int i = 0; i < numSamples; ++i)
  21414. {
  21415. dest[i] = *(float*)s;
  21416. #if JUCE_BIG_ENDIAN
  21417. uint32* const d = (uint32*) (dest + i);
  21418. *d = ByteOrder::swap (*d);
  21419. #endif
  21420. s += srcBytesPerSample;
  21421. }
  21422. }
  21423. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21424. {
  21425. const char* s = static_cast <const char*> (source);
  21426. for (int i = 0; i < numSamples; ++i)
  21427. {
  21428. dest[i] = *(float*)s;
  21429. #if JUCE_LITTLE_ENDIAN
  21430. uint32* const d = (uint32*) (dest + i);
  21431. *d = ByteOrder::swap (*d);
  21432. #endif
  21433. s += srcBytesPerSample;
  21434. }
  21435. }
  21436. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21437. const float* const source,
  21438. void* const dest,
  21439. const int numSamples)
  21440. {
  21441. switch (destFormat)
  21442. {
  21443. case int16LE:
  21444. convertFloatToInt16LE (source, dest, numSamples);
  21445. break;
  21446. case int16BE:
  21447. convertFloatToInt16BE (source, dest, numSamples);
  21448. break;
  21449. case int24LE:
  21450. convertFloatToInt24LE (source, dest, numSamples);
  21451. break;
  21452. case int24BE:
  21453. convertFloatToInt24BE (source, dest, numSamples);
  21454. break;
  21455. case int32LE:
  21456. convertFloatToInt32LE (source, dest, numSamples);
  21457. break;
  21458. case int32BE:
  21459. convertFloatToInt32BE (source, dest, numSamples);
  21460. break;
  21461. case float32LE:
  21462. convertFloatToFloat32LE (source, dest, numSamples);
  21463. break;
  21464. case float32BE:
  21465. convertFloatToFloat32BE (source, dest, numSamples);
  21466. break;
  21467. default:
  21468. jassertfalse;
  21469. break;
  21470. }
  21471. }
  21472. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21473. const void* const source,
  21474. float* const dest,
  21475. const int numSamples)
  21476. {
  21477. switch (sourceFormat)
  21478. {
  21479. case int16LE:
  21480. convertInt16LEToFloat (source, dest, numSamples);
  21481. break;
  21482. case int16BE:
  21483. convertInt16BEToFloat (source, dest, numSamples);
  21484. break;
  21485. case int24LE:
  21486. convertInt24LEToFloat (source, dest, numSamples);
  21487. break;
  21488. case int24BE:
  21489. convertInt24BEToFloat (source, dest, numSamples);
  21490. break;
  21491. case int32LE:
  21492. convertInt32LEToFloat (source, dest, numSamples);
  21493. break;
  21494. case int32BE:
  21495. convertInt32BEToFloat (source, dest, numSamples);
  21496. break;
  21497. case float32LE:
  21498. convertFloat32LEToFloat (source, dest, numSamples);
  21499. break;
  21500. case float32BE:
  21501. convertFloat32BEToFloat (source, dest, numSamples);
  21502. break;
  21503. default:
  21504. jassertfalse;
  21505. break;
  21506. }
  21507. }
  21508. void AudioDataConverters::interleaveSamples (const float** const source,
  21509. float* const dest,
  21510. const int numSamples,
  21511. const int numChannels)
  21512. {
  21513. for (int chan = 0; chan < numChannels; ++chan)
  21514. {
  21515. int i = chan;
  21516. const float* src = source [chan];
  21517. for (int j = 0; j < numSamples; ++j)
  21518. {
  21519. dest [i] = src [j];
  21520. i += numChannels;
  21521. }
  21522. }
  21523. }
  21524. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21525. float** const dest,
  21526. const int numSamples,
  21527. const int numChannels)
  21528. {
  21529. for (int chan = 0; chan < numChannels; ++chan)
  21530. {
  21531. int i = chan;
  21532. float* dst = dest [chan];
  21533. for (int j = 0; j < numSamples; ++j)
  21534. {
  21535. dst [j] = source [i];
  21536. i += numChannels;
  21537. }
  21538. }
  21539. }
  21540. #if JUCE_UNIT_TESTS
  21541. class AudioConversionTests : public UnitTest
  21542. {
  21543. public:
  21544. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21545. template <class F1, class E1, class F2, class E2>
  21546. struct Test5
  21547. {
  21548. static void test (UnitTest& unitTest)
  21549. {
  21550. test (unitTest, false);
  21551. test (unitTest, true);
  21552. }
  21553. static void test (UnitTest& unitTest, bool inPlace)
  21554. {
  21555. const int numSamples = 2048;
  21556. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21557. {
  21558. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21559. bool clippingFailed = false;
  21560. for (int i = 0; i < numSamples / 2; ++i)
  21561. {
  21562. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21563. if (! d.isFloatingPoint())
  21564. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21565. ++d;
  21566. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21567. ++d;
  21568. }
  21569. unitTest.expect (! clippingFailed);
  21570. }
  21571. // convert data from the source to dest format..
  21572. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21573. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21574. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21575. // ..and back again..
  21576. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21577. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21578. if (! inPlace)
  21579. zerostruct (reversed);
  21580. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21581. {
  21582. int biggestDiff = 0;
  21583. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21584. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21585. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21586. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21587. for (int i = 0; i < numSamples; ++i)
  21588. {
  21589. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21590. ++d1;
  21591. ++d2;
  21592. }
  21593. unitTest.expect (biggestDiff <= errorMargin);
  21594. }
  21595. }
  21596. };
  21597. template <class F1, class E1, class FormatType>
  21598. struct Test3
  21599. {
  21600. static void test (UnitTest& unitTest)
  21601. {
  21602. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21603. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21604. }
  21605. };
  21606. template <class FormatType, class Endianness>
  21607. struct Test2
  21608. {
  21609. static void test (UnitTest& unitTest)
  21610. {
  21611. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21612. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21613. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21614. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21615. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21616. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21617. }
  21618. };
  21619. template <class FormatType>
  21620. struct Test1
  21621. {
  21622. static void test (UnitTest& unitTest)
  21623. {
  21624. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21625. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21626. }
  21627. };
  21628. void runTest()
  21629. {
  21630. beginTest ("Round-trip conversion");
  21631. Test1 <AudioData::Int8>::test (*this);
  21632. Test1 <AudioData::Int16>::test (*this);
  21633. Test1 <AudioData::Int24>::test (*this);
  21634. Test1 <AudioData::Int32>::test (*this);
  21635. Test1 <AudioData::Float32>::test (*this);
  21636. }
  21637. };
  21638. static AudioConversionTests audioConversionUnitTests;
  21639. #endif
  21640. END_JUCE_NAMESPACE
  21641. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21642. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21643. BEGIN_JUCE_NAMESPACE
  21644. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21645. const int numSamples) throw()
  21646. : numChannels (numChannels_),
  21647. size (numSamples)
  21648. {
  21649. jassert (numSamples >= 0);
  21650. jassert (numChannels_ > 0);
  21651. allocateData();
  21652. }
  21653. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21654. : numChannels (other.numChannels),
  21655. size (other.size)
  21656. {
  21657. allocateData();
  21658. const size_t numBytes = size * sizeof (float);
  21659. for (int i = 0; i < numChannels; ++i)
  21660. memcpy (channels[i], other.channels[i], numBytes);
  21661. }
  21662. void AudioSampleBuffer::allocateData()
  21663. {
  21664. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21665. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21666. allocatedData.malloc (allocatedBytes);
  21667. channels = reinterpret_cast <float**> (allocatedData.getData());
  21668. float* chan = (float*) (allocatedData + channelListSize);
  21669. for (int i = 0; i < numChannels; ++i)
  21670. {
  21671. channels[i] = chan;
  21672. chan += size;
  21673. }
  21674. channels [numChannels] = 0;
  21675. }
  21676. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21677. const int numChannels_,
  21678. const int numSamples) throw()
  21679. : numChannels (numChannels_),
  21680. size (numSamples),
  21681. allocatedBytes (0)
  21682. {
  21683. jassert (numChannels_ > 0);
  21684. allocateChannels (dataToReferTo);
  21685. }
  21686. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21687. const int newNumChannels,
  21688. const int newNumSamples) throw()
  21689. {
  21690. jassert (newNumChannels > 0);
  21691. allocatedBytes = 0;
  21692. allocatedData.free();
  21693. numChannels = newNumChannels;
  21694. size = newNumSamples;
  21695. allocateChannels (dataToReferTo);
  21696. }
  21697. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21698. {
  21699. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21700. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21701. {
  21702. channels = static_cast <float**> (preallocatedChannelSpace);
  21703. }
  21704. else
  21705. {
  21706. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21707. channels = reinterpret_cast <float**> (allocatedData.getData());
  21708. }
  21709. for (int i = 0; i < numChannels; ++i)
  21710. {
  21711. // you have to pass in the same number of valid pointers as numChannels
  21712. jassert (dataToReferTo[i] != 0);
  21713. channels[i] = dataToReferTo[i];
  21714. }
  21715. channels [numChannels] = 0;
  21716. }
  21717. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21718. {
  21719. if (this != &other)
  21720. {
  21721. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21722. const size_t numBytes = size * sizeof (float);
  21723. for (int i = 0; i < numChannels; ++i)
  21724. memcpy (channels[i], other.channels[i], numBytes);
  21725. }
  21726. return *this;
  21727. }
  21728. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21729. {
  21730. }
  21731. void AudioSampleBuffer::setSize (const int newNumChannels,
  21732. const int newNumSamples,
  21733. const bool keepExistingContent,
  21734. const bool clearExtraSpace,
  21735. const bool avoidReallocating) throw()
  21736. {
  21737. jassert (newNumChannels > 0);
  21738. if (newNumSamples != size || newNumChannels != numChannels)
  21739. {
  21740. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21741. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21742. if (keepExistingContent)
  21743. {
  21744. HeapBlock <char> newData;
  21745. newData.allocate (newTotalBytes, clearExtraSpace);
  21746. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21747. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21748. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21749. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21750. for (int i = 0; i < numChansToCopy; ++i)
  21751. {
  21752. memcpy (newChan, channels[i], numBytesToCopy);
  21753. newChannels[i] = newChan;
  21754. newChan += newNumSamples;
  21755. }
  21756. allocatedData.swapWith (newData);
  21757. allocatedBytes = (int) newTotalBytes;
  21758. channels = newChannels;
  21759. }
  21760. else
  21761. {
  21762. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21763. {
  21764. if (clearExtraSpace)
  21765. zeromem (allocatedData, newTotalBytes);
  21766. }
  21767. else
  21768. {
  21769. allocatedBytes = newTotalBytes;
  21770. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21771. channels = reinterpret_cast <float**> (allocatedData.getData());
  21772. }
  21773. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21774. for (int i = 0; i < newNumChannels; ++i)
  21775. {
  21776. channels[i] = chan;
  21777. chan += newNumSamples;
  21778. }
  21779. }
  21780. channels [newNumChannels] = 0;
  21781. size = newNumSamples;
  21782. numChannels = newNumChannels;
  21783. }
  21784. }
  21785. void AudioSampleBuffer::clear() throw()
  21786. {
  21787. for (int i = 0; i < numChannels; ++i)
  21788. zeromem (channels[i], size * sizeof (float));
  21789. }
  21790. void AudioSampleBuffer::clear (const int startSample,
  21791. const int numSamples) throw()
  21792. {
  21793. jassert (startSample >= 0 && startSample + numSamples <= size);
  21794. for (int i = 0; i < numChannels; ++i)
  21795. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21796. }
  21797. void AudioSampleBuffer::clear (const int channel,
  21798. const int startSample,
  21799. const int numSamples) throw()
  21800. {
  21801. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21802. jassert (startSample >= 0 && startSample + numSamples <= size);
  21803. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21804. }
  21805. void AudioSampleBuffer::applyGain (const int channel,
  21806. const int startSample,
  21807. int numSamples,
  21808. const float gain) throw()
  21809. {
  21810. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21811. jassert (startSample >= 0 && startSample + numSamples <= size);
  21812. if (gain != 1.0f)
  21813. {
  21814. float* d = channels [channel] + startSample;
  21815. if (gain == 0.0f)
  21816. {
  21817. zeromem (d, sizeof (float) * numSamples);
  21818. }
  21819. else
  21820. {
  21821. while (--numSamples >= 0)
  21822. *d++ *= gain;
  21823. }
  21824. }
  21825. }
  21826. void AudioSampleBuffer::applyGainRamp (const int channel,
  21827. const int startSample,
  21828. int numSamples,
  21829. float startGain,
  21830. float endGain) throw()
  21831. {
  21832. if (startGain == endGain)
  21833. {
  21834. applyGain (channel, startSample, numSamples, startGain);
  21835. }
  21836. else
  21837. {
  21838. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21839. jassert (startSample >= 0 && startSample + numSamples <= size);
  21840. const float increment = (endGain - startGain) / numSamples;
  21841. float* d = channels [channel] + startSample;
  21842. while (--numSamples >= 0)
  21843. {
  21844. *d++ *= startGain;
  21845. startGain += increment;
  21846. }
  21847. }
  21848. }
  21849. void AudioSampleBuffer::applyGain (const int startSample,
  21850. const int numSamples,
  21851. const float gain) throw()
  21852. {
  21853. for (int i = 0; i < numChannels; ++i)
  21854. applyGain (i, startSample, numSamples, gain);
  21855. }
  21856. void AudioSampleBuffer::addFrom (const int destChannel,
  21857. const int destStartSample,
  21858. const AudioSampleBuffer& source,
  21859. const int sourceChannel,
  21860. const int sourceStartSample,
  21861. int numSamples,
  21862. const float gain) throw()
  21863. {
  21864. jassert (&source != this || sourceChannel != destChannel);
  21865. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21866. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21867. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21868. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21869. if (gain != 0.0f && numSamples > 0)
  21870. {
  21871. float* d = channels [destChannel] + destStartSample;
  21872. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21873. if (gain != 1.0f)
  21874. {
  21875. while (--numSamples >= 0)
  21876. *d++ += gain * *s++;
  21877. }
  21878. else
  21879. {
  21880. while (--numSamples >= 0)
  21881. *d++ += *s++;
  21882. }
  21883. }
  21884. }
  21885. void AudioSampleBuffer::addFrom (const int destChannel,
  21886. const int destStartSample,
  21887. const float* source,
  21888. int numSamples,
  21889. const float gain) throw()
  21890. {
  21891. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21892. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21893. jassert (source != 0);
  21894. if (gain != 0.0f && numSamples > 0)
  21895. {
  21896. float* d = channels [destChannel] + destStartSample;
  21897. if (gain != 1.0f)
  21898. {
  21899. while (--numSamples >= 0)
  21900. *d++ += gain * *source++;
  21901. }
  21902. else
  21903. {
  21904. while (--numSamples >= 0)
  21905. *d++ += *source++;
  21906. }
  21907. }
  21908. }
  21909. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21910. const int destStartSample,
  21911. const float* source,
  21912. int numSamples,
  21913. float startGain,
  21914. const float endGain) throw()
  21915. {
  21916. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21917. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21918. jassert (source != 0);
  21919. if (startGain == endGain)
  21920. {
  21921. addFrom (destChannel,
  21922. destStartSample,
  21923. source,
  21924. numSamples,
  21925. startGain);
  21926. }
  21927. else
  21928. {
  21929. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21930. {
  21931. const float increment = (endGain - startGain) / numSamples;
  21932. float* d = channels [destChannel] + destStartSample;
  21933. while (--numSamples >= 0)
  21934. {
  21935. *d++ += startGain * *source++;
  21936. startGain += increment;
  21937. }
  21938. }
  21939. }
  21940. }
  21941. void AudioSampleBuffer::copyFrom (const int destChannel,
  21942. const int destStartSample,
  21943. const AudioSampleBuffer& source,
  21944. const int sourceChannel,
  21945. const int sourceStartSample,
  21946. int numSamples) throw()
  21947. {
  21948. jassert (&source != this || sourceChannel != destChannel);
  21949. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21950. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21951. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21952. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21953. if (numSamples > 0)
  21954. {
  21955. memcpy (channels [destChannel] + destStartSample,
  21956. source.channels [sourceChannel] + sourceStartSample,
  21957. sizeof (float) * numSamples);
  21958. }
  21959. }
  21960. void AudioSampleBuffer::copyFrom (const int destChannel,
  21961. const int destStartSample,
  21962. const float* source,
  21963. int numSamples) throw()
  21964. {
  21965. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21966. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21967. jassert (source != 0);
  21968. if (numSamples > 0)
  21969. {
  21970. memcpy (channels [destChannel] + destStartSample,
  21971. source,
  21972. sizeof (float) * numSamples);
  21973. }
  21974. }
  21975. void AudioSampleBuffer::copyFrom (const int destChannel,
  21976. const int destStartSample,
  21977. const float* source,
  21978. int numSamples,
  21979. const float gain) throw()
  21980. {
  21981. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21982. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21983. jassert (source != 0);
  21984. if (numSamples > 0)
  21985. {
  21986. float* d = channels [destChannel] + destStartSample;
  21987. if (gain != 1.0f)
  21988. {
  21989. if (gain == 0)
  21990. {
  21991. zeromem (d, sizeof (float) * numSamples);
  21992. }
  21993. else
  21994. {
  21995. while (--numSamples >= 0)
  21996. *d++ = gain * *source++;
  21997. }
  21998. }
  21999. else
  22000. {
  22001. memcpy (d, source, sizeof (float) * numSamples);
  22002. }
  22003. }
  22004. }
  22005. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  22006. const int destStartSample,
  22007. const float* source,
  22008. int numSamples,
  22009. float startGain,
  22010. float endGain) throw()
  22011. {
  22012. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22013. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22014. jassert (source != 0);
  22015. if (startGain == endGain)
  22016. {
  22017. copyFrom (destChannel,
  22018. destStartSample,
  22019. source,
  22020. numSamples,
  22021. startGain);
  22022. }
  22023. else
  22024. {
  22025. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22026. {
  22027. const float increment = (endGain - startGain) / numSamples;
  22028. float* d = channels [destChannel] + destStartSample;
  22029. while (--numSamples >= 0)
  22030. {
  22031. *d++ = startGain * *source++;
  22032. startGain += increment;
  22033. }
  22034. }
  22035. }
  22036. }
  22037. void AudioSampleBuffer::findMinMax (const int channel,
  22038. const int startSample,
  22039. int numSamples,
  22040. float& minVal,
  22041. float& maxVal) const throw()
  22042. {
  22043. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22044. jassert (startSample >= 0 && startSample + numSamples <= size);
  22045. if (numSamples <= 0)
  22046. {
  22047. minVal = 0.0f;
  22048. maxVal = 0.0f;
  22049. }
  22050. else
  22051. {
  22052. const float* d = channels [channel] + startSample;
  22053. float mn = *d++;
  22054. float mx = mn;
  22055. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  22056. {
  22057. const float samp = *d++;
  22058. if (samp > mx)
  22059. mx = samp;
  22060. if (samp < mn)
  22061. mn = samp;
  22062. }
  22063. maxVal = mx;
  22064. minVal = mn;
  22065. }
  22066. }
  22067. float AudioSampleBuffer::getMagnitude (const int channel,
  22068. const int startSample,
  22069. const int numSamples) const throw()
  22070. {
  22071. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22072. jassert (startSample >= 0 && startSample + numSamples <= size);
  22073. float mn, mx;
  22074. findMinMax (channel, startSample, numSamples, mn, mx);
  22075. return jmax (mn, -mn, mx, -mx);
  22076. }
  22077. float AudioSampleBuffer::getMagnitude (const int startSample,
  22078. const int numSamples) const throw()
  22079. {
  22080. float mag = 0.0f;
  22081. for (int i = 0; i < numChannels; ++i)
  22082. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22083. return mag;
  22084. }
  22085. float AudioSampleBuffer::getRMSLevel (const int channel,
  22086. const int startSample,
  22087. const int numSamples) const throw()
  22088. {
  22089. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22090. jassert (startSample >= 0 && startSample + numSamples <= size);
  22091. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22092. return 0.0f;
  22093. const float* const data = channels [channel] + startSample;
  22094. double sum = 0.0;
  22095. for (int i = 0; i < numSamples; ++i)
  22096. {
  22097. const float sample = data [i];
  22098. sum += sample * sample;
  22099. }
  22100. return (float) std::sqrt (sum / numSamples);
  22101. }
  22102. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22103. const int startSample,
  22104. const int numSamples,
  22105. const int readerStartSample,
  22106. const bool useLeftChan,
  22107. const bool useRightChan)
  22108. {
  22109. jassert (reader != 0);
  22110. jassert (startSample >= 0 && startSample + numSamples <= size);
  22111. if (numSamples > 0)
  22112. {
  22113. int* chans[3];
  22114. if (useLeftChan == useRightChan)
  22115. {
  22116. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22117. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22118. }
  22119. else if (useLeftChan || (reader->numChannels == 1))
  22120. {
  22121. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22122. chans[1] = 0;
  22123. }
  22124. else if (useRightChan)
  22125. {
  22126. chans[0] = 0;
  22127. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22128. }
  22129. chans[2] = 0;
  22130. reader->read (chans, 2, readerStartSample, numSamples, true);
  22131. if (! reader->usesFloatingPointData)
  22132. {
  22133. for (int j = 0; j < 2; ++j)
  22134. {
  22135. float* const d = reinterpret_cast <float*> (chans[j]);
  22136. if (d != 0)
  22137. {
  22138. const float multiplier = 1.0f / 0x7fffffff;
  22139. for (int i = 0; i < numSamples; ++i)
  22140. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22141. }
  22142. }
  22143. }
  22144. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22145. {
  22146. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22147. memcpy (getSampleData (1, startSample),
  22148. getSampleData (0, startSample),
  22149. sizeof (float) * numSamples);
  22150. }
  22151. }
  22152. }
  22153. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22154. const int startSample,
  22155. const int numSamples) const
  22156. {
  22157. jassert (writer != 0);
  22158. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22159. }
  22160. END_JUCE_NAMESPACE
  22161. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22162. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22163. BEGIN_JUCE_NAMESPACE
  22164. IIRFilter::IIRFilter()
  22165. : active (false)
  22166. {
  22167. reset();
  22168. }
  22169. IIRFilter::IIRFilter (const IIRFilter& other)
  22170. : active (other.active)
  22171. {
  22172. const ScopedLock sl (other.processLock);
  22173. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22174. reset();
  22175. }
  22176. IIRFilter::~IIRFilter()
  22177. {
  22178. }
  22179. void IIRFilter::reset() throw()
  22180. {
  22181. const ScopedLock sl (processLock);
  22182. x1 = 0;
  22183. x2 = 0;
  22184. y1 = 0;
  22185. y2 = 0;
  22186. }
  22187. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22188. {
  22189. float out = coefficients[0] * in
  22190. + coefficients[1] * x1
  22191. + coefficients[2] * x2
  22192. - coefficients[4] * y1
  22193. - coefficients[5] * y2;
  22194. #if JUCE_INTEL
  22195. if (! (out < -1.0e-8 || out > 1.0e-8))
  22196. out = 0;
  22197. #endif
  22198. x2 = x1;
  22199. x1 = in;
  22200. y2 = y1;
  22201. y1 = out;
  22202. return out;
  22203. }
  22204. void IIRFilter::processSamples (float* const samples,
  22205. const int numSamples) throw()
  22206. {
  22207. const ScopedLock sl (processLock);
  22208. if (active)
  22209. {
  22210. for (int i = 0; i < numSamples; ++i)
  22211. {
  22212. const float in = samples[i];
  22213. float out = coefficients[0] * in
  22214. + coefficients[1] * x1
  22215. + coefficients[2] * x2
  22216. - coefficients[4] * y1
  22217. - coefficients[5] * y2;
  22218. #if JUCE_INTEL
  22219. if (! (out < -1.0e-8 || out > 1.0e-8))
  22220. out = 0;
  22221. #endif
  22222. x2 = x1;
  22223. x1 = in;
  22224. y2 = y1;
  22225. y1 = out;
  22226. samples[i] = out;
  22227. }
  22228. }
  22229. }
  22230. void IIRFilter::makeLowPass (const double sampleRate,
  22231. const double frequency) throw()
  22232. {
  22233. jassert (sampleRate > 0);
  22234. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22235. const double nSquared = n * n;
  22236. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22237. setCoefficients (c1,
  22238. c1 * 2.0f,
  22239. c1,
  22240. 1.0,
  22241. c1 * 2.0 * (1.0 - nSquared),
  22242. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22243. }
  22244. void IIRFilter::makeHighPass (const double sampleRate,
  22245. const double frequency) throw()
  22246. {
  22247. const double n = tan (double_Pi * frequency / sampleRate);
  22248. const double nSquared = n * n;
  22249. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22250. setCoefficients (c1,
  22251. c1 * -2.0f,
  22252. c1,
  22253. 1.0,
  22254. c1 * 2.0 * (nSquared - 1.0),
  22255. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22256. }
  22257. void IIRFilter::makeLowShelf (const double sampleRate,
  22258. const double cutOffFrequency,
  22259. const double Q,
  22260. const float gainFactor) throw()
  22261. {
  22262. jassert (sampleRate > 0);
  22263. jassert (Q > 0);
  22264. const double A = jmax (0.0f, gainFactor);
  22265. const double aminus1 = A - 1.0;
  22266. const double aplus1 = A + 1.0;
  22267. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22268. const double coso = std::cos (omega);
  22269. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22270. const double aminus1TimesCoso = aminus1 * coso;
  22271. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22272. A * 2.0 * (aminus1 - aplus1 * coso),
  22273. A * (aplus1 - aminus1TimesCoso - beta),
  22274. aplus1 + aminus1TimesCoso + beta,
  22275. -2.0 * (aminus1 + aplus1 * coso),
  22276. aplus1 + aminus1TimesCoso - beta);
  22277. }
  22278. void IIRFilter::makeHighShelf (const double sampleRate,
  22279. const double cutOffFrequency,
  22280. const double Q,
  22281. const float gainFactor) throw()
  22282. {
  22283. jassert (sampleRate > 0);
  22284. jassert (Q > 0);
  22285. const double A = jmax (0.0f, gainFactor);
  22286. const double aminus1 = A - 1.0;
  22287. const double aplus1 = A + 1.0;
  22288. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22289. const double coso = std::cos (omega);
  22290. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22291. const double aminus1TimesCoso = aminus1 * coso;
  22292. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22293. A * -2.0 * (aminus1 + aplus1 * coso),
  22294. A * (aplus1 + aminus1TimesCoso - beta),
  22295. aplus1 - aminus1TimesCoso + beta,
  22296. 2.0 * (aminus1 - aplus1 * coso),
  22297. aplus1 - aminus1TimesCoso - beta);
  22298. }
  22299. void IIRFilter::makeBandPass (const double sampleRate,
  22300. const double centreFrequency,
  22301. const double Q,
  22302. const float gainFactor) throw()
  22303. {
  22304. jassert (sampleRate > 0);
  22305. jassert (Q > 0);
  22306. const double A = jmax (0.0f, gainFactor);
  22307. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22308. const double alpha = 0.5 * std::sin (omega) / Q;
  22309. const double c2 = -2.0 * std::cos (omega);
  22310. const double alphaTimesA = alpha * A;
  22311. const double alphaOverA = alpha / A;
  22312. setCoefficients (1.0 + alphaTimesA,
  22313. c2,
  22314. 1.0 - alphaTimesA,
  22315. 1.0 + alphaOverA,
  22316. c2,
  22317. 1.0 - alphaOverA);
  22318. }
  22319. void IIRFilter::makeInactive() throw()
  22320. {
  22321. const ScopedLock sl (processLock);
  22322. active = false;
  22323. }
  22324. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22325. {
  22326. const ScopedLock sl (processLock);
  22327. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22328. active = other.active;
  22329. }
  22330. void IIRFilter::setCoefficients (double c1,
  22331. double c2,
  22332. double c3,
  22333. double c4,
  22334. double c5,
  22335. double c6) throw()
  22336. {
  22337. const double a = 1.0 / c4;
  22338. c1 *= a;
  22339. c2 *= a;
  22340. c3 *= a;
  22341. c5 *= a;
  22342. c6 *= a;
  22343. const ScopedLock sl (processLock);
  22344. coefficients[0] = (float) c1;
  22345. coefficients[1] = (float) c2;
  22346. coefficients[2] = (float) c3;
  22347. coefficients[3] = (float) c4;
  22348. coefficients[4] = (float) c5;
  22349. coefficients[5] = (float) c6;
  22350. active = true;
  22351. }
  22352. END_JUCE_NAMESPACE
  22353. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22354. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22355. BEGIN_JUCE_NAMESPACE
  22356. MidiBuffer::MidiBuffer() throw()
  22357. : bytesUsed (0)
  22358. {
  22359. }
  22360. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22361. : bytesUsed (0)
  22362. {
  22363. addEvent (message, 0);
  22364. }
  22365. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22366. : data (other.data),
  22367. bytesUsed (other.bytesUsed)
  22368. {
  22369. }
  22370. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22371. {
  22372. bytesUsed = other.bytesUsed;
  22373. data = other.data;
  22374. return *this;
  22375. }
  22376. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22377. {
  22378. data.swapWith (other.data);
  22379. swapVariables <int> (bytesUsed, other.bytesUsed);
  22380. }
  22381. MidiBuffer::~MidiBuffer()
  22382. {
  22383. }
  22384. inline uint8* MidiBuffer::getData() const throw()
  22385. {
  22386. return static_cast <uint8*> (data.getData());
  22387. }
  22388. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22389. {
  22390. return *static_cast <const int*> (d);
  22391. }
  22392. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22393. {
  22394. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22395. }
  22396. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22397. {
  22398. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22399. }
  22400. void MidiBuffer::clear() throw()
  22401. {
  22402. bytesUsed = 0;
  22403. }
  22404. void MidiBuffer::clear (const int startSample, const int numSamples)
  22405. {
  22406. uint8* const start = findEventAfter (getData(), startSample - 1);
  22407. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22408. if (end > start)
  22409. {
  22410. const int bytesToMove = bytesUsed - (int) (end - getData());
  22411. if (bytesToMove > 0)
  22412. memmove (start, end, bytesToMove);
  22413. bytesUsed -= (int) (end - start);
  22414. }
  22415. }
  22416. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22417. {
  22418. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22419. }
  22420. namespace MidiBufferHelpers
  22421. {
  22422. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22423. {
  22424. unsigned int byte = (unsigned int) *data;
  22425. int size = 0;
  22426. if (byte == 0xf0 || byte == 0xf7)
  22427. {
  22428. const uint8* d = data + 1;
  22429. while (d < data + maxBytes)
  22430. if (*d++ == 0xf7)
  22431. break;
  22432. size = (int) (d - data);
  22433. }
  22434. else if (byte == 0xff)
  22435. {
  22436. int n;
  22437. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22438. size = jmin (maxBytes, n + 2 + bytesLeft);
  22439. }
  22440. else if (byte >= 0x80)
  22441. {
  22442. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22443. }
  22444. return size;
  22445. }
  22446. }
  22447. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22448. {
  22449. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22450. if (numBytes > 0)
  22451. {
  22452. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22453. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22454. uint8* d = findEventAfter (getData(), sampleNumber);
  22455. const int bytesToMove = bytesUsed - (int) (d - getData());
  22456. if (bytesToMove > 0)
  22457. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22458. *reinterpret_cast <int*> (d) = sampleNumber;
  22459. d += sizeof (int);
  22460. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22461. d += sizeof (uint16);
  22462. memcpy (d, newData, numBytes);
  22463. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22464. }
  22465. }
  22466. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22467. const int startSample,
  22468. const int numSamples,
  22469. const int sampleDeltaToAdd)
  22470. {
  22471. Iterator i (otherBuffer);
  22472. i.setNextSamplePosition (startSample);
  22473. const uint8* eventData;
  22474. int eventSize, position;
  22475. while (i.getNextEvent (eventData, eventSize, position)
  22476. && (position < startSample + numSamples || numSamples < 0))
  22477. {
  22478. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22479. }
  22480. }
  22481. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22482. {
  22483. data.ensureSize (minimumNumBytes);
  22484. }
  22485. bool MidiBuffer::isEmpty() const throw()
  22486. {
  22487. return bytesUsed == 0;
  22488. }
  22489. int MidiBuffer::getNumEvents() const throw()
  22490. {
  22491. int n = 0;
  22492. const uint8* d = getData();
  22493. const uint8* const end = d + bytesUsed;
  22494. while (d < end)
  22495. {
  22496. d += getEventTotalSize (d);
  22497. ++n;
  22498. }
  22499. return n;
  22500. }
  22501. int MidiBuffer::getFirstEventTime() const throw()
  22502. {
  22503. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22504. }
  22505. int MidiBuffer::getLastEventTime() const throw()
  22506. {
  22507. if (bytesUsed == 0)
  22508. return 0;
  22509. const uint8* d = getData();
  22510. const uint8* const endData = d + bytesUsed;
  22511. for (;;)
  22512. {
  22513. const uint8* const nextOne = d + getEventTotalSize (d);
  22514. if (nextOne >= endData)
  22515. return getEventTime (d);
  22516. d = nextOne;
  22517. }
  22518. }
  22519. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22520. {
  22521. const uint8* const endData = getData() + bytesUsed;
  22522. while (d < endData && getEventTime (d) <= samplePosition)
  22523. d += getEventTotalSize (d);
  22524. return d;
  22525. }
  22526. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22527. : buffer (buffer_),
  22528. data (buffer_.getData())
  22529. {
  22530. }
  22531. MidiBuffer::Iterator::~Iterator() throw()
  22532. {
  22533. }
  22534. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22535. {
  22536. data = buffer.getData();
  22537. const uint8* dataEnd = data + buffer.bytesUsed;
  22538. while (data < dataEnd && getEventTime (data) < samplePosition)
  22539. data += getEventTotalSize (data);
  22540. }
  22541. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22542. {
  22543. if (data >= buffer.getData() + buffer.bytesUsed)
  22544. return false;
  22545. samplePosition = getEventTime (data);
  22546. numBytes = getEventDataSize (data);
  22547. data += sizeof (int) + sizeof (uint16);
  22548. midiData = data;
  22549. data += numBytes;
  22550. return true;
  22551. }
  22552. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22553. {
  22554. if (data >= buffer.getData() + buffer.bytesUsed)
  22555. return false;
  22556. samplePosition = getEventTime (data);
  22557. const int numBytes = getEventDataSize (data);
  22558. data += sizeof (int) + sizeof (uint16);
  22559. result = MidiMessage (data, numBytes, samplePosition);
  22560. data += numBytes;
  22561. return true;
  22562. }
  22563. END_JUCE_NAMESPACE
  22564. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22565. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22566. BEGIN_JUCE_NAMESPACE
  22567. namespace MidiFileHelpers
  22568. {
  22569. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22570. {
  22571. unsigned int buffer = v & 0x7F;
  22572. while ((v >>= 7) != 0)
  22573. {
  22574. buffer <<= 8;
  22575. buffer |= ((v & 0x7F) | 0x80);
  22576. }
  22577. for (;;)
  22578. {
  22579. out.writeByte ((char) buffer);
  22580. if (buffer & 0x80)
  22581. buffer >>= 8;
  22582. else
  22583. break;
  22584. }
  22585. }
  22586. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22587. {
  22588. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22589. data += 4;
  22590. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22591. {
  22592. bool ok = false;
  22593. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22594. {
  22595. for (int i = 0; i < 8; ++i)
  22596. {
  22597. ch = ByteOrder::bigEndianInt (data);
  22598. data += 4;
  22599. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22600. {
  22601. ok = true;
  22602. break;
  22603. }
  22604. }
  22605. }
  22606. if (! ok)
  22607. return false;
  22608. }
  22609. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22610. data += 4;
  22611. fileType = (short) ByteOrder::bigEndianShort (data);
  22612. data += 2;
  22613. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22614. data += 2;
  22615. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22616. data += 2;
  22617. bytesRemaining -= 6;
  22618. data += bytesRemaining;
  22619. return true;
  22620. }
  22621. double convertTicksToSeconds (const double time,
  22622. const MidiMessageSequence& tempoEvents,
  22623. const int timeFormat)
  22624. {
  22625. if (timeFormat > 0)
  22626. {
  22627. int numer = 4, denom = 4;
  22628. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22629. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22630. double secsPerTick = 0.5 * tickLen;
  22631. const int numEvents = tempoEvents.getNumEvents();
  22632. for (int i = 0; i < numEvents; ++i)
  22633. {
  22634. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22635. if (time <= m.getTimeStamp())
  22636. break;
  22637. if (timeFormat > 0)
  22638. {
  22639. correctedTempoTime = correctedTempoTime
  22640. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22641. }
  22642. else
  22643. {
  22644. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22645. }
  22646. tempoTime = m.getTimeStamp();
  22647. if (m.isTempoMetaEvent())
  22648. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22649. else if (m.isTimeSignatureMetaEvent())
  22650. m.getTimeSignatureInfo (numer, denom);
  22651. while (i + 1 < numEvents)
  22652. {
  22653. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22654. if (m2.getTimeStamp() == tempoTime)
  22655. {
  22656. ++i;
  22657. if (m2.isTempoMetaEvent())
  22658. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22659. else if (m2.isTimeSignatureMetaEvent())
  22660. m2.getTimeSignatureInfo (numer, denom);
  22661. }
  22662. else
  22663. {
  22664. break;
  22665. }
  22666. }
  22667. }
  22668. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22669. }
  22670. else
  22671. {
  22672. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22673. }
  22674. }
  22675. // a comparator that puts all the note-offs before note-ons that have the same time
  22676. struct Sorter
  22677. {
  22678. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22679. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22680. {
  22681. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22682. if (diff == 0)
  22683. {
  22684. if (first->message.isNoteOff() && second->message.isNoteOn())
  22685. return -1;
  22686. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22687. return 1;
  22688. else
  22689. return 0;
  22690. }
  22691. else
  22692. {
  22693. return (diff > 0) ? 1 : -1;
  22694. }
  22695. }
  22696. };
  22697. }
  22698. MidiFile::MidiFile()
  22699. : timeFormat ((short) (unsigned short) 0xe728)
  22700. {
  22701. }
  22702. MidiFile::~MidiFile()
  22703. {
  22704. clear();
  22705. }
  22706. void MidiFile::clear()
  22707. {
  22708. tracks.clear();
  22709. }
  22710. int MidiFile::getNumTracks() const throw()
  22711. {
  22712. return tracks.size();
  22713. }
  22714. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22715. {
  22716. return tracks [index];
  22717. }
  22718. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22719. {
  22720. tracks.add (new MidiMessageSequence (trackSequence));
  22721. }
  22722. short MidiFile::getTimeFormat() const throw()
  22723. {
  22724. return timeFormat;
  22725. }
  22726. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22727. {
  22728. timeFormat = (short) ticks;
  22729. }
  22730. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22731. const int subframeResolution) throw()
  22732. {
  22733. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22734. }
  22735. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22736. {
  22737. for (int i = tracks.size(); --i >= 0;)
  22738. {
  22739. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22740. for (int j = 0; j < numEvents; ++j)
  22741. {
  22742. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22743. if (m.isTempoMetaEvent())
  22744. tempoChangeEvents.addEvent (m);
  22745. }
  22746. }
  22747. }
  22748. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22749. {
  22750. for (int i = tracks.size(); --i >= 0;)
  22751. {
  22752. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22753. for (int j = 0; j < numEvents; ++j)
  22754. {
  22755. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22756. if (m.isTimeSignatureMetaEvent())
  22757. timeSigEvents.addEvent (m);
  22758. }
  22759. }
  22760. }
  22761. double MidiFile::getLastTimestamp() const
  22762. {
  22763. double t = 0.0;
  22764. for (int i = tracks.size(); --i >= 0;)
  22765. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22766. return t;
  22767. }
  22768. bool MidiFile::readFrom (InputStream& sourceStream)
  22769. {
  22770. clear();
  22771. MemoryBlock data;
  22772. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22773. // (put a sanity-check on the file size, as midi files are generally small)
  22774. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22775. {
  22776. size_t size = data.getSize();
  22777. const uint8* d = static_cast <const uint8*> (data.getData());
  22778. short fileType, expectedTracks;
  22779. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22780. {
  22781. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22782. int track = 0;
  22783. while (size > 0 && track < expectedTracks)
  22784. {
  22785. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22786. d += 4;
  22787. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22788. d += 4;
  22789. if (chunkSize <= 0)
  22790. break;
  22791. if (size < 0)
  22792. return false;
  22793. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22794. {
  22795. readNextTrack (d, chunkSize);
  22796. }
  22797. size -= chunkSize + 8;
  22798. d += chunkSize;
  22799. ++track;
  22800. }
  22801. return true;
  22802. }
  22803. }
  22804. return false;
  22805. }
  22806. void MidiFile::readNextTrack (const uint8* data, int size)
  22807. {
  22808. double time = 0;
  22809. char lastStatusByte = 0;
  22810. MidiMessageSequence result;
  22811. while (size > 0)
  22812. {
  22813. int bytesUsed;
  22814. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22815. data += bytesUsed;
  22816. size -= bytesUsed;
  22817. time += delay;
  22818. int messSize = 0;
  22819. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22820. if (messSize <= 0)
  22821. break;
  22822. size -= messSize;
  22823. data += messSize;
  22824. result.addEvent (mm);
  22825. const char firstByte = *(mm.getRawData());
  22826. if ((firstByte & 0xf0) != 0xf0)
  22827. lastStatusByte = firstByte;
  22828. }
  22829. // use a sort that puts all the note-offs before note-ons that have the same time
  22830. MidiFileHelpers::Sorter sorter;
  22831. result.list.sort (sorter, true);
  22832. result.updateMatchedPairs();
  22833. addTrack (result);
  22834. }
  22835. void MidiFile::convertTimestampTicksToSeconds()
  22836. {
  22837. MidiMessageSequence tempoEvents;
  22838. findAllTempoEvents (tempoEvents);
  22839. findAllTimeSigEvents (tempoEvents);
  22840. for (int i = 0; i < tracks.size(); ++i)
  22841. {
  22842. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22843. for (int j = ms.getNumEvents(); --j >= 0;)
  22844. {
  22845. MidiMessage& m = ms.getEventPointer(j)->message;
  22846. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22847. tempoEvents,
  22848. timeFormat));
  22849. }
  22850. }
  22851. }
  22852. bool MidiFile::writeTo (OutputStream& out)
  22853. {
  22854. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22855. out.writeIntBigEndian (6);
  22856. out.writeShortBigEndian (1); // type
  22857. out.writeShortBigEndian ((short) tracks.size());
  22858. out.writeShortBigEndian (timeFormat);
  22859. for (int i = 0; i < tracks.size(); ++i)
  22860. writeTrack (out, i);
  22861. out.flush();
  22862. return true;
  22863. }
  22864. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22865. {
  22866. MemoryOutputStream out;
  22867. const MidiMessageSequence& ms = *tracks[trackNum];
  22868. int lastTick = 0;
  22869. char lastStatusByte = 0;
  22870. for (int i = 0; i < ms.getNumEvents(); ++i)
  22871. {
  22872. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22873. const int tick = roundToInt (mm.getTimeStamp());
  22874. const int delta = jmax (0, tick - lastTick);
  22875. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22876. lastTick = tick;
  22877. const char statusByte = *(mm.getRawData());
  22878. if ((statusByte == lastStatusByte)
  22879. && ((statusByte & 0xf0) != 0xf0)
  22880. && i > 0
  22881. && mm.getRawDataSize() > 1)
  22882. {
  22883. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22884. }
  22885. else
  22886. {
  22887. out.write (mm.getRawData(), mm.getRawDataSize());
  22888. }
  22889. lastStatusByte = statusByte;
  22890. }
  22891. out.writeByte (0);
  22892. const MidiMessage m (MidiMessage::endOfTrack());
  22893. out.write (m.getRawData(),
  22894. m.getRawDataSize());
  22895. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22896. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22897. mainOut.write (out.getData(), (int) out.getDataSize());
  22898. }
  22899. END_JUCE_NAMESPACE
  22900. /*** End of inlined file: juce_MidiFile.cpp ***/
  22901. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22902. BEGIN_JUCE_NAMESPACE
  22903. MidiKeyboardState::MidiKeyboardState()
  22904. {
  22905. zerostruct (noteStates);
  22906. }
  22907. MidiKeyboardState::~MidiKeyboardState()
  22908. {
  22909. }
  22910. void MidiKeyboardState::reset()
  22911. {
  22912. const ScopedLock sl (lock);
  22913. zerostruct (noteStates);
  22914. eventsToAdd.clear();
  22915. }
  22916. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22917. {
  22918. jassert (midiChannel >= 0 && midiChannel <= 16);
  22919. return ((unsigned int) n) < 128
  22920. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22921. }
  22922. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22923. {
  22924. return ((unsigned int) n) < 128
  22925. && (noteStates[n] & midiChannelMask) != 0;
  22926. }
  22927. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22928. {
  22929. jassert (midiChannel >= 0 && midiChannel <= 16);
  22930. jassert (((unsigned int) midiNoteNumber) < 128);
  22931. const ScopedLock sl (lock);
  22932. if (((unsigned int) midiNoteNumber) < 128)
  22933. {
  22934. const int timeNow = (int) Time::getMillisecondCounter();
  22935. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22936. eventsToAdd.clear (0, timeNow - 500);
  22937. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22938. }
  22939. }
  22940. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22941. {
  22942. if (((unsigned int) midiNoteNumber) < 128)
  22943. {
  22944. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22945. for (int i = listeners.size(); --i >= 0;)
  22946. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22947. }
  22948. }
  22949. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22950. {
  22951. const ScopedLock sl (lock);
  22952. if (isNoteOn (midiChannel, midiNoteNumber))
  22953. {
  22954. const int timeNow = (int) Time::getMillisecondCounter();
  22955. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22956. eventsToAdd.clear (0, timeNow - 500);
  22957. noteOffInternal (midiChannel, midiNoteNumber);
  22958. }
  22959. }
  22960. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22961. {
  22962. if (isNoteOn (midiChannel, midiNoteNumber))
  22963. {
  22964. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22965. for (int i = listeners.size(); --i >= 0;)
  22966. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22967. }
  22968. }
  22969. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22970. {
  22971. const ScopedLock sl (lock);
  22972. if (midiChannel <= 0)
  22973. {
  22974. for (int i = 1; i <= 16; ++i)
  22975. allNotesOff (i);
  22976. }
  22977. else
  22978. {
  22979. for (int i = 0; i < 128; ++i)
  22980. noteOff (midiChannel, i);
  22981. }
  22982. }
  22983. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22984. {
  22985. if (message.isNoteOn())
  22986. {
  22987. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22988. }
  22989. else if (message.isNoteOff())
  22990. {
  22991. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22992. }
  22993. else if (message.isAllNotesOff())
  22994. {
  22995. for (int i = 0; i < 128; ++i)
  22996. noteOffInternal (message.getChannel(), i);
  22997. }
  22998. }
  22999. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  23000. const int startSample,
  23001. const int numSamples,
  23002. const bool injectIndirectEvents)
  23003. {
  23004. MidiBuffer::Iterator i (buffer);
  23005. MidiMessage message (0xf4, 0.0);
  23006. int time;
  23007. const ScopedLock sl (lock);
  23008. while (i.getNextEvent (message, time))
  23009. processNextMidiEvent (message);
  23010. if (injectIndirectEvents)
  23011. {
  23012. MidiBuffer::Iterator i2 (eventsToAdd);
  23013. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  23014. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  23015. while (i2.getNextEvent (message, time))
  23016. {
  23017. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  23018. buffer.addEvent (message, startSample + pos);
  23019. }
  23020. }
  23021. eventsToAdd.clear();
  23022. }
  23023. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  23024. {
  23025. const ScopedLock sl (lock);
  23026. listeners.addIfNotAlreadyThere (listener);
  23027. }
  23028. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  23029. {
  23030. const ScopedLock sl (lock);
  23031. listeners.removeValue (listener);
  23032. }
  23033. END_JUCE_NAMESPACE
  23034. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  23035. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  23036. BEGIN_JUCE_NAMESPACE
  23037. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  23038. {
  23039. numBytesUsed = 0;
  23040. int v = 0;
  23041. int i;
  23042. do
  23043. {
  23044. i = (int) *data++;
  23045. if (++numBytesUsed > 6)
  23046. break;
  23047. v = (v << 7) + (i & 0x7f);
  23048. } while (i & 0x80);
  23049. return v;
  23050. }
  23051. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  23052. {
  23053. // this method only works for valid starting bytes of a short midi message
  23054. jassert (firstByte >= 0x80
  23055. && firstByte != 0xf0
  23056. && firstByte != 0xf7);
  23057. static const char messageLengths[] =
  23058. {
  23059. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23060. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23061. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23062. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23063. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23064. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23065. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23066. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  23067. };
  23068. return messageLengths [firstByte & 0x7f];
  23069. }
  23070. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  23071. : timeStamp (t),
  23072. size (dataSize)
  23073. {
  23074. jassert (dataSize > 0);
  23075. if (dataSize <= 4)
  23076. data = static_cast<uint8*> (preallocatedData.asBytes);
  23077. else
  23078. data = new uint8 [dataSize];
  23079. memcpy (data, d, dataSize);
  23080. // check that the length matches the data..
  23081. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23082. }
  23083. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23084. : timeStamp (t),
  23085. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23086. size (1)
  23087. {
  23088. data[0] = (uint8) byte1;
  23089. // check that the length matches the data..
  23090. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23091. }
  23092. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23093. : timeStamp (t),
  23094. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23095. size (2)
  23096. {
  23097. data[0] = (uint8) byte1;
  23098. data[1] = (uint8) byte2;
  23099. // check that the length matches the data..
  23100. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23101. }
  23102. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23103. : timeStamp (t),
  23104. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23105. size (3)
  23106. {
  23107. data[0] = (uint8) byte1;
  23108. data[1] = (uint8) byte2;
  23109. data[2] = (uint8) byte3;
  23110. // check that the length matches the data..
  23111. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23112. }
  23113. MidiMessage::MidiMessage (const MidiMessage& other)
  23114. : timeStamp (other.timeStamp),
  23115. size (other.size)
  23116. {
  23117. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23118. {
  23119. data = new uint8 [size];
  23120. memcpy (data, other.data, size);
  23121. }
  23122. else
  23123. {
  23124. data = static_cast<uint8*> (preallocatedData.asBytes);
  23125. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23126. }
  23127. }
  23128. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23129. : timeStamp (newTimeStamp),
  23130. size (other.size)
  23131. {
  23132. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23133. {
  23134. data = new uint8 [size];
  23135. memcpy (data, other.data, size);
  23136. }
  23137. else
  23138. {
  23139. data = static_cast<uint8*> (preallocatedData.asBytes);
  23140. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23141. }
  23142. }
  23143. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23144. : timeStamp (t),
  23145. data (static_cast<uint8*> (preallocatedData.asBytes))
  23146. {
  23147. const uint8* src = static_cast <const uint8*> (src_);
  23148. unsigned int byte = (unsigned int) *src;
  23149. if (byte < 0x80)
  23150. {
  23151. byte = (unsigned int) (uint8) lastStatusByte;
  23152. numBytesUsed = -1;
  23153. }
  23154. else
  23155. {
  23156. numBytesUsed = 0;
  23157. --sz;
  23158. ++src;
  23159. }
  23160. if (byte >= 0x80)
  23161. {
  23162. if (byte == 0xf0)
  23163. {
  23164. const uint8* d = src;
  23165. bool haveReadAllLengthBytes = false;
  23166. while (d < src + sz)
  23167. {
  23168. if (*d >= 0x80)
  23169. {
  23170. if (*d == 0xf7)
  23171. {
  23172. ++d; // include the trailing 0xf7 when we hit it
  23173. break;
  23174. }
  23175. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  23176. break; // bytes, assume it's the end of the sysex
  23177. ++d;
  23178. continue;
  23179. }
  23180. haveReadAllLengthBytes = true;
  23181. ++d;
  23182. }
  23183. size = 1 + (int) (d - src);
  23184. data = new uint8 [size];
  23185. *data = (uint8) byte;
  23186. memcpy (data + 1, src, size - 1);
  23187. }
  23188. else if (byte == 0xff)
  23189. {
  23190. int n;
  23191. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23192. size = jmin (sz + 1, n + 2 + bytesLeft);
  23193. data = new uint8 [size];
  23194. *data = (uint8) byte;
  23195. memcpy (data + 1, src, size - 1);
  23196. }
  23197. else
  23198. {
  23199. preallocatedData.asInt32 = 0;
  23200. size = getMessageLengthFromFirstByte ((uint8) byte);
  23201. data[0] = (uint8) byte;
  23202. if (size > 1)
  23203. {
  23204. data[1] = src[0];
  23205. if (size > 2)
  23206. data[2] = src[1];
  23207. }
  23208. }
  23209. numBytesUsed += size;
  23210. }
  23211. else
  23212. {
  23213. preallocatedData.asInt32 = 0;
  23214. size = 0;
  23215. }
  23216. }
  23217. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23218. {
  23219. if (this != &other)
  23220. {
  23221. timeStamp = other.timeStamp;
  23222. size = other.size;
  23223. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23224. delete[] data;
  23225. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23226. {
  23227. data = new uint8 [size];
  23228. memcpy (data, other.data, size);
  23229. }
  23230. else
  23231. {
  23232. data = static_cast<uint8*> (preallocatedData.asBytes);
  23233. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23234. }
  23235. }
  23236. return *this;
  23237. }
  23238. MidiMessage::~MidiMessage()
  23239. {
  23240. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23241. delete[] data;
  23242. }
  23243. int MidiMessage::getChannel() const throw()
  23244. {
  23245. if ((data[0] & 0xf0) != 0xf0)
  23246. return (data[0] & 0xf) + 1;
  23247. else
  23248. return 0;
  23249. }
  23250. bool MidiMessage::isForChannel (const int channel) const throw()
  23251. {
  23252. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23253. return ((data[0] & 0xf) == channel - 1)
  23254. && ((data[0] & 0xf0) != 0xf0);
  23255. }
  23256. void MidiMessage::setChannel (const int channel) throw()
  23257. {
  23258. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23259. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23260. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23261. | (uint8)(channel - 1));
  23262. }
  23263. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23264. {
  23265. return ((data[0] & 0xf0) == 0x90)
  23266. && (returnTrueForVelocity0 || data[2] != 0);
  23267. }
  23268. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23269. {
  23270. return ((data[0] & 0xf0) == 0x80)
  23271. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23272. }
  23273. bool MidiMessage::isNoteOnOrOff() const throw()
  23274. {
  23275. const int d = data[0] & 0xf0;
  23276. return (d == 0x90) || (d == 0x80);
  23277. }
  23278. int MidiMessage::getNoteNumber() const throw()
  23279. {
  23280. return data[1];
  23281. }
  23282. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23283. {
  23284. if (isNoteOnOrOff())
  23285. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23286. }
  23287. uint8 MidiMessage::getVelocity() const throw()
  23288. {
  23289. if (isNoteOnOrOff())
  23290. return data[2];
  23291. else
  23292. return 0;
  23293. }
  23294. float MidiMessage::getFloatVelocity() const throw()
  23295. {
  23296. return getVelocity() * (1.0f / 127.0f);
  23297. }
  23298. void MidiMessage::setVelocity (const float newVelocity) throw()
  23299. {
  23300. if (isNoteOnOrOff())
  23301. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23302. }
  23303. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23304. {
  23305. if (isNoteOnOrOff())
  23306. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23307. }
  23308. bool MidiMessage::isAftertouch() const throw()
  23309. {
  23310. return (data[0] & 0xf0) == 0xa0;
  23311. }
  23312. int MidiMessage::getAfterTouchValue() const throw()
  23313. {
  23314. return data[2];
  23315. }
  23316. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23317. const int noteNum,
  23318. const int aftertouchValue) throw()
  23319. {
  23320. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23321. jassert (((unsigned int) noteNum) <= 127);
  23322. jassert (((unsigned int) aftertouchValue) <= 127);
  23323. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23324. noteNum & 0x7f,
  23325. aftertouchValue & 0x7f);
  23326. }
  23327. bool MidiMessage::isChannelPressure() const throw()
  23328. {
  23329. return (data[0] & 0xf0) == 0xd0;
  23330. }
  23331. int MidiMessage::getChannelPressureValue() const throw()
  23332. {
  23333. jassert (isChannelPressure());
  23334. return data[1];
  23335. }
  23336. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23337. const int pressure) throw()
  23338. {
  23339. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23340. jassert (((unsigned int) pressure) <= 127);
  23341. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23342. pressure & 0x7f);
  23343. }
  23344. bool MidiMessage::isProgramChange() const throw()
  23345. {
  23346. return (data[0] & 0xf0) == 0xc0;
  23347. }
  23348. int MidiMessage::getProgramChangeNumber() const throw()
  23349. {
  23350. return data[1];
  23351. }
  23352. const MidiMessage MidiMessage::programChange (const int channel,
  23353. const int programNumber) throw()
  23354. {
  23355. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23356. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23357. programNumber & 0x7f);
  23358. }
  23359. bool MidiMessage::isPitchWheel() const throw()
  23360. {
  23361. return (data[0] & 0xf0) == 0xe0;
  23362. }
  23363. int MidiMessage::getPitchWheelValue() const throw()
  23364. {
  23365. return data[1] | (data[2] << 7);
  23366. }
  23367. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23368. const int position) throw()
  23369. {
  23370. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23371. jassert (((unsigned int) position) <= 0x3fff);
  23372. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23373. position & 127,
  23374. (position >> 7) & 127);
  23375. }
  23376. bool MidiMessage::isController() const throw()
  23377. {
  23378. return (data[0] & 0xf0) == 0xb0;
  23379. }
  23380. int MidiMessage::getControllerNumber() const throw()
  23381. {
  23382. jassert (isController());
  23383. return data[1];
  23384. }
  23385. int MidiMessage::getControllerValue() const throw()
  23386. {
  23387. jassert (isController());
  23388. return data[2];
  23389. }
  23390. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23391. const int controllerType,
  23392. const int value) throw()
  23393. {
  23394. // the channel must be between 1 and 16 inclusive
  23395. jassert (channel > 0 && channel <= 16);
  23396. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23397. controllerType & 127,
  23398. value & 127);
  23399. }
  23400. const MidiMessage MidiMessage::noteOn (const int channel,
  23401. const int noteNumber,
  23402. const float velocity) throw()
  23403. {
  23404. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23405. }
  23406. const MidiMessage MidiMessage::noteOn (const int channel,
  23407. const int noteNumber,
  23408. const uint8 velocity) throw()
  23409. {
  23410. jassert (channel > 0 && channel <= 16);
  23411. jassert (((unsigned int) noteNumber) <= 127);
  23412. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23413. noteNumber & 127,
  23414. jlimit (0, 127, roundToInt (velocity)));
  23415. }
  23416. const MidiMessage MidiMessage::noteOff (const int channel,
  23417. const int noteNumber) throw()
  23418. {
  23419. jassert (channel > 0 && channel <= 16);
  23420. jassert (((unsigned int) noteNumber) <= 127);
  23421. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23422. }
  23423. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23424. {
  23425. return controllerEvent (channel, 123, 0);
  23426. }
  23427. bool MidiMessage::isAllNotesOff() const throw()
  23428. {
  23429. return (data[0] & 0xf0) == 0xb0
  23430. && data[1] == 123;
  23431. }
  23432. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23433. {
  23434. return controllerEvent (channel, 120, 0);
  23435. }
  23436. bool MidiMessage::isAllSoundOff() const throw()
  23437. {
  23438. return (data[0] & 0xf0) == 0xb0
  23439. && data[1] == 120;
  23440. }
  23441. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23442. {
  23443. return controllerEvent (channel, 121, 0);
  23444. }
  23445. const MidiMessage MidiMessage::masterVolume (const float volume)
  23446. {
  23447. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23448. uint8 buf[8];
  23449. buf[0] = 0xf0;
  23450. buf[1] = 0x7f;
  23451. buf[2] = 0x7f;
  23452. buf[3] = 0x04;
  23453. buf[4] = 0x01;
  23454. buf[5] = (uint8) (vol & 0x7f);
  23455. buf[6] = (uint8) (vol >> 7);
  23456. buf[7] = 0xf7;
  23457. return MidiMessage (buf, 8);
  23458. }
  23459. bool MidiMessage::isSysEx() const throw()
  23460. {
  23461. return *data == 0xf0;
  23462. }
  23463. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23464. {
  23465. MemoryBlock mm (dataSize + 2);
  23466. uint8* const m = static_cast <uint8*> (mm.getData());
  23467. m[0] = 0xf0;
  23468. memcpy (m + 1, sysexData, dataSize);
  23469. m[dataSize + 1] = 0xf7;
  23470. return MidiMessage (m, dataSize + 2);
  23471. }
  23472. const uint8* MidiMessage::getSysExData() const throw()
  23473. {
  23474. return (isSysEx()) ? getRawData() + 1 : 0;
  23475. }
  23476. int MidiMessage::getSysExDataSize() const throw()
  23477. {
  23478. return (isSysEx()) ? size - 2 : 0;
  23479. }
  23480. bool MidiMessage::isMetaEvent() const throw()
  23481. {
  23482. return *data == 0xff;
  23483. }
  23484. bool MidiMessage::isActiveSense() const throw()
  23485. {
  23486. return *data == 0xfe;
  23487. }
  23488. int MidiMessage::getMetaEventType() const throw()
  23489. {
  23490. if (*data != 0xff)
  23491. return -1;
  23492. else
  23493. return data[1];
  23494. }
  23495. int MidiMessage::getMetaEventLength() const throw()
  23496. {
  23497. if (*data == 0xff)
  23498. {
  23499. int n;
  23500. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23501. }
  23502. return 0;
  23503. }
  23504. const uint8* MidiMessage::getMetaEventData() const throw()
  23505. {
  23506. int n;
  23507. const uint8* d = data + 2;
  23508. readVariableLengthVal (d, n);
  23509. return d + n;
  23510. }
  23511. bool MidiMessage::isTrackMetaEvent() const throw()
  23512. {
  23513. return getMetaEventType() == 0;
  23514. }
  23515. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23516. {
  23517. return getMetaEventType() == 47;
  23518. }
  23519. bool MidiMessage::isTextMetaEvent() const throw()
  23520. {
  23521. const int t = getMetaEventType();
  23522. return t > 0 && t < 16;
  23523. }
  23524. const String MidiMessage::getTextFromTextMetaEvent() const
  23525. {
  23526. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23527. }
  23528. bool MidiMessage::isTrackNameEvent() const throw()
  23529. {
  23530. return (data[1] == 3)
  23531. && (*data == 0xff);
  23532. }
  23533. bool MidiMessage::isTempoMetaEvent() const throw()
  23534. {
  23535. return (data[1] == 81)
  23536. && (*data == 0xff);
  23537. }
  23538. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23539. {
  23540. return (data[1] == 0x20)
  23541. && (*data == 0xff)
  23542. && (data[2] == 1);
  23543. }
  23544. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23545. {
  23546. return data[3] + 1;
  23547. }
  23548. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23549. {
  23550. if (! isTempoMetaEvent())
  23551. return 0.0;
  23552. const uint8* const d = getMetaEventData();
  23553. return (((unsigned int) d[0] << 16)
  23554. | ((unsigned int) d[1] << 8)
  23555. | d[2])
  23556. / 1000000.0;
  23557. }
  23558. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23559. {
  23560. if (timeFormat > 0)
  23561. {
  23562. if (! isTempoMetaEvent())
  23563. return 0.5 / timeFormat;
  23564. return getTempoSecondsPerQuarterNote() / timeFormat;
  23565. }
  23566. else
  23567. {
  23568. const int frameCode = (-timeFormat) >> 8;
  23569. double framesPerSecond;
  23570. switch (frameCode)
  23571. {
  23572. case 24: framesPerSecond = 24.0; break;
  23573. case 25: framesPerSecond = 25.0; break;
  23574. case 29: framesPerSecond = 29.97; break;
  23575. case 30: framesPerSecond = 30.0; break;
  23576. default: framesPerSecond = 30.0; break;
  23577. }
  23578. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23579. }
  23580. }
  23581. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23582. {
  23583. uint8 d[8];
  23584. d[0] = 0xff;
  23585. d[1] = 81;
  23586. d[2] = 3;
  23587. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23588. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23589. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23590. return MidiMessage (d, 6, 0.0);
  23591. }
  23592. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23593. {
  23594. return (data[1] == 0x58)
  23595. && (*data == (uint8) 0xff);
  23596. }
  23597. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23598. {
  23599. if (isTimeSignatureMetaEvent())
  23600. {
  23601. const uint8* const d = getMetaEventData();
  23602. numerator = d[0];
  23603. denominator = 1 << d[1];
  23604. }
  23605. else
  23606. {
  23607. numerator = 4;
  23608. denominator = 4;
  23609. }
  23610. }
  23611. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23612. {
  23613. uint8 d[8];
  23614. d[0] = 0xff;
  23615. d[1] = 0x58;
  23616. d[2] = 0x04;
  23617. d[3] = (uint8) numerator;
  23618. int n = 1;
  23619. int powerOfTwo = 0;
  23620. while (n < denominator)
  23621. {
  23622. n <<= 1;
  23623. ++powerOfTwo;
  23624. }
  23625. d[4] = (uint8) powerOfTwo;
  23626. d[5] = 0x01;
  23627. d[6] = 96;
  23628. return MidiMessage (d, 7, 0.0);
  23629. }
  23630. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23631. {
  23632. uint8 d[8];
  23633. d[0] = 0xff;
  23634. d[1] = 0x20;
  23635. d[2] = 0x01;
  23636. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23637. return MidiMessage (d, 4, 0.0);
  23638. }
  23639. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23640. {
  23641. return getMetaEventType() == 89;
  23642. }
  23643. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23644. {
  23645. return (int) *getMetaEventData();
  23646. }
  23647. const MidiMessage MidiMessage::endOfTrack() throw()
  23648. {
  23649. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23650. }
  23651. bool MidiMessage::isSongPositionPointer() const throw()
  23652. {
  23653. return *data == 0xf2;
  23654. }
  23655. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23656. {
  23657. return data[1] | (data[2] << 7);
  23658. }
  23659. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23660. {
  23661. return MidiMessage (0xf2,
  23662. positionInMidiBeats & 127,
  23663. (positionInMidiBeats >> 7) & 127);
  23664. }
  23665. bool MidiMessage::isMidiStart() const throw()
  23666. {
  23667. return *data == 0xfa;
  23668. }
  23669. const MidiMessage MidiMessage::midiStart() throw()
  23670. {
  23671. return MidiMessage (0xfa);
  23672. }
  23673. bool MidiMessage::isMidiContinue() const throw()
  23674. {
  23675. return *data == 0xfb;
  23676. }
  23677. const MidiMessage MidiMessage::midiContinue() throw()
  23678. {
  23679. return MidiMessage (0xfb);
  23680. }
  23681. bool MidiMessage::isMidiStop() const throw()
  23682. {
  23683. return *data == 0xfc;
  23684. }
  23685. const MidiMessage MidiMessage::midiStop() throw()
  23686. {
  23687. return MidiMessage (0xfc);
  23688. }
  23689. bool MidiMessage::isMidiClock() const throw()
  23690. {
  23691. return *data == 0xf8;
  23692. }
  23693. const MidiMessage MidiMessage::midiClock() throw()
  23694. {
  23695. return MidiMessage (0xf8);
  23696. }
  23697. bool MidiMessage::isQuarterFrame() const throw()
  23698. {
  23699. return *data == 0xf1;
  23700. }
  23701. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23702. {
  23703. return ((int) data[1]) >> 4;
  23704. }
  23705. int MidiMessage::getQuarterFrameValue() const throw()
  23706. {
  23707. return ((int) data[1]) & 0x0f;
  23708. }
  23709. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23710. const int value) throw()
  23711. {
  23712. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23713. }
  23714. bool MidiMessage::isFullFrame() const throw()
  23715. {
  23716. return data[0] == 0xf0
  23717. && data[1] == 0x7f
  23718. && size >= 10
  23719. && data[3] == 0x01
  23720. && data[4] == 0x01;
  23721. }
  23722. void MidiMessage::getFullFrameParameters (int& hours,
  23723. int& minutes,
  23724. int& seconds,
  23725. int& frames,
  23726. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23727. {
  23728. jassert (isFullFrame());
  23729. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23730. hours = data[5] & 0x1f;
  23731. minutes = data[6];
  23732. seconds = data[7];
  23733. frames = data[8];
  23734. }
  23735. const MidiMessage MidiMessage::fullFrame (const int hours,
  23736. const int minutes,
  23737. const int seconds,
  23738. const int frames,
  23739. MidiMessage::SmpteTimecodeType timecodeType)
  23740. {
  23741. uint8 d[10];
  23742. d[0] = 0xf0;
  23743. d[1] = 0x7f;
  23744. d[2] = 0x7f;
  23745. d[3] = 0x01;
  23746. d[4] = 0x01;
  23747. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23748. d[6] = (uint8) minutes;
  23749. d[7] = (uint8) seconds;
  23750. d[8] = (uint8) frames;
  23751. d[9] = 0xf7;
  23752. return MidiMessage (d, 10, 0.0);
  23753. }
  23754. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23755. {
  23756. return data[0] == 0xf0
  23757. && data[1] == 0x7f
  23758. && data[3] == 0x06
  23759. && size > 5;
  23760. }
  23761. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23762. {
  23763. jassert (isMidiMachineControlMessage());
  23764. return (MidiMachineControlCommand) data[4];
  23765. }
  23766. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23767. {
  23768. uint8 d[6];
  23769. d[0] = 0xf0;
  23770. d[1] = 0x7f;
  23771. d[2] = 0x00;
  23772. d[3] = 0x06;
  23773. d[4] = (uint8) command;
  23774. d[5] = 0xf7;
  23775. return MidiMessage (d, 6, 0.0);
  23776. }
  23777. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23778. int& minutes,
  23779. int& seconds,
  23780. int& frames) const throw()
  23781. {
  23782. if (size >= 12
  23783. && data[0] == 0xf0
  23784. && data[1] == 0x7f
  23785. && data[3] == 0x06
  23786. && data[4] == 0x44
  23787. && data[5] == 0x06
  23788. && data[6] == 0x01)
  23789. {
  23790. hours = data[7] % 24; // (that some machines send out hours > 24)
  23791. minutes = data[8];
  23792. seconds = data[9];
  23793. frames = data[10];
  23794. return true;
  23795. }
  23796. return false;
  23797. }
  23798. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23799. int minutes,
  23800. int seconds,
  23801. int frames)
  23802. {
  23803. uint8 d[12];
  23804. d[0] = 0xf0;
  23805. d[1] = 0x7f;
  23806. d[2] = 0x00;
  23807. d[3] = 0x06;
  23808. d[4] = 0x44;
  23809. d[5] = 0x06;
  23810. d[6] = 0x01;
  23811. d[7] = (uint8) hours;
  23812. d[8] = (uint8) minutes;
  23813. d[9] = (uint8) seconds;
  23814. d[10] = (uint8) frames;
  23815. d[11] = 0xf7;
  23816. return MidiMessage (d, 12, 0.0);
  23817. }
  23818. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23819. {
  23820. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23821. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23822. if (((unsigned int) note) < 128)
  23823. {
  23824. String s (useSharps ? sharpNoteNames [note % 12]
  23825. : flatNoteNames [note % 12]);
  23826. if (includeOctaveNumber)
  23827. s << (note / 12 + (octaveNumForMiddleC - 5));
  23828. return s;
  23829. }
  23830. return String::empty;
  23831. }
  23832. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23833. {
  23834. noteNumber -= 12 * 6 + 9; // now 0 = A
  23835. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23836. }
  23837. const String MidiMessage::getGMInstrumentName (const int n)
  23838. {
  23839. const char* names[] =
  23840. {
  23841. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23842. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23843. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23844. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23845. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23846. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23847. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23848. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23849. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23850. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23851. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23852. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23853. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23854. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23855. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23856. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23857. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23858. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23859. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23860. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23861. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23862. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23863. "Applause", "Gunshot"
  23864. };
  23865. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23866. }
  23867. const String MidiMessage::getGMInstrumentBankName (const int n)
  23868. {
  23869. const char* names[] =
  23870. {
  23871. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23872. "Bass", "Strings", "Ensemble", "Brass",
  23873. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23874. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23875. };
  23876. return (((unsigned int) n) <= 15) ? names[n] : (const char*) 0;
  23877. }
  23878. const String MidiMessage::getRhythmInstrumentName (const int n)
  23879. {
  23880. const char* names[] =
  23881. {
  23882. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23883. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23884. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23885. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23886. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23887. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23888. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23889. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23890. "Mute Triangle", "Open Triangle"
  23891. };
  23892. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23893. }
  23894. const String MidiMessage::getControllerName (const int n)
  23895. {
  23896. const char* names[] =
  23897. {
  23898. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23899. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23900. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23901. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23902. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23903. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23904. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23905. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23906. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23907. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23908. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23909. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23910. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23911. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23912. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23913. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23914. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23915. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23916. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23918. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23919. "Poly Operation"
  23920. };
  23921. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23922. }
  23923. END_JUCE_NAMESPACE
  23924. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23925. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23926. BEGIN_JUCE_NAMESPACE
  23927. MidiMessageCollector::MidiMessageCollector()
  23928. : lastCallbackTime (0),
  23929. sampleRate (44100.0001)
  23930. {
  23931. }
  23932. MidiMessageCollector::~MidiMessageCollector()
  23933. {
  23934. }
  23935. void MidiMessageCollector::reset (const double sampleRate_)
  23936. {
  23937. jassert (sampleRate_ > 0);
  23938. const ScopedLock sl (midiCallbackLock);
  23939. sampleRate = sampleRate_;
  23940. incomingMessages.clear();
  23941. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23942. }
  23943. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23944. {
  23945. // you need to call reset() to set the correct sample rate before using this object
  23946. jassert (sampleRate != 44100.0001);
  23947. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23948. // for details of what the number should be.
  23949. jassert (message.getTimeStamp() != 0);
  23950. const ScopedLock sl (midiCallbackLock);
  23951. const int sampleNumber
  23952. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23953. incomingMessages.addEvent (message, sampleNumber);
  23954. // if the messages don't get used for over a second, we'd better
  23955. // get rid of any old ones to avoid the queue getting too big
  23956. if (sampleNumber > sampleRate)
  23957. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23958. }
  23959. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23960. const int numSamples)
  23961. {
  23962. // you need to call reset() to set the correct sample rate before using this object
  23963. jassert (sampleRate != 44100.0001);
  23964. const double timeNow = Time::getMillisecondCounterHiRes();
  23965. const double msElapsed = timeNow - lastCallbackTime;
  23966. const ScopedLock sl (midiCallbackLock);
  23967. lastCallbackTime = timeNow;
  23968. if (! incomingMessages.isEmpty())
  23969. {
  23970. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23971. int startSample = 0;
  23972. int scale = 1 << 16;
  23973. const uint8* midiData;
  23974. int numBytes, samplePosition;
  23975. MidiBuffer::Iterator iter (incomingMessages);
  23976. if (numSourceSamples > numSamples)
  23977. {
  23978. // if our list of events is longer than the buffer we're being
  23979. // asked for, scale them down to squeeze them all in..
  23980. const int maxBlockLengthToUse = numSamples << 5;
  23981. if (numSourceSamples > maxBlockLengthToUse)
  23982. {
  23983. startSample = numSourceSamples - maxBlockLengthToUse;
  23984. numSourceSamples = maxBlockLengthToUse;
  23985. iter.setNextSamplePosition (startSample);
  23986. }
  23987. scale = (numSamples << 10) / numSourceSamples;
  23988. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23989. {
  23990. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23991. destBuffer.addEvent (midiData, numBytes,
  23992. jlimit (0, numSamples - 1, samplePosition));
  23993. }
  23994. }
  23995. else
  23996. {
  23997. // if our event list is shorter than the number we need, put them
  23998. // towards the end of the buffer
  23999. startSample = numSamples - numSourceSamples;
  24000. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24001. {
  24002. destBuffer.addEvent (midiData, numBytes,
  24003. jlimit (0, numSamples - 1, samplePosition + startSample));
  24004. }
  24005. }
  24006. incomingMessages.clear();
  24007. }
  24008. }
  24009. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  24010. {
  24011. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  24012. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24013. addMessageToQueue (m);
  24014. }
  24015. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  24016. {
  24017. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  24018. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24019. addMessageToQueue (m);
  24020. }
  24021. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  24022. {
  24023. addMessageToQueue (message);
  24024. }
  24025. END_JUCE_NAMESPACE
  24026. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  24027. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  24028. BEGIN_JUCE_NAMESPACE
  24029. MidiMessageSequence::MidiMessageSequence()
  24030. {
  24031. }
  24032. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  24033. {
  24034. list.ensureStorageAllocated (other.list.size());
  24035. for (int i = 0; i < other.list.size(); ++i)
  24036. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  24037. }
  24038. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  24039. {
  24040. MidiMessageSequence otherCopy (other);
  24041. swapWith (otherCopy);
  24042. return *this;
  24043. }
  24044. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  24045. {
  24046. list.swapWithArray (other.list);
  24047. }
  24048. MidiMessageSequence::~MidiMessageSequence()
  24049. {
  24050. }
  24051. void MidiMessageSequence::clear()
  24052. {
  24053. list.clear();
  24054. }
  24055. int MidiMessageSequence::getNumEvents() const
  24056. {
  24057. return list.size();
  24058. }
  24059. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  24060. {
  24061. return list [index];
  24062. }
  24063. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  24064. {
  24065. const MidiEventHolder* const meh = list [index];
  24066. if (meh != 0 && meh->noteOffObject != 0)
  24067. return meh->noteOffObject->message.getTimeStamp();
  24068. else
  24069. return 0.0;
  24070. }
  24071. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  24072. {
  24073. const MidiEventHolder* const meh = list [index];
  24074. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  24075. }
  24076. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  24077. {
  24078. return list.indexOf (event);
  24079. }
  24080. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24081. {
  24082. const int numEvents = list.size();
  24083. int i;
  24084. for (i = 0; i < numEvents; ++i)
  24085. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24086. break;
  24087. return i;
  24088. }
  24089. double MidiMessageSequence::getStartTime() const
  24090. {
  24091. if (list.size() > 0)
  24092. return list.getUnchecked(0)->message.getTimeStamp();
  24093. else
  24094. return 0;
  24095. }
  24096. double MidiMessageSequence::getEndTime() const
  24097. {
  24098. if (list.size() > 0)
  24099. return list.getLast()->message.getTimeStamp();
  24100. else
  24101. return 0;
  24102. }
  24103. double MidiMessageSequence::getEventTime (const int index) const
  24104. {
  24105. if (((unsigned int) index) < (unsigned int) list.size())
  24106. return list.getUnchecked (index)->message.getTimeStamp();
  24107. return 0.0;
  24108. }
  24109. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24110. double timeAdjustment)
  24111. {
  24112. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24113. timeAdjustment += newMessage.getTimeStamp();
  24114. newOne->message.setTimeStamp (timeAdjustment);
  24115. int i;
  24116. for (i = list.size(); --i >= 0;)
  24117. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24118. break;
  24119. list.insert (i + 1, newOne);
  24120. }
  24121. void MidiMessageSequence::deleteEvent (const int index,
  24122. const bool deleteMatchingNoteUp)
  24123. {
  24124. if (((unsigned int) index) < (unsigned int) list.size())
  24125. {
  24126. if (deleteMatchingNoteUp)
  24127. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24128. list.remove (index);
  24129. }
  24130. }
  24131. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24132. double timeAdjustment,
  24133. double firstAllowableTime,
  24134. double endOfAllowableDestTimes)
  24135. {
  24136. firstAllowableTime -= timeAdjustment;
  24137. endOfAllowableDestTimes -= timeAdjustment;
  24138. for (int i = 0; i < other.list.size(); ++i)
  24139. {
  24140. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24141. const double t = m.getTimeStamp();
  24142. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24143. {
  24144. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24145. newOne->message.setTimeStamp (timeAdjustment + t);
  24146. list.add (newOne);
  24147. }
  24148. }
  24149. sort();
  24150. }
  24151. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24152. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24153. {
  24154. const double diff = first->message.getTimeStamp()
  24155. - second->message.getTimeStamp();
  24156. return (diff > 0) - (diff < 0);
  24157. }
  24158. void MidiMessageSequence::sort()
  24159. {
  24160. list.sort (*this, true);
  24161. }
  24162. void MidiMessageSequence::updateMatchedPairs()
  24163. {
  24164. for (int i = 0; i < list.size(); ++i)
  24165. {
  24166. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24167. if (m1.isNoteOn())
  24168. {
  24169. list.getUnchecked(i)->noteOffObject = 0;
  24170. const int note = m1.getNoteNumber();
  24171. const int chan = m1.getChannel();
  24172. const int len = list.size();
  24173. for (int j = i + 1; j < len; ++j)
  24174. {
  24175. const MidiMessage& m = list.getUnchecked(j)->message;
  24176. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24177. {
  24178. if (m.isNoteOff())
  24179. {
  24180. list.getUnchecked(i)->noteOffObject = list[j];
  24181. break;
  24182. }
  24183. else if (m.isNoteOn())
  24184. {
  24185. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24186. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24187. list.getUnchecked(i)->noteOffObject = list[j];
  24188. break;
  24189. }
  24190. }
  24191. }
  24192. }
  24193. }
  24194. }
  24195. void MidiMessageSequence::addTimeToMessages (const double delta)
  24196. {
  24197. for (int i = list.size(); --i >= 0;)
  24198. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24199. + delta);
  24200. }
  24201. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24202. MidiMessageSequence& destSequence,
  24203. const bool alsoIncludeMetaEvents) const
  24204. {
  24205. for (int i = 0; i < list.size(); ++i)
  24206. {
  24207. const MidiMessage& mm = list.getUnchecked(i)->message;
  24208. if (mm.isForChannel (channelNumberToExtract)
  24209. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24210. {
  24211. destSequence.addEvent (mm);
  24212. }
  24213. }
  24214. }
  24215. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24216. {
  24217. for (int i = 0; i < list.size(); ++i)
  24218. {
  24219. const MidiMessage& mm = list.getUnchecked(i)->message;
  24220. if (mm.isSysEx())
  24221. destSequence.addEvent (mm);
  24222. }
  24223. }
  24224. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24225. {
  24226. for (int i = list.size(); --i >= 0;)
  24227. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24228. list.remove(i);
  24229. }
  24230. void MidiMessageSequence::deleteSysExMessages()
  24231. {
  24232. for (int i = list.size(); --i >= 0;)
  24233. if (list.getUnchecked(i)->message.isSysEx())
  24234. list.remove(i);
  24235. }
  24236. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24237. const double time,
  24238. OwnedArray<MidiMessage>& dest)
  24239. {
  24240. bool doneProg = false;
  24241. bool donePitchWheel = false;
  24242. Array <int> doneControllers;
  24243. doneControllers.ensureStorageAllocated (32);
  24244. for (int i = list.size(); --i >= 0;)
  24245. {
  24246. const MidiMessage& mm = list.getUnchecked(i)->message;
  24247. if (mm.isForChannel (channelNumber)
  24248. && mm.getTimeStamp() <= time)
  24249. {
  24250. if (mm.isProgramChange())
  24251. {
  24252. if (! doneProg)
  24253. {
  24254. dest.add (new MidiMessage (mm, 0.0));
  24255. doneProg = true;
  24256. }
  24257. }
  24258. else if (mm.isController())
  24259. {
  24260. if (! doneControllers.contains (mm.getControllerNumber()))
  24261. {
  24262. dest.add (new MidiMessage (mm, 0.0));
  24263. doneControllers.add (mm.getControllerNumber());
  24264. }
  24265. }
  24266. else if (mm.isPitchWheel())
  24267. {
  24268. if (! donePitchWheel)
  24269. {
  24270. dest.add (new MidiMessage (mm, 0.0));
  24271. donePitchWheel = true;
  24272. }
  24273. }
  24274. }
  24275. }
  24276. }
  24277. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24278. : message (message_),
  24279. noteOffObject (0)
  24280. {
  24281. }
  24282. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24283. {
  24284. }
  24285. END_JUCE_NAMESPACE
  24286. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24287. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24288. BEGIN_JUCE_NAMESPACE
  24289. AudioPluginFormat::AudioPluginFormat() throw()
  24290. {
  24291. }
  24292. AudioPluginFormat::~AudioPluginFormat()
  24293. {
  24294. }
  24295. END_JUCE_NAMESPACE
  24296. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24297. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24298. BEGIN_JUCE_NAMESPACE
  24299. AudioPluginFormatManager::AudioPluginFormatManager()
  24300. {
  24301. }
  24302. AudioPluginFormatManager::~AudioPluginFormatManager()
  24303. {
  24304. clearSingletonInstance();
  24305. }
  24306. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24307. void AudioPluginFormatManager::addDefaultFormats()
  24308. {
  24309. #if JUCE_DEBUG
  24310. // you should only call this method once!
  24311. for (int i = formats.size(); --i >= 0;)
  24312. {
  24313. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24314. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24315. #endif
  24316. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24317. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24318. #endif
  24319. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24320. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24321. #endif
  24322. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24323. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24324. #endif
  24325. }
  24326. #endif
  24327. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24328. formats.add (new AudioUnitPluginFormat());
  24329. #endif
  24330. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24331. formats.add (new VSTPluginFormat());
  24332. #endif
  24333. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24334. formats.add (new DirectXPluginFormat());
  24335. #endif
  24336. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24337. formats.add (new LADSPAPluginFormat());
  24338. #endif
  24339. }
  24340. int AudioPluginFormatManager::getNumFormats()
  24341. {
  24342. return formats.size();
  24343. }
  24344. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24345. {
  24346. return formats [index];
  24347. }
  24348. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24349. {
  24350. formats.add (format);
  24351. }
  24352. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24353. String& errorMessage) const
  24354. {
  24355. AudioPluginInstance* result = 0;
  24356. for (int i = 0; i < formats.size(); ++i)
  24357. {
  24358. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24359. if (result != 0)
  24360. break;
  24361. }
  24362. if (result == 0)
  24363. {
  24364. if (! doesPluginStillExist (description))
  24365. errorMessage = TRANS ("This plug-in file no longer exists");
  24366. else
  24367. errorMessage = TRANS ("This plug-in failed to load correctly");
  24368. }
  24369. return result;
  24370. }
  24371. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24372. {
  24373. for (int i = 0; i < formats.size(); ++i)
  24374. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24375. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24376. return false;
  24377. }
  24378. END_JUCE_NAMESPACE
  24379. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24380. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24381. #define JUCE_PLUGIN_HOST 1
  24382. BEGIN_JUCE_NAMESPACE
  24383. AudioPluginInstance::AudioPluginInstance()
  24384. {
  24385. }
  24386. AudioPluginInstance::~AudioPluginInstance()
  24387. {
  24388. }
  24389. void* AudioPluginInstance::getPlatformSpecificData()
  24390. {
  24391. return 0;
  24392. }
  24393. END_JUCE_NAMESPACE
  24394. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24395. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24396. BEGIN_JUCE_NAMESPACE
  24397. KnownPluginList::KnownPluginList()
  24398. {
  24399. }
  24400. KnownPluginList::~KnownPluginList()
  24401. {
  24402. }
  24403. void KnownPluginList::clear()
  24404. {
  24405. if (types.size() > 0)
  24406. {
  24407. types.clear();
  24408. sendChangeMessage();
  24409. }
  24410. }
  24411. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24412. {
  24413. for (int i = 0; i < types.size(); ++i)
  24414. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24415. return types.getUnchecked(i);
  24416. return 0;
  24417. }
  24418. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24419. {
  24420. for (int i = 0; i < types.size(); ++i)
  24421. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24422. return types.getUnchecked(i);
  24423. return 0;
  24424. }
  24425. bool KnownPluginList::addType (const PluginDescription& type)
  24426. {
  24427. for (int i = types.size(); --i >= 0;)
  24428. {
  24429. if (types.getUnchecked(i)->isDuplicateOf (type))
  24430. {
  24431. // strange - found a duplicate plugin with different info..
  24432. jassert (types.getUnchecked(i)->name == type.name);
  24433. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24434. *types.getUnchecked(i) = type;
  24435. return false;
  24436. }
  24437. }
  24438. types.add (new PluginDescription (type));
  24439. sendChangeMessage();
  24440. return true;
  24441. }
  24442. void KnownPluginList::removeType (const int index)
  24443. {
  24444. types.remove (index);
  24445. sendChangeMessage();
  24446. }
  24447. namespace
  24448. {
  24449. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24450. {
  24451. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24452. return File (fileOrIdentifier).getLastModificationTime();
  24453. return Time (0);
  24454. }
  24455. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24456. {
  24457. return t1 != t2 || t1 == Time (0);
  24458. }
  24459. }
  24460. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24461. {
  24462. if (getTypeForFile (fileOrIdentifier) == 0)
  24463. return false;
  24464. for (int i = types.size(); --i >= 0;)
  24465. {
  24466. const PluginDescription* const d = types.getUnchecked(i);
  24467. if (d->fileOrIdentifier == fileOrIdentifier
  24468. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24469. {
  24470. return false;
  24471. }
  24472. }
  24473. return true;
  24474. }
  24475. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24476. const bool dontRescanIfAlreadyInList,
  24477. OwnedArray <PluginDescription>& typesFound,
  24478. AudioPluginFormat& format)
  24479. {
  24480. bool addedOne = false;
  24481. if (dontRescanIfAlreadyInList
  24482. && getTypeForFile (fileOrIdentifier) != 0)
  24483. {
  24484. bool needsRescanning = false;
  24485. for (int i = types.size(); --i >= 0;)
  24486. {
  24487. const PluginDescription* const d = types.getUnchecked(i);
  24488. if (d->fileOrIdentifier == fileOrIdentifier)
  24489. {
  24490. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24491. needsRescanning = true;
  24492. else
  24493. typesFound.add (new PluginDescription (*d));
  24494. }
  24495. }
  24496. if (! needsRescanning)
  24497. return false;
  24498. }
  24499. OwnedArray <PluginDescription> found;
  24500. format.findAllTypesForFile (found, fileOrIdentifier);
  24501. for (int i = 0; i < found.size(); ++i)
  24502. {
  24503. PluginDescription* const desc = found.getUnchecked(i);
  24504. jassert (desc != 0);
  24505. if (addType (*desc))
  24506. addedOne = true;
  24507. typesFound.add (new PluginDescription (*desc));
  24508. }
  24509. return addedOne;
  24510. }
  24511. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24512. OwnedArray <PluginDescription>& typesFound)
  24513. {
  24514. for (int i = 0; i < files.size(); ++i)
  24515. {
  24516. bool loaded = false;
  24517. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24518. {
  24519. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24520. if (scanAndAddFile (files[i], true, typesFound, *format))
  24521. loaded = true;
  24522. }
  24523. if (! loaded)
  24524. {
  24525. const File f (files[i]);
  24526. if (f.isDirectory())
  24527. {
  24528. StringArray s;
  24529. {
  24530. Array<File> subFiles;
  24531. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24532. for (int j = 0; j < subFiles.size(); ++j)
  24533. s.add (subFiles.getReference(j).getFullPathName());
  24534. }
  24535. scanAndAddDragAndDroppedFiles (s, typesFound);
  24536. }
  24537. }
  24538. }
  24539. }
  24540. class PluginSorter
  24541. {
  24542. public:
  24543. KnownPluginList::SortMethod method;
  24544. PluginSorter() throw() {}
  24545. int compareElements (const PluginDescription* const first,
  24546. const PluginDescription* const second) const
  24547. {
  24548. int diff = 0;
  24549. if (method == KnownPluginList::sortByCategory)
  24550. diff = first->category.compareLexicographically (second->category);
  24551. else if (method == KnownPluginList::sortByManufacturer)
  24552. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24553. else if (method == KnownPluginList::sortByFileSystemLocation)
  24554. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24555. .upToLastOccurrenceOf ("/", false, false)
  24556. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24557. .upToLastOccurrenceOf ("/", false, false));
  24558. if (diff == 0)
  24559. diff = first->name.compareLexicographically (second->name);
  24560. return diff;
  24561. }
  24562. };
  24563. void KnownPluginList::sort (const SortMethod method)
  24564. {
  24565. if (method != defaultOrder)
  24566. {
  24567. PluginSorter sorter;
  24568. sorter.method = method;
  24569. types.sort (sorter, true);
  24570. sendChangeMessage();
  24571. }
  24572. }
  24573. XmlElement* KnownPluginList::createXml() const
  24574. {
  24575. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24576. for (int i = 0; i < types.size(); ++i)
  24577. e->addChildElement (types.getUnchecked(i)->createXml());
  24578. return e;
  24579. }
  24580. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24581. {
  24582. clear();
  24583. if (xml.hasTagName ("KNOWNPLUGINS"))
  24584. {
  24585. forEachXmlChildElement (xml, e)
  24586. {
  24587. PluginDescription info;
  24588. if (info.loadFromXml (*e))
  24589. addType (info);
  24590. }
  24591. }
  24592. }
  24593. const int menuIdBase = 0x324503f4;
  24594. // This is used to turn a bunch of paths into a nested menu structure.
  24595. struct PluginFilesystemTree
  24596. {
  24597. private:
  24598. String folder;
  24599. OwnedArray <PluginFilesystemTree> subFolders;
  24600. Array <PluginDescription*> plugins;
  24601. void addPlugin (PluginDescription* const pd, const String& path)
  24602. {
  24603. if (path.isEmpty())
  24604. {
  24605. plugins.add (pd);
  24606. }
  24607. else
  24608. {
  24609. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24610. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24611. for (int i = subFolders.size(); --i >= 0;)
  24612. {
  24613. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24614. {
  24615. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24616. return;
  24617. }
  24618. }
  24619. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24620. newFolder->folder = firstSubFolder;
  24621. subFolders.add (newFolder);
  24622. newFolder->addPlugin (pd, remainingPath);
  24623. }
  24624. }
  24625. // removes any deeply nested folders that don't contain any actual plugins
  24626. void optimise()
  24627. {
  24628. for (int i = subFolders.size(); --i >= 0;)
  24629. {
  24630. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24631. sub->optimise();
  24632. if (sub->plugins.size() == 0)
  24633. {
  24634. for (int j = 0; j < sub->subFolders.size(); ++j)
  24635. subFolders.add (sub->subFolders.getUnchecked(j));
  24636. sub->subFolders.clear (false);
  24637. subFolders.remove (i);
  24638. }
  24639. }
  24640. }
  24641. public:
  24642. void buildTree (const Array <PluginDescription*>& allPlugins)
  24643. {
  24644. for (int i = 0; i < allPlugins.size(); ++i)
  24645. {
  24646. String path (allPlugins.getUnchecked(i)
  24647. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24648. .upToLastOccurrenceOf ("/", false, false));
  24649. if (path.substring (1, 2) == ":")
  24650. path = path.substring (2);
  24651. addPlugin (allPlugins.getUnchecked(i), path);
  24652. }
  24653. optimise();
  24654. }
  24655. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24656. {
  24657. int i;
  24658. for (i = 0; i < subFolders.size(); ++i)
  24659. {
  24660. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24661. PopupMenu subMenu;
  24662. sub->addToMenu (subMenu, allPlugins);
  24663. #if JUCE_MAC
  24664. // avoid the special AU formatting nonsense on Mac..
  24665. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24666. #else
  24667. m.addSubMenu (sub->folder, subMenu);
  24668. #endif
  24669. }
  24670. for (i = 0; i < plugins.size(); ++i)
  24671. {
  24672. PluginDescription* const plugin = plugins.getUnchecked(i);
  24673. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24674. plugin->name, true, false);
  24675. }
  24676. }
  24677. };
  24678. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24679. {
  24680. Array <PluginDescription*> sorted;
  24681. {
  24682. PluginSorter sorter;
  24683. sorter.method = sortMethod;
  24684. for (int i = 0; i < types.size(); ++i)
  24685. sorted.addSorted (sorter, types.getUnchecked(i));
  24686. }
  24687. if (sortMethod == sortByCategory
  24688. || sortMethod == sortByManufacturer)
  24689. {
  24690. String lastSubMenuName;
  24691. PopupMenu sub;
  24692. for (int i = 0; i < sorted.size(); ++i)
  24693. {
  24694. const PluginDescription* const pd = sorted.getUnchecked(i);
  24695. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24696. : pd->manufacturerName);
  24697. if (! thisSubMenuName.containsNonWhitespaceChars())
  24698. thisSubMenuName = "Other";
  24699. if (thisSubMenuName != lastSubMenuName)
  24700. {
  24701. if (sub.getNumItems() > 0)
  24702. {
  24703. menu.addSubMenu (lastSubMenuName, sub);
  24704. sub.clear();
  24705. }
  24706. lastSubMenuName = thisSubMenuName;
  24707. }
  24708. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24709. }
  24710. if (sub.getNumItems() > 0)
  24711. menu.addSubMenu (lastSubMenuName, sub);
  24712. }
  24713. else if (sortMethod == sortByFileSystemLocation)
  24714. {
  24715. PluginFilesystemTree root;
  24716. root.buildTree (sorted);
  24717. root.addToMenu (menu, types);
  24718. }
  24719. else
  24720. {
  24721. for (int i = 0; i < sorted.size(); ++i)
  24722. {
  24723. const PluginDescription* const pd = sorted.getUnchecked(i);
  24724. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24725. }
  24726. }
  24727. }
  24728. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24729. {
  24730. const int i = menuResultCode - menuIdBase;
  24731. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24732. }
  24733. END_JUCE_NAMESPACE
  24734. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24735. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24736. BEGIN_JUCE_NAMESPACE
  24737. PluginDescription::PluginDescription()
  24738. : uid (0),
  24739. isInstrument (false),
  24740. numInputChannels (0),
  24741. numOutputChannels (0)
  24742. {
  24743. }
  24744. PluginDescription::~PluginDescription()
  24745. {
  24746. }
  24747. PluginDescription::PluginDescription (const PluginDescription& other)
  24748. : name (other.name),
  24749. descriptiveName (other.descriptiveName),
  24750. pluginFormatName (other.pluginFormatName),
  24751. category (other.category),
  24752. manufacturerName (other.manufacturerName),
  24753. version (other.version),
  24754. fileOrIdentifier (other.fileOrIdentifier),
  24755. lastFileModTime (other.lastFileModTime),
  24756. uid (other.uid),
  24757. isInstrument (other.isInstrument),
  24758. numInputChannels (other.numInputChannels),
  24759. numOutputChannels (other.numOutputChannels)
  24760. {
  24761. }
  24762. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24763. {
  24764. name = other.name;
  24765. descriptiveName = other.descriptiveName;
  24766. pluginFormatName = other.pluginFormatName;
  24767. category = other.category;
  24768. manufacturerName = other.manufacturerName;
  24769. version = other.version;
  24770. fileOrIdentifier = other.fileOrIdentifier;
  24771. uid = other.uid;
  24772. isInstrument = other.isInstrument;
  24773. lastFileModTime = other.lastFileModTime;
  24774. numInputChannels = other.numInputChannels;
  24775. numOutputChannels = other.numOutputChannels;
  24776. return *this;
  24777. }
  24778. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24779. {
  24780. return fileOrIdentifier == other.fileOrIdentifier
  24781. && uid == other.uid;
  24782. }
  24783. const String PluginDescription::createIdentifierString() const
  24784. {
  24785. return pluginFormatName
  24786. + "-" + name
  24787. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24788. + "-" + String::toHexString (uid);
  24789. }
  24790. XmlElement* PluginDescription::createXml() const
  24791. {
  24792. XmlElement* const e = new XmlElement ("PLUGIN");
  24793. e->setAttribute ("name", name);
  24794. if (descriptiveName != name)
  24795. e->setAttribute ("descriptiveName", descriptiveName);
  24796. e->setAttribute ("format", pluginFormatName);
  24797. e->setAttribute ("category", category);
  24798. e->setAttribute ("manufacturer", manufacturerName);
  24799. e->setAttribute ("version", version);
  24800. e->setAttribute ("file", fileOrIdentifier);
  24801. e->setAttribute ("uid", String::toHexString (uid));
  24802. e->setAttribute ("isInstrument", isInstrument);
  24803. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24804. e->setAttribute ("numInputs", numInputChannels);
  24805. e->setAttribute ("numOutputs", numOutputChannels);
  24806. return e;
  24807. }
  24808. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24809. {
  24810. if (xml.hasTagName ("PLUGIN"))
  24811. {
  24812. name = xml.getStringAttribute ("name");
  24813. descriptiveName = xml.getStringAttribute ("name", name);
  24814. pluginFormatName = xml.getStringAttribute ("format");
  24815. category = xml.getStringAttribute ("category");
  24816. manufacturerName = xml.getStringAttribute ("manufacturer");
  24817. version = xml.getStringAttribute ("version");
  24818. fileOrIdentifier = xml.getStringAttribute ("file");
  24819. uid = xml.getStringAttribute ("uid").getHexValue32();
  24820. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24821. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24822. numInputChannels = xml.getIntAttribute ("numInputs");
  24823. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24824. return true;
  24825. }
  24826. return false;
  24827. }
  24828. END_JUCE_NAMESPACE
  24829. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24830. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24831. BEGIN_JUCE_NAMESPACE
  24832. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24833. AudioPluginFormat& formatToLookFor,
  24834. FileSearchPath directoriesToSearch,
  24835. const bool recursive,
  24836. const File& deadMansPedalFile_)
  24837. : list (listToAddTo),
  24838. format (formatToLookFor),
  24839. deadMansPedalFile (deadMansPedalFile_),
  24840. nextIndex (0),
  24841. progress (0)
  24842. {
  24843. directoriesToSearch.removeRedundantPaths();
  24844. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24845. // If any plugins have crashed recently when being loaded, move them to the
  24846. // end of the list to give the others a chance to load correctly..
  24847. const StringArray crashedPlugins (getDeadMansPedalFile());
  24848. for (int i = 0; i < crashedPlugins.size(); ++i)
  24849. {
  24850. const String f = crashedPlugins[i];
  24851. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24852. if (f == filesOrIdentifiersToScan[j])
  24853. filesOrIdentifiersToScan.move (j, -1);
  24854. }
  24855. }
  24856. PluginDirectoryScanner::~PluginDirectoryScanner()
  24857. {
  24858. }
  24859. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24860. {
  24861. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24862. }
  24863. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24864. {
  24865. String file (filesOrIdentifiersToScan [nextIndex]);
  24866. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24867. {
  24868. OwnedArray <PluginDescription> typesFound;
  24869. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24870. StringArray crashedPlugins (getDeadMansPedalFile());
  24871. crashedPlugins.removeString (file);
  24872. crashedPlugins.add (file);
  24873. setDeadMansPedalFile (crashedPlugins);
  24874. list.scanAndAddFile (file,
  24875. dontRescanIfAlreadyInList,
  24876. typesFound,
  24877. format);
  24878. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24879. crashedPlugins.removeString (file);
  24880. setDeadMansPedalFile (crashedPlugins);
  24881. if (typesFound.size() == 0)
  24882. failedFiles.add (file);
  24883. }
  24884. return skipNextFile();
  24885. }
  24886. bool PluginDirectoryScanner::skipNextFile()
  24887. {
  24888. if (nextIndex >= filesOrIdentifiersToScan.size())
  24889. return false;
  24890. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24891. return nextIndex < filesOrIdentifiersToScan.size();
  24892. }
  24893. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24894. {
  24895. StringArray lines;
  24896. if (deadMansPedalFile != File::nonexistent)
  24897. {
  24898. lines.addLines (deadMansPedalFile.loadFileAsString());
  24899. lines.removeEmptyStrings();
  24900. }
  24901. return lines;
  24902. }
  24903. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24904. {
  24905. if (deadMansPedalFile != File::nonexistent)
  24906. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24907. }
  24908. END_JUCE_NAMESPACE
  24909. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24910. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24911. BEGIN_JUCE_NAMESPACE
  24912. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24913. const File& deadMansPedalFile_,
  24914. PropertiesFile* const propertiesToUse_)
  24915. : list (listToEdit),
  24916. deadMansPedalFile (deadMansPedalFile_),
  24917. optionsButton ("Options..."),
  24918. propertiesToUse (propertiesToUse_)
  24919. {
  24920. listBox.setModel (this);
  24921. addAndMakeVisible (&listBox);
  24922. addAndMakeVisible (&optionsButton);
  24923. optionsButton.addButtonListener (this);
  24924. optionsButton.setTriggeredOnMouseDown (true);
  24925. setSize (400, 600);
  24926. list.addChangeListener (this);
  24927. changeListenerCallback (0);
  24928. }
  24929. PluginListComponent::~PluginListComponent()
  24930. {
  24931. list.removeChangeListener (this);
  24932. }
  24933. void PluginListComponent::resized()
  24934. {
  24935. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24936. optionsButton.changeWidthToFitText (24);
  24937. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24938. }
  24939. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24940. {
  24941. listBox.updateContent();
  24942. listBox.repaint();
  24943. }
  24944. int PluginListComponent::getNumRows()
  24945. {
  24946. return list.getNumTypes();
  24947. }
  24948. void PluginListComponent::paintListBoxItem (int row,
  24949. Graphics& g,
  24950. int width, int height,
  24951. bool rowIsSelected)
  24952. {
  24953. if (rowIsSelected)
  24954. g.fillAll (findColour (TextEditor::highlightColourId));
  24955. const PluginDescription* const pd = list.getType (row);
  24956. if (pd != 0)
  24957. {
  24958. GlyphArrangement ga;
  24959. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24960. g.setColour (Colours::black);
  24961. ga.draw (g);
  24962. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24963. String desc;
  24964. desc << pd->pluginFormatName
  24965. << (pd->isInstrument ? " instrument" : " effect")
  24966. << " - "
  24967. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24968. << " / "
  24969. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24970. if (pd->manufacturerName.isNotEmpty())
  24971. desc << " - " << pd->manufacturerName;
  24972. if (pd->version.isNotEmpty())
  24973. desc << " - " << pd->version;
  24974. if (pd->category.isNotEmpty())
  24975. desc << " - category: '" << pd->category << '\'';
  24976. g.setColour (Colours::grey);
  24977. ga.clear();
  24978. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24979. ga.draw (g);
  24980. }
  24981. }
  24982. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24983. {
  24984. list.removeType (lastRowSelected);
  24985. }
  24986. void PluginListComponent::buttonClicked (Button* button)
  24987. {
  24988. if (button == &optionsButton)
  24989. {
  24990. PopupMenu menu;
  24991. menu.addItem (1, TRANS("Clear list"));
  24992. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  24993. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  24994. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24995. menu.addSeparator();
  24996. menu.addItem (2, TRANS("Sort alphabetically"));
  24997. menu.addItem (3, TRANS("Sort by category"));
  24998. menu.addItem (4, TRANS("Sort by manufacturer"));
  24999. menu.addSeparator();
  25000. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  25001. {
  25002. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  25003. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  25004. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  25005. }
  25006. const int r = menu.showAt (&optionsButton);
  25007. if (r == 1)
  25008. {
  25009. list.clear();
  25010. }
  25011. else if (r == 2)
  25012. {
  25013. list.sort (KnownPluginList::sortAlphabetically);
  25014. }
  25015. else if (r == 3)
  25016. {
  25017. list.sort (KnownPluginList::sortByCategory);
  25018. }
  25019. else if (r == 4)
  25020. {
  25021. list.sort (KnownPluginList::sortByManufacturer);
  25022. }
  25023. else if (r == 5)
  25024. {
  25025. const SparseSet <int> selected (listBox.getSelectedRows());
  25026. for (int i = list.getNumTypes(); --i >= 0;)
  25027. if (selected.contains (i))
  25028. list.removeType (i);
  25029. }
  25030. else if (r == 6)
  25031. {
  25032. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  25033. if (desc != 0)
  25034. {
  25035. if (File (desc->fileOrIdentifier).existsAsFile())
  25036. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  25037. }
  25038. }
  25039. else if (r == 7)
  25040. {
  25041. for (int i = list.getNumTypes(); --i >= 0;)
  25042. {
  25043. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  25044. {
  25045. list.removeType (i);
  25046. }
  25047. }
  25048. }
  25049. else if (r != 0)
  25050. {
  25051. typeToScan = r - 10;
  25052. startTimer (1);
  25053. }
  25054. }
  25055. }
  25056. void PluginListComponent::timerCallback()
  25057. {
  25058. stopTimer();
  25059. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  25060. }
  25061. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  25062. {
  25063. return true;
  25064. }
  25065. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  25066. {
  25067. OwnedArray <PluginDescription> typesFound;
  25068. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  25069. }
  25070. void PluginListComponent::scanFor (AudioPluginFormat* format)
  25071. {
  25072. if (format == 0)
  25073. return;
  25074. FileSearchPath path (format->getDefaultLocationsToSearch());
  25075. if (propertiesToUse != 0)
  25076. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25077. {
  25078. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  25079. FileSearchPathListComponent pathList;
  25080. pathList.setSize (500, 300);
  25081. pathList.setPath (path);
  25082. aw.addCustomComponent (&pathList);
  25083. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  25084. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25085. if (aw.runModalLoop() == 0)
  25086. return;
  25087. path = pathList.getPath();
  25088. }
  25089. if (propertiesToUse != 0)
  25090. {
  25091. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25092. propertiesToUse->saveIfNeeded();
  25093. }
  25094. double progress = 0.0;
  25095. AlertWindow aw (TRANS("Scanning for plugins..."),
  25096. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25097. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25098. aw.addProgressBarComponent (progress);
  25099. aw.enterModalState();
  25100. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25101. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25102. for (;;)
  25103. {
  25104. aw.setMessage (TRANS("Testing:\n\n")
  25105. + scanner.getNextPluginFileThatWillBeScanned());
  25106. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25107. if (! scanner.scanNextFile (true))
  25108. break;
  25109. if (! aw.isCurrentlyModal())
  25110. break;
  25111. progress = scanner.getProgress();
  25112. }
  25113. if (scanner.getFailedFiles().size() > 0)
  25114. {
  25115. StringArray shortNames;
  25116. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25117. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25118. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25119. TRANS("Scan complete"),
  25120. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25121. + shortNames.joinIntoString (", "));
  25122. }
  25123. }
  25124. END_JUCE_NAMESPACE
  25125. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25126. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25127. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25128. #include <AudioUnit/AudioUnit.h>
  25129. #include <AudioUnit/AUCocoaUIView.h>
  25130. #include <CoreAudioKit/AUGenericView.h>
  25131. #if JUCE_SUPPORT_CARBON
  25132. #include <AudioToolbox/AudioUnitUtilities.h>
  25133. #include <AudioUnit/AudioUnitCarbonView.h>
  25134. #endif
  25135. BEGIN_JUCE_NAMESPACE
  25136. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25137. #endif
  25138. #if JUCE_MAC
  25139. // Change this to disable logging of various activities
  25140. #ifndef AU_LOGGING
  25141. #define AU_LOGGING 1
  25142. #endif
  25143. #if AU_LOGGING
  25144. #define log(a) Logger::writeToLog(a);
  25145. #else
  25146. #define log(a)
  25147. #endif
  25148. namespace AudioUnitFormatHelpers
  25149. {
  25150. static int insideCallback = 0;
  25151. const String osTypeToString (OSType type)
  25152. {
  25153. char s[4];
  25154. s[0] = (char) (((uint32) type) >> 24);
  25155. s[1] = (char) (((uint32) type) >> 16);
  25156. s[2] = (char) (((uint32) type) >> 8);
  25157. s[3] = (char) ((uint32) type);
  25158. return String (s, 4);
  25159. }
  25160. OSType stringToOSType (const String& s1)
  25161. {
  25162. const String s (s1 + " ");
  25163. return (((OSType) (unsigned char) s[0]) << 24)
  25164. | (((OSType) (unsigned char) s[1]) << 16)
  25165. | (((OSType) (unsigned char) s[2]) << 8)
  25166. | ((OSType) (unsigned char) s[3]);
  25167. }
  25168. static const char* auIdentifierPrefix = "AudioUnit:";
  25169. const String createAUPluginIdentifier (const ComponentDescription& desc)
  25170. {
  25171. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25172. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25173. String s (auIdentifierPrefix);
  25174. if (desc.componentType == kAudioUnitType_MusicDevice)
  25175. s << "Synths/";
  25176. else if (desc.componentType == kAudioUnitType_MusicEffect
  25177. || desc.componentType == kAudioUnitType_Effect)
  25178. s << "Effects/";
  25179. else if (desc.componentType == kAudioUnitType_Generator)
  25180. s << "Generators/";
  25181. else if (desc.componentType == kAudioUnitType_Panner)
  25182. s << "Panners/";
  25183. s << osTypeToString (desc.componentType) << ","
  25184. << osTypeToString (desc.componentSubType) << ","
  25185. << osTypeToString (desc.componentManufacturer);
  25186. return s;
  25187. }
  25188. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25189. {
  25190. Handle componentNameHandle = NewHandle (sizeof (void*));
  25191. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25192. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25193. {
  25194. ComponentDescription desc;
  25195. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25196. {
  25197. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25198. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25199. if (nameString != 0 && nameString[0] != 0)
  25200. {
  25201. const String all ((const char*) nameString + 1, nameString[0]);
  25202. DBG ("name: "+ all);
  25203. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25204. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25205. }
  25206. if (infoString != 0 && infoString[0] != 0)
  25207. {
  25208. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25209. }
  25210. if (name.isEmpty())
  25211. name = "<Unknown>";
  25212. }
  25213. DisposeHandle (componentNameHandle);
  25214. DisposeHandle (componentInfoHandle);
  25215. }
  25216. }
  25217. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25218. String& name, String& version, String& manufacturer)
  25219. {
  25220. zerostruct (desc);
  25221. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25222. {
  25223. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25224. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25225. StringArray tokens;
  25226. tokens.addTokens (s, ",", String::empty);
  25227. tokens.trim();
  25228. tokens.removeEmptyStrings();
  25229. if (tokens.size() == 3)
  25230. {
  25231. desc.componentType = stringToOSType (tokens[0]);
  25232. desc.componentSubType = stringToOSType (tokens[1]);
  25233. desc.componentManufacturer = stringToOSType (tokens[2]);
  25234. ComponentRecord* comp = FindNextComponent (0, &desc);
  25235. if (comp != 0)
  25236. {
  25237. getAUDetails (comp, name, manufacturer);
  25238. return true;
  25239. }
  25240. }
  25241. }
  25242. return false;
  25243. }
  25244. }
  25245. class AudioUnitPluginWindowCarbon;
  25246. class AudioUnitPluginWindowCocoa;
  25247. class AudioUnitPluginInstance : public AudioPluginInstance
  25248. {
  25249. public:
  25250. ~AudioUnitPluginInstance();
  25251. void initialise();
  25252. // AudioPluginInstance methods:
  25253. void fillInPluginDescription (PluginDescription& desc) const
  25254. {
  25255. desc.name = pluginName;
  25256. desc.descriptiveName = pluginName;
  25257. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25258. desc.uid = ((int) componentDesc.componentType)
  25259. ^ ((int) componentDesc.componentSubType)
  25260. ^ ((int) componentDesc.componentManufacturer);
  25261. desc.lastFileModTime = 0;
  25262. desc.pluginFormatName = "AudioUnit";
  25263. desc.category = getCategory();
  25264. desc.manufacturerName = manufacturer;
  25265. desc.version = version;
  25266. desc.numInputChannels = getNumInputChannels();
  25267. desc.numOutputChannels = getNumOutputChannels();
  25268. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25269. }
  25270. void* getPlatformSpecificData() { return audioUnit; }
  25271. const String getName() const { return pluginName; }
  25272. bool acceptsMidi() const { return wantsMidiMessages; }
  25273. bool producesMidi() const { return false; }
  25274. // AudioProcessor methods:
  25275. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25276. void releaseResources();
  25277. void processBlock (AudioSampleBuffer& buffer,
  25278. MidiBuffer& midiMessages);
  25279. bool hasEditor() const;
  25280. AudioProcessorEditor* createEditor();
  25281. const String getInputChannelName (int index) const;
  25282. bool isInputChannelStereoPair (int index) const;
  25283. const String getOutputChannelName (int index) const;
  25284. bool isOutputChannelStereoPair (int index) const;
  25285. int getNumParameters();
  25286. float getParameter (int index);
  25287. void setParameter (int index, float newValue);
  25288. const String getParameterName (int index);
  25289. const String getParameterText (int index);
  25290. bool isParameterAutomatable (int index) const;
  25291. int getNumPrograms();
  25292. int getCurrentProgram();
  25293. void setCurrentProgram (int index);
  25294. const String getProgramName (int index);
  25295. void changeProgramName (int index, const String& newName);
  25296. void getStateInformation (MemoryBlock& destData);
  25297. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25298. void setStateInformation (const void* data, int sizeInBytes);
  25299. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25300. private:
  25301. friend class AudioUnitPluginWindowCarbon;
  25302. friend class AudioUnitPluginWindowCocoa;
  25303. friend class AudioUnitPluginFormat;
  25304. ComponentDescription componentDesc;
  25305. String pluginName, manufacturer, version;
  25306. String fileOrIdentifier;
  25307. CriticalSection lock;
  25308. bool wantsMidiMessages, wasPlaying, prepared;
  25309. HeapBlock <AudioBufferList> outputBufferList;
  25310. AudioTimeStamp timeStamp;
  25311. AudioSampleBuffer* currentBuffer;
  25312. AudioUnit audioUnit;
  25313. Array <int> parameterIds;
  25314. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25315. void setPluginCallbacks();
  25316. void getParameterListFromPlugin();
  25317. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25318. const AudioTimeStamp* inTimeStamp,
  25319. UInt32 inBusNumber,
  25320. UInt32 inNumberFrames,
  25321. AudioBufferList* ioData) const;
  25322. static OSStatus renderGetInputCallback (void* inRefCon,
  25323. AudioUnitRenderActionFlags* ioActionFlags,
  25324. const AudioTimeStamp* inTimeStamp,
  25325. UInt32 inBusNumber,
  25326. UInt32 inNumberFrames,
  25327. AudioBufferList* ioData)
  25328. {
  25329. return ((AudioUnitPluginInstance*) inRefCon)
  25330. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25331. }
  25332. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25333. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25334. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25335. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25336. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25337. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25338. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25339. {
  25340. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25341. }
  25342. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25343. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25344. Float64* outCurrentMeasureDownBeat)
  25345. {
  25346. return ((AudioUnitPluginInstance*) inHostUserData)
  25347. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25348. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25349. }
  25350. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25351. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25352. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25353. {
  25354. return ((AudioUnitPluginInstance*) inHostUserData)
  25355. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25356. outCurrentSampleInTimeLine, outIsCycling,
  25357. outCycleStartBeat, outCycleEndBeat);
  25358. }
  25359. void getNumChannels (int& numIns, int& numOuts)
  25360. {
  25361. numIns = 0;
  25362. numOuts = 0;
  25363. AUChannelInfo supportedChannels [128];
  25364. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25365. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25366. 0, supportedChannels, &supportedChannelsSize) == noErr
  25367. && supportedChannelsSize > 0)
  25368. {
  25369. int explicitNumIns = 0;
  25370. int explicitNumOuts = 0;
  25371. int maximumNumIns = 0;
  25372. int maximumNumOuts = 0;
  25373. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25374. {
  25375. const int inChannels = (int) supportedChannels[i].inChannels;
  25376. const int outChannels = (int) supportedChannels[i].outChannels;
  25377. if (inChannels < 0)
  25378. maximumNumIns = jmin (maximumNumIns, inChannels);
  25379. else
  25380. explicitNumIns = jmax (explicitNumIns, inChannels);
  25381. if (outChannels < 0)
  25382. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25383. else
  25384. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25385. }
  25386. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25387. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25388. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25389. {
  25390. numIns = numOuts = 2;
  25391. }
  25392. else
  25393. {
  25394. numIns = explicitNumIns;
  25395. numOuts = explicitNumOuts;
  25396. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25397. numIns = 2;
  25398. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25399. numOuts = 2;
  25400. }
  25401. }
  25402. else
  25403. {
  25404. // (this really means the plugin will take any number of ins/outs as long
  25405. // as they are the same)
  25406. numIns = numOuts = 2;
  25407. }
  25408. }
  25409. const String getCategory() const;
  25410. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25411. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25412. };
  25413. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25414. : fileOrIdentifier (fileOrIdentifier),
  25415. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25416. audioUnit (0),
  25417. currentBuffer (0)
  25418. {
  25419. using namespace AudioUnitFormatHelpers;
  25420. try
  25421. {
  25422. ++insideCallback;
  25423. log ("Opening AU: " + fileOrIdentifier);
  25424. if (getComponentDescFromFile (fileOrIdentifier))
  25425. {
  25426. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25427. if (comp != 0)
  25428. {
  25429. audioUnit = (AudioUnit) OpenComponent (comp);
  25430. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25431. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25432. }
  25433. }
  25434. --insideCallback;
  25435. }
  25436. catch (...)
  25437. {
  25438. --insideCallback;
  25439. }
  25440. }
  25441. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25442. {
  25443. const ScopedLock sl (lock);
  25444. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25445. if (audioUnit != 0)
  25446. {
  25447. AudioUnitUninitialize (audioUnit);
  25448. CloseComponent (audioUnit);
  25449. audioUnit = 0;
  25450. }
  25451. }
  25452. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25453. {
  25454. zerostruct (componentDesc);
  25455. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25456. return true;
  25457. const File file (fileOrIdentifier);
  25458. if (! file.hasFileExtension (".component"))
  25459. return false;
  25460. const char* const utf8 = fileOrIdentifier.toUTF8();
  25461. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25462. strlen (utf8), file.isDirectory());
  25463. if (url != 0)
  25464. {
  25465. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25466. CFRelease (url);
  25467. if (bundleRef != 0)
  25468. {
  25469. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25470. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25471. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25472. if (pluginName.isEmpty())
  25473. pluginName = file.getFileNameWithoutExtension();
  25474. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25475. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25476. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25477. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25478. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25479. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25480. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25481. UseResFile (resFileId);
  25482. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25483. {
  25484. Handle h = Get1IndResource ('thng', i);
  25485. if (h != 0)
  25486. {
  25487. HLock (h);
  25488. const uint32* const types = (const uint32*) *h;
  25489. if (types[0] == kAudioUnitType_MusicDevice
  25490. || types[0] == kAudioUnitType_MusicEffect
  25491. || types[0] == kAudioUnitType_Effect
  25492. || types[0] == kAudioUnitType_Generator
  25493. || types[0] == kAudioUnitType_Panner)
  25494. {
  25495. componentDesc.componentType = types[0];
  25496. componentDesc.componentSubType = types[1];
  25497. componentDesc.componentManufacturer = types[2];
  25498. break;
  25499. }
  25500. HUnlock (h);
  25501. ReleaseResource (h);
  25502. }
  25503. }
  25504. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25505. CFRelease (bundleRef);
  25506. }
  25507. }
  25508. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25509. }
  25510. void AudioUnitPluginInstance::initialise()
  25511. {
  25512. getParameterListFromPlugin();
  25513. setPluginCallbacks();
  25514. int numIns, numOuts;
  25515. getNumChannels (numIns, numOuts);
  25516. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25517. setLatencySamples (0);
  25518. }
  25519. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25520. {
  25521. parameterIds.clear();
  25522. if (audioUnit != 0)
  25523. {
  25524. UInt32 paramListSize = 0;
  25525. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25526. 0, 0, &paramListSize);
  25527. if (paramListSize > 0)
  25528. {
  25529. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25530. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25531. 0, &parameterIds.getReference(0), &paramListSize);
  25532. }
  25533. }
  25534. }
  25535. void AudioUnitPluginInstance::setPluginCallbacks()
  25536. {
  25537. if (audioUnit != 0)
  25538. {
  25539. {
  25540. AURenderCallbackStruct info;
  25541. zerostruct (info);
  25542. info.inputProcRefCon = this;
  25543. info.inputProc = renderGetInputCallback;
  25544. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25545. 0, &info, sizeof (info));
  25546. }
  25547. {
  25548. HostCallbackInfo info;
  25549. zerostruct (info);
  25550. info.hostUserData = this;
  25551. info.beatAndTempoProc = getBeatAndTempoCallback;
  25552. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25553. info.transportStateProc = getTransportStateCallback;
  25554. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25555. 0, &info, sizeof (info));
  25556. }
  25557. }
  25558. }
  25559. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25560. int samplesPerBlockExpected)
  25561. {
  25562. if (audioUnit != 0)
  25563. {
  25564. releaseResources();
  25565. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25566. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25567. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25568. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25569. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25570. {
  25571. Float64 sr = sampleRate_;
  25572. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25573. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25574. }
  25575. int numIns, numOuts;
  25576. getNumChannels (numIns, numOuts);
  25577. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25578. Float64 latencySecs = 0.0;
  25579. UInt32 latencySize = sizeof (latencySecs);
  25580. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25581. 0, &latencySecs, &latencySize);
  25582. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25583. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25584. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25585. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25586. {
  25587. AudioStreamBasicDescription stream;
  25588. zerostruct (stream);
  25589. stream.mSampleRate = sampleRate_;
  25590. stream.mFormatID = kAudioFormatLinearPCM;
  25591. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25592. stream.mFramesPerPacket = 1;
  25593. stream.mBytesPerPacket = 4;
  25594. stream.mBytesPerFrame = 4;
  25595. stream.mBitsPerChannel = 32;
  25596. stream.mChannelsPerFrame = numIns;
  25597. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25598. 0, &stream, sizeof (stream));
  25599. stream.mChannelsPerFrame = numOuts;
  25600. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25601. 0, &stream, sizeof (stream));
  25602. }
  25603. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25604. outputBufferList->mNumberBuffers = numOuts;
  25605. for (int i = numOuts; --i >= 0;)
  25606. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25607. zerostruct (timeStamp);
  25608. timeStamp.mSampleTime = 0;
  25609. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25610. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25611. currentBuffer = 0;
  25612. wasPlaying = false;
  25613. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25614. }
  25615. }
  25616. void AudioUnitPluginInstance::releaseResources()
  25617. {
  25618. if (prepared)
  25619. {
  25620. AudioUnitUninitialize (audioUnit);
  25621. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25622. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25623. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25624. outputBufferList.free();
  25625. currentBuffer = 0;
  25626. prepared = false;
  25627. }
  25628. }
  25629. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25630. const AudioTimeStamp* inTimeStamp,
  25631. UInt32 inBusNumber,
  25632. UInt32 inNumberFrames,
  25633. AudioBufferList* ioData) const
  25634. {
  25635. if (inBusNumber == 0
  25636. && currentBuffer != 0)
  25637. {
  25638. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25639. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25640. {
  25641. if (i < currentBuffer->getNumChannels())
  25642. {
  25643. memcpy (ioData->mBuffers[i].mData,
  25644. currentBuffer->getSampleData (i, 0),
  25645. sizeof (float) * inNumberFrames);
  25646. }
  25647. else
  25648. {
  25649. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25650. }
  25651. }
  25652. }
  25653. return noErr;
  25654. }
  25655. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25656. MidiBuffer& midiMessages)
  25657. {
  25658. const int numSamples = buffer.getNumSamples();
  25659. if (prepared)
  25660. {
  25661. AudioUnitRenderActionFlags flags = 0;
  25662. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25663. for (int i = getNumOutputChannels(); --i >= 0;)
  25664. {
  25665. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25666. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25667. }
  25668. currentBuffer = &buffer;
  25669. if (wantsMidiMessages)
  25670. {
  25671. const uint8* midiEventData;
  25672. int midiEventSize, midiEventPosition;
  25673. MidiBuffer::Iterator i (midiMessages);
  25674. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25675. {
  25676. if (midiEventSize <= 3)
  25677. MusicDeviceMIDIEvent (audioUnit,
  25678. midiEventData[0], midiEventData[1], midiEventData[2],
  25679. midiEventPosition);
  25680. else
  25681. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25682. }
  25683. midiMessages.clear();
  25684. }
  25685. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25686. 0, numSamples, outputBufferList);
  25687. timeStamp.mSampleTime += numSamples;
  25688. }
  25689. else
  25690. {
  25691. // Plugin not working correctly, so just bypass..
  25692. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25693. buffer.clear (i, 0, buffer.getNumSamples());
  25694. }
  25695. }
  25696. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25697. {
  25698. AudioPlayHead* const ph = getPlayHead();
  25699. AudioPlayHead::CurrentPositionInfo result;
  25700. if (ph != 0 && ph->getCurrentPosition (result))
  25701. {
  25702. if (outCurrentBeat != 0)
  25703. *outCurrentBeat = result.ppqPosition;
  25704. if (outCurrentTempo != 0)
  25705. *outCurrentTempo = result.bpm;
  25706. }
  25707. else
  25708. {
  25709. if (outCurrentBeat != 0)
  25710. *outCurrentBeat = 0;
  25711. if (outCurrentTempo != 0)
  25712. *outCurrentTempo = 120.0;
  25713. }
  25714. return noErr;
  25715. }
  25716. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25717. Float32* outTimeSig_Numerator,
  25718. UInt32* outTimeSig_Denominator,
  25719. Float64* outCurrentMeasureDownBeat) const
  25720. {
  25721. AudioPlayHead* const ph = getPlayHead();
  25722. AudioPlayHead::CurrentPositionInfo result;
  25723. if (ph != 0 && ph->getCurrentPosition (result))
  25724. {
  25725. if (outTimeSig_Numerator != 0)
  25726. *outTimeSig_Numerator = result.timeSigNumerator;
  25727. if (outTimeSig_Denominator != 0)
  25728. *outTimeSig_Denominator = result.timeSigDenominator;
  25729. if (outDeltaSampleOffsetToNextBeat != 0)
  25730. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25731. if (outCurrentMeasureDownBeat != 0)
  25732. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25733. }
  25734. else
  25735. {
  25736. if (outDeltaSampleOffsetToNextBeat != 0)
  25737. *outDeltaSampleOffsetToNextBeat = 0;
  25738. if (outTimeSig_Numerator != 0)
  25739. *outTimeSig_Numerator = 4;
  25740. if (outTimeSig_Denominator != 0)
  25741. *outTimeSig_Denominator = 4;
  25742. if (outCurrentMeasureDownBeat != 0)
  25743. *outCurrentMeasureDownBeat = 0;
  25744. }
  25745. return noErr;
  25746. }
  25747. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25748. Boolean* outTransportStateChanged,
  25749. Float64* outCurrentSampleInTimeLine,
  25750. Boolean* outIsCycling,
  25751. Float64* outCycleStartBeat,
  25752. Float64* outCycleEndBeat)
  25753. {
  25754. AudioPlayHead* const ph = getPlayHead();
  25755. AudioPlayHead::CurrentPositionInfo result;
  25756. if (ph != 0 && ph->getCurrentPosition (result))
  25757. {
  25758. if (outIsPlaying != 0)
  25759. *outIsPlaying = result.isPlaying;
  25760. if (outTransportStateChanged != 0)
  25761. {
  25762. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25763. wasPlaying = result.isPlaying;
  25764. }
  25765. if (outCurrentSampleInTimeLine != 0)
  25766. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25767. if (outIsCycling != 0)
  25768. *outIsCycling = false;
  25769. if (outCycleStartBeat != 0)
  25770. *outCycleStartBeat = 0;
  25771. if (outCycleEndBeat != 0)
  25772. *outCycleEndBeat = 0;
  25773. }
  25774. else
  25775. {
  25776. if (outIsPlaying != 0)
  25777. *outIsPlaying = false;
  25778. if (outTransportStateChanged != 0)
  25779. *outTransportStateChanged = false;
  25780. if (outCurrentSampleInTimeLine != 0)
  25781. *outCurrentSampleInTimeLine = 0;
  25782. if (outIsCycling != 0)
  25783. *outIsCycling = false;
  25784. if (outCycleStartBeat != 0)
  25785. *outCycleStartBeat = 0;
  25786. if (outCycleEndBeat != 0)
  25787. *outCycleEndBeat = 0;
  25788. }
  25789. return noErr;
  25790. }
  25791. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25792. public Timer
  25793. {
  25794. public:
  25795. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25796. : AudioProcessorEditor (&plugin_),
  25797. plugin (plugin_)
  25798. {
  25799. addAndMakeVisible (&wrapper);
  25800. setOpaque (true);
  25801. setVisible (true);
  25802. setSize (100, 100);
  25803. createView (createGenericViewIfNeeded);
  25804. }
  25805. ~AudioUnitPluginWindowCocoa()
  25806. {
  25807. const bool wasValid = isValid();
  25808. wrapper.setView (0);
  25809. if (wasValid)
  25810. plugin.editorBeingDeleted (this);
  25811. }
  25812. bool isValid() const { return wrapper.getView() != 0; }
  25813. void paint (Graphics& g)
  25814. {
  25815. g.fillAll (Colours::white);
  25816. }
  25817. void resized()
  25818. {
  25819. wrapper.setSize (getWidth(), getHeight());
  25820. }
  25821. void timerCallback()
  25822. {
  25823. wrapper.resizeToFitView();
  25824. startTimer (jmin (713, getTimerInterval() + 51));
  25825. }
  25826. void childBoundsChanged (Component* child)
  25827. {
  25828. setSize (wrapper.getWidth(), wrapper.getHeight());
  25829. startTimer (70);
  25830. }
  25831. private:
  25832. AudioUnitPluginInstance& plugin;
  25833. NSViewComponent wrapper;
  25834. bool createView (const bool createGenericViewIfNeeded)
  25835. {
  25836. NSView* pluginView = 0;
  25837. UInt32 dataSize = 0;
  25838. Boolean isWritable = false;
  25839. AudioUnitInitialize (plugin.audioUnit);
  25840. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25841. 0, &dataSize, &isWritable) == noErr
  25842. && dataSize != 0
  25843. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25844. 0, &dataSize, &isWritable) == noErr)
  25845. {
  25846. HeapBlock <AudioUnitCocoaViewInfo> info;
  25847. info.calloc (dataSize, 1);
  25848. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25849. 0, info, &dataSize) == noErr)
  25850. {
  25851. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25852. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25853. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25854. Class viewClass = [viewBundle classNamed: viewClassName];
  25855. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25856. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25857. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25858. {
  25859. id factory = [[[viewClass alloc] init] autorelease];
  25860. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25861. withSize: NSMakeSize (getWidth(), getHeight())];
  25862. }
  25863. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25864. CFRelease (info->mCocoaAUViewClass[i]);
  25865. CFRelease (info->mCocoaAUViewBundleLocation);
  25866. }
  25867. }
  25868. if (createGenericViewIfNeeded && (pluginView == 0))
  25869. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25870. wrapper.setView (pluginView);
  25871. if (pluginView != 0)
  25872. {
  25873. timerCallback();
  25874. startTimer (70);
  25875. }
  25876. return pluginView != 0;
  25877. }
  25878. };
  25879. #if JUCE_SUPPORT_CARBON
  25880. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25881. {
  25882. public:
  25883. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25884. : AudioProcessorEditor (&plugin_),
  25885. plugin (plugin_),
  25886. viewComponent (0)
  25887. {
  25888. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25889. setOpaque (true);
  25890. setVisible (true);
  25891. setSize (400, 300);
  25892. ComponentDescription viewList [16];
  25893. UInt32 viewListSize = sizeof (viewList);
  25894. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25895. 0, &viewList, &viewListSize);
  25896. componentRecord = FindNextComponent (0, &viewList[0]);
  25897. }
  25898. ~AudioUnitPluginWindowCarbon()
  25899. {
  25900. innerWrapper = 0;
  25901. if (isValid())
  25902. plugin.editorBeingDeleted (this);
  25903. }
  25904. bool isValid() const throw() { return componentRecord != 0; }
  25905. void paint (Graphics& g)
  25906. {
  25907. g.fillAll (Colours::black);
  25908. }
  25909. void resized()
  25910. {
  25911. innerWrapper->setSize (getWidth(), getHeight());
  25912. }
  25913. bool keyStateChanged (bool)
  25914. {
  25915. return false;
  25916. }
  25917. bool keyPressed (const KeyPress&)
  25918. {
  25919. return false;
  25920. }
  25921. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25922. AudioUnitCarbonView getViewComponent()
  25923. {
  25924. if (viewComponent == 0 && componentRecord != 0)
  25925. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25926. return viewComponent;
  25927. }
  25928. void closeViewComponent()
  25929. {
  25930. if (viewComponent != 0)
  25931. {
  25932. log ("Closing AU GUI: " + plugin.getName());
  25933. CloseComponent (viewComponent);
  25934. viewComponent = 0;
  25935. }
  25936. }
  25937. private:
  25938. AudioUnitPluginInstance& plugin;
  25939. ComponentRecord* componentRecord;
  25940. AudioUnitCarbonView viewComponent;
  25941. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25942. {
  25943. public:
  25944. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25945. : owner (owner_)
  25946. {
  25947. }
  25948. ~InnerWrapperComponent()
  25949. {
  25950. deleteWindow();
  25951. }
  25952. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25953. {
  25954. log ("Opening AU GUI: " + owner->plugin.getName());
  25955. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25956. if (viewComponent == 0)
  25957. return 0;
  25958. Float32Point pos = { 0, 0 };
  25959. Float32Point size = { 250, 200 };
  25960. HIViewRef pluginView = 0;
  25961. AudioUnitCarbonViewCreate (viewComponent,
  25962. owner->getAudioUnit(),
  25963. windowRef,
  25964. rootView,
  25965. &pos,
  25966. &size,
  25967. (ControlRef*) &pluginView);
  25968. return pluginView;
  25969. }
  25970. void removeView (HIViewRef)
  25971. {
  25972. owner->closeViewComponent();
  25973. }
  25974. private:
  25975. AudioUnitPluginWindowCarbon* const owner;
  25976. };
  25977. friend class InnerWrapperComponent;
  25978. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25979. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  25980. };
  25981. #endif
  25982. bool AudioUnitPluginInstance::hasEditor() const
  25983. {
  25984. return true;
  25985. }
  25986. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25987. {
  25988. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25989. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25990. w = 0;
  25991. #if JUCE_SUPPORT_CARBON
  25992. if (w == 0)
  25993. {
  25994. w = new AudioUnitPluginWindowCarbon (*this);
  25995. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25996. w = 0;
  25997. }
  25998. #endif
  25999. if (w == 0)
  26000. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  26001. return w.release();
  26002. }
  26003. const String AudioUnitPluginInstance::getCategory() const
  26004. {
  26005. const char* result = 0;
  26006. switch (componentDesc.componentType)
  26007. {
  26008. case kAudioUnitType_Effect:
  26009. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  26010. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  26011. case kAudioUnitType_Generator: result = "Generator"; break;
  26012. case kAudioUnitType_Panner: result = "Panner"; break;
  26013. default: break;
  26014. }
  26015. return result;
  26016. }
  26017. int AudioUnitPluginInstance::getNumParameters()
  26018. {
  26019. return parameterIds.size();
  26020. }
  26021. float AudioUnitPluginInstance::getParameter (int index)
  26022. {
  26023. const ScopedLock sl (lock);
  26024. Float32 value = 0.0f;
  26025. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26026. {
  26027. AudioUnitGetParameter (audioUnit,
  26028. (UInt32) parameterIds.getUnchecked (index),
  26029. kAudioUnitScope_Global, 0,
  26030. &value);
  26031. }
  26032. return value;
  26033. }
  26034. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  26035. {
  26036. const ScopedLock sl (lock);
  26037. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26038. {
  26039. AudioUnitSetParameter (audioUnit,
  26040. (UInt32) parameterIds.getUnchecked (index),
  26041. kAudioUnitScope_Global, 0,
  26042. newValue, 0);
  26043. }
  26044. }
  26045. const String AudioUnitPluginInstance::getParameterName (int index)
  26046. {
  26047. AudioUnitParameterInfo info;
  26048. zerostruct (info);
  26049. UInt32 sz = sizeof (info);
  26050. String name;
  26051. if (AudioUnitGetProperty (audioUnit,
  26052. kAudioUnitProperty_ParameterInfo,
  26053. kAudioUnitScope_Global,
  26054. parameterIds [index], &info, &sz) == noErr)
  26055. {
  26056. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  26057. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  26058. else
  26059. name = String (info.name, sizeof (info.name));
  26060. }
  26061. return name;
  26062. }
  26063. const String AudioUnitPluginInstance::getParameterText (int index)
  26064. {
  26065. return String (getParameter (index));
  26066. }
  26067. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  26068. {
  26069. AudioUnitParameterInfo info;
  26070. UInt32 sz = sizeof (info);
  26071. if (AudioUnitGetProperty (audioUnit,
  26072. kAudioUnitProperty_ParameterInfo,
  26073. kAudioUnitScope_Global,
  26074. parameterIds [index], &info, &sz) == noErr)
  26075. {
  26076. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  26077. }
  26078. return true;
  26079. }
  26080. int AudioUnitPluginInstance::getNumPrograms()
  26081. {
  26082. CFArrayRef presets;
  26083. UInt32 sz = sizeof (CFArrayRef);
  26084. int num = 0;
  26085. if (AudioUnitGetProperty (audioUnit,
  26086. kAudioUnitProperty_FactoryPresets,
  26087. kAudioUnitScope_Global,
  26088. 0, &presets, &sz) == noErr)
  26089. {
  26090. num = (int) CFArrayGetCount (presets);
  26091. CFRelease (presets);
  26092. }
  26093. return num;
  26094. }
  26095. int AudioUnitPluginInstance::getCurrentProgram()
  26096. {
  26097. AUPreset current;
  26098. current.presetNumber = 0;
  26099. UInt32 sz = sizeof (AUPreset);
  26100. AudioUnitGetProperty (audioUnit,
  26101. kAudioUnitProperty_FactoryPresets,
  26102. kAudioUnitScope_Global,
  26103. 0, &current, &sz);
  26104. return current.presetNumber;
  26105. }
  26106. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26107. {
  26108. AUPreset current;
  26109. current.presetNumber = newIndex;
  26110. current.presetName = 0;
  26111. AudioUnitSetProperty (audioUnit,
  26112. kAudioUnitProperty_FactoryPresets,
  26113. kAudioUnitScope_Global,
  26114. 0, &current, sizeof (AUPreset));
  26115. }
  26116. const String AudioUnitPluginInstance::getProgramName (int index)
  26117. {
  26118. String s;
  26119. CFArrayRef presets;
  26120. UInt32 sz = sizeof (CFArrayRef);
  26121. if (AudioUnitGetProperty (audioUnit,
  26122. kAudioUnitProperty_FactoryPresets,
  26123. kAudioUnitScope_Global,
  26124. 0, &presets, &sz) == noErr)
  26125. {
  26126. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26127. {
  26128. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26129. if (p != 0 && p->presetNumber == index)
  26130. {
  26131. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26132. break;
  26133. }
  26134. }
  26135. CFRelease (presets);
  26136. }
  26137. return s;
  26138. }
  26139. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26140. {
  26141. jassertfalse; // xxx not implemented!
  26142. }
  26143. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26144. {
  26145. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  26146. return "Input " + String (index + 1);
  26147. return String::empty;
  26148. }
  26149. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26150. {
  26151. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  26152. return false;
  26153. return true;
  26154. }
  26155. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26156. {
  26157. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  26158. return "Output " + String (index + 1);
  26159. return String::empty;
  26160. }
  26161. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26162. {
  26163. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  26164. return false;
  26165. return true;
  26166. }
  26167. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26168. {
  26169. getCurrentProgramStateInformation (destData);
  26170. }
  26171. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26172. {
  26173. CFPropertyListRef propertyList = 0;
  26174. UInt32 sz = sizeof (CFPropertyListRef);
  26175. if (AudioUnitGetProperty (audioUnit,
  26176. kAudioUnitProperty_ClassInfo,
  26177. kAudioUnitScope_Global,
  26178. 0, &propertyList, &sz) == noErr)
  26179. {
  26180. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26181. CFWriteStreamOpen (stream);
  26182. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26183. CFWriteStreamClose (stream);
  26184. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26185. destData.setSize (bytesWritten);
  26186. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26187. CFRelease (data);
  26188. CFRelease (stream);
  26189. CFRelease (propertyList);
  26190. }
  26191. }
  26192. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26193. {
  26194. setCurrentProgramStateInformation (data, sizeInBytes);
  26195. }
  26196. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26197. {
  26198. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26199. (const UInt8*) data,
  26200. sizeInBytes,
  26201. kCFAllocatorNull);
  26202. CFReadStreamOpen (stream);
  26203. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26204. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26205. stream,
  26206. 0,
  26207. kCFPropertyListImmutable,
  26208. &format,
  26209. 0);
  26210. CFRelease (stream);
  26211. if (propertyList != 0)
  26212. AudioUnitSetProperty (audioUnit,
  26213. kAudioUnitProperty_ClassInfo,
  26214. kAudioUnitScope_Global,
  26215. 0, &propertyList, sizeof (propertyList));
  26216. }
  26217. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26218. {
  26219. }
  26220. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26221. {
  26222. }
  26223. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26224. const String& fileOrIdentifier)
  26225. {
  26226. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26227. return;
  26228. PluginDescription desc;
  26229. desc.fileOrIdentifier = fileOrIdentifier;
  26230. desc.uid = 0;
  26231. try
  26232. {
  26233. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26234. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26235. if (auInstance != 0)
  26236. {
  26237. auInstance->fillInPluginDescription (desc);
  26238. results.add (new PluginDescription (desc));
  26239. }
  26240. }
  26241. catch (...)
  26242. {
  26243. // crashed while loading...
  26244. }
  26245. }
  26246. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26247. {
  26248. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26249. {
  26250. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26251. if (result->audioUnit != 0)
  26252. {
  26253. result->initialise();
  26254. return result.release();
  26255. }
  26256. }
  26257. return 0;
  26258. }
  26259. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26260. const bool /*recursive*/)
  26261. {
  26262. StringArray result;
  26263. ComponentRecord* comp = 0;
  26264. ComponentDescription desc;
  26265. zerostruct (desc);
  26266. for (;;)
  26267. {
  26268. zerostruct (desc);
  26269. comp = FindNextComponent (comp, &desc);
  26270. if (comp == 0)
  26271. break;
  26272. GetComponentInfo (comp, &desc, 0, 0, 0);
  26273. if (desc.componentType == kAudioUnitType_MusicDevice
  26274. || desc.componentType == kAudioUnitType_MusicEffect
  26275. || desc.componentType == kAudioUnitType_Effect
  26276. || desc.componentType == kAudioUnitType_Generator
  26277. || desc.componentType == kAudioUnitType_Panner)
  26278. {
  26279. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26280. DBG (s);
  26281. result.add (s);
  26282. }
  26283. }
  26284. return result;
  26285. }
  26286. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26287. {
  26288. ComponentDescription desc;
  26289. String name, version, manufacturer;
  26290. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26291. return FindNextComponent (0, &desc) != 0;
  26292. const File f (fileOrIdentifier);
  26293. return f.hasFileExtension (".component")
  26294. && f.isDirectory();
  26295. }
  26296. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26297. {
  26298. ComponentDescription desc;
  26299. String name, version, manufacturer;
  26300. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26301. if (name.isEmpty())
  26302. name = fileOrIdentifier;
  26303. return name;
  26304. }
  26305. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26306. {
  26307. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26308. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26309. else
  26310. return File (desc.fileOrIdentifier).exists();
  26311. }
  26312. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26313. {
  26314. return FileSearchPath ("/(Default AudioUnit locations)");
  26315. }
  26316. #endif
  26317. END_JUCE_NAMESPACE
  26318. #undef log
  26319. #endif
  26320. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26321. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26322. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26323. #define JUCE_MAC_VST_INCLUDED 1
  26324. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26325. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26326. #if JUCE_WINDOWS
  26327. #undef _WIN32_WINNT
  26328. #define _WIN32_WINNT 0x500
  26329. #undef STRICT
  26330. #define STRICT
  26331. #include <windows.h>
  26332. #include <float.h>
  26333. #pragma warning (disable : 4312 4355)
  26334. #elif JUCE_LINUX
  26335. #include <float.h>
  26336. #include <sys/time.h>
  26337. #include <X11/Xlib.h>
  26338. #include <X11/Xutil.h>
  26339. #include <X11/Xatom.h>
  26340. #undef Font
  26341. #undef KeyPress
  26342. #undef Drawable
  26343. #undef Time
  26344. #else
  26345. #include <Cocoa/Cocoa.h>
  26346. #include <Carbon/Carbon.h>
  26347. #endif
  26348. #if ! (JUCE_MAC && JUCE_64BIT)
  26349. BEGIN_JUCE_NAMESPACE
  26350. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26351. #endif
  26352. #undef PRAGMA_ALIGN_SUPPORTED
  26353. #define VST_FORCE_DEPRECATED 0
  26354. #if JUCE_MSVC
  26355. #pragma warning (push)
  26356. #pragma warning (disable: 4996)
  26357. #endif
  26358. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26359. your include path if you want to add VST support.
  26360. If you're not interested in VSTs, you can disable them by changing the
  26361. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26362. */
  26363. #include <pluginterfaces/vst2.x/aeffectx.h>
  26364. #if JUCE_MSVC
  26365. #pragma warning (pop)
  26366. #endif
  26367. #if JUCE_LINUX
  26368. #define Font JUCE_NAMESPACE::Font
  26369. #define KeyPress JUCE_NAMESPACE::KeyPress
  26370. #define Drawable JUCE_NAMESPACE::Drawable
  26371. #define Time JUCE_NAMESPACE::Time
  26372. #endif
  26373. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26374. #ifdef __aeffect__
  26375. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26376. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26377. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26378. events to the list.
  26379. This is used by both the VST hosting code and the plugin wrapper.
  26380. */
  26381. class VSTMidiEventList
  26382. {
  26383. public:
  26384. VSTMidiEventList()
  26385. : numEventsUsed (0), numEventsAllocated (0)
  26386. {
  26387. }
  26388. ~VSTMidiEventList()
  26389. {
  26390. freeEvents();
  26391. }
  26392. void clear()
  26393. {
  26394. numEventsUsed = 0;
  26395. if (events != 0)
  26396. events->numEvents = 0;
  26397. }
  26398. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26399. {
  26400. ensureSize (numEventsUsed + 1);
  26401. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26402. events->numEvents = ++numEventsUsed;
  26403. if (numBytes <= 4)
  26404. {
  26405. if (e->type == kVstSysExType)
  26406. {
  26407. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26408. e->type = kVstMidiType;
  26409. e->byteSize = sizeof (VstMidiEvent);
  26410. e->noteLength = 0;
  26411. e->noteOffset = 0;
  26412. e->detune = 0;
  26413. e->noteOffVelocity = 0;
  26414. }
  26415. e->deltaFrames = frameOffset;
  26416. memcpy (e->midiData, midiData, numBytes);
  26417. }
  26418. else
  26419. {
  26420. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26421. if (se->type == kVstSysExType)
  26422. delete[] se->sysexDump;
  26423. se->sysexDump = new char [numBytes];
  26424. memcpy (se->sysexDump, midiData, numBytes);
  26425. se->type = kVstSysExType;
  26426. se->byteSize = sizeof (VstMidiSysexEvent);
  26427. se->deltaFrames = frameOffset;
  26428. se->flags = 0;
  26429. se->dumpBytes = numBytes;
  26430. se->resvd1 = 0;
  26431. se->resvd2 = 0;
  26432. }
  26433. }
  26434. // Handy method to pull the events out of an event buffer supplied by the host
  26435. // or plugin.
  26436. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26437. {
  26438. for (int i = 0; i < events->numEvents; ++i)
  26439. {
  26440. const VstEvent* const e = events->events[i];
  26441. if (e != 0)
  26442. {
  26443. if (e->type == kVstMidiType)
  26444. {
  26445. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26446. 4, e->deltaFrames);
  26447. }
  26448. else if (e->type == kVstSysExType)
  26449. {
  26450. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26451. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26452. e->deltaFrames);
  26453. }
  26454. }
  26455. }
  26456. }
  26457. void ensureSize (int numEventsNeeded)
  26458. {
  26459. if (numEventsNeeded > numEventsAllocated)
  26460. {
  26461. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26462. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26463. if (events == 0)
  26464. events.calloc (size, 1);
  26465. else
  26466. events.realloc (size, 1);
  26467. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26468. {
  26469. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26470. (int) sizeof (VstMidiSysexEvent)));
  26471. e->type = kVstMidiType;
  26472. e->byteSize = sizeof (VstMidiEvent);
  26473. events->events[i] = (VstEvent*) e;
  26474. }
  26475. numEventsAllocated = numEventsNeeded;
  26476. }
  26477. }
  26478. void freeEvents()
  26479. {
  26480. if (events != 0)
  26481. {
  26482. for (int i = numEventsAllocated; --i >= 0;)
  26483. {
  26484. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26485. if (e->type == kVstSysExType)
  26486. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26487. juce_free (e);
  26488. }
  26489. events.free();
  26490. numEventsUsed = 0;
  26491. numEventsAllocated = 0;
  26492. }
  26493. }
  26494. HeapBlock <VstEvents> events;
  26495. private:
  26496. int numEventsUsed, numEventsAllocated;
  26497. };
  26498. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26499. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26500. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26501. #if ! JUCE_WINDOWS
  26502. static void _fpreset() {}
  26503. static void _clearfp() {}
  26504. #endif
  26505. extern void juce_callAnyTimersSynchronously();
  26506. const int fxbVersionNum = 1;
  26507. struct fxProgram
  26508. {
  26509. long chunkMagic; // 'CcnK'
  26510. long byteSize; // of this chunk, excl. magic + byteSize
  26511. long fxMagic; // 'FxCk'
  26512. long version;
  26513. long fxID; // fx unique id
  26514. long fxVersion;
  26515. long numParams;
  26516. char prgName[28];
  26517. float params[1]; // variable no. of parameters
  26518. };
  26519. struct fxSet
  26520. {
  26521. long chunkMagic; // 'CcnK'
  26522. long byteSize; // of this chunk, excl. magic + byteSize
  26523. long fxMagic; // 'FxBk'
  26524. long version;
  26525. long fxID; // fx unique id
  26526. long fxVersion;
  26527. long numPrograms;
  26528. char future[128];
  26529. fxProgram programs[1]; // variable no. of programs
  26530. };
  26531. struct fxChunkSet
  26532. {
  26533. long chunkMagic; // 'CcnK'
  26534. long byteSize; // of this chunk, excl. magic + byteSize
  26535. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26536. long version;
  26537. long fxID; // fx unique id
  26538. long fxVersion;
  26539. long numPrograms;
  26540. char future[128];
  26541. long chunkSize;
  26542. char chunk[8]; // variable
  26543. };
  26544. struct fxProgramSet
  26545. {
  26546. long chunkMagic; // 'CcnK'
  26547. long byteSize; // of this chunk, excl. magic + byteSize
  26548. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26549. long version;
  26550. long fxID; // fx unique id
  26551. long fxVersion;
  26552. long numPrograms;
  26553. char name[28];
  26554. long chunkSize;
  26555. char chunk[8]; // variable
  26556. };
  26557. namespace
  26558. {
  26559. long vst_swap (const long x) throw()
  26560. {
  26561. #ifdef JUCE_LITTLE_ENDIAN
  26562. return (long) ByteOrder::swap ((uint32) x);
  26563. #else
  26564. return x;
  26565. #endif
  26566. }
  26567. float vst_swapFloat (const float x) throw()
  26568. {
  26569. #ifdef JUCE_LITTLE_ENDIAN
  26570. union { uint32 asInt; float asFloat; } n;
  26571. n.asFloat = x;
  26572. n.asInt = ByteOrder::swap (n.asInt);
  26573. return n.asFloat;
  26574. #else
  26575. return x;
  26576. #endif
  26577. }
  26578. double getVSTHostTimeNanoseconds()
  26579. {
  26580. #if JUCE_WINDOWS
  26581. return timeGetTime() * 1000000.0;
  26582. #elif JUCE_LINUX
  26583. timeval micro;
  26584. gettimeofday (&micro, 0);
  26585. return micro.tv_usec * 1000.0;
  26586. #elif JUCE_MAC
  26587. UnsignedWide micro;
  26588. Microseconds (&micro);
  26589. return micro.lo * 1000.0;
  26590. #endif
  26591. }
  26592. }
  26593. typedef AEffect* (*MainCall) (audioMasterCallback);
  26594. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26595. static int shellUIDToCreate = 0;
  26596. static int insideVSTCallback = 0;
  26597. class VSTPluginWindow;
  26598. // Change this to disable logging of various VST activities
  26599. #ifndef VST_LOGGING
  26600. #define VST_LOGGING 1
  26601. #endif
  26602. #if VST_LOGGING
  26603. #define log(a) Logger::writeToLog(a);
  26604. #else
  26605. #define log(a)
  26606. #endif
  26607. #if JUCE_MAC && JUCE_PPC
  26608. static void* NewCFMFromMachO (void* const machofp) throw()
  26609. {
  26610. void* result = (void*) new char[8];
  26611. ((void**) result)[0] = machofp;
  26612. ((void**) result)[1] = result;
  26613. return result;
  26614. }
  26615. #endif
  26616. #if JUCE_LINUX
  26617. extern Display* display;
  26618. extern XContext windowHandleXContext;
  26619. typedef void (*EventProcPtr) (XEvent* ev);
  26620. static bool xErrorTriggered;
  26621. namespace
  26622. {
  26623. int temporaryErrorHandler (Display*, XErrorEvent*)
  26624. {
  26625. xErrorTriggered = true;
  26626. return 0;
  26627. }
  26628. int getPropertyFromXWindow (Window handle, Atom atom)
  26629. {
  26630. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26631. xErrorTriggered = false;
  26632. int userSize;
  26633. unsigned long bytes, userCount;
  26634. unsigned char* data;
  26635. Atom userType;
  26636. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26637. &userType, &userSize, &userCount, &bytes, &data);
  26638. XSetErrorHandler (oldErrorHandler);
  26639. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26640. : 0;
  26641. }
  26642. Window getChildWindow (Window windowToCheck)
  26643. {
  26644. Window rootWindow, parentWindow;
  26645. Window* childWindows;
  26646. unsigned int numChildren;
  26647. XQueryTree (display,
  26648. windowToCheck,
  26649. &rootWindow,
  26650. &parentWindow,
  26651. &childWindows,
  26652. &numChildren);
  26653. if (numChildren > 0)
  26654. return childWindows [0];
  26655. return 0;
  26656. }
  26657. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26658. {
  26659. if (e.mods.isLeftButtonDown())
  26660. {
  26661. ev.xbutton.button = Button1;
  26662. ev.xbutton.state |= Button1Mask;
  26663. }
  26664. else if (e.mods.isRightButtonDown())
  26665. {
  26666. ev.xbutton.button = Button3;
  26667. ev.xbutton.state |= Button3Mask;
  26668. }
  26669. else if (e.mods.isMiddleButtonDown())
  26670. {
  26671. ev.xbutton.button = Button2;
  26672. ev.xbutton.state |= Button2Mask;
  26673. }
  26674. }
  26675. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26676. {
  26677. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26678. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26679. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26680. }
  26681. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26682. {
  26683. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26684. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26685. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26686. }
  26687. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26688. {
  26689. if (increment < 0)
  26690. {
  26691. ev.xbutton.button = Button5;
  26692. ev.xbutton.state |= Button5Mask;
  26693. }
  26694. else if (increment > 0)
  26695. {
  26696. ev.xbutton.button = Button4;
  26697. ev.xbutton.state |= Button4Mask;
  26698. }
  26699. }
  26700. }
  26701. #endif
  26702. class ModuleHandle : public ReferenceCountedObject
  26703. {
  26704. public:
  26705. File file;
  26706. MainCall moduleMain;
  26707. String pluginName;
  26708. static Array <ModuleHandle*>& getActiveModules()
  26709. {
  26710. static Array <ModuleHandle*> activeModules;
  26711. return activeModules;
  26712. }
  26713. static ModuleHandle* findOrCreateModule (const File& file)
  26714. {
  26715. for (int i = getActiveModules().size(); --i >= 0;)
  26716. {
  26717. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26718. if (module->file == file)
  26719. return module;
  26720. }
  26721. _fpreset(); // (doesn't do any harm)
  26722. ++insideVSTCallback;
  26723. shellUIDToCreate = 0;
  26724. log ("Attempting to load VST: " + file.getFullPathName());
  26725. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26726. if (! m->open())
  26727. m = 0;
  26728. --insideVSTCallback;
  26729. _fpreset(); // (doesn't do any harm)
  26730. return m.release();
  26731. }
  26732. ModuleHandle (const File& file_)
  26733. : file (file_),
  26734. moduleMain (0),
  26735. #if JUCE_WINDOWS || JUCE_LINUX
  26736. hModule (0)
  26737. #elif JUCE_MAC
  26738. fragId (0),
  26739. resHandle (0),
  26740. bundleRef (0),
  26741. resFileId (0)
  26742. #endif
  26743. {
  26744. getActiveModules().add (this);
  26745. #if JUCE_WINDOWS || JUCE_LINUX
  26746. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26747. #elif JUCE_MAC
  26748. FSRef ref;
  26749. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26750. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26751. #endif
  26752. }
  26753. ~ModuleHandle()
  26754. {
  26755. getActiveModules().removeValue (this);
  26756. close();
  26757. }
  26758. #if JUCE_WINDOWS || JUCE_LINUX
  26759. void* hModule;
  26760. String fullParentDirectoryPathName;
  26761. bool open()
  26762. {
  26763. #if JUCE_WINDOWS
  26764. static bool timePeriodSet = false;
  26765. if (! timePeriodSet)
  26766. {
  26767. timePeriodSet = true;
  26768. timeBeginPeriod (2);
  26769. }
  26770. #endif
  26771. pluginName = file.getFileNameWithoutExtension();
  26772. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26773. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26774. if (moduleMain == 0)
  26775. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26776. return moduleMain != 0;
  26777. }
  26778. void close()
  26779. {
  26780. _fpreset(); // (doesn't do any harm)
  26781. PlatformUtilities::freeDynamicLibrary (hModule);
  26782. }
  26783. void closeEffect (AEffect* eff)
  26784. {
  26785. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26786. }
  26787. #else
  26788. CFragConnectionID fragId;
  26789. Handle resHandle;
  26790. CFBundleRef bundleRef;
  26791. FSSpec parentDirFSSpec;
  26792. short resFileId;
  26793. bool open()
  26794. {
  26795. bool ok = false;
  26796. const String filename (file.getFullPathName());
  26797. if (file.hasFileExtension (".vst"))
  26798. {
  26799. const char* const utf8 = filename.toUTF8();
  26800. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26801. strlen (utf8), file.isDirectory());
  26802. if (url != 0)
  26803. {
  26804. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26805. CFRelease (url);
  26806. if (bundleRef != 0)
  26807. {
  26808. if (CFBundleLoadExecutable (bundleRef))
  26809. {
  26810. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26811. if (moduleMain == 0)
  26812. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26813. if (moduleMain != 0)
  26814. {
  26815. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26816. if (name != 0)
  26817. {
  26818. if (CFGetTypeID (name) == CFStringGetTypeID())
  26819. {
  26820. char buffer[1024];
  26821. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26822. pluginName = buffer;
  26823. }
  26824. }
  26825. if (pluginName.isEmpty())
  26826. pluginName = file.getFileNameWithoutExtension();
  26827. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26828. ok = true;
  26829. }
  26830. }
  26831. if (! ok)
  26832. {
  26833. CFBundleUnloadExecutable (bundleRef);
  26834. CFRelease (bundleRef);
  26835. bundleRef = 0;
  26836. }
  26837. }
  26838. }
  26839. }
  26840. #if JUCE_PPC
  26841. else
  26842. {
  26843. FSRef fn;
  26844. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26845. {
  26846. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26847. if (resFileId != -1)
  26848. {
  26849. const int numEffs = Count1Resources ('aEff');
  26850. for (int i = 0; i < numEffs; ++i)
  26851. {
  26852. resHandle = Get1IndResource ('aEff', i + 1);
  26853. if (resHandle != 0)
  26854. {
  26855. OSType type;
  26856. Str255 name;
  26857. SInt16 id;
  26858. GetResInfo (resHandle, &id, &type, name);
  26859. pluginName = String ((const char*) name + 1, name[0]);
  26860. DetachResource (resHandle);
  26861. HLock (resHandle);
  26862. Ptr ptr;
  26863. Str255 errorText;
  26864. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26865. name, kPrivateCFragCopy,
  26866. &fragId, &ptr, errorText);
  26867. if (err == noErr)
  26868. {
  26869. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26870. ok = true;
  26871. }
  26872. else
  26873. {
  26874. HUnlock (resHandle);
  26875. }
  26876. break;
  26877. }
  26878. }
  26879. if (! ok)
  26880. CloseResFile (resFileId);
  26881. }
  26882. }
  26883. }
  26884. #endif
  26885. return ok;
  26886. }
  26887. void close()
  26888. {
  26889. #if JUCE_PPC
  26890. if (fragId != 0)
  26891. {
  26892. if (moduleMain != 0)
  26893. disposeMachOFromCFM ((void*) moduleMain);
  26894. CloseConnection (&fragId);
  26895. HUnlock (resHandle);
  26896. if (resFileId != 0)
  26897. CloseResFile (resFileId);
  26898. }
  26899. else
  26900. #endif
  26901. if (bundleRef != 0)
  26902. {
  26903. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26904. if (CFGetRetainCount (bundleRef) == 1)
  26905. CFBundleUnloadExecutable (bundleRef);
  26906. if (CFGetRetainCount (bundleRef) > 0)
  26907. CFRelease (bundleRef);
  26908. }
  26909. }
  26910. void closeEffect (AEffect* eff)
  26911. {
  26912. #if JUCE_PPC
  26913. if (fragId != 0)
  26914. {
  26915. Array<void*> thingsToDelete;
  26916. thingsToDelete.add ((void*) eff->dispatcher);
  26917. thingsToDelete.add ((void*) eff->process);
  26918. thingsToDelete.add ((void*) eff->setParameter);
  26919. thingsToDelete.add ((void*) eff->getParameter);
  26920. thingsToDelete.add ((void*) eff->processReplacing);
  26921. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26922. for (int i = thingsToDelete.size(); --i >= 0;)
  26923. disposeMachOFromCFM (thingsToDelete[i]);
  26924. }
  26925. else
  26926. #endif
  26927. {
  26928. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26929. }
  26930. }
  26931. #if JUCE_PPC
  26932. static void* newMachOFromCFM (void* cfmfp)
  26933. {
  26934. if (cfmfp == 0)
  26935. return 0;
  26936. UInt32* const mfp = new UInt32[6];
  26937. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26938. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26939. mfp[2] = 0x800c0000;
  26940. mfp[3] = 0x804c0004;
  26941. mfp[4] = 0x7c0903a6;
  26942. mfp[5] = 0x4e800420;
  26943. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26944. return mfp;
  26945. }
  26946. static void disposeMachOFromCFM (void* ptr)
  26947. {
  26948. delete[] static_cast <UInt32*> (ptr);
  26949. }
  26950. void coerceAEffectFunctionCalls (AEffect* eff)
  26951. {
  26952. if (fragId != 0)
  26953. {
  26954. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26955. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26956. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26957. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26958. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26959. }
  26960. }
  26961. #endif
  26962. #endif
  26963. private:
  26964. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  26965. };
  26966. /**
  26967. An instance of a plugin, created by a VSTPluginFormat.
  26968. */
  26969. class VSTPluginInstance : public AudioPluginInstance,
  26970. private Timer,
  26971. private AsyncUpdater
  26972. {
  26973. public:
  26974. ~VSTPluginInstance();
  26975. // AudioPluginInstance methods:
  26976. void fillInPluginDescription (PluginDescription& desc) const
  26977. {
  26978. desc.name = name;
  26979. {
  26980. char buffer [512];
  26981. zerostruct (buffer);
  26982. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26983. desc.descriptiveName = String (buffer).trim();
  26984. if (desc.descriptiveName.isEmpty())
  26985. desc.descriptiveName = name;
  26986. }
  26987. desc.fileOrIdentifier = module->file.getFullPathName();
  26988. desc.uid = getUID();
  26989. desc.lastFileModTime = module->file.getLastModificationTime();
  26990. desc.pluginFormatName = "VST";
  26991. desc.category = getCategory();
  26992. {
  26993. char buffer [kVstMaxVendorStrLen + 8];
  26994. zerostruct (buffer);
  26995. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26996. desc.manufacturerName = buffer;
  26997. }
  26998. desc.version = getVersion();
  26999. desc.numInputChannels = getNumInputChannels();
  27000. desc.numOutputChannels = getNumOutputChannels();
  27001. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  27002. }
  27003. void* getPlatformSpecificData() { return effect; }
  27004. const String getName() const { return name; }
  27005. int getUID() const;
  27006. bool acceptsMidi() const { return wantsMidiMessages; }
  27007. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  27008. // AudioProcessor methods:
  27009. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  27010. void releaseResources();
  27011. void processBlock (AudioSampleBuffer& buffer,
  27012. MidiBuffer& midiMessages);
  27013. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  27014. AudioProcessorEditor* createEditor();
  27015. const String getInputChannelName (int index) const;
  27016. bool isInputChannelStereoPair (int index) const;
  27017. const String getOutputChannelName (int index) const;
  27018. bool isOutputChannelStereoPair (int index) const;
  27019. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  27020. float getParameter (int index);
  27021. void setParameter (int index, float newValue);
  27022. const String getParameterName (int index);
  27023. const String getParameterText (int index);
  27024. bool isParameterAutomatable (int index) const;
  27025. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  27026. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  27027. void setCurrentProgram (int index);
  27028. const String getProgramName (int index);
  27029. void changeProgramName (int index, const String& newName);
  27030. void getStateInformation (MemoryBlock& destData);
  27031. void getCurrentProgramStateInformation (MemoryBlock& destData);
  27032. void setStateInformation (const void* data, int sizeInBytes);
  27033. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  27034. void timerCallback();
  27035. void handleAsyncUpdate();
  27036. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  27037. private:
  27038. friend class VSTPluginWindow;
  27039. friend class VSTPluginFormat;
  27040. AEffect* effect;
  27041. String name;
  27042. CriticalSection lock;
  27043. bool wantsMidiMessages, initialised, isPowerOn;
  27044. mutable StringArray programNames;
  27045. AudioSampleBuffer tempBuffer;
  27046. CriticalSection midiInLock;
  27047. MidiBuffer incomingMidi;
  27048. VSTMidiEventList midiEventsToSend;
  27049. VstTimeInfo vstHostTime;
  27050. ReferenceCountedObjectPtr <ModuleHandle> module;
  27051. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  27052. bool restoreProgramSettings (const fxProgram* const prog);
  27053. const String getCurrentProgramName();
  27054. void setParamsInProgramBlock (fxProgram* const prog);
  27055. void updateStoredProgramNames();
  27056. void initialise();
  27057. void handleMidiFromPlugin (const VstEvents* const events);
  27058. void createTempParameterStore (MemoryBlock& dest);
  27059. void restoreFromTempParameterStore (const MemoryBlock& mb);
  27060. const String getParameterLabel (int index) const;
  27061. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  27062. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  27063. void setChunkData (const char* data, int size, bool isPreset);
  27064. bool loadFromFXBFile (const void* data, int numBytes);
  27065. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  27066. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  27067. const String getVersion() const;
  27068. const String getCategory() const;
  27069. void setPower (const bool on);
  27070. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  27071. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  27072. };
  27073. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  27074. : effect (0),
  27075. wantsMidiMessages (false),
  27076. initialised (false),
  27077. isPowerOn (false),
  27078. tempBuffer (1, 1),
  27079. module (module_)
  27080. {
  27081. try
  27082. {
  27083. _fpreset();
  27084. ++insideVSTCallback;
  27085. name = module->pluginName;
  27086. log ("Creating VST instance: " + name);
  27087. #if JUCE_MAC
  27088. if (module->resFileId != 0)
  27089. UseResFile (module->resFileId);
  27090. #if JUCE_PPC
  27091. if (module->fragId != 0)
  27092. {
  27093. static void* audioMasterCoerced = 0;
  27094. if (audioMasterCoerced == 0)
  27095. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  27096. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  27097. }
  27098. else
  27099. #endif
  27100. #endif
  27101. {
  27102. effect = module->moduleMain (&audioMaster);
  27103. }
  27104. --insideVSTCallback;
  27105. if (effect != 0 && effect->magic == kEffectMagic)
  27106. {
  27107. #if JUCE_PPC
  27108. module->coerceAEffectFunctionCalls (effect);
  27109. #endif
  27110. jassert (effect->resvd2 == 0);
  27111. jassert (effect->object != 0);
  27112. _fpreset(); // some dodgy plugs fuck around with this
  27113. }
  27114. else
  27115. {
  27116. effect = 0;
  27117. }
  27118. }
  27119. catch (...)
  27120. {
  27121. --insideVSTCallback;
  27122. }
  27123. }
  27124. VSTPluginInstance::~VSTPluginInstance()
  27125. {
  27126. const ScopedLock sl (lock);
  27127. jassert (insideVSTCallback == 0);
  27128. if (effect != 0 && effect->magic == kEffectMagic)
  27129. {
  27130. try
  27131. {
  27132. #if JUCE_MAC
  27133. if (module->resFileId != 0)
  27134. UseResFile (module->resFileId);
  27135. #endif
  27136. // Must delete any editors before deleting the plugin instance!
  27137. jassert (getActiveEditor() == 0);
  27138. _fpreset(); // some dodgy plugs fuck around with this
  27139. module->closeEffect (effect);
  27140. }
  27141. catch (...)
  27142. {}
  27143. }
  27144. module = 0;
  27145. effect = 0;
  27146. }
  27147. void VSTPluginInstance::initialise()
  27148. {
  27149. if (initialised || effect == 0)
  27150. return;
  27151. log ("Initialising VST: " + module->pluginName);
  27152. initialised = true;
  27153. dispatch (effIdentify, 0, 0, 0, 0);
  27154. if (getSampleRate() > 0)
  27155. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27156. if (getBlockSize() > 0)
  27157. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27158. dispatch (effOpen, 0, 0, 0, 0);
  27159. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27160. getSampleRate(), getBlockSize());
  27161. if (getNumPrograms() > 1)
  27162. setCurrentProgram (0);
  27163. else
  27164. dispatch (effSetProgram, 0, 0, 0, 0);
  27165. int i;
  27166. for (i = effect->numInputs; --i >= 0;)
  27167. dispatch (effConnectInput, i, 1, 0, 0);
  27168. for (i = effect->numOutputs; --i >= 0;)
  27169. dispatch (effConnectOutput, i, 1, 0, 0);
  27170. updateStoredProgramNames();
  27171. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27172. setLatencySamples (effect->initialDelay);
  27173. }
  27174. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27175. int samplesPerBlockExpected)
  27176. {
  27177. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27178. sampleRate_, samplesPerBlockExpected);
  27179. setLatencySamples (effect->initialDelay);
  27180. vstHostTime.tempo = 120.0;
  27181. vstHostTime.timeSigNumerator = 4;
  27182. vstHostTime.timeSigDenominator = 4;
  27183. vstHostTime.sampleRate = sampleRate_;
  27184. vstHostTime.samplePos = 0;
  27185. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27186. initialise();
  27187. if (initialised)
  27188. {
  27189. wantsMidiMessages = wantsMidiMessages
  27190. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27191. if (wantsMidiMessages)
  27192. midiEventsToSend.ensureSize (256);
  27193. else
  27194. midiEventsToSend.freeEvents();
  27195. incomingMidi.clear();
  27196. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27197. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27198. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27199. if (! isPowerOn)
  27200. setPower (true);
  27201. // dodgy hack to force some plugins to initialise the sample rate..
  27202. if ((! hasEditor()) && getNumParameters() > 0)
  27203. {
  27204. const float old = getParameter (0);
  27205. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27206. setParameter (0, old);
  27207. }
  27208. dispatch (effStartProcess, 0, 0, 0, 0);
  27209. }
  27210. }
  27211. void VSTPluginInstance::releaseResources()
  27212. {
  27213. if (initialised)
  27214. {
  27215. dispatch (effStopProcess, 0, 0, 0, 0);
  27216. setPower (false);
  27217. }
  27218. tempBuffer.setSize (1, 1);
  27219. incomingMidi.clear();
  27220. midiEventsToSend.freeEvents();
  27221. }
  27222. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27223. MidiBuffer& midiMessages)
  27224. {
  27225. const int numSamples = buffer.getNumSamples();
  27226. if (initialised)
  27227. {
  27228. AudioPlayHead* playHead = getPlayHead();
  27229. if (playHead != 0)
  27230. {
  27231. AudioPlayHead::CurrentPositionInfo position;
  27232. playHead->getCurrentPosition (position);
  27233. vstHostTime.tempo = position.bpm;
  27234. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27235. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27236. vstHostTime.ppqPos = position.ppqPosition;
  27237. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27238. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27239. if (position.isPlaying)
  27240. vstHostTime.flags |= kVstTransportPlaying;
  27241. else
  27242. vstHostTime.flags &= ~kVstTransportPlaying;
  27243. }
  27244. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27245. if (wantsMidiMessages)
  27246. {
  27247. midiEventsToSend.clear();
  27248. midiEventsToSend.ensureSize (1);
  27249. MidiBuffer::Iterator iter (midiMessages);
  27250. const uint8* midiData;
  27251. int numBytesOfMidiData, samplePosition;
  27252. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27253. {
  27254. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27255. jlimit (0, numSamples - 1, samplePosition));
  27256. }
  27257. try
  27258. {
  27259. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27260. }
  27261. catch (...)
  27262. {}
  27263. }
  27264. _clearfp();
  27265. if ((effect->flags & effFlagsCanReplacing) != 0)
  27266. {
  27267. try
  27268. {
  27269. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27270. }
  27271. catch (...)
  27272. {}
  27273. }
  27274. else
  27275. {
  27276. tempBuffer.setSize (effect->numOutputs, numSamples);
  27277. tempBuffer.clear();
  27278. try
  27279. {
  27280. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27281. }
  27282. catch (...)
  27283. {}
  27284. for (int i = effect->numOutputs; --i >= 0;)
  27285. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27286. }
  27287. }
  27288. else
  27289. {
  27290. // Not initialised, so just bypass..
  27291. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27292. buffer.clear (i, 0, buffer.getNumSamples());
  27293. }
  27294. {
  27295. // copy any incoming midi..
  27296. const ScopedLock sl (midiInLock);
  27297. midiMessages.swapWith (incomingMidi);
  27298. incomingMidi.clear();
  27299. }
  27300. }
  27301. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27302. {
  27303. if (events != 0)
  27304. {
  27305. const ScopedLock sl (midiInLock);
  27306. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27307. }
  27308. }
  27309. static Array <VSTPluginWindow*> activeVSTWindows;
  27310. class VSTPluginWindow : public AudioProcessorEditor,
  27311. #if ! JUCE_MAC
  27312. public ComponentMovementWatcher,
  27313. #endif
  27314. public Timer
  27315. {
  27316. public:
  27317. VSTPluginWindow (VSTPluginInstance& plugin_)
  27318. : AudioProcessorEditor (&plugin_),
  27319. #if ! JUCE_MAC
  27320. ComponentMovementWatcher (this),
  27321. #endif
  27322. plugin (plugin_),
  27323. isOpen (false),
  27324. wasShowing (false),
  27325. pluginRefusesToResize (false),
  27326. pluginWantsKeys (false),
  27327. alreadyInside (false),
  27328. recursiveResize (false)
  27329. {
  27330. #if JUCE_WINDOWS
  27331. sizeCheckCount = 0;
  27332. pluginHWND = 0;
  27333. #elif JUCE_LINUX
  27334. pluginWindow = None;
  27335. pluginProc = None;
  27336. #else
  27337. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27338. #endif
  27339. activeVSTWindows.add (this);
  27340. setSize (1, 1);
  27341. setOpaque (true);
  27342. setVisible (true);
  27343. }
  27344. ~VSTPluginWindow()
  27345. {
  27346. #if JUCE_MAC
  27347. innerWrapper = 0;
  27348. #else
  27349. closePluginWindow();
  27350. #endif
  27351. activeVSTWindows.removeValue (this);
  27352. plugin.editorBeingDeleted (this);
  27353. }
  27354. #if ! JUCE_MAC
  27355. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27356. {
  27357. if (recursiveResize)
  27358. return;
  27359. Component* const topComp = getTopLevelComponent();
  27360. if (topComp->getPeer() != 0)
  27361. {
  27362. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27363. recursiveResize = true;
  27364. #if JUCE_WINDOWS
  27365. if (pluginHWND != 0)
  27366. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27367. #elif JUCE_LINUX
  27368. if (pluginWindow != 0)
  27369. {
  27370. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27371. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27372. XMapRaised (display, pluginWindow);
  27373. }
  27374. #endif
  27375. recursiveResize = false;
  27376. }
  27377. }
  27378. void componentVisibilityChanged (Component&)
  27379. {
  27380. const bool isShowingNow = isShowing();
  27381. if (wasShowing != isShowingNow)
  27382. {
  27383. wasShowing = isShowingNow;
  27384. if (isShowingNow)
  27385. openPluginWindow();
  27386. else
  27387. closePluginWindow();
  27388. }
  27389. componentMovedOrResized (true, true);
  27390. }
  27391. void componentPeerChanged()
  27392. {
  27393. closePluginWindow();
  27394. openPluginWindow();
  27395. }
  27396. #endif
  27397. bool keyStateChanged (bool)
  27398. {
  27399. return pluginWantsKeys;
  27400. }
  27401. bool keyPressed (const KeyPress&)
  27402. {
  27403. return pluginWantsKeys;
  27404. }
  27405. #if JUCE_MAC
  27406. void paint (Graphics& g)
  27407. {
  27408. g.fillAll (Colours::black);
  27409. }
  27410. #else
  27411. void paint (Graphics& g)
  27412. {
  27413. if (isOpen)
  27414. {
  27415. ComponentPeer* const peer = getPeer();
  27416. if (peer != 0)
  27417. {
  27418. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27419. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27420. #if JUCE_LINUX
  27421. if (pluginWindow != 0)
  27422. {
  27423. const Rectangle<int> clip (g.getClipBounds());
  27424. XEvent ev;
  27425. zerostruct (ev);
  27426. ev.xexpose.type = Expose;
  27427. ev.xexpose.display = display;
  27428. ev.xexpose.window = pluginWindow;
  27429. ev.xexpose.x = clip.getX();
  27430. ev.xexpose.y = clip.getY();
  27431. ev.xexpose.width = clip.getWidth();
  27432. ev.xexpose.height = clip.getHeight();
  27433. sendEventToChild (&ev);
  27434. }
  27435. #endif
  27436. }
  27437. }
  27438. else
  27439. {
  27440. g.fillAll (Colours::black);
  27441. }
  27442. }
  27443. #endif
  27444. void timerCallback()
  27445. {
  27446. #if JUCE_WINDOWS
  27447. if (--sizeCheckCount <= 0)
  27448. {
  27449. sizeCheckCount = 10;
  27450. checkPluginWindowSize();
  27451. }
  27452. #endif
  27453. try
  27454. {
  27455. static bool reentrant = false;
  27456. if (! reentrant)
  27457. {
  27458. reentrant = true;
  27459. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27460. reentrant = false;
  27461. }
  27462. }
  27463. catch (...)
  27464. {}
  27465. }
  27466. void mouseDown (const MouseEvent& e)
  27467. {
  27468. #if JUCE_LINUX
  27469. if (pluginWindow == 0)
  27470. return;
  27471. toFront (true);
  27472. XEvent ev;
  27473. zerostruct (ev);
  27474. ev.xbutton.display = display;
  27475. ev.xbutton.type = ButtonPress;
  27476. ev.xbutton.window = pluginWindow;
  27477. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27478. ev.xbutton.time = CurrentTime;
  27479. ev.xbutton.x = e.x;
  27480. ev.xbutton.y = e.y;
  27481. ev.xbutton.x_root = e.getScreenX();
  27482. ev.xbutton.y_root = e.getScreenY();
  27483. translateJuceToXButtonModifiers (e, ev);
  27484. sendEventToChild (&ev);
  27485. #elif JUCE_WINDOWS
  27486. (void) e;
  27487. toFront (true);
  27488. #endif
  27489. }
  27490. void broughtToFront()
  27491. {
  27492. activeVSTWindows.removeValue (this);
  27493. activeVSTWindows.add (this);
  27494. #if JUCE_MAC
  27495. dispatch (effEditTop, 0, 0, 0, 0);
  27496. #endif
  27497. }
  27498. private:
  27499. VSTPluginInstance& plugin;
  27500. bool isOpen, wasShowing, recursiveResize;
  27501. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27502. #if JUCE_WINDOWS
  27503. HWND pluginHWND;
  27504. void* originalWndProc;
  27505. int sizeCheckCount;
  27506. #elif JUCE_LINUX
  27507. Window pluginWindow;
  27508. EventProcPtr pluginProc;
  27509. #endif
  27510. #if JUCE_MAC
  27511. void openPluginWindow (WindowRef parentWindow)
  27512. {
  27513. if (isOpen || parentWindow == 0)
  27514. return;
  27515. isOpen = true;
  27516. ERect* rect = 0;
  27517. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27518. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27519. // do this before and after like in the steinberg example
  27520. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27521. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27522. // Install keyboard hooks
  27523. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27524. // double-check it's not too tiny
  27525. int w = 250, h = 150;
  27526. if (rect != 0)
  27527. {
  27528. w = rect->right - rect->left;
  27529. h = rect->bottom - rect->top;
  27530. if (w == 0 || h == 0)
  27531. {
  27532. w = 250;
  27533. h = 150;
  27534. }
  27535. }
  27536. w = jmax (w, 32);
  27537. h = jmax (h, 32);
  27538. setSize (w, h);
  27539. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27540. repaint();
  27541. }
  27542. #else
  27543. void openPluginWindow()
  27544. {
  27545. if (isOpen || getWindowHandle() == 0)
  27546. return;
  27547. log ("Opening VST UI: " + plugin.name);
  27548. isOpen = true;
  27549. ERect* rect = 0;
  27550. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27551. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27552. // do this before and after like in the steinberg example
  27553. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27554. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27555. // Install keyboard hooks
  27556. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27557. #if JUCE_WINDOWS
  27558. originalWndProc = 0;
  27559. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27560. if (pluginHWND == 0)
  27561. {
  27562. isOpen = false;
  27563. setSize (300, 150);
  27564. return;
  27565. }
  27566. #pragma warning (push)
  27567. #pragma warning (disable: 4244)
  27568. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27569. if (! pluginWantsKeys)
  27570. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27571. #pragma warning (pop)
  27572. int w, h;
  27573. RECT r;
  27574. GetWindowRect (pluginHWND, &r);
  27575. w = r.right - r.left;
  27576. h = r.bottom - r.top;
  27577. if (rect != 0)
  27578. {
  27579. const int rw = rect->right - rect->left;
  27580. const int rh = rect->bottom - rect->top;
  27581. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27582. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27583. {
  27584. // very dodgy logic to decide which size is right.
  27585. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27586. {
  27587. SetWindowPos (pluginHWND, 0,
  27588. 0, 0, rw, rh,
  27589. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27590. GetWindowRect (pluginHWND, &r);
  27591. w = r.right - r.left;
  27592. h = r.bottom - r.top;
  27593. pluginRefusesToResize = (w != rw) || (h != rh);
  27594. w = rw;
  27595. h = rh;
  27596. }
  27597. }
  27598. }
  27599. #elif JUCE_LINUX
  27600. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27601. if (pluginWindow != 0)
  27602. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27603. XInternAtom (display, "_XEventProc", False));
  27604. int w = 250, h = 150;
  27605. if (rect != 0)
  27606. {
  27607. w = rect->right - rect->left;
  27608. h = rect->bottom - rect->top;
  27609. if (w == 0 || h == 0)
  27610. {
  27611. w = 250;
  27612. h = 150;
  27613. }
  27614. }
  27615. if (pluginWindow != 0)
  27616. XMapRaised (display, pluginWindow);
  27617. #endif
  27618. // double-check it's not too tiny
  27619. w = jmax (w, 32);
  27620. h = jmax (h, 32);
  27621. setSize (w, h);
  27622. #if JUCE_WINDOWS
  27623. checkPluginWindowSize();
  27624. #endif
  27625. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27626. repaint();
  27627. }
  27628. #endif
  27629. #if ! JUCE_MAC
  27630. void closePluginWindow()
  27631. {
  27632. if (isOpen)
  27633. {
  27634. log ("Closing VST UI: " + plugin.getName());
  27635. isOpen = false;
  27636. dispatch (effEditClose, 0, 0, 0, 0);
  27637. #if JUCE_WINDOWS
  27638. #pragma warning (push)
  27639. #pragma warning (disable: 4244)
  27640. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27641. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27642. #pragma warning (pop)
  27643. stopTimer();
  27644. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27645. DestroyWindow (pluginHWND);
  27646. pluginHWND = 0;
  27647. #elif JUCE_LINUX
  27648. stopTimer();
  27649. pluginWindow = 0;
  27650. pluginProc = 0;
  27651. #endif
  27652. }
  27653. }
  27654. #endif
  27655. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27656. {
  27657. return plugin.dispatch (opcode, index, value, ptr, opt);
  27658. }
  27659. #if JUCE_WINDOWS
  27660. void checkPluginWindowSize()
  27661. {
  27662. RECT r;
  27663. GetWindowRect (pluginHWND, &r);
  27664. const int w = r.right - r.left;
  27665. const int h = r.bottom - r.top;
  27666. if (isShowing() && w > 0 && h > 0
  27667. && (w != getWidth() || h != getHeight())
  27668. && ! pluginRefusesToResize)
  27669. {
  27670. setSize (w, h);
  27671. sizeCheckCount = 0;
  27672. }
  27673. }
  27674. // hooks to get keyboard events from VST windows..
  27675. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27676. {
  27677. for (int i = activeVSTWindows.size(); --i >= 0;)
  27678. {
  27679. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27680. if (w->pluginHWND == hW)
  27681. {
  27682. if (message == WM_CHAR
  27683. || message == WM_KEYDOWN
  27684. || message == WM_SYSKEYDOWN
  27685. || message == WM_KEYUP
  27686. || message == WM_SYSKEYUP
  27687. || message == WM_APPCOMMAND)
  27688. {
  27689. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27690. message, wParam, lParam);
  27691. }
  27692. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27693. (HWND) w->pluginHWND,
  27694. message,
  27695. wParam,
  27696. lParam);
  27697. }
  27698. }
  27699. return DefWindowProc (hW, message, wParam, lParam);
  27700. }
  27701. #endif
  27702. #if JUCE_LINUX
  27703. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27704. void sendEventToChild (XEvent* event)
  27705. {
  27706. if (pluginProc != 0)
  27707. {
  27708. // if the plugin publishes an event procedure, pass the event directly..
  27709. pluginProc (event);
  27710. }
  27711. else if (pluginWindow != 0)
  27712. {
  27713. // if the plugin has a window, then send the event to the window so that
  27714. // its message thread will pick it up..
  27715. XSendEvent (display, pluginWindow, False, 0L, event);
  27716. XFlush (display);
  27717. }
  27718. }
  27719. void mouseEnter (const MouseEvent& e)
  27720. {
  27721. if (pluginWindow != 0)
  27722. {
  27723. XEvent ev;
  27724. zerostruct (ev);
  27725. ev.xcrossing.display = display;
  27726. ev.xcrossing.type = EnterNotify;
  27727. ev.xcrossing.window = pluginWindow;
  27728. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27729. ev.xcrossing.time = CurrentTime;
  27730. ev.xcrossing.x = e.x;
  27731. ev.xcrossing.y = e.y;
  27732. ev.xcrossing.x_root = e.getScreenX();
  27733. ev.xcrossing.y_root = e.getScreenY();
  27734. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27735. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27736. translateJuceToXCrossingModifiers (e, ev);
  27737. sendEventToChild (&ev);
  27738. }
  27739. }
  27740. void mouseExit (const MouseEvent& e)
  27741. {
  27742. if (pluginWindow != 0)
  27743. {
  27744. XEvent ev;
  27745. zerostruct (ev);
  27746. ev.xcrossing.display = display;
  27747. ev.xcrossing.type = LeaveNotify;
  27748. ev.xcrossing.window = pluginWindow;
  27749. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27750. ev.xcrossing.time = CurrentTime;
  27751. ev.xcrossing.x = e.x;
  27752. ev.xcrossing.y = e.y;
  27753. ev.xcrossing.x_root = e.getScreenX();
  27754. ev.xcrossing.y_root = e.getScreenY();
  27755. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27756. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27757. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27758. translateJuceToXCrossingModifiers (e, ev);
  27759. sendEventToChild (&ev);
  27760. }
  27761. }
  27762. void mouseMove (const MouseEvent& e)
  27763. {
  27764. if (pluginWindow != 0)
  27765. {
  27766. XEvent ev;
  27767. zerostruct (ev);
  27768. ev.xmotion.display = display;
  27769. ev.xmotion.type = MotionNotify;
  27770. ev.xmotion.window = pluginWindow;
  27771. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27772. ev.xmotion.time = CurrentTime;
  27773. ev.xmotion.is_hint = NotifyNormal;
  27774. ev.xmotion.x = e.x;
  27775. ev.xmotion.y = e.y;
  27776. ev.xmotion.x_root = e.getScreenX();
  27777. ev.xmotion.y_root = e.getScreenY();
  27778. sendEventToChild (&ev);
  27779. }
  27780. }
  27781. void mouseDrag (const MouseEvent& e)
  27782. {
  27783. if (pluginWindow != 0)
  27784. {
  27785. XEvent ev;
  27786. zerostruct (ev);
  27787. ev.xmotion.display = display;
  27788. ev.xmotion.type = MotionNotify;
  27789. ev.xmotion.window = pluginWindow;
  27790. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27791. ev.xmotion.time = CurrentTime;
  27792. ev.xmotion.x = e.x ;
  27793. ev.xmotion.y = e.y;
  27794. ev.xmotion.x_root = e.getScreenX();
  27795. ev.xmotion.y_root = e.getScreenY();
  27796. ev.xmotion.is_hint = NotifyNormal;
  27797. translateJuceToXMotionModifiers (e, ev);
  27798. sendEventToChild (&ev);
  27799. }
  27800. }
  27801. void mouseUp (const MouseEvent& e)
  27802. {
  27803. if (pluginWindow != 0)
  27804. {
  27805. XEvent ev;
  27806. zerostruct (ev);
  27807. ev.xbutton.display = display;
  27808. ev.xbutton.type = ButtonRelease;
  27809. ev.xbutton.window = pluginWindow;
  27810. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27811. ev.xbutton.time = CurrentTime;
  27812. ev.xbutton.x = e.x;
  27813. ev.xbutton.y = e.y;
  27814. ev.xbutton.x_root = e.getScreenX();
  27815. ev.xbutton.y_root = e.getScreenY();
  27816. translateJuceToXButtonModifiers (e, ev);
  27817. sendEventToChild (&ev);
  27818. }
  27819. }
  27820. void mouseWheelMove (const MouseEvent& e,
  27821. float incrementX,
  27822. float incrementY)
  27823. {
  27824. if (pluginWindow != 0)
  27825. {
  27826. XEvent ev;
  27827. zerostruct (ev);
  27828. ev.xbutton.display = display;
  27829. ev.xbutton.type = ButtonPress;
  27830. ev.xbutton.window = pluginWindow;
  27831. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27832. ev.xbutton.time = CurrentTime;
  27833. ev.xbutton.x = e.x;
  27834. ev.xbutton.y = e.y;
  27835. ev.xbutton.x_root = e.getScreenX();
  27836. ev.xbutton.y_root = e.getScreenY();
  27837. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27838. sendEventToChild (&ev);
  27839. // TODO - put a usleep here ?
  27840. ev.xbutton.type = ButtonRelease;
  27841. sendEventToChild (&ev);
  27842. }
  27843. }
  27844. #endif
  27845. #if JUCE_MAC
  27846. #if ! JUCE_SUPPORT_CARBON
  27847. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27848. #endif
  27849. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27850. {
  27851. public:
  27852. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27853. : owner (owner_),
  27854. alreadyInside (false)
  27855. {
  27856. }
  27857. ~InnerWrapperComponent()
  27858. {
  27859. deleteWindow();
  27860. }
  27861. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27862. {
  27863. owner->openPluginWindow (windowRef);
  27864. return 0;
  27865. }
  27866. void removeView (HIViewRef)
  27867. {
  27868. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27869. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27870. }
  27871. bool getEmbeddedViewSize (int& w, int& h)
  27872. {
  27873. ERect* rect = 0;
  27874. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27875. w = rect->right - rect->left;
  27876. h = rect->bottom - rect->top;
  27877. return true;
  27878. }
  27879. void mouseDown (int x, int y)
  27880. {
  27881. if (! alreadyInside)
  27882. {
  27883. alreadyInside = true;
  27884. getTopLevelComponent()->toFront (true);
  27885. owner->dispatch (effEditMouse, x, y, 0, 0);
  27886. alreadyInside = false;
  27887. }
  27888. else
  27889. {
  27890. PostEvent (::mouseDown, 0);
  27891. }
  27892. }
  27893. void paint()
  27894. {
  27895. ComponentPeer* const peer = getPeer();
  27896. if (peer != 0)
  27897. {
  27898. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27899. ERect r;
  27900. r.left = pos.getX();
  27901. r.right = r.left + getWidth();
  27902. r.top = pos.getY();
  27903. r.bottom = r.top + getHeight();
  27904. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27905. }
  27906. }
  27907. private:
  27908. VSTPluginWindow* const owner;
  27909. bool alreadyInside;
  27910. };
  27911. friend class InnerWrapperComponent;
  27912. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27913. void resized()
  27914. {
  27915. innerWrapper->setSize (getWidth(), getHeight());
  27916. }
  27917. #endif
  27918. private:
  27919. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  27920. };
  27921. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27922. {
  27923. if (hasEditor())
  27924. return new VSTPluginWindow (*this);
  27925. return 0;
  27926. }
  27927. void VSTPluginInstance::handleAsyncUpdate()
  27928. {
  27929. // indicates that something about the plugin has changed..
  27930. updateHostDisplay();
  27931. }
  27932. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27933. {
  27934. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27935. {
  27936. changeProgramName (getCurrentProgram(), prog->prgName);
  27937. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27938. setParameter (i, vst_swapFloat (prog->params[i]));
  27939. return true;
  27940. }
  27941. return false;
  27942. }
  27943. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27944. const int dataSize)
  27945. {
  27946. if (dataSize < 28)
  27947. return false;
  27948. const fxSet* const set = (const fxSet*) data;
  27949. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27950. || vst_swap (set->version) > fxbVersionNum)
  27951. return false;
  27952. if (vst_swap (set->fxMagic) == 'FxBk')
  27953. {
  27954. // bank of programs
  27955. if (vst_swap (set->numPrograms) >= 0)
  27956. {
  27957. const int oldProg = getCurrentProgram();
  27958. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27959. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27960. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27961. {
  27962. if (i != oldProg)
  27963. {
  27964. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27965. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27966. return false;
  27967. if (vst_swap (set->numPrograms) > 0)
  27968. setCurrentProgram (i);
  27969. if (! restoreProgramSettings (prog))
  27970. return false;
  27971. }
  27972. }
  27973. if (vst_swap (set->numPrograms) > 0)
  27974. setCurrentProgram (oldProg);
  27975. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27976. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27977. return false;
  27978. if (! restoreProgramSettings (prog))
  27979. return false;
  27980. }
  27981. }
  27982. else if (vst_swap (set->fxMagic) == 'FxCk')
  27983. {
  27984. // single program
  27985. const fxProgram* const prog = (const fxProgram*) data;
  27986. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27987. return false;
  27988. changeProgramName (getCurrentProgram(), prog->prgName);
  27989. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27990. setParameter (i, vst_swapFloat (prog->params[i]));
  27991. }
  27992. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27993. {
  27994. // non-preset chunk
  27995. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27996. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27997. return false;
  27998. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27999. }
  28000. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  28001. {
  28002. // preset chunk
  28003. const fxProgramSet* const cset = (const fxProgramSet*) data;
  28004. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  28005. return false;
  28006. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  28007. changeProgramName (getCurrentProgram(), cset->name);
  28008. }
  28009. else
  28010. {
  28011. return false;
  28012. }
  28013. return true;
  28014. }
  28015. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  28016. {
  28017. const int numParams = getNumParameters();
  28018. prog->chunkMagic = vst_swap ('CcnK');
  28019. prog->byteSize = 0;
  28020. prog->fxMagic = vst_swap ('FxCk');
  28021. prog->version = vst_swap (fxbVersionNum);
  28022. prog->fxID = vst_swap (getUID());
  28023. prog->fxVersion = vst_swap (getVersionNumber());
  28024. prog->numParams = vst_swap (numParams);
  28025. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  28026. for (int i = 0; i < numParams; ++i)
  28027. prog->params[i] = vst_swapFloat (getParameter (i));
  28028. }
  28029. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  28030. {
  28031. const int numPrograms = getNumPrograms();
  28032. const int numParams = getNumParameters();
  28033. if (usesChunks())
  28034. {
  28035. if (isFXB)
  28036. {
  28037. MemoryBlock chunk;
  28038. getChunkData (chunk, false, maxSizeMB);
  28039. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  28040. dest.setSize (totalLen, true);
  28041. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  28042. set->chunkMagic = vst_swap ('CcnK');
  28043. set->byteSize = 0;
  28044. set->fxMagic = vst_swap ('FBCh');
  28045. set->version = vst_swap (fxbVersionNum);
  28046. set->fxID = vst_swap (getUID());
  28047. set->fxVersion = vst_swap (getVersionNumber());
  28048. set->numPrograms = vst_swap (numPrograms);
  28049. set->chunkSize = vst_swap ((long) chunk.getSize());
  28050. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28051. }
  28052. else
  28053. {
  28054. MemoryBlock chunk;
  28055. getChunkData (chunk, true, maxSizeMB);
  28056. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  28057. dest.setSize (totalLen, true);
  28058. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  28059. set->chunkMagic = vst_swap ('CcnK');
  28060. set->byteSize = 0;
  28061. set->fxMagic = vst_swap ('FPCh');
  28062. set->version = vst_swap (fxbVersionNum);
  28063. set->fxID = vst_swap (getUID());
  28064. set->fxVersion = vst_swap (getVersionNumber());
  28065. set->numPrograms = vst_swap (numPrograms);
  28066. set->chunkSize = vst_swap ((long) chunk.getSize());
  28067. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  28068. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28069. }
  28070. }
  28071. else
  28072. {
  28073. if (isFXB)
  28074. {
  28075. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28076. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  28077. dest.setSize (len, true);
  28078. fxSet* const set = (fxSet*) dest.getData();
  28079. set->chunkMagic = vst_swap ('CcnK');
  28080. set->byteSize = 0;
  28081. set->fxMagic = vst_swap ('FxBk');
  28082. set->version = vst_swap (fxbVersionNum);
  28083. set->fxID = vst_swap (getUID());
  28084. set->fxVersion = vst_swap (getVersionNumber());
  28085. set->numPrograms = vst_swap (numPrograms);
  28086. const int oldProgram = getCurrentProgram();
  28087. MemoryBlock oldSettings;
  28088. createTempParameterStore (oldSettings);
  28089. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  28090. for (int i = 0; i < numPrograms; ++i)
  28091. {
  28092. if (i != oldProgram)
  28093. {
  28094. setCurrentProgram (i);
  28095. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  28096. }
  28097. }
  28098. setCurrentProgram (oldProgram);
  28099. restoreFromTempParameterStore (oldSettings);
  28100. }
  28101. else
  28102. {
  28103. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28104. dest.setSize (totalLen, true);
  28105. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28106. }
  28107. }
  28108. return true;
  28109. }
  28110. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28111. {
  28112. if (usesChunks())
  28113. {
  28114. void* data = 0;
  28115. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28116. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28117. {
  28118. mb.setSize (bytes);
  28119. mb.copyFrom (data, 0, bytes);
  28120. }
  28121. }
  28122. }
  28123. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28124. {
  28125. if (size > 0 && usesChunks())
  28126. {
  28127. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28128. if (! isPreset)
  28129. updateStoredProgramNames();
  28130. }
  28131. }
  28132. void VSTPluginInstance::timerCallback()
  28133. {
  28134. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28135. stopTimer();
  28136. }
  28137. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28138. {
  28139. const ScopedLock sl (lock);
  28140. ++insideVSTCallback;
  28141. int result = 0;
  28142. try
  28143. {
  28144. if (effect != 0)
  28145. {
  28146. #if JUCE_MAC
  28147. if (module->resFileId != 0)
  28148. UseResFile (module->resFileId);
  28149. #endif
  28150. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28151. #if JUCE_MAC
  28152. module->resFileId = CurResFile();
  28153. #endif
  28154. --insideVSTCallback;
  28155. return result;
  28156. }
  28157. }
  28158. catch (...)
  28159. {
  28160. }
  28161. --insideVSTCallback;
  28162. return result;
  28163. }
  28164. namespace
  28165. {
  28166. static const int defaultVSTSampleRateValue = 16384;
  28167. static const int defaultVSTBlockSizeValue = 512;
  28168. // handles non plugin-specific callbacks..
  28169. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28170. {
  28171. (void) index;
  28172. (void) value;
  28173. (void) opt;
  28174. switch (opcode)
  28175. {
  28176. case audioMasterCanDo:
  28177. {
  28178. static const char* canDos[] = { "supplyIdle",
  28179. "sendVstEvents",
  28180. "sendVstMidiEvent",
  28181. "sendVstTimeInfo",
  28182. "receiveVstEvents",
  28183. "receiveVstMidiEvent",
  28184. "supportShell",
  28185. "shellCategory" };
  28186. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28187. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28188. return 1;
  28189. return 0;
  28190. }
  28191. case audioMasterVersion: return 0x2400;
  28192. case audioMasterCurrentId: return shellUIDToCreate;
  28193. case audioMasterGetNumAutomatableParameters: return 0;
  28194. case audioMasterGetAutomationState: return 1;
  28195. case audioMasterGetVendorVersion: return 0x0101;
  28196. case audioMasterGetVendorString:
  28197. case audioMasterGetProductString:
  28198. {
  28199. String hostName ("Juce VST Host");
  28200. if (JUCEApplication::getInstance() != 0)
  28201. hostName = JUCEApplication::getInstance()->getApplicationName();
  28202. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28203. break;
  28204. }
  28205. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28206. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28207. case audioMasterSetOutputSampleRate: return 0;
  28208. default:
  28209. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28210. break;
  28211. }
  28212. return 0;
  28213. }
  28214. }
  28215. // handles callbacks for a specific plugin
  28216. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28217. {
  28218. switch (opcode)
  28219. {
  28220. case audioMasterAutomate:
  28221. sendParamChangeMessageToListeners (index, opt);
  28222. break;
  28223. case audioMasterProcessEvents:
  28224. handleMidiFromPlugin ((const VstEvents*) ptr);
  28225. break;
  28226. case audioMasterGetTime:
  28227. #if JUCE_MSVC
  28228. #pragma warning (push)
  28229. #pragma warning (disable: 4311)
  28230. #endif
  28231. return (VstIntPtr) &vstHostTime;
  28232. #if JUCE_MSVC
  28233. #pragma warning (pop)
  28234. #endif
  28235. break;
  28236. case audioMasterIdle:
  28237. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28238. {
  28239. ++insideVSTCallback;
  28240. #if JUCE_MAC
  28241. if (getActiveEditor() != 0)
  28242. dispatch (effEditIdle, 0, 0, 0, 0);
  28243. #endif
  28244. juce_callAnyTimersSynchronously();
  28245. handleUpdateNowIfNeeded();
  28246. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28247. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28248. --insideVSTCallback;
  28249. }
  28250. break;
  28251. case audioMasterUpdateDisplay:
  28252. triggerAsyncUpdate();
  28253. break;
  28254. case audioMasterTempoAt:
  28255. // returns (10000 * bpm)
  28256. break;
  28257. case audioMasterNeedIdle:
  28258. startTimer (50);
  28259. break;
  28260. case audioMasterSizeWindow:
  28261. if (getActiveEditor() != 0)
  28262. getActiveEditor()->setSize (index, value);
  28263. return 1;
  28264. case audioMasterGetSampleRate:
  28265. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28266. case audioMasterGetBlockSize:
  28267. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28268. case audioMasterWantMidi:
  28269. wantsMidiMessages = true;
  28270. break;
  28271. case audioMasterGetDirectory:
  28272. #if JUCE_MAC
  28273. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28274. #else
  28275. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28276. #endif
  28277. case audioMasterGetAutomationState:
  28278. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28279. break;
  28280. // none of these are handled (yet)..
  28281. case audioMasterBeginEdit:
  28282. case audioMasterEndEdit:
  28283. case audioMasterSetTime:
  28284. case audioMasterPinConnected:
  28285. case audioMasterGetParameterQuantization:
  28286. case audioMasterIOChanged:
  28287. case audioMasterGetInputLatency:
  28288. case audioMasterGetOutputLatency:
  28289. case audioMasterGetPreviousPlug:
  28290. case audioMasterGetNextPlug:
  28291. case audioMasterWillReplaceOrAccumulate:
  28292. case audioMasterGetCurrentProcessLevel:
  28293. case audioMasterOfflineStart:
  28294. case audioMasterOfflineRead:
  28295. case audioMasterOfflineWrite:
  28296. case audioMasterOfflineGetCurrentPass:
  28297. case audioMasterOfflineGetCurrentMetaPass:
  28298. case audioMasterVendorSpecific:
  28299. case audioMasterSetIcon:
  28300. case audioMasterGetLanguage:
  28301. case audioMasterOpenWindow:
  28302. case audioMasterCloseWindow:
  28303. break;
  28304. default:
  28305. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28306. }
  28307. return 0;
  28308. }
  28309. // entry point for all callbacks from the plugin
  28310. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28311. {
  28312. try
  28313. {
  28314. if (effect != 0 && effect->resvd2 != 0)
  28315. {
  28316. return ((VSTPluginInstance*)(effect->resvd2))
  28317. ->handleCallback (opcode, index, value, ptr, opt);
  28318. }
  28319. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28320. }
  28321. catch (...)
  28322. {
  28323. return 0;
  28324. }
  28325. }
  28326. const String VSTPluginInstance::getVersion() const
  28327. {
  28328. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28329. String s;
  28330. if (v == 0 || v == -1)
  28331. v = getVersionNumber();
  28332. if (v != 0)
  28333. {
  28334. int versionBits[4];
  28335. int n = 0;
  28336. while (v != 0)
  28337. {
  28338. versionBits [n++] = (v & 0xff);
  28339. v >>= 8;
  28340. }
  28341. s << 'V';
  28342. while (n > 0)
  28343. {
  28344. s << versionBits [--n];
  28345. if (n > 0)
  28346. s << '.';
  28347. }
  28348. }
  28349. return s;
  28350. }
  28351. int VSTPluginInstance::getUID() const
  28352. {
  28353. int uid = effect != 0 ? effect->uniqueID : 0;
  28354. if (uid == 0)
  28355. uid = module->file.hashCode();
  28356. return uid;
  28357. }
  28358. const String VSTPluginInstance::getCategory() const
  28359. {
  28360. const char* result = 0;
  28361. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28362. {
  28363. case kPlugCategEffect: result = "Effect"; break;
  28364. case kPlugCategSynth: result = "Synth"; break;
  28365. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28366. case kPlugCategMastering: result = "Mastering"; break;
  28367. case kPlugCategSpacializer: result = "Spacial"; break;
  28368. case kPlugCategRoomFx: result = "Reverb"; break;
  28369. case kPlugSurroundFx: result = "Surround"; break;
  28370. case kPlugCategRestoration: result = "Restoration"; break;
  28371. case kPlugCategGenerator: result = "Tone generation"; break;
  28372. default: break;
  28373. }
  28374. return result;
  28375. }
  28376. float VSTPluginInstance::getParameter (int index)
  28377. {
  28378. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28379. {
  28380. try
  28381. {
  28382. const ScopedLock sl (lock);
  28383. return effect->getParameter (effect, index);
  28384. }
  28385. catch (...)
  28386. {
  28387. }
  28388. }
  28389. return 0.0f;
  28390. }
  28391. void VSTPluginInstance::setParameter (int index, float newValue)
  28392. {
  28393. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28394. {
  28395. try
  28396. {
  28397. const ScopedLock sl (lock);
  28398. if (effect->getParameter (effect, index) != newValue)
  28399. effect->setParameter (effect, index, newValue);
  28400. }
  28401. catch (...)
  28402. {
  28403. }
  28404. }
  28405. }
  28406. const String VSTPluginInstance::getParameterName (int index)
  28407. {
  28408. if (effect != 0)
  28409. {
  28410. jassert (index >= 0 && index < effect->numParams);
  28411. char nm [256];
  28412. zerostruct (nm);
  28413. dispatch (effGetParamName, index, 0, nm, 0);
  28414. return String (nm).trim();
  28415. }
  28416. return String::empty;
  28417. }
  28418. const String VSTPluginInstance::getParameterLabel (int index) const
  28419. {
  28420. if (effect != 0)
  28421. {
  28422. jassert (index >= 0 && index < effect->numParams);
  28423. char nm [256];
  28424. zerostruct (nm);
  28425. dispatch (effGetParamLabel, index, 0, nm, 0);
  28426. return String (nm).trim();
  28427. }
  28428. return String::empty;
  28429. }
  28430. const String VSTPluginInstance::getParameterText (int index)
  28431. {
  28432. if (effect != 0)
  28433. {
  28434. jassert (index >= 0 && index < effect->numParams);
  28435. char nm [256];
  28436. zerostruct (nm);
  28437. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28438. return String (nm).trim();
  28439. }
  28440. return String::empty;
  28441. }
  28442. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28443. {
  28444. if (effect != 0)
  28445. {
  28446. jassert (index >= 0 && index < effect->numParams);
  28447. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28448. }
  28449. return false;
  28450. }
  28451. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28452. {
  28453. dest.setSize (64 + 4 * getNumParameters());
  28454. dest.fillWith (0);
  28455. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28456. float* const p = (float*) (((char*) dest.getData()) + 64);
  28457. for (int i = 0; i < getNumParameters(); ++i)
  28458. p[i] = getParameter(i);
  28459. }
  28460. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28461. {
  28462. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28463. float* p = (float*) (((char*) m.getData()) + 64);
  28464. for (int i = 0; i < getNumParameters(); ++i)
  28465. setParameter (i, p[i]);
  28466. }
  28467. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28468. {
  28469. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28470. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28471. }
  28472. const String VSTPluginInstance::getProgramName (int index)
  28473. {
  28474. if (index == getCurrentProgram())
  28475. {
  28476. return getCurrentProgramName();
  28477. }
  28478. else if (effect != 0)
  28479. {
  28480. char nm [256];
  28481. zerostruct (nm);
  28482. if (dispatch (effGetProgramNameIndexed,
  28483. jlimit (0, getNumPrograms(), index),
  28484. -1, nm, 0) != 0)
  28485. {
  28486. return String (nm).trim();
  28487. }
  28488. }
  28489. return programNames [index];
  28490. }
  28491. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28492. {
  28493. if (index == getCurrentProgram())
  28494. {
  28495. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28496. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28497. }
  28498. else
  28499. {
  28500. jassertfalse; // xxx not implemented!
  28501. }
  28502. }
  28503. void VSTPluginInstance::updateStoredProgramNames()
  28504. {
  28505. if (effect != 0 && getNumPrograms() > 0)
  28506. {
  28507. char nm [256];
  28508. zerostruct (nm);
  28509. // only do this if the plugin can't use indexed names..
  28510. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28511. {
  28512. const int oldProgram = getCurrentProgram();
  28513. MemoryBlock oldSettings;
  28514. createTempParameterStore (oldSettings);
  28515. for (int i = 0; i < getNumPrograms(); ++i)
  28516. {
  28517. setCurrentProgram (i);
  28518. getCurrentProgramName(); // (this updates the list)
  28519. }
  28520. setCurrentProgram (oldProgram);
  28521. restoreFromTempParameterStore (oldSettings);
  28522. }
  28523. }
  28524. }
  28525. const String VSTPluginInstance::getCurrentProgramName()
  28526. {
  28527. if (effect != 0)
  28528. {
  28529. char nm [256];
  28530. zerostruct (nm);
  28531. dispatch (effGetProgramName, 0, 0, nm, 0);
  28532. const int index = getCurrentProgram();
  28533. if (programNames[index].isEmpty())
  28534. {
  28535. while (programNames.size() < index)
  28536. programNames.add (String::empty);
  28537. programNames.set (index, String (nm).trim());
  28538. }
  28539. return String (nm).trim();
  28540. }
  28541. return String::empty;
  28542. }
  28543. const String VSTPluginInstance::getInputChannelName (int index) const
  28544. {
  28545. if (index >= 0 && index < getNumInputChannels())
  28546. {
  28547. VstPinProperties pinProps;
  28548. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28549. return String (pinProps.label, sizeof (pinProps.label));
  28550. }
  28551. return String::empty;
  28552. }
  28553. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28554. {
  28555. if (index < 0 || index >= getNumInputChannels())
  28556. return false;
  28557. VstPinProperties pinProps;
  28558. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28559. return (pinProps.flags & kVstPinIsStereo) != 0;
  28560. return true;
  28561. }
  28562. const String VSTPluginInstance::getOutputChannelName (int index) const
  28563. {
  28564. if (index >= 0 && index < getNumOutputChannels())
  28565. {
  28566. VstPinProperties pinProps;
  28567. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28568. return String (pinProps.label, sizeof (pinProps.label));
  28569. }
  28570. return String::empty;
  28571. }
  28572. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28573. {
  28574. if (index < 0 || index >= getNumOutputChannels())
  28575. return false;
  28576. VstPinProperties pinProps;
  28577. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28578. return (pinProps.flags & kVstPinIsStereo) != 0;
  28579. return true;
  28580. }
  28581. void VSTPluginInstance::setPower (const bool on)
  28582. {
  28583. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28584. isPowerOn = on;
  28585. }
  28586. const int defaultMaxSizeMB = 64;
  28587. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28588. {
  28589. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28590. }
  28591. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28592. {
  28593. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28594. }
  28595. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28596. {
  28597. loadFromFXBFile (data, sizeInBytes);
  28598. }
  28599. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28600. {
  28601. loadFromFXBFile (data, sizeInBytes);
  28602. }
  28603. VSTPluginFormat::VSTPluginFormat()
  28604. {
  28605. }
  28606. VSTPluginFormat::~VSTPluginFormat()
  28607. {
  28608. }
  28609. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28610. const String& fileOrIdentifier)
  28611. {
  28612. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28613. return;
  28614. PluginDescription desc;
  28615. desc.fileOrIdentifier = fileOrIdentifier;
  28616. desc.uid = 0;
  28617. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28618. if (instance == 0)
  28619. return;
  28620. try
  28621. {
  28622. #if JUCE_MAC
  28623. if (instance->module->resFileId != 0)
  28624. UseResFile (instance->module->resFileId);
  28625. #endif
  28626. instance->fillInPluginDescription (desc);
  28627. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28628. if (category != kPlugCategShell)
  28629. {
  28630. // Normal plugin...
  28631. results.add (new PluginDescription (desc));
  28632. ++insideVSTCallback;
  28633. instance->dispatch (effOpen, 0, 0, 0, 0);
  28634. --insideVSTCallback;
  28635. }
  28636. else
  28637. {
  28638. // It's a shell plugin, so iterate all the subtypes...
  28639. char shellEffectName [64];
  28640. for (;;)
  28641. {
  28642. zerostruct (shellEffectName);
  28643. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28644. if (uid == 0)
  28645. {
  28646. break;
  28647. }
  28648. else
  28649. {
  28650. desc.uid = uid;
  28651. desc.name = shellEffectName;
  28652. desc.descriptiveName = shellEffectName;
  28653. bool alreadyThere = false;
  28654. for (int i = results.size(); --i >= 0;)
  28655. {
  28656. PluginDescription* const d = results.getUnchecked(i);
  28657. if (d->isDuplicateOf (desc))
  28658. {
  28659. alreadyThere = true;
  28660. break;
  28661. }
  28662. }
  28663. if (! alreadyThere)
  28664. results.add (new PluginDescription (desc));
  28665. }
  28666. }
  28667. }
  28668. }
  28669. catch (...)
  28670. {
  28671. // crashed while loading...
  28672. }
  28673. }
  28674. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28675. {
  28676. ScopedPointer <VSTPluginInstance> result;
  28677. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28678. {
  28679. File file (desc.fileOrIdentifier);
  28680. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28681. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28682. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28683. if (module != 0)
  28684. {
  28685. shellUIDToCreate = desc.uid;
  28686. result = new VSTPluginInstance (module);
  28687. if (result->effect != 0)
  28688. {
  28689. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28690. result->initialise();
  28691. }
  28692. else
  28693. {
  28694. result = 0;
  28695. }
  28696. }
  28697. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28698. }
  28699. return result.release();
  28700. }
  28701. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28702. {
  28703. const File f (fileOrIdentifier);
  28704. #if JUCE_MAC
  28705. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28706. return true;
  28707. #if JUCE_PPC
  28708. FSRef fileRef;
  28709. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28710. {
  28711. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28712. if (resFileId != -1)
  28713. {
  28714. const int numEffects = Count1Resources ('aEff');
  28715. CloseResFile (resFileId);
  28716. if (numEffects > 0)
  28717. return true;
  28718. }
  28719. }
  28720. #endif
  28721. return false;
  28722. #elif JUCE_WINDOWS
  28723. return f.existsAsFile() && f.hasFileExtension (".dll");
  28724. #elif JUCE_LINUX
  28725. return f.existsAsFile() && f.hasFileExtension (".so");
  28726. #endif
  28727. }
  28728. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28729. {
  28730. return fileOrIdentifier;
  28731. }
  28732. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28733. {
  28734. return File (desc.fileOrIdentifier).exists();
  28735. }
  28736. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28737. {
  28738. StringArray results;
  28739. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28740. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28741. return results;
  28742. }
  28743. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28744. {
  28745. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28746. // .component or .vst directories.
  28747. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28748. while (iter.next())
  28749. {
  28750. const File f (iter.getFile());
  28751. bool isPlugin = false;
  28752. if (fileMightContainThisPluginType (f.getFullPathName()))
  28753. {
  28754. isPlugin = true;
  28755. results.add (f.getFullPathName());
  28756. }
  28757. if (recursive && (! isPlugin) && f.isDirectory())
  28758. recursiveFileSearch (results, f, true);
  28759. }
  28760. }
  28761. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28762. {
  28763. #if JUCE_MAC
  28764. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28765. #elif JUCE_WINDOWS
  28766. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28767. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28768. #elif JUCE_LINUX
  28769. return FileSearchPath ("/usr/lib/vst");
  28770. #endif
  28771. }
  28772. END_JUCE_NAMESPACE
  28773. #endif
  28774. #undef log
  28775. #endif
  28776. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28777. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28778. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28779. BEGIN_JUCE_NAMESPACE
  28780. AudioProcessor::AudioProcessor()
  28781. : playHead (0),
  28782. activeEditor (0),
  28783. sampleRate (0),
  28784. blockSize (0),
  28785. numInputChannels (0),
  28786. numOutputChannels (0),
  28787. latencySamples (0),
  28788. suspended (false),
  28789. nonRealtime (false)
  28790. {
  28791. }
  28792. AudioProcessor::~AudioProcessor()
  28793. {
  28794. // ooh, nasty - the editor should have been deleted before the filter
  28795. // that it refers to is deleted..
  28796. jassert (activeEditor == 0);
  28797. #if JUCE_DEBUG
  28798. // This will fail if you've called beginParameterChangeGesture() for one
  28799. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28800. jassert (changingParams.countNumberOfSetBits() == 0);
  28801. #endif
  28802. }
  28803. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28804. {
  28805. playHead = newPlayHead;
  28806. }
  28807. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28808. {
  28809. const ScopedLock sl (listenerLock);
  28810. listeners.addIfNotAlreadyThere (newListener);
  28811. }
  28812. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28813. {
  28814. const ScopedLock sl (listenerLock);
  28815. listeners.removeValue (listenerToRemove);
  28816. }
  28817. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28818. const int numOuts,
  28819. const double sampleRate_,
  28820. const int blockSize_) throw()
  28821. {
  28822. numInputChannels = numIns;
  28823. numOutputChannels = numOuts;
  28824. sampleRate = sampleRate_;
  28825. blockSize = blockSize_;
  28826. }
  28827. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28828. {
  28829. nonRealtime = nonRealtime_;
  28830. }
  28831. void AudioProcessor::setLatencySamples (const int newLatency)
  28832. {
  28833. if (latencySamples != newLatency)
  28834. {
  28835. latencySamples = newLatency;
  28836. updateHostDisplay();
  28837. }
  28838. }
  28839. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28840. const float newValue)
  28841. {
  28842. setParameter (parameterIndex, newValue);
  28843. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28844. }
  28845. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28846. {
  28847. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28848. for (int i = listeners.size(); --i >= 0;)
  28849. {
  28850. AudioProcessorListener* l;
  28851. {
  28852. const ScopedLock sl (listenerLock);
  28853. l = listeners [i];
  28854. }
  28855. if (l != 0)
  28856. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28857. }
  28858. }
  28859. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28860. {
  28861. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28862. #if JUCE_DEBUG
  28863. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28864. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28865. jassert (! changingParams [parameterIndex]);
  28866. changingParams.setBit (parameterIndex);
  28867. #endif
  28868. for (int i = listeners.size(); --i >= 0;)
  28869. {
  28870. AudioProcessorListener* l;
  28871. {
  28872. const ScopedLock sl (listenerLock);
  28873. l = listeners [i];
  28874. }
  28875. if (l != 0)
  28876. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28877. }
  28878. }
  28879. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28880. {
  28881. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28882. #if JUCE_DEBUG
  28883. // This means you've called endParameterChangeGesture without having previously called
  28884. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28885. // calls matched correctly.
  28886. jassert (changingParams [parameterIndex]);
  28887. changingParams.clearBit (parameterIndex);
  28888. #endif
  28889. for (int i = listeners.size(); --i >= 0;)
  28890. {
  28891. AudioProcessorListener* l;
  28892. {
  28893. const ScopedLock sl (listenerLock);
  28894. l = listeners [i];
  28895. }
  28896. if (l != 0)
  28897. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28898. }
  28899. }
  28900. void AudioProcessor::updateHostDisplay()
  28901. {
  28902. for (int i = listeners.size(); --i >= 0;)
  28903. {
  28904. AudioProcessorListener* l;
  28905. {
  28906. const ScopedLock sl (listenerLock);
  28907. l = listeners [i];
  28908. }
  28909. if (l != 0)
  28910. l->audioProcessorChanged (this);
  28911. }
  28912. }
  28913. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28914. {
  28915. return true;
  28916. }
  28917. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28918. {
  28919. return false;
  28920. }
  28921. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28922. {
  28923. const ScopedLock sl (callbackLock);
  28924. suspended = shouldBeSuspended;
  28925. }
  28926. void AudioProcessor::reset()
  28927. {
  28928. }
  28929. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28930. {
  28931. const ScopedLock sl (callbackLock);
  28932. jassert (activeEditor == editor);
  28933. if (activeEditor == editor)
  28934. activeEditor = 0;
  28935. }
  28936. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28937. {
  28938. if (activeEditor != 0)
  28939. return activeEditor;
  28940. AudioProcessorEditor* const ed = createEditor();
  28941. // You must make your hasEditor() method return a consistent result!
  28942. jassert (hasEditor() == (ed != 0));
  28943. if (ed != 0)
  28944. {
  28945. // you must give your editor comp a size before returning it..
  28946. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28947. const ScopedLock sl (callbackLock);
  28948. activeEditor = ed;
  28949. }
  28950. return ed;
  28951. }
  28952. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28953. {
  28954. getStateInformation (destData);
  28955. }
  28956. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28957. {
  28958. setStateInformation (data, sizeInBytes);
  28959. }
  28960. // magic number to identify memory blocks that we've stored as XML
  28961. const uint32 magicXmlNumber = 0x21324356;
  28962. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28963. JUCE_NAMESPACE::MemoryBlock& destData)
  28964. {
  28965. const String xmlString (xml.createDocument (String::empty, true, false));
  28966. const int stringLength = xmlString.getNumBytesAsUTF8();
  28967. destData.setSize (stringLength + 10);
  28968. char* const d = static_cast<char*> (destData.getData());
  28969. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28970. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28971. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28972. }
  28973. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28974. const int sizeInBytes)
  28975. {
  28976. if (sizeInBytes > 8
  28977. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28978. {
  28979. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28980. if (stringLength > 0)
  28981. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28982. jmin ((sizeInBytes - 8), stringLength)));
  28983. }
  28984. return 0;
  28985. }
  28986. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28987. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28988. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28989. {
  28990. return timeInSeconds == other.timeInSeconds
  28991. && ppqPosition == other.ppqPosition
  28992. && editOriginTime == other.editOriginTime
  28993. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28994. && frameRate == other.frameRate
  28995. && isPlaying == other.isPlaying
  28996. && isRecording == other.isRecording
  28997. && bpm == other.bpm
  28998. && timeSigNumerator == other.timeSigNumerator
  28999. && timeSigDenominator == other.timeSigDenominator;
  29000. }
  29001. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  29002. {
  29003. return ! operator== (other);
  29004. }
  29005. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  29006. {
  29007. zerostruct (*this);
  29008. timeSigNumerator = 4;
  29009. timeSigDenominator = 4;
  29010. bpm = 120;
  29011. }
  29012. END_JUCE_NAMESPACE
  29013. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  29014. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  29015. BEGIN_JUCE_NAMESPACE
  29016. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  29017. : owner (owner_)
  29018. {
  29019. // the filter must be valid..
  29020. jassert (owner != 0);
  29021. }
  29022. AudioProcessorEditor::~AudioProcessorEditor()
  29023. {
  29024. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  29025. // filter for some reason..
  29026. jassert (owner->getActiveEditor() != this);
  29027. }
  29028. END_JUCE_NAMESPACE
  29029. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  29030. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  29031. BEGIN_JUCE_NAMESPACE
  29032. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  29033. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  29034. : id (id_),
  29035. processor (processor_),
  29036. isPrepared (false)
  29037. {
  29038. jassert (processor_ != 0);
  29039. }
  29040. AudioProcessorGraph::Node::~Node()
  29041. {
  29042. }
  29043. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  29044. AudioProcessorGraph* const graph)
  29045. {
  29046. if (! isPrepared)
  29047. {
  29048. isPrepared = true;
  29049. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29050. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  29051. if (ioProc != 0)
  29052. ioProc->setParentGraph (graph);
  29053. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  29054. processor->getNumOutputChannels(),
  29055. sampleRate, blockSize);
  29056. processor->prepareToPlay (sampleRate, blockSize);
  29057. }
  29058. }
  29059. void AudioProcessorGraph::Node::unprepare()
  29060. {
  29061. if (isPrepared)
  29062. {
  29063. isPrepared = false;
  29064. processor->releaseResources();
  29065. }
  29066. }
  29067. AudioProcessorGraph::AudioProcessorGraph()
  29068. : lastNodeId (0),
  29069. renderingBuffers (1, 1),
  29070. currentAudioOutputBuffer (1, 1)
  29071. {
  29072. }
  29073. AudioProcessorGraph::~AudioProcessorGraph()
  29074. {
  29075. clearRenderingSequence();
  29076. clear();
  29077. }
  29078. const String AudioProcessorGraph::getName() const
  29079. {
  29080. return "Audio Graph";
  29081. }
  29082. void AudioProcessorGraph::clear()
  29083. {
  29084. nodes.clear();
  29085. connections.clear();
  29086. triggerAsyncUpdate();
  29087. }
  29088. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  29089. {
  29090. for (int i = nodes.size(); --i >= 0;)
  29091. if (nodes.getUnchecked(i)->id == nodeId)
  29092. return nodes.getUnchecked(i);
  29093. return 0;
  29094. }
  29095. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  29096. uint32 nodeId)
  29097. {
  29098. if (newProcessor == 0)
  29099. {
  29100. jassertfalse;
  29101. return 0;
  29102. }
  29103. if (nodeId == 0)
  29104. {
  29105. nodeId = ++lastNodeId;
  29106. }
  29107. else
  29108. {
  29109. // you can't add a node with an id that already exists in the graph..
  29110. jassert (getNodeForId (nodeId) == 0);
  29111. removeNode (nodeId);
  29112. }
  29113. lastNodeId = nodeId;
  29114. Node* const n = new Node (nodeId, newProcessor);
  29115. nodes.add (n);
  29116. triggerAsyncUpdate();
  29117. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29118. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29119. if (ioProc != 0)
  29120. ioProc->setParentGraph (this);
  29121. return n;
  29122. }
  29123. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29124. {
  29125. disconnectNode (nodeId);
  29126. for (int i = nodes.size(); --i >= 0;)
  29127. {
  29128. if (nodes.getUnchecked(i)->id == nodeId)
  29129. {
  29130. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29131. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29132. if (ioProc != 0)
  29133. ioProc->setParentGraph (0);
  29134. nodes.remove (i);
  29135. triggerAsyncUpdate();
  29136. return true;
  29137. }
  29138. }
  29139. return false;
  29140. }
  29141. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29142. const int sourceChannelIndex,
  29143. const uint32 destNodeId,
  29144. const int destChannelIndex) const
  29145. {
  29146. for (int i = connections.size(); --i >= 0;)
  29147. {
  29148. const Connection* const c = connections.getUnchecked(i);
  29149. if (c->sourceNodeId == sourceNodeId
  29150. && c->destNodeId == destNodeId
  29151. && c->sourceChannelIndex == sourceChannelIndex
  29152. && c->destChannelIndex == destChannelIndex)
  29153. {
  29154. return c;
  29155. }
  29156. }
  29157. return 0;
  29158. }
  29159. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29160. const uint32 possibleDestNodeId) const
  29161. {
  29162. for (int i = connections.size(); --i >= 0;)
  29163. {
  29164. const Connection* const c = connections.getUnchecked(i);
  29165. if (c->sourceNodeId == possibleSourceNodeId
  29166. && c->destNodeId == possibleDestNodeId)
  29167. {
  29168. return true;
  29169. }
  29170. }
  29171. return false;
  29172. }
  29173. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29174. const int sourceChannelIndex,
  29175. const uint32 destNodeId,
  29176. const int destChannelIndex) const
  29177. {
  29178. if (sourceChannelIndex < 0
  29179. || destChannelIndex < 0
  29180. || sourceNodeId == destNodeId
  29181. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29182. return false;
  29183. const Node* const source = getNodeForId (sourceNodeId);
  29184. if (source == 0
  29185. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29186. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29187. return false;
  29188. const Node* const dest = getNodeForId (destNodeId);
  29189. if (dest == 0
  29190. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29191. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29192. return false;
  29193. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29194. destNodeId, destChannelIndex) == 0;
  29195. }
  29196. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29197. const int sourceChannelIndex,
  29198. const uint32 destNodeId,
  29199. const int destChannelIndex)
  29200. {
  29201. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29202. return false;
  29203. Connection* const c = new Connection();
  29204. c->sourceNodeId = sourceNodeId;
  29205. c->sourceChannelIndex = sourceChannelIndex;
  29206. c->destNodeId = destNodeId;
  29207. c->destChannelIndex = destChannelIndex;
  29208. connections.add (c);
  29209. triggerAsyncUpdate();
  29210. return true;
  29211. }
  29212. void AudioProcessorGraph::removeConnection (const int index)
  29213. {
  29214. connections.remove (index);
  29215. triggerAsyncUpdate();
  29216. }
  29217. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29218. const uint32 destNodeId, const int destChannelIndex)
  29219. {
  29220. bool doneAnything = false;
  29221. for (int i = connections.size(); --i >= 0;)
  29222. {
  29223. const Connection* const c = connections.getUnchecked(i);
  29224. if (c->sourceNodeId == sourceNodeId
  29225. && c->destNodeId == destNodeId
  29226. && c->sourceChannelIndex == sourceChannelIndex
  29227. && c->destChannelIndex == destChannelIndex)
  29228. {
  29229. removeConnection (i);
  29230. doneAnything = true;
  29231. triggerAsyncUpdate();
  29232. }
  29233. }
  29234. return doneAnything;
  29235. }
  29236. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29237. {
  29238. bool doneAnything = false;
  29239. for (int i = connections.size(); --i >= 0;)
  29240. {
  29241. const Connection* const c = connections.getUnchecked(i);
  29242. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29243. {
  29244. removeConnection (i);
  29245. doneAnything = true;
  29246. triggerAsyncUpdate();
  29247. }
  29248. }
  29249. return doneAnything;
  29250. }
  29251. bool AudioProcessorGraph::removeIllegalConnections()
  29252. {
  29253. bool doneAnything = false;
  29254. for (int i = connections.size(); --i >= 0;)
  29255. {
  29256. const Connection* const c = connections.getUnchecked(i);
  29257. const Node* const source = getNodeForId (c->sourceNodeId);
  29258. const Node* const dest = getNodeForId (c->destNodeId);
  29259. if (source == 0 || dest == 0
  29260. || (c->sourceChannelIndex != midiChannelIndex
  29261. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29262. || (c->sourceChannelIndex == midiChannelIndex
  29263. && ! source->processor->producesMidi())
  29264. || (c->destChannelIndex != midiChannelIndex
  29265. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29266. || (c->destChannelIndex == midiChannelIndex
  29267. && ! dest->processor->acceptsMidi()))
  29268. {
  29269. removeConnection (i);
  29270. doneAnything = true;
  29271. triggerAsyncUpdate();
  29272. }
  29273. }
  29274. return doneAnything;
  29275. }
  29276. namespace GraphRenderingOps
  29277. {
  29278. class AudioGraphRenderingOp
  29279. {
  29280. public:
  29281. AudioGraphRenderingOp() {}
  29282. virtual ~AudioGraphRenderingOp() {}
  29283. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29284. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29285. const int numSamples) = 0;
  29286. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  29287. };
  29288. class ClearChannelOp : public AudioGraphRenderingOp
  29289. {
  29290. public:
  29291. ClearChannelOp (const int channelNum_)
  29292. : channelNum (channelNum_)
  29293. {}
  29294. ~ClearChannelOp() {}
  29295. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29296. {
  29297. sharedBufferChans.clear (channelNum, 0, numSamples);
  29298. }
  29299. private:
  29300. const int channelNum;
  29301. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  29302. };
  29303. class CopyChannelOp : public AudioGraphRenderingOp
  29304. {
  29305. public:
  29306. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29307. : srcChannelNum (srcChannelNum_),
  29308. dstChannelNum (dstChannelNum_)
  29309. {}
  29310. ~CopyChannelOp() {}
  29311. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29312. {
  29313. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29314. }
  29315. private:
  29316. const int srcChannelNum, dstChannelNum;
  29317. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29318. };
  29319. class AddChannelOp : public AudioGraphRenderingOp
  29320. {
  29321. public:
  29322. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29323. : srcChannelNum (srcChannelNum_),
  29324. dstChannelNum (dstChannelNum_)
  29325. {}
  29326. ~AddChannelOp() {}
  29327. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29328. {
  29329. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29330. }
  29331. private:
  29332. const int srcChannelNum, dstChannelNum;
  29333. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29334. };
  29335. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29336. {
  29337. public:
  29338. ClearMidiBufferOp (const int bufferNum_)
  29339. : bufferNum (bufferNum_)
  29340. {}
  29341. ~ClearMidiBufferOp() {}
  29342. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29343. {
  29344. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29345. }
  29346. private:
  29347. const int bufferNum;
  29348. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29349. };
  29350. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29351. {
  29352. public:
  29353. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29354. : srcBufferNum (srcBufferNum_),
  29355. dstBufferNum (dstBufferNum_)
  29356. {}
  29357. ~CopyMidiBufferOp() {}
  29358. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29359. {
  29360. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29361. }
  29362. private:
  29363. const int srcBufferNum, dstBufferNum;
  29364. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29365. };
  29366. class AddMidiBufferOp : public AudioGraphRenderingOp
  29367. {
  29368. public:
  29369. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29370. : srcBufferNum (srcBufferNum_),
  29371. dstBufferNum (dstBufferNum_)
  29372. {}
  29373. ~AddMidiBufferOp() {}
  29374. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29375. {
  29376. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29377. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29378. }
  29379. private:
  29380. const int srcBufferNum, dstBufferNum;
  29381. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29382. };
  29383. class ProcessBufferOp : public AudioGraphRenderingOp
  29384. {
  29385. public:
  29386. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29387. const Array <int>& audioChannelsToUse_,
  29388. const int totalChans_,
  29389. const int midiBufferToUse_)
  29390. : node (node_),
  29391. processor (node_->getProcessor()),
  29392. audioChannelsToUse (audioChannelsToUse_),
  29393. totalChans (jmax (1, totalChans_)),
  29394. midiBufferToUse (midiBufferToUse_)
  29395. {
  29396. channels.calloc (totalChans);
  29397. while (audioChannelsToUse.size() < totalChans)
  29398. audioChannelsToUse.add (0);
  29399. }
  29400. ~ProcessBufferOp()
  29401. {
  29402. }
  29403. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29404. {
  29405. for (int i = totalChans; --i >= 0;)
  29406. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29407. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29408. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29409. }
  29410. const AudioProcessorGraph::Node::Ptr node;
  29411. AudioProcessor* const processor;
  29412. private:
  29413. Array <int> audioChannelsToUse;
  29414. HeapBlock <float*> channels;
  29415. int totalChans;
  29416. int midiBufferToUse;
  29417. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29418. };
  29419. /** Used to calculate the correct sequence of rendering ops needed, based on
  29420. the best re-use of shared buffers at each stage.
  29421. */
  29422. class RenderingOpSequenceCalculator
  29423. {
  29424. public:
  29425. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29426. const Array<void*>& orderedNodes_,
  29427. Array<void*>& renderingOps)
  29428. : graph (graph_),
  29429. orderedNodes (orderedNodes_)
  29430. {
  29431. nodeIds.add (-2); // first buffer is read-only zeros
  29432. channels.add (0);
  29433. midiNodeIds.add (-2);
  29434. for (int i = 0; i < orderedNodes.size(); ++i)
  29435. {
  29436. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29437. renderingOps, i);
  29438. markAnyUnusedBuffersAsFree (i);
  29439. }
  29440. }
  29441. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29442. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29443. private:
  29444. AudioProcessorGraph& graph;
  29445. const Array<void*>& orderedNodes;
  29446. Array <int> nodeIds, channels, midiNodeIds;
  29447. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29448. Array<void*>& renderingOps,
  29449. const int ourRenderingIndex)
  29450. {
  29451. const int numIns = node->getProcessor()->getNumInputChannels();
  29452. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29453. const int totalChans = jmax (numIns, numOuts);
  29454. Array <int> audioChannelsToUse;
  29455. int midiBufferToUse = -1;
  29456. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29457. {
  29458. // get a list of all the inputs to this node
  29459. Array <int> sourceNodes, sourceOutputChans;
  29460. for (int i = graph.getNumConnections(); --i >= 0;)
  29461. {
  29462. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29463. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29464. {
  29465. sourceNodes.add (c->sourceNodeId);
  29466. sourceOutputChans.add (c->sourceChannelIndex);
  29467. }
  29468. }
  29469. int bufIndex = -1;
  29470. if (sourceNodes.size() == 0)
  29471. {
  29472. // unconnected input channel
  29473. if (inputChan >= numOuts)
  29474. {
  29475. bufIndex = getReadOnlyEmptyBuffer();
  29476. jassert (bufIndex >= 0);
  29477. }
  29478. else
  29479. {
  29480. bufIndex = getFreeBuffer (false);
  29481. renderingOps.add (new ClearChannelOp (bufIndex));
  29482. }
  29483. }
  29484. else if (sourceNodes.size() == 1)
  29485. {
  29486. // channel with a straightforward single input..
  29487. const int srcNode = sourceNodes.getUnchecked(0);
  29488. const int srcChan = sourceOutputChans.getUnchecked(0);
  29489. bufIndex = getBufferContaining (srcNode, srcChan);
  29490. if (bufIndex < 0)
  29491. {
  29492. // if not found, this is probably a feedback loop
  29493. bufIndex = getReadOnlyEmptyBuffer();
  29494. jassert (bufIndex >= 0);
  29495. }
  29496. if (inputChan < numOuts
  29497. && isBufferNeededLater (ourRenderingIndex,
  29498. inputChan,
  29499. srcNode, srcChan))
  29500. {
  29501. // can't mess up this channel because it's needed later by another node, so we
  29502. // need to use a copy of it..
  29503. const int newFreeBuffer = getFreeBuffer (false);
  29504. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29505. bufIndex = newFreeBuffer;
  29506. }
  29507. }
  29508. else
  29509. {
  29510. // channel with a mix of several inputs..
  29511. // try to find a re-usable channel from our inputs..
  29512. int reusableInputIndex = -1;
  29513. for (int i = 0; i < sourceNodes.size(); ++i)
  29514. {
  29515. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29516. sourceOutputChans.getUnchecked(i));
  29517. if (sourceBufIndex >= 0
  29518. && ! isBufferNeededLater (ourRenderingIndex,
  29519. inputChan,
  29520. sourceNodes.getUnchecked(i),
  29521. sourceOutputChans.getUnchecked(i)))
  29522. {
  29523. // we've found one of our input chans that can be re-used..
  29524. reusableInputIndex = i;
  29525. bufIndex = sourceBufIndex;
  29526. break;
  29527. }
  29528. }
  29529. if (reusableInputIndex < 0)
  29530. {
  29531. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29532. bufIndex = getFreeBuffer (false);
  29533. jassert (bufIndex != 0);
  29534. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29535. sourceOutputChans.getUnchecked (0));
  29536. if (srcIndex < 0)
  29537. {
  29538. // if not found, this is probably a feedback loop
  29539. renderingOps.add (new ClearChannelOp (bufIndex));
  29540. }
  29541. else
  29542. {
  29543. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29544. }
  29545. reusableInputIndex = 0;
  29546. }
  29547. for (int j = 0; j < sourceNodes.size(); ++j)
  29548. {
  29549. if (j != reusableInputIndex)
  29550. {
  29551. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29552. sourceOutputChans.getUnchecked(j));
  29553. if (srcIndex >= 0)
  29554. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29555. }
  29556. }
  29557. }
  29558. jassert (bufIndex >= 0);
  29559. audioChannelsToUse.add (bufIndex);
  29560. if (inputChan < numOuts)
  29561. markBufferAsContaining (bufIndex, node->id, inputChan);
  29562. }
  29563. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29564. {
  29565. const int bufIndex = getFreeBuffer (false);
  29566. jassert (bufIndex != 0);
  29567. audioChannelsToUse.add (bufIndex);
  29568. markBufferAsContaining (bufIndex, node->id, outputChan);
  29569. }
  29570. // Now the same thing for midi..
  29571. Array <int> midiSourceNodes;
  29572. for (int i = graph.getNumConnections(); --i >= 0;)
  29573. {
  29574. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29575. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29576. midiSourceNodes.add (c->sourceNodeId);
  29577. }
  29578. if (midiSourceNodes.size() == 0)
  29579. {
  29580. // No midi inputs..
  29581. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29582. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29583. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29584. }
  29585. else if (midiSourceNodes.size() == 1)
  29586. {
  29587. // One midi input..
  29588. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29589. AudioProcessorGraph::midiChannelIndex);
  29590. if (midiBufferToUse >= 0)
  29591. {
  29592. if (isBufferNeededLater (ourRenderingIndex,
  29593. AudioProcessorGraph::midiChannelIndex,
  29594. midiSourceNodes.getUnchecked(0),
  29595. AudioProcessorGraph::midiChannelIndex))
  29596. {
  29597. // can't mess up this channel because it's needed later by another node, so we
  29598. // need to use a copy of it..
  29599. const int newFreeBuffer = getFreeBuffer (true);
  29600. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29601. midiBufferToUse = newFreeBuffer;
  29602. }
  29603. }
  29604. else
  29605. {
  29606. // probably a feedback loop, so just use an empty one..
  29607. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29608. }
  29609. }
  29610. else
  29611. {
  29612. // More than one midi input being mixed..
  29613. int reusableInputIndex = -1;
  29614. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29615. {
  29616. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29617. AudioProcessorGraph::midiChannelIndex);
  29618. if (sourceBufIndex >= 0
  29619. && ! isBufferNeededLater (ourRenderingIndex,
  29620. AudioProcessorGraph::midiChannelIndex,
  29621. midiSourceNodes.getUnchecked(i),
  29622. AudioProcessorGraph::midiChannelIndex))
  29623. {
  29624. // we've found one of our input buffers that can be re-used..
  29625. reusableInputIndex = i;
  29626. midiBufferToUse = sourceBufIndex;
  29627. break;
  29628. }
  29629. }
  29630. if (reusableInputIndex < 0)
  29631. {
  29632. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29633. midiBufferToUse = getFreeBuffer (true);
  29634. jassert (midiBufferToUse >= 0);
  29635. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29636. AudioProcessorGraph::midiChannelIndex);
  29637. if (srcIndex >= 0)
  29638. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29639. else
  29640. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29641. reusableInputIndex = 0;
  29642. }
  29643. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29644. {
  29645. if (j != reusableInputIndex)
  29646. {
  29647. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29648. AudioProcessorGraph::midiChannelIndex);
  29649. if (srcIndex >= 0)
  29650. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29651. }
  29652. }
  29653. }
  29654. if (node->getProcessor()->producesMidi())
  29655. markBufferAsContaining (midiBufferToUse, node->id,
  29656. AudioProcessorGraph::midiChannelIndex);
  29657. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29658. totalChans, midiBufferToUse));
  29659. }
  29660. int getFreeBuffer (const bool forMidi)
  29661. {
  29662. if (forMidi)
  29663. {
  29664. for (int i = 1; i < midiNodeIds.size(); ++i)
  29665. if (midiNodeIds.getUnchecked(i) < 0)
  29666. return i;
  29667. midiNodeIds.add (-1);
  29668. return midiNodeIds.size() - 1;
  29669. }
  29670. else
  29671. {
  29672. for (int i = 1; i < nodeIds.size(); ++i)
  29673. if (nodeIds.getUnchecked(i) < 0)
  29674. return i;
  29675. nodeIds.add (-1);
  29676. channels.add (0);
  29677. return nodeIds.size() - 1;
  29678. }
  29679. }
  29680. int getReadOnlyEmptyBuffer() const
  29681. {
  29682. return 0;
  29683. }
  29684. int getBufferContaining (const int nodeId, const int outputChannel) const
  29685. {
  29686. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29687. {
  29688. for (int i = midiNodeIds.size(); --i >= 0;)
  29689. if (midiNodeIds.getUnchecked(i) == nodeId)
  29690. return i;
  29691. }
  29692. else
  29693. {
  29694. for (int i = nodeIds.size(); --i >= 0;)
  29695. if (nodeIds.getUnchecked(i) == nodeId
  29696. && channels.getUnchecked(i) == outputChannel)
  29697. return i;
  29698. }
  29699. return -1;
  29700. }
  29701. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29702. {
  29703. int i;
  29704. for (i = 0; i < nodeIds.size(); ++i)
  29705. {
  29706. if (nodeIds.getUnchecked(i) >= 0
  29707. && ! isBufferNeededLater (stepIndex, -1,
  29708. nodeIds.getUnchecked(i),
  29709. channels.getUnchecked(i)))
  29710. {
  29711. nodeIds.set (i, -1);
  29712. }
  29713. }
  29714. for (i = 0; i < midiNodeIds.size(); ++i)
  29715. {
  29716. if (midiNodeIds.getUnchecked(i) >= 0
  29717. && ! isBufferNeededLater (stepIndex, -1,
  29718. midiNodeIds.getUnchecked(i),
  29719. AudioProcessorGraph::midiChannelIndex))
  29720. {
  29721. midiNodeIds.set (i, -1);
  29722. }
  29723. }
  29724. }
  29725. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29726. int inputChannelOfIndexToIgnore,
  29727. const int nodeId,
  29728. const int outputChanIndex) const
  29729. {
  29730. while (stepIndexToSearchFrom < orderedNodes.size())
  29731. {
  29732. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29733. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29734. {
  29735. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29736. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29737. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29738. return true;
  29739. }
  29740. else
  29741. {
  29742. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29743. if (i != inputChannelOfIndexToIgnore
  29744. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29745. node->id, i) != 0)
  29746. return true;
  29747. }
  29748. inputChannelOfIndexToIgnore = -1;
  29749. ++stepIndexToSearchFrom;
  29750. }
  29751. return false;
  29752. }
  29753. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29754. {
  29755. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29756. {
  29757. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29758. midiNodeIds.set (bufferNum, nodeId);
  29759. }
  29760. else
  29761. {
  29762. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29763. nodeIds.set (bufferNum, nodeId);
  29764. channels.set (bufferNum, outputIndex);
  29765. }
  29766. }
  29767. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29768. };
  29769. }
  29770. void AudioProcessorGraph::clearRenderingSequence()
  29771. {
  29772. const ScopedLock sl (renderLock);
  29773. for (int i = renderingOps.size(); --i >= 0;)
  29774. {
  29775. GraphRenderingOps::AudioGraphRenderingOp* const r
  29776. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29777. renderingOps.remove (i);
  29778. delete r;
  29779. }
  29780. }
  29781. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29782. const uint32 possibleDestinationId,
  29783. const int recursionCheck) const
  29784. {
  29785. if (recursionCheck > 0)
  29786. {
  29787. for (int i = connections.size(); --i >= 0;)
  29788. {
  29789. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29790. if (c->destNodeId == possibleDestinationId
  29791. && (c->sourceNodeId == possibleInputId
  29792. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29793. return true;
  29794. }
  29795. }
  29796. return false;
  29797. }
  29798. void AudioProcessorGraph::buildRenderingSequence()
  29799. {
  29800. Array<void*> newRenderingOps;
  29801. int numRenderingBuffersNeeded = 2;
  29802. int numMidiBuffersNeeded = 1;
  29803. {
  29804. MessageManagerLock mml;
  29805. Array<void*> orderedNodes;
  29806. int i;
  29807. for (i = 0; i < nodes.size(); ++i)
  29808. {
  29809. Node* const node = nodes.getUnchecked(i);
  29810. node->prepare (getSampleRate(), getBlockSize(), this);
  29811. int j = 0;
  29812. for (; j < orderedNodes.size(); ++j)
  29813. if (isAnInputTo (node->id,
  29814. ((Node*) orderedNodes.getUnchecked (j))->id,
  29815. nodes.size() + 1))
  29816. break;
  29817. orderedNodes.insert (j, node);
  29818. }
  29819. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29820. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29821. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29822. }
  29823. Array<void*> oldRenderingOps (renderingOps);
  29824. {
  29825. // swap over to the new rendering sequence..
  29826. const ScopedLock sl (renderLock);
  29827. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29828. renderingBuffers.clear();
  29829. for (int i = midiBuffers.size(); --i >= 0;)
  29830. midiBuffers.getUnchecked(i)->clear();
  29831. while (midiBuffers.size() < numMidiBuffersNeeded)
  29832. midiBuffers.add (new MidiBuffer());
  29833. renderingOps = newRenderingOps;
  29834. }
  29835. for (int i = oldRenderingOps.size(); --i >= 0;)
  29836. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29837. }
  29838. void AudioProcessorGraph::handleAsyncUpdate()
  29839. {
  29840. buildRenderingSequence();
  29841. }
  29842. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29843. {
  29844. currentAudioInputBuffer = 0;
  29845. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29846. currentMidiInputBuffer = 0;
  29847. currentMidiOutputBuffer.clear();
  29848. clearRenderingSequence();
  29849. buildRenderingSequence();
  29850. }
  29851. void AudioProcessorGraph::releaseResources()
  29852. {
  29853. for (int i = 0; i < nodes.size(); ++i)
  29854. nodes.getUnchecked(i)->unprepare();
  29855. renderingBuffers.setSize (1, 1);
  29856. midiBuffers.clear();
  29857. currentAudioInputBuffer = 0;
  29858. currentAudioOutputBuffer.setSize (1, 1);
  29859. currentMidiInputBuffer = 0;
  29860. currentMidiOutputBuffer.clear();
  29861. }
  29862. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29863. {
  29864. const int numSamples = buffer.getNumSamples();
  29865. const ScopedLock sl (renderLock);
  29866. currentAudioInputBuffer = &buffer;
  29867. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29868. currentAudioOutputBuffer.clear();
  29869. currentMidiInputBuffer = &midiMessages;
  29870. currentMidiOutputBuffer.clear();
  29871. int i;
  29872. for (i = 0; i < renderingOps.size(); ++i)
  29873. {
  29874. GraphRenderingOps::AudioGraphRenderingOp* const op
  29875. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29876. op->perform (renderingBuffers, midiBuffers, numSamples);
  29877. }
  29878. for (i = 0; i < buffer.getNumChannels(); ++i)
  29879. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29880. midiMessages.clear();
  29881. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29882. }
  29883. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29884. {
  29885. return "Input " + String (channelIndex + 1);
  29886. }
  29887. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29888. {
  29889. return "Output " + String (channelIndex + 1);
  29890. }
  29891. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29892. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29893. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29894. bool AudioProcessorGraph::producesMidi() const { return true; }
  29895. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29896. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29897. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29898. : type (type_),
  29899. graph (0)
  29900. {
  29901. }
  29902. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29903. {
  29904. }
  29905. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29906. {
  29907. switch (type)
  29908. {
  29909. case audioOutputNode: return "Audio Output";
  29910. case audioInputNode: return "Audio Input";
  29911. case midiOutputNode: return "Midi Output";
  29912. case midiInputNode: return "Midi Input";
  29913. default: break;
  29914. }
  29915. return String::empty;
  29916. }
  29917. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29918. {
  29919. d.name = getName();
  29920. d.uid = d.name.hashCode();
  29921. d.category = "I/O devices";
  29922. d.pluginFormatName = "Internal";
  29923. d.manufacturerName = "Raw Material Software";
  29924. d.version = "1.0";
  29925. d.isInstrument = false;
  29926. d.numInputChannels = getNumInputChannels();
  29927. if (type == audioOutputNode && graph != 0)
  29928. d.numInputChannels = graph->getNumInputChannels();
  29929. d.numOutputChannels = getNumOutputChannels();
  29930. if (type == audioInputNode && graph != 0)
  29931. d.numOutputChannels = graph->getNumOutputChannels();
  29932. }
  29933. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29934. {
  29935. jassert (graph != 0);
  29936. }
  29937. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29938. {
  29939. }
  29940. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29941. MidiBuffer& midiMessages)
  29942. {
  29943. jassert (graph != 0);
  29944. switch (type)
  29945. {
  29946. case audioOutputNode:
  29947. {
  29948. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29949. buffer.getNumChannels()); --i >= 0;)
  29950. {
  29951. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29952. }
  29953. break;
  29954. }
  29955. case audioInputNode:
  29956. {
  29957. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29958. buffer.getNumChannels()); --i >= 0;)
  29959. {
  29960. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29961. }
  29962. break;
  29963. }
  29964. case midiOutputNode:
  29965. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29966. break;
  29967. case midiInputNode:
  29968. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29969. break;
  29970. default:
  29971. break;
  29972. }
  29973. }
  29974. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29975. {
  29976. return type == midiOutputNode;
  29977. }
  29978. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29979. {
  29980. return type == midiInputNode;
  29981. }
  29982. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29983. {
  29984. switch (type)
  29985. {
  29986. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29987. case midiOutputNode: return "Midi Output";
  29988. default: break;
  29989. }
  29990. return String::empty;
  29991. }
  29992. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29993. {
  29994. switch (type)
  29995. {
  29996. case audioInputNode: return "Input " + String (channelIndex + 1);
  29997. case midiInputNode: return "Midi Input";
  29998. default: break;
  29999. }
  30000. return String::empty;
  30001. }
  30002. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  30003. {
  30004. return type == audioInputNode || type == audioOutputNode;
  30005. }
  30006. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  30007. {
  30008. return isInputChannelStereoPair (index);
  30009. }
  30010. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  30011. {
  30012. return type == audioInputNode || type == midiInputNode;
  30013. }
  30014. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  30015. {
  30016. return type == audioOutputNode || type == midiOutputNode;
  30017. }
  30018. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  30019. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  30020. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  30021. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  30022. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  30023. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  30024. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  30025. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  30026. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  30027. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  30028. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  30029. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  30030. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  30031. {
  30032. }
  30033. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  30034. {
  30035. }
  30036. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  30037. {
  30038. graph = newGraph;
  30039. if (graph != 0)
  30040. {
  30041. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  30042. type == audioInputNode ? graph->getNumInputChannels() : 0,
  30043. getSampleRate(),
  30044. getBlockSize());
  30045. updateHostDisplay();
  30046. }
  30047. }
  30048. END_JUCE_NAMESPACE
  30049. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  30050. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30051. BEGIN_JUCE_NAMESPACE
  30052. AudioProcessorPlayer::AudioProcessorPlayer()
  30053. : processor (0),
  30054. sampleRate (0),
  30055. blockSize (0),
  30056. isPrepared (false),
  30057. numInputChans (0),
  30058. numOutputChans (0),
  30059. tempBuffer (1, 1)
  30060. {
  30061. }
  30062. AudioProcessorPlayer::~AudioProcessorPlayer()
  30063. {
  30064. setProcessor (0);
  30065. }
  30066. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  30067. {
  30068. if (processor != processorToPlay)
  30069. {
  30070. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  30071. {
  30072. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  30073. sampleRate, blockSize);
  30074. processorToPlay->prepareToPlay (sampleRate, blockSize);
  30075. }
  30076. AudioProcessor* oldOne;
  30077. {
  30078. const ScopedLock sl (lock);
  30079. oldOne = isPrepared ? processor : 0;
  30080. processor = processorToPlay;
  30081. isPrepared = true;
  30082. }
  30083. if (oldOne != 0)
  30084. oldOne->releaseResources();
  30085. }
  30086. }
  30087. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  30088. const int numInputChannels,
  30089. float** const outputChannelData,
  30090. const int numOutputChannels,
  30091. const int numSamples)
  30092. {
  30093. // these should have been prepared by audioDeviceAboutToStart()...
  30094. jassert (sampleRate > 0 && blockSize > 0);
  30095. incomingMidi.clear();
  30096. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30097. int i, totalNumChans = 0;
  30098. if (numInputChannels > numOutputChannels)
  30099. {
  30100. // if there aren't enough output channels for the number of
  30101. // inputs, we need to create some temporary extra ones (can't
  30102. // use the input data in case it gets written to)
  30103. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30104. false, false, true);
  30105. for (i = 0; i < numOutputChannels; ++i)
  30106. {
  30107. channels[totalNumChans] = outputChannelData[i];
  30108. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30109. ++totalNumChans;
  30110. }
  30111. for (i = numOutputChannels; i < numInputChannels; ++i)
  30112. {
  30113. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30114. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30115. ++totalNumChans;
  30116. }
  30117. }
  30118. else
  30119. {
  30120. for (i = 0; i < numInputChannels; ++i)
  30121. {
  30122. channels[totalNumChans] = outputChannelData[i];
  30123. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30124. ++totalNumChans;
  30125. }
  30126. for (i = numInputChannels; i < numOutputChannels; ++i)
  30127. {
  30128. channels[totalNumChans] = outputChannelData[i];
  30129. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30130. ++totalNumChans;
  30131. }
  30132. }
  30133. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30134. const ScopedLock sl (lock);
  30135. if (processor != 0)
  30136. {
  30137. const ScopedLock sl (processor->getCallbackLock());
  30138. if (processor->isSuspended())
  30139. {
  30140. for (i = 0; i < numOutputChannels; ++i)
  30141. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30142. }
  30143. else
  30144. {
  30145. processor->processBlock (buffer, incomingMidi);
  30146. }
  30147. }
  30148. }
  30149. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30150. {
  30151. const ScopedLock sl (lock);
  30152. sampleRate = device->getCurrentSampleRate();
  30153. blockSize = device->getCurrentBufferSizeSamples();
  30154. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30155. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30156. messageCollector.reset (sampleRate);
  30157. zeromem (channels, sizeof (channels));
  30158. if (processor != 0)
  30159. {
  30160. if (isPrepared)
  30161. processor->releaseResources();
  30162. AudioProcessor* const oldProcessor = processor;
  30163. setProcessor (0);
  30164. setProcessor (oldProcessor);
  30165. }
  30166. }
  30167. void AudioProcessorPlayer::audioDeviceStopped()
  30168. {
  30169. const ScopedLock sl (lock);
  30170. if (processor != 0 && isPrepared)
  30171. processor->releaseResources();
  30172. sampleRate = 0.0;
  30173. blockSize = 0;
  30174. isPrepared = false;
  30175. tempBuffer.setSize (1, 1);
  30176. }
  30177. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30178. {
  30179. messageCollector.addMessageToQueue (message);
  30180. }
  30181. END_JUCE_NAMESPACE
  30182. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30183. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30184. BEGIN_JUCE_NAMESPACE
  30185. class ProcessorParameterPropertyComp : public PropertyComponent,
  30186. public AudioProcessorListener,
  30187. public Timer
  30188. {
  30189. public:
  30190. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  30191. : PropertyComponent (name),
  30192. owner (owner_),
  30193. index (index_),
  30194. paramHasChanged (false),
  30195. slider (owner_, index_)
  30196. {
  30197. startTimer (100);
  30198. addAndMakeVisible (&slider);
  30199. owner_.addListener (this);
  30200. }
  30201. ~ProcessorParameterPropertyComp()
  30202. {
  30203. owner.removeListener (this);
  30204. }
  30205. void refresh()
  30206. {
  30207. paramHasChanged = false;
  30208. slider.setValue (owner.getParameter (index), false);
  30209. }
  30210. void audioProcessorChanged (AudioProcessor*) {}
  30211. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30212. {
  30213. if (parameterIndex == index)
  30214. paramHasChanged = true;
  30215. }
  30216. void timerCallback()
  30217. {
  30218. if (paramHasChanged)
  30219. {
  30220. refresh();
  30221. startTimer (1000 / 50);
  30222. }
  30223. else
  30224. {
  30225. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  30226. }
  30227. }
  30228. private:
  30229. class ParamSlider : public Slider
  30230. {
  30231. public:
  30232. ParamSlider (AudioProcessor& owner_, const int index_)
  30233. : owner (owner_),
  30234. index (index_)
  30235. {
  30236. setRange (0.0, 1.0, 0.0);
  30237. setSliderStyle (Slider::LinearBar);
  30238. setTextBoxIsEditable (false);
  30239. setScrollWheelEnabled (false);
  30240. }
  30241. void valueChanged()
  30242. {
  30243. const float newVal = (float) getValue();
  30244. if (owner.getParameter (index) != newVal)
  30245. owner.setParameter (index, newVal);
  30246. }
  30247. const String getTextFromValue (double /*value*/)
  30248. {
  30249. return owner.getParameterText (index);
  30250. }
  30251. private:
  30252. AudioProcessor& owner;
  30253. const int index;
  30254. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  30255. };
  30256. AudioProcessor& owner;
  30257. const int index;
  30258. bool volatile paramHasChanged;
  30259. ParamSlider slider;
  30260. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  30261. };
  30262. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30263. : AudioProcessorEditor (owner_)
  30264. {
  30265. jassert (owner_ != 0);
  30266. setOpaque (true);
  30267. addAndMakeVisible (&panel);
  30268. Array <PropertyComponent*> params;
  30269. const int numParams = owner_->getNumParameters();
  30270. int totalHeight = 0;
  30271. for (int i = 0; i < numParams; ++i)
  30272. {
  30273. String name (owner_->getParameterName (i));
  30274. if (name.trim().isEmpty())
  30275. name = "Unnamed";
  30276. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30277. params.add (pc);
  30278. totalHeight += pc->getPreferredHeight();
  30279. }
  30280. panel.addProperties (params);
  30281. setSize (400, jlimit (25, 400, totalHeight));
  30282. }
  30283. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30284. {
  30285. }
  30286. void GenericAudioProcessorEditor::paint (Graphics& g)
  30287. {
  30288. g.fillAll (Colours::white);
  30289. }
  30290. void GenericAudioProcessorEditor::resized()
  30291. {
  30292. panel.setBounds (getLocalBounds());
  30293. }
  30294. END_JUCE_NAMESPACE
  30295. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30296. /*** Start of inlined file: juce_Sampler.cpp ***/
  30297. BEGIN_JUCE_NAMESPACE
  30298. SamplerSound::SamplerSound (const String& name_,
  30299. AudioFormatReader& source,
  30300. const BigInteger& midiNotes_,
  30301. const int midiNoteForNormalPitch,
  30302. const double attackTimeSecs,
  30303. const double releaseTimeSecs,
  30304. const double maxSampleLengthSeconds)
  30305. : name (name_),
  30306. midiNotes (midiNotes_),
  30307. midiRootNote (midiNoteForNormalPitch)
  30308. {
  30309. sourceSampleRate = source.sampleRate;
  30310. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30311. {
  30312. length = 0;
  30313. attackSamples = 0;
  30314. releaseSamples = 0;
  30315. }
  30316. else
  30317. {
  30318. length = jmin ((int) source.lengthInSamples,
  30319. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30320. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30321. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30322. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30323. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30324. }
  30325. }
  30326. SamplerSound::~SamplerSound()
  30327. {
  30328. }
  30329. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30330. {
  30331. return midiNotes [midiNoteNumber];
  30332. }
  30333. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30334. {
  30335. return true;
  30336. }
  30337. SamplerVoice::SamplerVoice()
  30338. : pitchRatio (0.0),
  30339. sourceSamplePosition (0.0),
  30340. lgain (0.0f),
  30341. rgain (0.0f),
  30342. isInAttack (false),
  30343. isInRelease (false)
  30344. {
  30345. }
  30346. SamplerVoice::~SamplerVoice()
  30347. {
  30348. }
  30349. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30350. {
  30351. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30352. }
  30353. void SamplerVoice::startNote (const int midiNoteNumber,
  30354. const float velocity,
  30355. SynthesiserSound* s,
  30356. const int /*currentPitchWheelPosition*/)
  30357. {
  30358. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30359. jassert (sound != 0); // this object can only play SamplerSounds!
  30360. if (sound != 0)
  30361. {
  30362. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30363. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30364. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30365. sourceSamplePosition = 0.0;
  30366. lgain = velocity;
  30367. rgain = velocity;
  30368. isInAttack = (sound->attackSamples > 0);
  30369. isInRelease = false;
  30370. if (isInAttack)
  30371. {
  30372. attackReleaseLevel = 0.0f;
  30373. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30374. }
  30375. else
  30376. {
  30377. attackReleaseLevel = 1.0f;
  30378. attackDelta = 0.0f;
  30379. }
  30380. if (sound->releaseSamples > 0)
  30381. {
  30382. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30383. }
  30384. else
  30385. {
  30386. releaseDelta = 0.0f;
  30387. }
  30388. }
  30389. }
  30390. void SamplerVoice::stopNote (const bool allowTailOff)
  30391. {
  30392. if (allowTailOff)
  30393. {
  30394. isInAttack = false;
  30395. isInRelease = true;
  30396. }
  30397. else
  30398. {
  30399. clearCurrentNote();
  30400. }
  30401. }
  30402. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30403. {
  30404. }
  30405. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30406. const int /*newValue*/)
  30407. {
  30408. }
  30409. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30410. {
  30411. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30412. if (playingSound != 0)
  30413. {
  30414. const float* const inL = playingSound->data->getSampleData (0, 0);
  30415. const float* const inR = playingSound->data->getNumChannels() > 1
  30416. ? playingSound->data->getSampleData (1, 0) : 0;
  30417. float* outL = outputBuffer.getSampleData (0, startSample);
  30418. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30419. while (--numSamples >= 0)
  30420. {
  30421. const int pos = (int) sourceSamplePosition;
  30422. const float alpha = (float) (sourceSamplePosition - pos);
  30423. const float invAlpha = 1.0f - alpha;
  30424. // just using a very simple linear interpolation here..
  30425. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30426. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30427. : l;
  30428. l *= lgain;
  30429. r *= rgain;
  30430. if (isInAttack)
  30431. {
  30432. l *= attackReleaseLevel;
  30433. r *= attackReleaseLevel;
  30434. attackReleaseLevel += attackDelta;
  30435. if (attackReleaseLevel >= 1.0f)
  30436. {
  30437. attackReleaseLevel = 1.0f;
  30438. isInAttack = false;
  30439. }
  30440. }
  30441. else if (isInRelease)
  30442. {
  30443. l *= attackReleaseLevel;
  30444. r *= attackReleaseLevel;
  30445. attackReleaseLevel += releaseDelta;
  30446. if (attackReleaseLevel <= 0.0f)
  30447. {
  30448. stopNote (false);
  30449. break;
  30450. }
  30451. }
  30452. if (outR != 0)
  30453. {
  30454. *outL++ += l;
  30455. *outR++ += r;
  30456. }
  30457. else
  30458. {
  30459. *outL++ += (l + r) * 0.5f;
  30460. }
  30461. sourceSamplePosition += pitchRatio;
  30462. if (sourceSamplePosition > playingSound->length)
  30463. {
  30464. stopNote (false);
  30465. break;
  30466. }
  30467. }
  30468. }
  30469. }
  30470. END_JUCE_NAMESPACE
  30471. /*** End of inlined file: juce_Sampler.cpp ***/
  30472. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30473. BEGIN_JUCE_NAMESPACE
  30474. SynthesiserSound::SynthesiserSound()
  30475. {
  30476. }
  30477. SynthesiserSound::~SynthesiserSound()
  30478. {
  30479. }
  30480. SynthesiserVoice::SynthesiserVoice()
  30481. : currentSampleRate (44100.0),
  30482. currentlyPlayingNote (-1),
  30483. noteOnTime (0),
  30484. currentlyPlayingSound (0)
  30485. {
  30486. }
  30487. SynthesiserVoice::~SynthesiserVoice()
  30488. {
  30489. }
  30490. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30491. {
  30492. return currentlyPlayingSound != 0
  30493. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30494. }
  30495. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30496. {
  30497. currentSampleRate = newRate;
  30498. }
  30499. void SynthesiserVoice::clearCurrentNote()
  30500. {
  30501. currentlyPlayingNote = -1;
  30502. currentlyPlayingSound = 0;
  30503. }
  30504. Synthesiser::Synthesiser()
  30505. : sampleRate (0),
  30506. lastNoteOnCounter (0),
  30507. shouldStealNotes (true)
  30508. {
  30509. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30510. lastPitchWheelValues[i] = 0x2000;
  30511. }
  30512. Synthesiser::~Synthesiser()
  30513. {
  30514. }
  30515. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30516. {
  30517. const ScopedLock sl (lock);
  30518. return voices [index];
  30519. }
  30520. void Synthesiser::clearVoices()
  30521. {
  30522. const ScopedLock sl (lock);
  30523. voices.clear();
  30524. }
  30525. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30526. {
  30527. const ScopedLock sl (lock);
  30528. voices.add (newVoice);
  30529. }
  30530. void Synthesiser::removeVoice (const int index)
  30531. {
  30532. const ScopedLock sl (lock);
  30533. voices.remove (index);
  30534. }
  30535. void Synthesiser::clearSounds()
  30536. {
  30537. const ScopedLock sl (lock);
  30538. sounds.clear();
  30539. }
  30540. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30541. {
  30542. const ScopedLock sl (lock);
  30543. sounds.add (newSound);
  30544. }
  30545. void Synthesiser::removeSound (const int index)
  30546. {
  30547. const ScopedLock sl (lock);
  30548. sounds.remove (index);
  30549. }
  30550. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30551. {
  30552. shouldStealNotes = shouldStealNotes_;
  30553. }
  30554. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30555. {
  30556. if (sampleRate != newRate)
  30557. {
  30558. const ScopedLock sl (lock);
  30559. allNotesOff (0, false);
  30560. sampleRate = newRate;
  30561. for (int i = voices.size(); --i >= 0;)
  30562. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30563. }
  30564. }
  30565. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30566. const MidiBuffer& midiData,
  30567. int startSample,
  30568. int numSamples)
  30569. {
  30570. // must set the sample rate before using this!
  30571. jassert (sampleRate != 0);
  30572. const ScopedLock sl (lock);
  30573. MidiBuffer::Iterator midiIterator (midiData);
  30574. midiIterator.setNextSamplePosition (startSample);
  30575. MidiMessage m (0xf4, 0.0);
  30576. while (numSamples > 0)
  30577. {
  30578. int midiEventPos;
  30579. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30580. && midiEventPos < startSample + numSamples;
  30581. const int numThisTime = useEvent ? midiEventPos - startSample
  30582. : numSamples;
  30583. if (numThisTime > 0)
  30584. {
  30585. for (int i = voices.size(); --i >= 0;)
  30586. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30587. }
  30588. if (useEvent)
  30589. {
  30590. if (m.isNoteOn())
  30591. {
  30592. const int channel = m.getChannel();
  30593. noteOn (channel,
  30594. m.getNoteNumber(),
  30595. m.getFloatVelocity());
  30596. }
  30597. else if (m.isNoteOff())
  30598. {
  30599. noteOff (m.getChannel(),
  30600. m.getNoteNumber(),
  30601. true);
  30602. }
  30603. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30604. {
  30605. allNotesOff (m.getChannel(), true);
  30606. }
  30607. else if (m.isPitchWheel())
  30608. {
  30609. const int channel = m.getChannel();
  30610. const int wheelPos = m.getPitchWheelValue();
  30611. lastPitchWheelValues [channel - 1] = wheelPos;
  30612. handlePitchWheel (channel, wheelPos);
  30613. }
  30614. else if (m.isController())
  30615. {
  30616. handleController (m.getChannel(),
  30617. m.getControllerNumber(),
  30618. m.getControllerValue());
  30619. }
  30620. }
  30621. startSample += numThisTime;
  30622. numSamples -= numThisTime;
  30623. }
  30624. }
  30625. void Synthesiser::noteOn (const int midiChannel,
  30626. const int midiNoteNumber,
  30627. const float velocity)
  30628. {
  30629. const ScopedLock sl (lock);
  30630. for (int i = sounds.size(); --i >= 0;)
  30631. {
  30632. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30633. if (sound->appliesToNote (midiNoteNumber)
  30634. && sound->appliesToChannel (midiChannel))
  30635. {
  30636. startVoice (findFreeVoice (sound, shouldStealNotes),
  30637. sound, midiChannel, midiNoteNumber, velocity);
  30638. }
  30639. }
  30640. }
  30641. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30642. SynthesiserSound* const sound,
  30643. const int midiChannel,
  30644. const int midiNoteNumber,
  30645. const float velocity)
  30646. {
  30647. if (voice != 0 && sound != 0)
  30648. {
  30649. if (voice->currentlyPlayingSound != 0)
  30650. voice->stopNote (false);
  30651. voice->startNote (midiNoteNumber,
  30652. velocity,
  30653. sound,
  30654. lastPitchWheelValues [midiChannel - 1]);
  30655. voice->currentlyPlayingNote = midiNoteNumber;
  30656. voice->noteOnTime = ++lastNoteOnCounter;
  30657. voice->currentlyPlayingSound = sound;
  30658. }
  30659. }
  30660. void Synthesiser::noteOff (const int midiChannel,
  30661. const int midiNoteNumber,
  30662. const bool allowTailOff)
  30663. {
  30664. const ScopedLock sl (lock);
  30665. for (int i = voices.size(); --i >= 0;)
  30666. {
  30667. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30668. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30669. {
  30670. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30671. if (sound != 0
  30672. && sound->appliesToNote (midiNoteNumber)
  30673. && sound->appliesToChannel (midiChannel))
  30674. {
  30675. voice->stopNote (allowTailOff);
  30676. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30677. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30678. }
  30679. }
  30680. }
  30681. }
  30682. void Synthesiser::allNotesOff (const int midiChannel,
  30683. const bool allowTailOff)
  30684. {
  30685. const ScopedLock sl (lock);
  30686. for (int i = voices.size(); --i >= 0;)
  30687. {
  30688. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30689. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30690. voice->stopNote (allowTailOff);
  30691. }
  30692. }
  30693. void Synthesiser::handlePitchWheel (const int midiChannel,
  30694. const int wheelValue)
  30695. {
  30696. const ScopedLock sl (lock);
  30697. for (int i = voices.size(); --i >= 0;)
  30698. {
  30699. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30700. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30701. {
  30702. voice->pitchWheelMoved (wheelValue);
  30703. }
  30704. }
  30705. }
  30706. void Synthesiser::handleController (const int midiChannel,
  30707. const int controllerNumber,
  30708. const int controllerValue)
  30709. {
  30710. const ScopedLock sl (lock);
  30711. for (int i = voices.size(); --i >= 0;)
  30712. {
  30713. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30714. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30715. voice->controllerMoved (controllerNumber, controllerValue);
  30716. }
  30717. }
  30718. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30719. const bool stealIfNoneAvailable) const
  30720. {
  30721. const ScopedLock sl (lock);
  30722. for (int i = voices.size(); --i >= 0;)
  30723. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30724. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30725. return voices.getUnchecked (i);
  30726. if (stealIfNoneAvailable)
  30727. {
  30728. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30729. SynthesiserVoice* oldest = 0;
  30730. for (int i = voices.size(); --i >= 0;)
  30731. {
  30732. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30733. if (voice->canPlaySound (soundToPlay)
  30734. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30735. oldest = voice;
  30736. }
  30737. jassert (oldest != 0);
  30738. return oldest;
  30739. }
  30740. return 0;
  30741. }
  30742. END_JUCE_NAMESPACE
  30743. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30744. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30745. BEGIN_JUCE_NAMESPACE
  30746. // special message of our own with a string in it
  30747. class ActionMessage : public Message
  30748. {
  30749. public:
  30750. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30751. : message (messageText)
  30752. {
  30753. pointerParameter = listener_;
  30754. }
  30755. const String message;
  30756. private:
  30757. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30758. };
  30759. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30760. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30761. {
  30762. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30763. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30764. if (owner->actionListeners.contains (target))
  30765. target->actionListenerCallback (am.message);
  30766. }
  30767. ActionBroadcaster::ActionBroadcaster()
  30768. {
  30769. // are you trying to create this object before or after juce has been intialised??
  30770. jassert (MessageManager::instance != 0);
  30771. callback.owner = this;
  30772. }
  30773. ActionBroadcaster::~ActionBroadcaster()
  30774. {
  30775. // all event-based objects must be deleted BEFORE juce is shut down!
  30776. jassert (MessageManager::instance != 0);
  30777. }
  30778. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30779. {
  30780. const ScopedLock sl (actionListenerLock);
  30781. if (listener != 0)
  30782. actionListeners.add (listener);
  30783. }
  30784. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30785. {
  30786. const ScopedLock sl (actionListenerLock);
  30787. actionListeners.removeValue (listener);
  30788. }
  30789. void ActionBroadcaster::removeAllActionListeners()
  30790. {
  30791. const ScopedLock sl (actionListenerLock);
  30792. actionListeners.clear();
  30793. }
  30794. void ActionBroadcaster::sendActionMessage (const String& message) const
  30795. {
  30796. const ScopedLock sl (actionListenerLock);
  30797. for (int i = actionListeners.size(); --i >= 0;)
  30798. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30799. }
  30800. END_JUCE_NAMESPACE
  30801. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30802. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30803. BEGIN_JUCE_NAMESPACE
  30804. class AsyncUpdater::AsyncUpdaterMessage : public CallbackMessage
  30805. {
  30806. public:
  30807. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30808. : owner (owner_)
  30809. {
  30810. }
  30811. void messageCallback()
  30812. {
  30813. if (owner.pendingMessage.compareAndSetBool (0, this))
  30814. owner.handleAsyncUpdate();
  30815. }
  30816. AsyncUpdater& owner;
  30817. };
  30818. AsyncUpdater::AsyncUpdater() throw()
  30819. {
  30820. }
  30821. AsyncUpdater::~AsyncUpdater()
  30822. {
  30823. // You're deleting this object with a background thread while there's an update
  30824. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30825. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30826. // deleting this object, or find some other way to avoid such a race condition.
  30827. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30828. pendingMessage = 0;
  30829. }
  30830. void AsyncUpdater::triggerAsyncUpdate()
  30831. {
  30832. if (pendingMessage.value == 0)
  30833. {
  30834. ScopedPointer<AsyncUpdaterMessage> pending (new AsyncUpdaterMessage (*this));
  30835. if (pendingMessage.compareAndSetBool (pending, 0))
  30836. pending.release()->post();
  30837. }
  30838. }
  30839. void AsyncUpdater::cancelPendingUpdate() throw()
  30840. {
  30841. pendingMessage = 0;
  30842. }
  30843. void AsyncUpdater::handleUpdateNowIfNeeded()
  30844. {
  30845. // This can only be called by the event thread.
  30846. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30847. if (pendingMessage.exchange (0) != 0)
  30848. handleAsyncUpdate();
  30849. }
  30850. bool AsyncUpdater::isUpdatePending() const throw()
  30851. {
  30852. return pendingMessage.value != 0;
  30853. }
  30854. END_JUCE_NAMESPACE
  30855. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30856. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30857. BEGIN_JUCE_NAMESPACE
  30858. ChangeBroadcaster::ChangeBroadcaster() throw()
  30859. {
  30860. // are you trying to create this object before or after juce has been intialised??
  30861. jassert (MessageManager::instance != 0);
  30862. callback.owner = this;
  30863. }
  30864. ChangeBroadcaster::~ChangeBroadcaster()
  30865. {
  30866. // all event-based objects must be deleted BEFORE juce is shut down!
  30867. jassert (MessageManager::instance != 0);
  30868. }
  30869. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30870. {
  30871. // Listeners can only be safely added when the event thread is locked
  30872. // You can use a MessageManagerLock if you need to call this from another thread.
  30873. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30874. changeListeners.add (listener);
  30875. }
  30876. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30877. {
  30878. // Listeners can only be safely added when the event thread is locked
  30879. // You can use a MessageManagerLock if you need to call this from another thread.
  30880. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30881. changeListeners.remove (listener);
  30882. }
  30883. void ChangeBroadcaster::removeAllChangeListeners()
  30884. {
  30885. // Listeners can only be safely added when the event thread is locked
  30886. // You can use a MessageManagerLock if you need to call this from another thread.
  30887. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30888. changeListeners.clear();
  30889. }
  30890. void ChangeBroadcaster::sendChangeMessage()
  30891. {
  30892. if (changeListeners.size() > 0)
  30893. callback.triggerAsyncUpdate();
  30894. }
  30895. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30896. {
  30897. // This can only be called by the event thread.
  30898. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30899. callback.cancelPendingUpdate();
  30900. callListeners();
  30901. }
  30902. void ChangeBroadcaster::dispatchPendingMessages()
  30903. {
  30904. callback.handleUpdateNowIfNeeded();
  30905. }
  30906. void ChangeBroadcaster::callListeners()
  30907. {
  30908. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30909. }
  30910. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30911. : owner (0)
  30912. {
  30913. }
  30914. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30915. {
  30916. jassert (owner != 0);
  30917. owner->callListeners();
  30918. }
  30919. END_JUCE_NAMESPACE
  30920. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30921. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30922. BEGIN_JUCE_NAMESPACE
  30923. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30924. const uint32 magicMessageHeaderNumber)
  30925. : Thread ("Juce IPC connection"),
  30926. callbackConnectionState (false),
  30927. useMessageThread (callbacksOnMessageThread),
  30928. magicMessageHeader (magicMessageHeaderNumber),
  30929. pipeReceiveMessageTimeout (-1)
  30930. {
  30931. }
  30932. InterprocessConnection::~InterprocessConnection()
  30933. {
  30934. callbackConnectionState = false;
  30935. disconnect();
  30936. }
  30937. bool InterprocessConnection::connectToSocket (const String& hostName,
  30938. const int portNumber,
  30939. const int timeOutMillisecs)
  30940. {
  30941. disconnect();
  30942. const ScopedLock sl (pipeAndSocketLock);
  30943. socket = new StreamingSocket();
  30944. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30945. {
  30946. connectionMadeInt();
  30947. startThread();
  30948. return true;
  30949. }
  30950. else
  30951. {
  30952. socket = 0;
  30953. return false;
  30954. }
  30955. }
  30956. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30957. const int pipeReceiveMessageTimeoutMs)
  30958. {
  30959. disconnect();
  30960. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30961. if (newPipe->openExisting (pipeName))
  30962. {
  30963. const ScopedLock sl (pipeAndSocketLock);
  30964. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30965. initialiseWithPipe (newPipe.release());
  30966. return true;
  30967. }
  30968. return false;
  30969. }
  30970. bool InterprocessConnection::createPipe (const String& pipeName,
  30971. const int pipeReceiveMessageTimeoutMs)
  30972. {
  30973. disconnect();
  30974. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30975. if (newPipe->createNewPipe (pipeName))
  30976. {
  30977. const ScopedLock sl (pipeAndSocketLock);
  30978. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30979. initialiseWithPipe (newPipe.release());
  30980. return true;
  30981. }
  30982. return false;
  30983. }
  30984. void InterprocessConnection::disconnect()
  30985. {
  30986. if (socket != 0)
  30987. socket->close();
  30988. if (pipe != 0)
  30989. {
  30990. pipe->cancelPendingReads();
  30991. pipe->close();
  30992. }
  30993. stopThread (4000);
  30994. {
  30995. const ScopedLock sl (pipeAndSocketLock);
  30996. socket = 0;
  30997. pipe = 0;
  30998. }
  30999. connectionLostInt();
  31000. }
  31001. bool InterprocessConnection::isConnected() const
  31002. {
  31003. const ScopedLock sl (pipeAndSocketLock);
  31004. return ((socket != 0 && socket->isConnected())
  31005. || (pipe != 0 && pipe->isOpen()))
  31006. && isThreadRunning();
  31007. }
  31008. const String InterprocessConnection::getConnectedHostName() const
  31009. {
  31010. if (pipe != 0)
  31011. {
  31012. return "localhost";
  31013. }
  31014. else if (socket != 0)
  31015. {
  31016. if (! socket->isLocal())
  31017. return socket->getHostName();
  31018. return "localhost";
  31019. }
  31020. return String::empty;
  31021. }
  31022. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  31023. {
  31024. uint32 messageHeader[2];
  31025. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  31026. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  31027. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  31028. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  31029. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  31030. size_t bytesWritten = 0;
  31031. const ScopedLock sl (pipeAndSocketLock);
  31032. if (socket != 0)
  31033. {
  31034. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  31035. }
  31036. else if (pipe != 0)
  31037. {
  31038. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  31039. }
  31040. if (bytesWritten < 0)
  31041. {
  31042. // error..
  31043. return false;
  31044. }
  31045. return (bytesWritten == messageData.getSize());
  31046. }
  31047. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31048. {
  31049. jassert (socket == 0);
  31050. socket = socket_;
  31051. connectionMadeInt();
  31052. startThread();
  31053. }
  31054. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31055. {
  31056. jassert (pipe == 0);
  31057. pipe = pipe_;
  31058. connectionMadeInt();
  31059. startThread();
  31060. }
  31061. const int messageMagicNumber = 0xb734128b;
  31062. void InterprocessConnection::handleMessage (const Message& message)
  31063. {
  31064. if (message.intParameter1 == messageMagicNumber)
  31065. {
  31066. switch (message.intParameter2)
  31067. {
  31068. case 0:
  31069. {
  31070. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31071. messageReceived (*data);
  31072. break;
  31073. }
  31074. case 1:
  31075. connectionMade();
  31076. break;
  31077. case 2:
  31078. connectionLost();
  31079. break;
  31080. }
  31081. }
  31082. }
  31083. void InterprocessConnection::connectionMadeInt()
  31084. {
  31085. if (! callbackConnectionState)
  31086. {
  31087. callbackConnectionState = true;
  31088. if (useMessageThread)
  31089. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31090. else
  31091. connectionMade();
  31092. }
  31093. }
  31094. void InterprocessConnection::connectionLostInt()
  31095. {
  31096. if (callbackConnectionState)
  31097. {
  31098. callbackConnectionState = false;
  31099. if (useMessageThread)
  31100. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31101. else
  31102. connectionLost();
  31103. }
  31104. }
  31105. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31106. {
  31107. jassert (callbackConnectionState);
  31108. if (useMessageThread)
  31109. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31110. else
  31111. messageReceived (data);
  31112. }
  31113. bool InterprocessConnection::readNextMessageInt()
  31114. {
  31115. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31116. uint32 messageHeader[2];
  31117. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31118. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31119. if (bytes == sizeof (messageHeader)
  31120. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31121. {
  31122. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31123. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31124. {
  31125. MemoryBlock messageData (bytesInMessage, true);
  31126. int bytesRead = 0;
  31127. while (bytesInMessage > 0)
  31128. {
  31129. if (threadShouldExit())
  31130. return false;
  31131. const int numThisTime = jmin (bytesInMessage, 65536);
  31132. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31133. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31134. if (bytesIn <= 0)
  31135. break;
  31136. bytesRead += bytesIn;
  31137. bytesInMessage -= bytesIn;
  31138. }
  31139. if (bytesRead >= 0)
  31140. deliverDataInt (messageData);
  31141. }
  31142. }
  31143. else if (bytes < 0)
  31144. {
  31145. {
  31146. const ScopedLock sl (pipeAndSocketLock);
  31147. socket = 0;
  31148. }
  31149. connectionLostInt();
  31150. return false;
  31151. }
  31152. return true;
  31153. }
  31154. void InterprocessConnection::run()
  31155. {
  31156. while (! threadShouldExit())
  31157. {
  31158. if (socket != 0)
  31159. {
  31160. const int ready = socket->waitUntilReady (true, 0);
  31161. if (ready < 0)
  31162. {
  31163. {
  31164. const ScopedLock sl (pipeAndSocketLock);
  31165. socket = 0;
  31166. }
  31167. connectionLostInt();
  31168. break;
  31169. }
  31170. else if (ready > 0)
  31171. {
  31172. if (! readNextMessageInt())
  31173. break;
  31174. }
  31175. else
  31176. {
  31177. Thread::sleep (2);
  31178. }
  31179. }
  31180. else if (pipe != 0)
  31181. {
  31182. if (! pipe->isOpen())
  31183. {
  31184. {
  31185. const ScopedLock sl (pipeAndSocketLock);
  31186. pipe = 0;
  31187. }
  31188. connectionLostInt();
  31189. break;
  31190. }
  31191. else
  31192. {
  31193. if (! readNextMessageInt())
  31194. break;
  31195. }
  31196. }
  31197. else
  31198. {
  31199. break;
  31200. }
  31201. }
  31202. }
  31203. END_JUCE_NAMESPACE
  31204. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31205. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31206. BEGIN_JUCE_NAMESPACE
  31207. InterprocessConnectionServer::InterprocessConnectionServer()
  31208. : Thread ("Juce IPC server")
  31209. {
  31210. }
  31211. InterprocessConnectionServer::~InterprocessConnectionServer()
  31212. {
  31213. stop();
  31214. }
  31215. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31216. {
  31217. stop();
  31218. socket = new StreamingSocket();
  31219. if (socket->createListener (portNumber))
  31220. {
  31221. startThread();
  31222. return true;
  31223. }
  31224. socket = 0;
  31225. return false;
  31226. }
  31227. void InterprocessConnectionServer::stop()
  31228. {
  31229. signalThreadShouldExit();
  31230. if (socket != 0)
  31231. socket->close();
  31232. stopThread (4000);
  31233. socket = 0;
  31234. }
  31235. void InterprocessConnectionServer::run()
  31236. {
  31237. while ((! threadShouldExit()) && socket != 0)
  31238. {
  31239. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31240. if (clientSocket != 0)
  31241. {
  31242. InterprocessConnection* newConnection = createConnectionObject();
  31243. if (newConnection != 0)
  31244. newConnection->initialiseWithSocket (clientSocket.release());
  31245. }
  31246. }
  31247. }
  31248. END_JUCE_NAMESPACE
  31249. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31250. /*** Start of inlined file: juce_Message.cpp ***/
  31251. BEGIN_JUCE_NAMESPACE
  31252. Message::Message() throw()
  31253. : intParameter1 (0),
  31254. intParameter2 (0),
  31255. intParameter3 (0),
  31256. pointerParameter (0),
  31257. messageRecipient (0)
  31258. {
  31259. }
  31260. Message::Message (const int intParameter1_,
  31261. const int intParameter2_,
  31262. const int intParameter3_,
  31263. void* const pointerParameter_) throw()
  31264. : intParameter1 (intParameter1_),
  31265. intParameter2 (intParameter2_),
  31266. intParameter3 (intParameter3_),
  31267. pointerParameter (pointerParameter_),
  31268. messageRecipient (0)
  31269. {
  31270. }
  31271. Message::~Message()
  31272. {
  31273. }
  31274. END_JUCE_NAMESPACE
  31275. /*** End of inlined file: juce_Message.cpp ***/
  31276. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31277. BEGIN_JUCE_NAMESPACE
  31278. MessageListener::MessageListener() throw()
  31279. {
  31280. // are you trying to create a messagelistener before or after juce has been intialised??
  31281. jassert (MessageManager::instance != 0);
  31282. if (MessageManager::instance != 0)
  31283. MessageManager::instance->messageListeners.add (this);
  31284. }
  31285. MessageListener::~MessageListener()
  31286. {
  31287. if (MessageManager::instance != 0)
  31288. MessageManager::instance->messageListeners.removeValue (this);
  31289. }
  31290. void MessageListener::postMessage (Message* const message) const throw()
  31291. {
  31292. message->messageRecipient = const_cast <MessageListener*> (this);
  31293. if (MessageManager::instance == 0)
  31294. MessageManager::getInstance();
  31295. MessageManager::instance->postMessageToQueue (message);
  31296. }
  31297. bool MessageListener::isValidMessageListener() const throw()
  31298. {
  31299. return (MessageManager::instance != 0)
  31300. && MessageManager::instance->messageListeners.contains (this);
  31301. }
  31302. END_JUCE_NAMESPACE
  31303. /*** End of inlined file: juce_MessageListener.cpp ***/
  31304. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31305. BEGIN_JUCE_NAMESPACE
  31306. // platform-specific functions..
  31307. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31308. bool juce_postMessageToSystemQueue (Message* message);
  31309. MessageManager* MessageManager::instance = 0;
  31310. static const int quitMessageId = 0xfffff321;
  31311. MessageManager::MessageManager() throw()
  31312. : quitMessagePosted (false),
  31313. quitMessageReceived (false),
  31314. threadWithLock (0)
  31315. {
  31316. messageThreadId = Thread::getCurrentThreadId();
  31317. }
  31318. MessageManager::~MessageManager() throw()
  31319. {
  31320. broadcaster = 0;
  31321. doPlatformSpecificShutdown();
  31322. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31323. jassert (messageListeners.size() == 0);
  31324. jassert (instance == this);
  31325. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31326. }
  31327. MessageManager* MessageManager::getInstance() throw()
  31328. {
  31329. if (instance == 0)
  31330. {
  31331. instance = new MessageManager();
  31332. doPlatformSpecificInitialisation();
  31333. }
  31334. return instance;
  31335. }
  31336. void MessageManager::postMessageToQueue (Message* const message)
  31337. {
  31338. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31339. delete message;
  31340. }
  31341. CallbackMessage::CallbackMessage() throw() {}
  31342. CallbackMessage::~CallbackMessage() {}
  31343. void CallbackMessage::post()
  31344. {
  31345. if (MessageManager::instance != 0)
  31346. MessageManager::instance->postMessageToQueue (this);
  31347. }
  31348. // not for public use..
  31349. void MessageManager::deliverMessage (Message* const message)
  31350. {
  31351. JUCE_TRY
  31352. {
  31353. const ScopedPointer <Message> messageDeleter (message);
  31354. MessageListener* const recipient = message->messageRecipient;
  31355. if (recipient == 0)
  31356. {
  31357. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31358. if (callbackMessage != 0)
  31359. {
  31360. callbackMessage->messageCallback();
  31361. }
  31362. else if (message->intParameter1 == quitMessageId)
  31363. {
  31364. quitMessageReceived = true;
  31365. }
  31366. }
  31367. else if (messageListeners.contains (recipient))
  31368. {
  31369. recipient->handleMessage (*message);
  31370. }
  31371. }
  31372. JUCE_CATCH_EXCEPTION
  31373. }
  31374. #if ! (JUCE_MAC || JUCE_IOS)
  31375. void MessageManager::runDispatchLoop()
  31376. {
  31377. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31378. runDispatchLoopUntil (-1);
  31379. }
  31380. void MessageManager::stopDispatchLoop()
  31381. {
  31382. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31383. quitMessagePosted = true;
  31384. }
  31385. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31386. {
  31387. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31388. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31389. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31390. && ! quitMessageReceived)
  31391. {
  31392. JUCE_TRY
  31393. {
  31394. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31395. {
  31396. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31397. if (msToWait > 0)
  31398. Thread::sleep (jmin (5, msToWait));
  31399. }
  31400. }
  31401. JUCE_CATCH_EXCEPTION
  31402. }
  31403. return ! quitMessageReceived;
  31404. }
  31405. #endif
  31406. void MessageManager::deliverBroadcastMessage (const String& value)
  31407. {
  31408. if (broadcaster != 0)
  31409. broadcaster->sendActionMessage (value);
  31410. }
  31411. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31412. {
  31413. if (broadcaster == 0)
  31414. broadcaster = new ActionBroadcaster();
  31415. broadcaster->addActionListener (listener);
  31416. }
  31417. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31418. {
  31419. if (broadcaster != 0)
  31420. broadcaster->removeActionListener (listener);
  31421. }
  31422. bool MessageManager::isThisTheMessageThread() const throw()
  31423. {
  31424. return Thread::getCurrentThreadId() == messageThreadId;
  31425. }
  31426. void MessageManager::setCurrentThreadAsMessageThread()
  31427. {
  31428. if (messageThreadId != Thread::getCurrentThreadId())
  31429. {
  31430. messageThreadId = Thread::getCurrentThreadId();
  31431. // This is needed on windows to make sure the message window is created by this thread
  31432. doPlatformSpecificShutdown();
  31433. doPlatformSpecificInitialisation();
  31434. }
  31435. }
  31436. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31437. {
  31438. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31439. return thisThread == messageThreadId || thisThread == threadWithLock;
  31440. }
  31441. /* The only safe way to lock the message thread while another thread does
  31442. some work is by posting a special message, whose purpose is to tie up the event
  31443. loop until the other thread has finished its business.
  31444. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31445. get locked before making an event callback, because if the same OS lock gets indirectly
  31446. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31447. in Cocoa).
  31448. */
  31449. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31450. {
  31451. public:
  31452. SharedEvents() {}
  31453. /* This class just holds a couple of events to communicate between the BlockingMessage
  31454. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31455. this shared data must be kept in a separate, ref-counted container. */
  31456. WaitableEvent lockedEvent, releaseEvent;
  31457. private:
  31458. JUCE_DECLARE_NON_COPYABLE (SharedEvents);
  31459. };
  31460. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31461. {
  31462. public:
  31463. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31464. void messageCallback()
  31465. {
  31466. events->lockedEvent.signal();
  31467. events->releaseEvent.wait();
  31468. }
  31469. private:
  31470. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31471. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31472. };
  31473. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31474. : sharedEvents (0),
  31475. locked (false)
  31476. {
  31477. init (threadToCheck, 0);
  31478. }
  31479. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31480. : sharedEvents (0),
  31481. locked (false)
  31482. {
  31483. init (0, jobToCheckForExitSignal);
  31484. }
  31485. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31486. {
  31487. if (MessageManager::instance != 0)
  31488. {
  31489. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31490. {
  31491. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31492. }
  31493. else
  31494. {
  31495. if (threadToCheck == 0 && job == 0)
  31496. {
  31497. MessageManager::instance->lockingLock.enter();
  31498. }
  31499. else
  31500. {
  31501. while (! MessageManager::instance->lockingLock.tryEnter())
  31502. {
  31503. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31504. || (job != 0 && job->shouldExit()))
  31505. return;
  31506. Thread::sleep (1);
  31507. }
  31508. }
  31509. sharedEvents = new SharedEvents();
  31510. sharedEvents->incReferenceCount();
  31511. (new BlockingMessage (sharedEvents))->post();
  31512. while (! sharedEvents->lockedEvent.wait (50))
  31513. {
  31514. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31515. || (job != 0 && job->shouldExit()))
  31516. {
  31517. sharedEvents->releaseEvent.signal();
  31518. sharedEvents->decReferenceCount();
  31519. sharedEvents = 0;
  31520. MessageManager::instance->lockingLock.exit();
  31521. return;
  31522. }
  31523. }
  31524. jassert (MessageManager::instance->threadWithLock == 0);
  31525. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31526. locked = true;
  31527. }
  31528. }
  31529. }
  31530. MessageManagerLock::~MessageManagerLock() throw()
  31531. {
  31532. if (sharedEvents != 0)
  31533. {
  31534. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31535. sharedEvents->releaseEvent.signal();
  31536. sharedEvents->decReferenceCount();
  31537. if (MessageManager::instance != 0)
  31538. {
  31539. MessageManager::instance->threadWithLock = 0;
  31540. MessageManager::instance->lockingLock.exit();
  31541. }
  31542. }
  31543. }
  31544. END_JUCE_NAMESPACE
  31545. /*** End of inlined file: juce_MessageManager.cpp ***/
  31546. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31547. BEGIN_JUCE_NAMESPACE
  31548. class MultiTimer::MultiTimerCallback : public Timer
  31549. {
  31550. public:
  31551. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31552. : timerId (timerId_),
  31553. owner (owner_)
  31554. {
  31555. }
  31556. ~MultiTimerCallback()
  31557. {
  31558. }
  31559. void timerCallback()
  31560. {
  31561. owner.timerCallback (timerId);
  31562. }
  31563. const int timerId;
  31564. private:
  31565. MultiTimer& owner;
  31566. };
  31567. MultiTimer::MultiTimer() throw()
  31568. {
  31569. }
  31570. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31571. {
  31572. }
  31573. MultiTimer::~MultiTimer()
  31574. {
  31575. const ScopedLock sl (timerListLock);
  31576. timers.clear();
  31577. }
  31578. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31579. {
  31580. const ScopedLock sl (timerListLock);
  31581. for (int i = timers.size(); --i >= 0;)
  31582. {
  31583. MultiTimerCallback* const t = timers.getUnchecked(i);
  31584. if (t->timerId == timerId)
  31585. {
  31586. t->startTimer (intervalInMilliseconds);
  31587. return;
  31588. }
  31589. }
  31590. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31591. timers.add (newTimer);
  31592. newTimer->startTimer (intervalInMilliseconds);
  31593. }
  31594. void MultiTimer::stopTimer (const int timerId) throw()
  31595. {
  31596. const ScopedLock sl (timerListLock);
  31597. for (int i = timers.size(); --i >= 0;)
  31598. {
  31599. MultiTimerCallback* const t = timers.getUnchecked(i);
  31600. if (t->timerId == timerId)
  31601. t->stopTimer();
  31602. }
  31603. }
  31604. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31605. {
  31606. const ScopedLock sl (timerListLock);
  31607. for (int i = timers.size(); --i >= 0;)
  31608. {
  31609. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31610. if (t->timerId == timerId)
  31611. return t->isTimerRunning();
  31612. }
  31613. return false;
  31614. }
  31615. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31616. {
  31617. const ScopedLock sl (timerListLock);
  31618. for (int i = timers.size(); --i >= 0;)
  31619. {
  31620. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31621. if (t->timerId == timerId)
  31622. return t->getTimerInterval();
  31623. }
  31624. return 0;
  31625. }
  31626. END_JUCE_NAMESPACE
  31627. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31628. /*** Start of inlined file: juce_Timer.cpp ***/
  31629. BEGIN_JUCE_NAMESPACE
  31630. class InternalTimerThread : private Thread,
  31631. private MessageListener,
  31632. private DeletedAtShutdown,
  31633. private AsyncUpdater
  31634. {
  31635. public:
  31636. InternalTimerThread()
  31637. : Thread ("Juce Timer"),
  31638. firstTimer (0),
  31639. callbackNeeded (0)
  31640. {
  31641. triggerAsyncUpdate();
  31642. }
  31643. ~InternalTimerThread() throw()
  31644. {
  31645. stopThread (4000);
  31646. jassert (instance == this || instance == 0);
  31647. if (instance == this)
  31648. instance = 0;
  31649. }
  31650. void run()
  31651. {
  31652. uint32 lastTime = Time::getMillisecondCounter();
  31653. while (! threadShouldExit())
  31654. {
  31655. const uint32 now = Time::getMillisecondCounter();
  31656. if (now <= lastTime)
  31657. {
  31658. wait (2);
  31659. continue;
  31660. }
  31661. const int elapsed = now - lastTime;
  31662. lastTime = now;
  31663. int timeUntilFirstTimer = 1000;
  31664. {
  31665. const ScopedLock sl (lock);
  31666. decrementAllCounters (elapsed);
  31667. if (firstTimer != 0)
  31668. timeUntilFirstTimer = firstTimer->countdownMs;
  31669. }
  31670. if (timeUntilFirstTimer <= 0)
  31671. {
  31672. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31673. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31674. but if it fails it means the message-thread changed the value from under us so at least
  31675. some processing is happenening and we can just loop around and try again
  31676. */
  31677. if (callbackNeeded.compareAndSetBool (1, 0))
  31678. {
  31679. postMessage (new Message());
  31680. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31681. when the app has a modal loop), so this is how long to wait before assuming the
  31682. message has been lost and trying again.
  31683. */
  31684. const uint32 messageDeliveryTimeout = now + 2000;
  31685. while (callbackNeeded.get() != 0)
  31686. {
  31687. wait (4);
  31688. if (threadShouldExit())
  31689. return;
  31690. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31691. break;
  31692. }
  31693. }
  31694. }
  31695. else
  31696. {
  31697. // don't wait for too long because running this loop also helps keep the
  31698. // Time::getApproximateMillisecondTimer value stay up-to-date
  31699. wait (jlimit (1, 50, timeUntilFirstTimer));
  31700. }
  31701. }
  31702. }
  31703. void callTimers()
  31704. {
  31705. const ScopedLock sl (lock);
  31706. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31707. {
  31708. Timer* const t = firstTimer;
  31709. t->countdownMs = t->periodMs;
  31710. removeTimer (t);
  31711. addTimer (t);
  31712. const ScopedUnlock ul (lock);
  31713. JUCE_TRY
  31714. {
  31715. t->timerCallback();
  31716. }
  31717. JUCE_CATCH_EXCEPTION
  31718. }
  31719. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31720. before the boolean is set. This set should never fail since if it was false in the first place,
  31721. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31722. get a message then the value is true and the other thread can only set it to true again and
  31723. we will get another callback to set it to false.
  31724. */
  31725. callbackNeeded.set (0);
  31726. }
  31727. void handleMessage (const Message&)
  31728. {
  31729. callTimers();
  31730. }
  31731. void callTimersSynchronously()
  31732. {
  31733. if (! isThreadRunning())
  31734. {
  31735. // (This is relied on by some plugins in cases where the MM has
  31736. // had to restart and the async callback never started)
  31737. cancelPendingUpdate();
  31738. triggerAsyncUpdate();
  31739. }
  31740. callTimers();
  31741. }
  31742. static void callAnyTimersSynchronously()
  31743. {
  31744. if (InternalTimerThread::instance != 0)
  31745. InternalTimerThread::instance->callTimersSynchronously();
  31746. }
  31747. static inline void add (Timer* const tim) throw()
  31748. {
  31749. if (instance == 0)
  31750. instance = new InternalTimerThread();
  31751. const ScopedLock sl (instance->lock);
  31752. instance->addTimer (tim);
  31753. }
  31754. static inline void remove (Timer* const tim) throw()
  31755. {
  31756. if (instance != 0)
  31757. {
  31758. const ScopedLock sl (instance->lock);
  31759. instance->removeTimer (tim);
  31760. }
  31761. }
  31762. static inline void resetCounter (Timer* const tim,
  31763. const int newCounter) throw()
  31764. {
  31765. if (instance != 0)
  31766. {
  31767. tim->countdownMs = newCounter;
  31768. tim->periodMs = newCounter;
  31769. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31770. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31771. {
  31772. const ScopedLock sl (instance->lock);
  31773. instance->removeTimer (tim);
  31774. instance->addTimer (tim);
  31775. }
  31776. }
  31777. }
  31778. private:
  31779. friend class Timer;
  31780. static InternalTimerThread* instance;
  31781. static CriticalSection lock;
  31782. Timer* volatile firstTimer;
  31783. Atomic <int> callbackNeeded;
  31784. void addTimer (Timer* const t) throw()
  31785. {
  31786. #if JUCE_DEBUG
  31787. Timer* tt = firstTimer;
  31788. while (tt != 0)
  31789. {
  31790. // trying to add a timer that's already here - shouldn't get to this point,
  31791. // so if you get this assertion, let me know!
  31792. jassert (tt != t);
  31793. tt = tt->next;
  31794. }
  31795. jassert (t->previous == 0 && t->next == 0);
  31796. #endif
  31797. Timer* i = firstTimer;
  31798. if (i == 0 || i->countdownMs > t->countdownMs)
  31799. {
  31800. t->next = firstTimer;
  31801. firstTimer = t;
  31802. }
  31803. else
  31804. {
  31805. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31806. i = i->next;
  31807. jassert (i != 0);
  31808. t->next = i->next;
  31809. t->previous = i;
  31810. i->next = t;
  31811. }
  31812. if (t->next != 0)
  31813. t->next->previous = t;
  31814. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31815. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31816. notify();
  31817. }
  31818. void removeTimer (Timer* const t) throw()
  31819. {
  31820. #if JUCE_DEBUG
  31821. Timer* tt = firstTimer;
  31822. bool found = false;
  31823. while (tt != 0)
  31824. {
  31825. if (tt == t)
  31826. {
  31827. found = true;
  31828. break;
  31829. }
  31830. tt = tt->next;
  31831. }
  31832. // trying to remove a timer that's not here - shouldn't get to this point,
  31833. // so if you get this assertion, let me know!
  31834. jassert (found);
  31835. #endif
  31836. if (t->previous != 0)
  31837. {
  31838. jassert (firstTimer != t);
  31839. t->previous->next = t->next;
  31840. }
  31841. else
  31842. {
  31843. jassert (firstTimer == t);
  31844. firstTimer = t->next;
  31845. }
  31846. if (t->next != 0)
  31847. t->next->previous = t->previous;
  31848. t->next = 0;
  31849. t->previous = 0;
  31850. }
  31851. void decrementAllCounters (const int numMillisecs) const
  31852. {
  31853. Timer* t = firstTimer;
  31854. while (t != 0)
  31855. {
  31856. t->countdownMs -= numMillisecs;
  31857. t = t->next;
  31858. }
  31859. }
  31860. void handleAsyncUpdate()
  31861. {
  31862. startThread (7);
  31863. }
  31864. JUCE_DECLARE_NON_COPYABLE (InternalTimerThread);
  31865. };
  31866. InternalTimerThread* InternalTimerThread::instance = 0;
  31867. CriticalSection InternalTimerThread::lock;
  31868. void juce_callAnyTimersSynchronously()
  31869. {
  31870. InternalTimerThread::callAnyTimersSynchronously();
  31871. }
  31872. #if JUCE_DEBUG
  31873. static SortedSet <Timer*> activeTimers;
  31874. #endif
  31875. Timer::Timer() throw()
  31876. : countdownMs (0),
  31877. periodMs (0),
  31878. previous (0),
  31879. next (0)
  31880. {
  31881. #if JUCE_DEBUG
  31882. activeTimers.add (this);
  31883. #endif
  31884. }
  31885. Timer::Timer (const Timer&) throw()
  31886. : countdownMs (0),
  31887. periodMs (0),
  31888. previous (0),
  31889. next (0)
  31890. {
  31891. #if JUCE_DEBUG
  31892. activeTimers.add (this);
  31893. #endif
  31894. }
  31895. Timer::~Timer()
  31896. {
  31897. stopTimer();
  31898. #if JUCE_DEBUG
  31899. activeTimers.removeValue (this);
  31900. #endif
  31901. }
  31902. void Timer::startTimer (const int interval) throw()
  31903. {
  31904. const ScopedLock sl (InternalTimerThread::lock);
  31905. #if JUCE_DEBUG
  31906. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31907. jassert (activeTimers.contains (this));
  31908. #endif
  31909. if (periodMs == 0)
  31910. {
  31911. countdownMs = interval;
  31912. periodMs = jmax (1, interval);
  31913. InternalTimerThread::add (this);
  31914. }
  31915. else
  31916. {
  31917. InternalTimerThread::resetCounter (this, interval);
  31918. }
  31919. }
  31920. void Timer::stopTimer() throw()
  31921. {
  31922. const ScopedLock sl (InternalTimerThread::lock);
  31923. #if JUCE_DEBUG
  31924. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31925. jassert (activeTimers.contains (this));
  31926. #endif
  31927. if (periodMs > 0)
  31928. {
  31929. InternalTimerThread::remove (this);
  31930. periodMs = 0;
  31931. }
  31932. }
  31933. END_JUCE_NAMESPACE
  31934. /*** End of inlined file: juce_Timer.cpp ***/
  31935. #endif
  31936. #if JUCE_BUILD_GUI
  31937. /*** Start of inlined file: juce_Component.cpp ***/
  31938. BEGIN_JUCE_NAMESPACE
  31939. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31940. Component* Component::currentlyFocusedComponent = 0;
  31941. class Component::MouseListenerList
  31942. {
  31943. public:
  31944. MouseListenerList()
  31945. : numDeepMouseListeners (0)
  31946. {
  31947. }
  31948. ~MouseListenerList()
  31949. {
  31950. }
  31951. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31952. {
  31953. if (! listeners.contains (newListener))
  31954. {
  31955. if (wantsEventsForAllNestedChildComponents)
  31956. {
  31957. listeners.insert (0, newListener);
  31958. ++numDeepMouseListeners;
  31959. }
  31960. else
  31961. {
  31962. listeners.add (newListener);
  31963. }
  31964. }
  31965. }
  31966. void removeListener (MouseListener* const listenerToRemove)
  31967. {
  31968. const int index = listeners.indexOf (listenerToRemove);
  31969. if (index >= 0)
  31970. {
  31971. if (index < numDeepMouseListeners)
  31972. --numDeepMouseListeners;
  31973. listeners.remove (index);
  31974. }
  31975. }
  31976. static void sendMouseEvent (Component* comp, BailOutChecker& checker,
  31977. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  31978. {
  31979. if (checker.shouldBailOut())
  31980. return;
  31981. {
  31982. MouseListenerList* const list = comp->mouseListeners_;
  31983. if (list != 0)
  31984. {
  31985. for (int i = list->listeners.size(); --i >= 0;)
  31986. {
  31987. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31988. if (checker.shouldBailOut())
  31989. return;
  31990. i = jmin (i, list->listeners.size());
  31991. }
  31992. }
  31993. }
  31994. Component* p = comp->parentComponent_;
  31995. while (p != 0)
  31996. {
  31997. MouseListenerList* const list = p->mouseListeners_;
  31998. if (list != 0 && list->numDeepMouseListeners > 0)
  31999. {
  32000. BailOutChecker checker2 (comp, p);
  32001. for (int i = list->numDeepMouseListeners; --i >= 0;)
  32002. {
  32003. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  32004. if (checker2.shouldBailOut())
  32005. return;
  32006. i = jmin (i, list->numDeepMouseListeners);
  32007. }
  32008. }
  32009. p = p->parentComponent_;
  32010. }
  32011. }
  32012. static void sendWheelEvent (Component* comp, BailOutChecker& checker, const MouseEvent& e,
  32013. const float wheelIncrementX, const float wheelIncrementY)
  32014. {
  32015. if (checker.shouldBailOut())
  32016. return;
  32017. {
  32018. MouseListenerList* const list = comp->mouseListeners_;
  32019. if (list != 0)
  32020. {
  32021. for (int i = list->listeners.size(); --i >= 0;)
  32022. {
  32023. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  32024. if (checker.shouldBailOut())
  32025. return;
  32026. i = jmin (i, list->listeners.size());
  32027. }
  32028. }
  32029. }
  32030. Component* p = comp->parentComponent_;
  32031. while (p != 0)
  32032. {
  32033. MouseListenerList* const list = p->mouseListeners_;
  32034. if (list != 0 && list->numDeepMouseListeners > 0)
  32035. {
  32036. BailOutChecker checker2 (comp, p);
  32037. for (int i = list->numDeepMouseListeners; --i >= 0;)
  32038. {
  32039. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  32040. if (checker2.shouldBailOut())
  32041. return;
  32042. i = jmin (i, list->numDeepMouseListeners);
  32043. }
  32044. }
  32045. p = p->parentComponent_;
  32046. }
  32047. }
  32048. private:
  32049. Array <MouseListener*> listeners;
  32050. int numDeepMouseListeners;
  32051. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  32052. };
  32053. class Component::ComponentHelpers
  32054. {
  32055. public:
  32056. static void* runModalLoopCallback (void* userData)
  32057. {
  32058. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32059. }
  32060. static const Identifier getColourPropertyId (const int colourId)
  32061. {
  32062. String s;
  32063. s.preallocateStorage (18);
  32064. s << "jcclr_" << String::toHexString (colourId);
  32065. return s;
  32066. }
  32067. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  32068. {
  32069. return ((unsigned int) localPoint.getX()) < (unsigned int) comp.getWidth()
  32070. && ((unsigned int) localPoint.getY()) < (unsigned int) comp.getHeight()
  32071. && comp.hitTest (localPoint.getX(), localPoint.getY());
  32072. }
  32073. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  32074. {
  32075. if (comp.affineTransform_ == 0)
  32076. return pointInParentSpace - comp.getPosition();
  32077. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform_->inverted()).toInt() - comp.getPosition();
  32078. }
  32079. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  32080. {
  32081. if (comp.affineTransform_ == 0)
  32082. return areaInParentSpace - comp.getPosition();
  32083. return areaInParentSpace.toFloat().transformed (comp.affineTransform_->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  32084. }
  32085. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  32086. {
  32087. if (comp.affineTransform_ == 0)
  32088. return pointInLocalSpace + comp.getPosition();
  32089. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform_).toInt();
  32090. }
  32091. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  32092. {
  32093. if (comp.affineTransform_ == 0)
  32094. return areaInLocalSpace + comp.getPosition();
  32095. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform_).getSmallestIntegerContainer();
  32096. }
  32097. template <typename Type>
  32098. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  32099. {
  32100. const Component* const directParent = target.getParentComponent();
  32101. jassert (directParent != 0);
  32102. if (directParent == parent)
  32103. return convertFromParentSpace (target, coordInParent);
  32104. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  32105. }
  32106. template <typename Type>
  32107. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  32108. {
  32109. while (source != 0)
  32110. {
  32111. if (source == target)
  32112. return p;
  32113. if (source->isParentOf (target))
  32114. return convertFromDistantParentSpace (source, *target, p);
  32115. if (source->isOnDesktop())
  32116. {
  32117. p = source->getPeer()->localToGlobal (p);
  32118. source = 0;
  32119. }
  32120. else
  32121. {
  32122. p = convertToParentSpace (*source, p);
  32123. source = source->getParentComponent();
  32124. }
  32125. }
  32126. jassert (source == 0);
  32127. if (target == 0)
  32128. return p;
  32129. const Component* const topLevelComp = target->getTopLevelComponent();
  32130. if (topLevelComp->isOnDesktop())
  32131. p = topLevelComp->getPeer()->globalToLocal (p);
  32132. else
  32133. p = convertFromParentSpace (*topLevelComp, p);
  32134. if (topLevelComp == target)
  32135. return p;
  32136. return convertFromDistantParentSpace (topLevelComp, *target, p);
  32137. }
  32138. static const Rectangle<int> getUnclippedArea (const Component& comp)
  32139. {
  32140. Rectangle<int> r (comp.getLocalBounds());
  32141. Component* const p = comp.getParentComponent();
  32142. if (p != 0)
  32143. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  32144. return r;
  32145. }
  32146. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  32147. {
  32148. for (int i = comp.childComponentList_.size(); --i >= 0;)
  32149. {
  32150. const Component& child = *comp.childComponentList_.getUnchecked(i);
  32151. if (child.isVisible() && ! child.isTransformed())
  32152. {
  32153. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds_));
  32154. if (! newClip.isEmpty())
  32155. {
  32156. if (child.isOpaque())
  32157. {
  32158. g.excludeClipRegion (newClip + delta);
  32159. }
  32160. else
  32161. {
  32162. const Point<int> childPos (child.getPosition());
  32163. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  32164. }
  32165. }
  32166. }
  32167. }
  32168. }
  32169. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  32170. const Point<int>& delta,
  32171. const Rectangle<int>& clipRect,
  32172. const Component* const compToAvoid)
  32173. {
  32174. for (int i = comp.childComponentList_.size(); --i >= 0;)
  32175. {
  32176. const Component* const c = comp.childComponentList_.getUnchecked(i);
  32177. if (c != compToAvoid && c->isVisible())
  32178. {
  32179. if (c->isOpaque())
  32180. {
  32181. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32182. childBounds.translate (delta.getX(), delta.getY());
  32183. result.subtract (childBounds);
  32184. }
  32185. else
  32186. {
  32187. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32188. newClip.translate (-c->getX(), -c->getY());
  32189. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  32190. newClip, compToAvoid);
  32191. }
  32192. }
  32193. }
  32194. }
  32195. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  32196. {
  32197. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  32198. : Desktop::getInstance().getMainMonitorArea();
  32199. }
  32200. };
  32201. Component::Component()
  32202. : parentComponent_ (0),
  32203. lookAndFeel_ (0),
  32204. effect_ (0),
  32205. bufferedImage_ (0),
  32206. componentFlags_ (0),
  32207. componentTransparency (0)
  32208. {
  32209. }
  32210. Component::Component (const String& name)
  32211. : componentName_ (name),
  32212. parentComponent_ (0),
  32213. lookAndFeel_ (0),
  32214. effect_ (0),
  32215. bufferedImage_ (0),
  32216. componentFlags_ (0),
  32217. componentTransparency (0)
  32218. {
  32219. }
  32220. Component::~Component()
  32221. {
  32222. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  32223. static_jassert (sizeof (flags) <= sizeof (componentFlags_));
  32224. #endif
  32225. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32226. if (parentComponent_ != 0)
  32227. {
  32228. parentComponent_->removeChildComponent (this);
  32229. }
  32230. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32231. {
  32232. giveAwayFocus();
  32233. }
  32234. if (flags.hasHeavyweightPeerFlag)
  32235. removeFromDesktop();
  32236. for (int i = childComponentList_.size(); --i >= 0;)
  32237. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  32238. }
  32239. void Component::setName (const String& name)
  32240. {
  32241. // if component methods are being called from threads other than the message
  32242. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32243. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32244. if (componentName_ != name)
  32245. {
  32246. componentName_ = name;
  32247. if (flags.hasHeavyweightPeerFlag)
  32248. {
  32249. ComponentPeer* const peer = getPeer();
  32250. jassert (peer != 0);
  32251. if (peer != 0)
  32252. peer->setTitle (name);
  32253. }
  32254. BailOutChecker checker (this);
  32255. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32256. }
  32257. }
  32258. void Component::setVisible (bool shouldBeVisible)
  32259. {
  32260. if (flags.visibleFlag != shouldBeVisible)
  32261. {
  32262. // if component methods are being called from threads other than the message
  32263. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32264. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32265. SafePointer<Component> safePointer (this);
  32266. flags.visibleFlag = shouldBeVisible;
  32267. internalRepaint (0, 0, getWidth(), getHeight());
  32268. sendFakeMouseMove();
  32269. if (! shouldBeVisible)
  32270. {
  32271. if (currentlyFocusedComponent == this
  32272. || isParentOf (currentlyFocusedComponent))
  32273. {
  32274. if (parentComponent_ != 0)
  32275. parentComponent_->grabKeyboardFocus();
  32276. else
  32277. giveAwayFocus();
  32278. }
  32279. }
  32280. if (safePointer != 0)
  32281. {
  32282. sendVisibilityChangeMessage();
  32283. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32284. {
  32285. ComponentPeer* const peer = getPeer();
  32286. jassert (peer != 0);
  32287. if (peer != 0)
  32288. {
  32289. peer->setVisible (shouldBeVisible);
  32290. internalHierarchyChanged();
  32291. }
  32292. }
  32293. }
  32294. }
  32295. }
  32296. void Component::visibilityChanged()
  32297. {
  32298. }
  32299. void Component::sendVisibilityChangeMessage()
  32300. {
  32301. BailOutChecker checker (this);
  32302. visibilityChanged();
  32303. if (! checker.shouldBailOut())
  32304. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32305. }
  32306. bool Component::isShowing() const
  32307. {
  32308. if (flags.visibleFlag)
  32309. {
  32310. if (parentComponent_ != 0)
  32311. {
  32312. return parentComponent_->isShowing();
  32313. }
  32314. else
  32315. {
  32316. const ComponentPeer* const peer = getPeer();
  32317. return peer != 0 && ! peer->isMinimised();
  32318. }
  32319. }
  32320. return false;
  32321. }
  32322. void* Component::getWindowHandle() const
  32323. {
  32324. const ComponentPeer* const peer = getPeer();
  32325. if (peer != 0)
  32326. return peer->getNativeHandle();
  32327. return 0;
  32328. }
  32329. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32330. {
  32331. // if component methods are being called from threads other than the message
  32332. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32333. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32334. if (isOpaque())
  32335. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32336. else
  32337. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32338. int currentStyleFlags = 0;
  32339. // don't use getPeer(), so that we only get the peer that's specifically
  32340. // for this comp, and not for one of its parents.
  32341. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32342. if (peer != 0)
  32343. currentStyleFlags = peer->getStyleFlags();
  32344. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32345. {
  32346. SafePointer<Component> safePointer (this);
  32347. #if JUCE_LINUX
  32348. // it's wise to give the component a non-zero size before
  32349. // putting it on the desktop, as X windows get confused by this, and
  32350. // a (1, 1) minimum size is enforced here.
  32351. setSize (jmax (1, getWidth()),
  32352. jmax (1, getHeight()));
  32353. #endif
  32354. const Point<int> topLeft (getScreenPosition());
  32355. bool wasFullscreen = false;
  32356. bool wasMinimised = false;
  32357. ComponentBoundsConstrainer* currentConstainer = 0;
  32358. Rectangle<int> oldNonFullScreenBounds;
  32359. if (peer != 0)
  32360. {
  32361. wasFullscreen = peer->isFullScreen();
  32362. wasMinimised = peer->isMinimised();
  32363. currentConstainer = peer->getConstrainer();
  32364. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32365. removeFromDesktop();
  32366. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32367. }
  32368. if (parentComponent_ != 0)
  32369. parentComponent_->removeChildComponent (this);
  32370. if (safePointer != 0)
  32371. {
  32372. flags.hasHeavyweightPeerFlag = true;
  32373. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32374. Desktop::getInstance().addDesktopComponent (this);
  32375. bounds_.setPosition (topLeft);
  32376. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32377. peer->setVisible (isVisible());
  32378. if (wasFullscreen)
  32379. {
  32380. peer->setFullScreen (true);
  32381. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32382. }
  32383. if (wasMinimised)
  32384. peer->setMinimised (true);
  32385. if (isAlwaysOnTop())
  32386. peer->setAlwaysOnTop (true);
  32387. peer->setConstrainer (currentConstainer);
  32388. repaint();
  32389. }
  32390. internalHierarchyChanged();
  32391. }
  32392. }
  32393. void Component::removeFromDesktop()
  32394. {
  32395. // if component methods are being called from threads other than the message
  32396. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32397. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32398. if (flags.hasHeavyweightPeerFlag)
  32399. {
  32400. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32401. flags.hasHeavyweightPeerFlag = false;
  32402. jassert (peer != 0);
  32403. delete peer;
  32404. Desktop::getInstance().removeDesktopComponent (this);
  32405. }
  32406. }
  32407. bool Component::isOnDesktop() const throw()
  32408. {
  32409. return flags.hasHeavyweightPeerFlag;
  32410. }
  32411. void Component::userTriedToCloseWindow()
  32412. {
  32413. /* This means that the user's trying to get rid of your window with the 'close window' system
  32414. menu option (on windows) or possibly the task manager - you should really handle this
  32415. and delete or hide your component in an appropriate way.
  32416. If you want to ignore the event and don't want to trigger this assertion, just override
  32417. this method and do nothing.
  32418. */
  32419. jassertfalse;
  32420. }
  32421. void Component::minimisationStateChanged (bool)
  32422. {
  32423. }
  32424. void Component::setOpaque (const bool shouldBeOpaque)
  32425. {
  32426. if (shouldBeOpaque != flags.opaqueFlag)
  32427. {
  32428. flags.opaqueFlag = shouldBeOpaque;
  32429. if (flags.hasHeavyweightPeerFlag)
  32430. {
  32431. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32432. if (peer != 0)
  32433. {
  32434. // to make it recreate the heavyweight window
  32435. addToDesktop (peer->getStyleFlags());
  32436. }
  32437. }
  32438. repaint();
  32439. }
  32440. }
  32441. bool Component::isOpaque() const throw()
  32442. {
  32443. return flags.opaqueFlag;
  32444. }
  32445. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32446. {
  32447. if (shouldBeBuffered != flags.bufferToImageFlag)
  32448. {
  32449. bufferedImage_ = Image::null;
  32450. flags.bufferToImageFlag = shouldBeBuffered;
  32451. }
  32452. }
  32453. void Component::toFront (const bool setAsForeground)
  32454. {
  32455. // if component methods are being called from threads other than the message
  32456. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32457. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32458. if (flags.hasHeavyweightPeerFlag)
  32459. {
  32460. ComponentPeer* const peer = getPeer();
  32461. if (peer != 0)
  32462. {
  32463. peer->toFront (setAsForeground);
  32464. if (setAsForeground && ! hasKeyboardFocus (true))
  32465. grabKeyboardFocus();
  32466. }
  32467. }
  32468. else if (parentComponent_ != 0)
  32469. {
  32470. Array<Component*>& childList = parentComponent_->childComponentList_;
  32471. if (childList.getLast() != this)
  32472. {
  32473. const int index = childList.indexOf (this);
  32474. if (index >= 0)
  32475. {
  32476. int insertIndex = -1;
  32477. if (! flags.alwaysOnTopFlag)
  32478. {
  32479. insertIndex = childList.size() - 1;
  32480. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32481. --insertIndex;
  32482. }
  32483. if (index != insertIndex)
  32484. {
  32485. childList.move (index, insertIndex);
  32486. sendFakeMouseMove();
  32487. repaintParent();
  32488. }
  32489. }
  32490. }
  32491. if (setAsForeground)
  32492. {
  32493. internalBroughtToFront();
  32494. grabKeyboardFocus();
  32495. }
  32496. }
  32497. }
  32498. void Component::toBehind (Component* const other)
  32499. {
  32500. if (other != 0 && other != this)
  32501. {
  32502. // the two components must belong to the same parent..
  32503. jassert (parentComponent_ == other->parentComponent_);
  32504. if (parentComponent_ != 0)
  32505. {
  32506. Array<Component*>& childList = parentComponent_->childComponentList_;
  32507. const int index = childList.indexOf (this);
  32508. if (index >= 0 && childList [index + 1] != other)
  32509. {
  32510. int otherIndex = childList.indexOf (other);
  32511. if (otherIndex >= 0)
  32512. {
  32513. if (index < otherIndex)
  32514. --otherIndex;
  32515. childList.move (index, otherIndex);
  32516. sendFakeMouseMove();
  32517. repaintParent();
  32518. }
  32519. }
  32520. }
  32521. else if (isOnDesktop())
  32522. {
  32523. jassert (other->isOnDesktop());
  32524. if (other->isOnDesktop())
  32525. {
  32526. ComponentPeer* const us = getPeer();
  32527. ComponentPeer* const them = other->getPeer();
  32528. jassert (us != 0 && them != 0);
  32529. if (us != 0 && them != 0)
  32530. us->toBehind (them);
  32531. }
  32532. }
  32533. }
  32534. }
  32535. void Component::toBack()
  32536. {
  32537. Array<Component*>& childList = parentComponent_->childComponentList_;
  32538. if (isOnDesktop())
  32539. {
  32540. jassertfalse; //xxx need to add this to native window
  32541. }
  32542. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32543. {
  32544. const int index = childList.indexOf (this);
  32545. if (index > 0)
  32546. {
  32547. int insertIndex = 0;
  32548. if (flags.alwaysOnTopFlag)
  32549. {
  32550. while (insertIndex < childList.size()
  32551. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32552. {
  32553. ++insertIndex;
  32554. }
  32555. }
  32556. if (index != insertIndex)
  32557. {
  32558. childList.move (index, insertIndex);
  32559. sendFakeMouseMove();
  32560. repaintParent();
  32561. }
  32562. }
  32563. }
  32564. }
  32565. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32566. {
  32567. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32568. {
  32569. flags.alwaysOnTopFlag = shouldStayOnTop;
  32570. if (isOnDesktop())
  32571. {
  32572. ComponentPeer* const peer = getPeer();
  32573. jassert (peer != 0);
  32574. if (peer != 0)
  32575. {
  32576. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32577. {
  32578. // some kinds of peer can't change their always-on-top status, so
  32579. // for these, we'll need to create a new window
  32580. const int oldFlags = peer->getStyleFlags();
  32581. removeFromDesktop();
  32582. addToDesktop (oldFlags);
  32583. }
  32584. }
  32585. }
  32586. if (shouldStayOnTop)
  32587. toFront (false);
  32588. internalHierarchyChanged();
  32589. }
  32590. }
  32591. bool Component::isAlwaysOnTop() const throw()
  32592. {
  32593. return flags.alwaysOnTopFlag;
  32594. }
  32595. int Component::proportionOfWidth (const float proportion) const throw()
  32596. {
  32597. return roundToInt (proportion * bounds_.getWidth());
  32598. }
  32599. int Component::proportionOfHeight (const float proportion) const throw()
  32600. {
  32601. return roundToInt (proportion * bounds_.getHeight());
  32602. }
  32603. int Component::getParentWidth() const throw()
  32604. {
  32605. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32606. : getParentMonitorArea().getWidth();
  32607. }
  32608. int Component::getParentHeight() const throw()
  32609. {
  32610. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32611. : getParentMonitorArea().getHeight();
  32612. }
  32613. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32614. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32615. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32616. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32617. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32618. {
  32619. return ComponentHelpers::convertCoordinate (this, source, point);
  32620. }
  32621. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32622. {
  32623. return ComponentHelpers::convertCoordinate (this, source, area);
  32624. }
  32625. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32626. {
  32627. return ComponentHelpers::convertCoordinate (0, this, point);
  32628. }
  32629. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32630. {
  32631. return ComponentHelpers::convertCoordinate (0, this, area);
  32632. }
  32633. /* Deprecated methods... */
  32634. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32635. {
  32636. return localPointToGlobal (relativePosition);
  32637. }
  32638. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32639. {
  32640. return getLocalPoint (0, screenPosition);
  32641. }
  32642. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32643. {
  32644. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32645. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32646. }
  32647. void Component::setBounds (const int x, const int y, int w, int h)
  32648. {
  32649. // if component methods are being called from threads other than the message
  32650. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32651. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32652. if (w < 0) w = 0;
  32653. if (h < 0) h = 0;
  32654. const bool wasResized = (getWidth() != w || getHeight() != h);
  32655. const bool wasMoved = (getX() != x || getY() != y);
  32656. #if JUCE_DEBUG
  32657. // It's a very bad idea to try to resize a window during its paint() method!
  32658. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32659. #endif
  32660. if (wasMoved || wasResized)
  32661. {
  32662. const bool showing = isShowing();
  32663. if (showing)
  32664. {
  32665. // send a fake mouse move to trigger enter/exit messages if needed..
  32666. sendFakeMouseMove();
  32667. if (! flags.hasHeavyweightPeerFlag)
  32668. repaintParent();
  32669. }
  32670. bounds_.setBounds (x, y, w, h);
  32671. if (showing)
  32672. {
  32673. if (wasResized)
  32674. repaint();
  32675. else if (! flags.hasHeavyweightPeerFlag)
  32676. repaintParent();
  32677. }
  32678. if (flags.hasHeavyweightPeerFlag)
  32679. {
  32680. ComponentPeer* const peer = getPeer();
  32681. if (peer != 0)
  32682. {
  32683. if (wasMoved && wasResized)
  32684. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32685. else if (wasMoved)
  32686. peer->setPosition (getX(), getY());
  32687. else if (wasResized)
  32688. peer->setSize (getWidth(), getHeight());
  32689. }
  32690. }
  32691. sendMovedResizedMessages (wasMoved, wasResized);
  32692. }
  32693. }
  32694. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32695. {
  32696. JUCE_TRY
  32697. {
  32698. if (wasMoved)
  32699. moved();
  32700. if (wasResized)
  32701. {
  32702. resized();
  32703. for (int i = childComponentList_.size(); --i >= 0;)
  32704. {
  32705. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32706. i = jmin (i, childComponentList_.size());
  32707. }
  32708. }
  32709. BailOutChecker checker (this);
  32710. if (parentComponent_ != 0)
  32711. parentComponent_->childBoundsChanged (this);
  32712. if (! checker.shouldBailOut())
  32713. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32714. *this, wasMoved, wasResized);
  32715. }
  32716. JUCE_CATCH_EXCEPTION
  32717. }
  32718. void Component::setSize (const int w, const int h)
  32719. {
  32720. setBounds (getX(), getY(), w, h);
  32721. }
  32722. void Component::setTopLeftPosition (const int x, const int y)
  32723. {
  32724. setBounds (x, y, getWidth(), getHeight());
  32725. }
  32726. void Component::setTopRightPosition (const int x, const int y)
  32727. {
  32728. setTopLeftPosition (x - getWidth(), y);
  32729. }
  32730. void Component::setBounds (const Rectangle<int>& r)
  32731. {
  32732. setBounds (r.getX(),
  32733. r.getY(),
  32734. r.getWidth(),
  32735. r.getHeight());
  32736. }
  32737. void Component::setBoundsRelative (const float x, const float y,
  32738. const float w, const float h)
  32739. {
  32740. const int pw = getParentWidth();
  32741. const int ph = getParentHeight();
  32742. setBounds (roundToInt (x * pw),
  32743. roundToInt (y * ph),
  32744. roundToInt (w * pw),
  32745. roundToInt (h * ph));
  32746. }
  32747. void Component::setCentrePosition (const int x, const int y)
  32748. {
  32749. setTopLeftPosition (x - getWidth() / 2,
  32750. y - getHeight() / 2);
  32751. }
  32752. void Component::setCentreRelative (const float x, const float y)
  32753. {
  32754. setCentrePosition (roundToInt (getParentWidth() * x),
  32755. roundToInt (getParentHeight() * y));
  32756. }
  32757. void Component::centreWithSize (const int width, const int height)
  32758. {
  32759. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32760. setBounds (parentArea.getCentreX() - width / 2,
  32761. parentArea.getCentreY() - height / 2,
  32762. width, height);
  32763. }
  32764. void Component::setBoundsInset (const BorderSize& borders)
  32765. {
  32766. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32767. }
  32768. void Component::setBoundsToFit (int x, int y, int width, int height,
  32769. const Justification& justification,
  32770. const bool onlyReduceInSize)
  32771. {
  32772. // it's no good calling this method unless both the component and
  32773. // target rectangle have a finite size.
  32774. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32775. if (getWidth() > 0 && getHeight() > 0
  32776. && width > 0 && height > 0)
  32777. {
  32778. int newW, newH;
  32779. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32780. {
  32781. newW = getWidth();
  32782. newH = getHeight();
  32783. }
  32784. else
  32785. {
  32786. const double imageRatio = getHeight() / (double) getWidth();
  32787. const double targetRatio = height / (double) width;
  32788. if (imageRatio <= targetRatio)
  32789. {
  32790. newW = width;
  32791. newH = jmin (height, roundToInt (newW * imageRatio));
  32792. }
  32793. else
  32794. {
  32795. newH = height;
  32796. newW = jmin (width, roundToInt (newH / imageRatio));
  32797. }
  32798. }
  32799. if (newW > 0 && newH > 0)
  32800. {
  32801. int newX, newY;
  32802. justification.applyToRectangle (newX, newY, newW, newH,
  32803. x, y, width, height);
  32804. setBounds (newX, newY, newW, newH);
  32805. }
  32806. }
  32807. }
  32808. bool Component::isTransformed() const throw()
  32809. {
  32810. return affineTransform_ != 0;
  32811. }
  32812. void Component::setTransform (const AffineTransform& newTransform)
  32813. {
  32814. // If you pass in a transform with no inverse, the component will have no dimensions,
  32815. // and there will be all sorts of maths errors when converting coordinates.
  32816. jassert (! newTransform.isSingularity());
  32817. if (newTransform.isIdentity())
  32818. {
  32819. if (affineTransform_ != 0)
  32820. {
  32821. repaint();
  32822. affineTransform_ = 0;
  32823. repaint();
  32824. sendMovedResizedMessages (false, false);
  32825. }
  32826. }
  32827. else if (affineTransform_ == 0)
  32828. {
  32829. repaint();
  32830. affineTransform_ = new AffineTransform (newTransform);
  32831. repaint();
  32832. sendMovedResizedMessages (false, false);
  32833. }
  32834. else if (*affineTransform_ != newTransform)
  32835. {
  32836. repaint();
  32837. *affineTransform_ = newTransform;
  32838. repaint();
  32839. sendMovedResizedMessages (false, false);
  32840. }
  32841. }
  32842. const AffineTransform Component::getTransform() const
  32843. {
  32844. return affineTransform_ != 0 ? *affineTransform_ : AffineTransform::identity;
  32845. }
  32846. bool Component::hitTest (int x, int y)
  32847. {
  32848. if (! flags.ignoresMouseClicksFlag)
  32849. return true;
  32850. if (flags.allowChildMouseClicksFlag)
  32851. {
  32852. for (int i = getNumChildComponents(); --i >= 0;)
  32853. {
  32854. Component& child = *getChildComponent (i);
  32855. if (child.isVisible()
  32856. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32857. return true;
  32858. }
  32859. }
  32860. return false;
  32861. }
  32862. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32863. const bool allowClicksOnChildComponents) throw()
  32864. {
  32865. flags.ignoresMouseClicksFlag = ! allowClicks;
  32866. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32867. }
  32868. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32869. bool& allowsClicksOnChildComponents) const throw()
  32870. {
  32871. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32872. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32873. }
  32874. bool Component::contains (const Point<int>& point)
  32875. {
  32876. if (ComponentHelpers::hitTest (*this, point))
  32877. {
  32878. if (parentComponent_ != 0)
  32879. {
  32880. return parentComponent_->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32881. }
  32882. else if (flags.hasHeavyweightPeerFlag)
  32883. {
  32884. const ComponentPeer* const peer = getPeer();
  32885. if (peer != 0)
  32886. return peer->contains (point, true);
  32887. }
  32888. }
  32889. return false;
  32890. }
  32891. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32892. {
  32893. if (! contains (point))
  32894. return false;
  32895. Component* const top = getTopLevelComponent();
  32896. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32897. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32898. }
  32899. Component* Component::getComponentAt (const Point<int>& position)
  32900. {
  32901. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32902. {
  32903. for (int i = childComponentList_.size(); --i >= 0;)
  32904. {
  32905. Component* child = childComponentList_.getUnchecked(i);
  32906. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32907. if (child != 0)
  32908. return child;
  32909. }
  32910. return this;
  32911. }
  32912. return 0;
  32913. }
  32914. Component* Component::getComponentAt (const int x, const int y)
  32915. {
  32916. return getComponentAt (Point<int> (x, y));
  32917. }
  32918. void Component::addChildComponent (Component* const child, int zOrder)
  32919. {
  32920. // if component methods are being called from threads other than the message
  32921. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32922. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32923. if (child != 0 && child->parentComponent_ != this)
  32924. {
  32925. if (child->parentComponent_ != 0)
  32926. child->parentComponent_->removeChildComponent (child);
  32927. else
  32928. child->removeFromDesktop();
  32929. child->parentComponent_ = this;
  32930. if (child->isVisible())
  32931. child->repaintParent();
  32932. if (! child->isAlwaysOnTop())
  32933. {
  32934. if (zOrder < 0 || zOrder > childComponentList_.size())
  32935. zOrder = childComponentList_.size();
  32936. while (zOrder > 0)
  32937. {
  32938. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32939. break;
  32940. --zOrder;
  32941. }
  32942. }
  32943. childComponentList_.insert (zOrder, child);
  32944. child->internalHierarchyChanged();
  32945. internalChildrenChanged();
  32946. }
  32947. }
  32948. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32949. {
  32950. if (child != 0)
  32951. {
  32952. child->setVisible (true);
  32953. addChildComponent (child, zOrder);
  32954. }
  32955. }
  32956. void Component::removeChildComponent (Component* const child)
  32957. {
  32958. removeChildComponent (childComponentList_.indexOf (child));
  32959. }
  32960. Component* Component::removeChildComponent (const int index)
  32961. {
  32962. // if component methods are being called from threads other than the message
  32963. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32964. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32965. Component* const child = childComponentList_ [index];
  32966. if (child != 0)
  32967. {
  32968. const bool childShowing = child->isShowing();
  32969. if (childShowing)
  32970. {
  32971. sendFakeMouseMove();
  32972. child->repaintParent();
  32973. }
  32974. childComponentList_.remove (index);
  32975. child->parentComponent_ = 0;
  32976. if (childShowing)
  32977. {
  32978. JUCE_TRY
  32979. {
  32980. if ((currentlyFocusedComponent == child)
  32981. || child->isParentOf (currentlyFocusedComponent))
  32982. {
  32983. // get rid first to force the grabKeyboardFocus to change to us.
  32984. giveAwayFocus();
  32985. grabKeyboardFocus();
  32986. }
  32987. }
  32988. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32989. catch (const std::exception& e)
  32990. {
  32991. currentlyFocusedComponent = 0;
  32992. Desktop::getInstance().triggerFocusCallback();
  32993. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32994. }
  32995. catch (...)
  32996. {
  32997. currentlyFocusedComponent = 0;
  32998. Desktop::getInstance().triggerFocusCallback();
  32999. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33000. }
  33001. #endif
  33002. }
  33003. child->internalHierarchyChanged();
  33004. internalChildrenChanged();
  33005. }
  33006. return child;
  33007. }
  33008. void Component::removeAllChildren()
  33009. {
  33010. while (childComponentList_.size() > 0)
  33011. removeChildComponent (childComponentList_.size() - 1);
  33012. }
  33013. void Component::deleteAllChildren()
  33014. {
  33015. while (childComponentList_.size() > 0)
  33016. delete (removeChildComponent (childComponentList_.size() - 1));
  33017. }
  33018. int Component::getNumChildComponents() const throw()
  33019. {
  33020. return childComponentList_.size();
  33021. }
  33022. Component* Component::getChildComponent (const int index) const throw()
  33023. {
  33024. return childComponentList_ [index];
  33025. }
  33026. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  33027. {
  33028. return childComponentList_.indexOf (const_cast <Component*> (child));
  33029. }
  33030. Component* Component::getTopLevelComponent() const throw()
  33031. {
  33032. const Component* comp = this;
  33033. while (comp->parentComponent_ != 0)
  33034. comp = comp->parentComponent_;
  33035. return const_cast <Component*> (comp);
  33036. }
  33037. bool Component::isParentOf (const Component* possibleChild) const throw()
  33038. {
  33039. while (possibleChild != 0)
  33040. {
  33041. possibleChild = possibleChild->parentComponent_;
  33042. if (possibleChild == this)
  33043. return true;
  33044. }
  33045. return false;
  33046. }
  33047. void Component::parentHierarchyChanged()
  33048. {
  33049. }
  33050. void Component::childrenChanged()
  33051. {
  33052. }
  33053. void Component::internalChildrenChanged()
  33054. {
  33055. if (componentListeners.isEmpty())
  33056. {
  33057. childrenChanged();
  33058. }
  33059. else
  33060. {
  33061. BailOutChecker checker (this);
  33062. childrenChanged();
  33063. if (! checker.shouldBailOut())
  33064. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  33065. }
  33066. }
  33067. void Component::internalHierarchyChanged()
  33068. {
  33069. BailOutChecker checker (this);
  33070. parentHierarchyChanged();
  33071. if (checker.shouldBailOut())
  33072. return;
  33073. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  33074. if (checker.shouldBailOut())
  33075. return;
  33076. for (int i = childComponentList_.size(); --i >= 0;)
  33077. {
  33078. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  33079. if (checker.shouldBailOut())
  33080. {
  33081. // you really shouldn't delete the parent component during a callback telling you
  33082. // that it's changed..
  33083. jassertfalse;
  33084. return;
  33085. }
  33086. i = jmin (i, childComponentList_.size());
  33087. }
  33088. }
  33089. int Component::runModalLoop()
  33090. {
  33091. if (! MessageManager::getInstance()->isThisTheMessageThread())
  33092. {
  33093. // use a callback so this can be called from non-gui threads
  33094. return (int) (pointer_sized_int) MessageManager::getInstance()
  33095. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  33096. }
  33097. if (! isCurrentlyModal())
  33098. enterModalState (true);
  33099. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  33100. }
  33101. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  33102. {
  33103. // if component methods are being called from threads other than the message
  33104. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33105. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33106. // Check for an attempt to make a component modal when it already is!
  33107. // This can cause nasty problems..
  33108. jassert (! flags.currentlyModalFlag);
  33109. if (! isCurrentlyModal())
  33110. {
  33111. ModalComponentManager::getInstance()->startModal (this, callback);
  33112. flags.currentlyModalFlag = true;
  33113. setVisible (true);
  33114. if (takeKeyboardFocus_)
  33115. grabKeyboardFocus();
  33116. }
  33117. }
  33118. void Component::exitModalState (const int returnValue)
  33119. {
  33120. if (isCurrentlyModal())
  33121. {
  33122. if (MessageManager::getInstance()->isThisTheMessageThread())
  33123. {
  33124. ModalComponentManager::getInstance()->endModal (this, returnValue);
  33125. flags.currentlyModalFlag = false;
  33126. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33127. }
  33128. else
  33129. {
  33130. class ExitModalStateMessage : public CallbackMessage
  33131. {
  33132. public:
  33133. ExitModalStateMessage (Component* const target_, const int result_)
  33134. : target (target_), result (result_) {}
  33135. void messageCallback()
  33136. {
  33137. if (target != 0)
  33138. target->exitModalState (result);
  33139. }
  33140. private:
  33141. Component::SafePointer<Component> target;
  33142. int result;
  33143. };
  33144. (new ExitModalStateMessage (this, returnValue))->post();
  33145. }
  33146. }
  33147. }
  33148. bool Component::isCurrentlyModal() const throw()
  33149. {
  33150. return flags.currentlyModalFlag
  33151. && getCurrentlyModalComponent() == this;
  33152. }
  33153. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33154. {
  33155. Component* const mc = getCurrentlyModalComponent();
  33156. return mc != 0
  33157. && mc != this
  33158. && (! mc->isParentOf (this))
  33159. && ! mc->canModalEventBeSentToComponent (this);
  33160. }
  33161. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33162. {
  33163. return ModalComponentManager::getInstance()->getNumModalComponents();
  33164. }
  33165. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33166. {
  33167. return ModalComponentManager::getInstance()->getModalComponent (index);
  33168. }
  33169. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33170. {
  33171. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33172. }
  33173. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33174. {
  33175. return flags.bringToFrontOnClickFlag;
  33176. }
  33177. void Component::setMouseCursor (const MouseCursor& cursor)
  33178. {
  33179. if (cursor_ != cursor)
  33180. {
  33181. cursor_ = cursor;
  33182. if (flags.visibleFlag)
  33183. updateMouseCursor();
  33184. }
  33185. }
  33186. const MouseCursor Component::getMouseCursor()
  33187. {
  33188. return cursor_;
  33189. }
  33190. void Component::updateMouseCursor() const
  33191. {
  33192. sendFakeMouseMove();
  33193. }
  33194. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33195. {
  33196. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33197. }
  33198. void Component::setAlpha (const float newAlpha)
  33199. {
  33200. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  33201. if (componentTransparency != newIntAlpha)
  33202. {
  33203. componentTransparency = newIntAlpha;
  33204. if (flags.hasHeavyweightPeerFlag)
  33205. {
  33206. ComponentPeer* const peer = getPeer();
  33207. if (peer != 0)
  33208. peer->setAlpha (newAlpha);
  33209. }
  33210. else
  33211. {
  33212. repaint();
  33213. }
  33214. }
  33215. }
  33216. float Component::getAlpha() const
  33217. {
  33218. return (255 - componentTransparency) / 255.0f;
  33219. }
  33220. void Component::repaintParent()
  33221. {
  33222. if (flags.visibleFlag)
  33223. internalRepaint (0, 0, getWidth(), getHeight());
  33224. }
  33225. void Component::repaint()
  33226. {
  33227. repaint (0, 0, getWidth(), getHeight());
  33228. }
  33229. void Component::repaint (const int x, const int y,
  33230. const int w, const int h)
  33231. {
  33232. bufferedImage_ = Image::null;
  33233. if (flags.visibleFlag)
  33234. internalRepaint (x, y, w, h);
  33235. }
  33236. void Component::repaint (const Rectangle<int>& area)
  33237. {
  33238. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33239. }
  33240. void Component::internalRepaint (int x, int y, int w, int h)
  33241. {
  33242. // if component methods are being called from threads other than the message
  33243. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33244. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33245. if (x < 0)
  33246. {
  33247. w += x;
  33248. x = 0;
  33249. }
  33250. if (x + w > getWidth())
  33251. w = getWidth() - x;
  33252. if (w > 0)
  33253. {
  33254. if (y < 0)
  33255. {
  33256. h += y;
  33257. y = 0;
  33258. }
  33259. if (y + h > getHeight())
  33260. h = getHeight() - y;
  33261. if (h > 0)
  33262. {
  33263. if (parentComponent_ != 0)
  33264. {
  33265. if (parentComponent_->flags.visibleFlag)
  33266. {
  33267. if (affineTransform_ == 0)
  33268. {
  33269. parentComponent_->internalRepaint (x + getX(), y + getY(), w, h);
  33270. }
  33271. else
  33272. {
  33273. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  33274. parentComponent_->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  33275. }
  33276. }
  33277. }
  33278. else if (flags.hasHeavyweightPeerFlag)
  33279. {
  33280. ComponentPeer* const peer = getPeer();
  33281. if (peer != 0)
  33282. peer->repaint (Rectangle<int> (x, y, w, h));
  33283. }
  33284. }
  33285. }
  33286. }
  33287. void Component::paintComponent (Graphics& g)
  33288. {
  33289. if (flags.bufferToImageFlag)
  33290. {
  33291. if (bufferedImage_.isNull())
  33292. {
  33293. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33294. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33295. Graphics imG (bufferedImage_);
  33296. paint (imG);
  33297. }
  33298. g.setColour (Colours::black.withAlpha (getAlpha()));
  33299. g.drawImageAt (bufferedImage_, 0, 0);
  33300. }
  33301. else
  33302. {
  33303. paint (g);
  33304. }
  33305. }
  33306. void Component::paintWithinParentContext (Graphics& g)
  33307. {
  33308. g.setOrigin (getX(), getY());
  33309. paintEntireComponent (g, false);
  33310. }
  33311. void Component::paintComponentAndChildren (Graphics& g)
  33312. {
  33313. const Rectangle<int> clipBounds (g.getClipBounds());
  33314. if (flags.dontClipGraphicsFlag)
  33315. {
  33316. paintComponent (g);
  33317. }
  33318. else
  33319. {
  33320. g.saveState();
  33321. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33322. if (! g.isClipEmpty())
  33323. paintComponent (g);
  33324. g.restoreState();
  33325. }
  33326. for (int i = 0; i < childComponentList_.size(); ++i)
  33327. {
  33328. Component& child = *childComponentList_.getUnchecked (i);
  33329. if (child.isVisible())
  33330. {
  33331. if (child.affineTransform_ != 0)
  33332. {
  33333. g.saveState();
  33334. g.addTransform (*child.affineTransform_);
  33335. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33336. child.paintWithinParentContext (g);
  33337. g.restoreState();
  33338. }
  33339. else if (clipBounds.intersects (child.getBounds()))
  33340. {
  33341. g.saveState();
  33342. if (child.flags.dontClipGraphicsFlag)
  33343. {
  33344. child.paintWithinParentContext (g);
  33345. }
  33346. else if (g.reduceClipRegion (child.getBounds()))
  33347. {
  33348. bool nothingClipped = true;
  33349. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33350. {
  33351. const Component& sibling = *childComponentList_.getUnchecked (j);
  33352. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform_ == 0)
  33353. {
  33354. nothingClipped = false;
  33355. g.excludeClipRegion (sibling.getBounds());
  33356. }
  33357. }
  33358. if (nothingClipped || ! g.isClipEmpty())
  33359. child.paintWithinParentContext (g);
  33360. }
  33361. g.restoreState();
  33362. }
  33363. }
  33364. }
  33365. g.saveState();
  33366. paintOverChildren (g);
  33367. g.restoreState();
  33368. }
  33369. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33370. {
  33371. jassert (! g.isClipEmpty());
  33372. #if JUCE_DEBUG
  33373. flags.isInsidePaintCall = true;
  33374. #endif
  33375. if (effect_ != 0)
  33376. {
  33377. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33378. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33379. {
  33380. Graphics g2 (effectImage);
  33381. paintComponentAndChildren (g2);
  33382. }
  33383. effect_->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33384. }
  33385. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33386. {
  33387. if (componentTransparency < 255)
  33388. {
  33389. g.beginTransparencyLayer (getAlpha());
  33390. paintComponentAndChildren (g);
  33391. g.endTransparencyLayer();
  33392. }
  33393. }
  33394. else
  33395. {
  33396. paintComponentAndChildren (g);
  33397. }
  33398. #if JUCE_DEBUG
  33399. flags.isInsidePaintCall = false;
  33400. #endif
  33401. }
  33402. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33403. {
  33404. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33405. }
  33406. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33407. const bool clipImageToComponentBounds)
  33408. {
  33409. Rectangle<int> r (areaToGrab);
  33410. if (clipImageToComponentBounds)
  33411. r = r.getIntersection (getLocalBounds());
  33412. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33413. jmax (1, r.getWidth()),
  33414. jmax (1, r.getHeight()),
  33415. true);
  33416. Graphics imageContext (componentImage);
  33417. imageContext.setOrigin (-r.getX(), -r.getY());
  33418. paintEntireComponent (imageContext, true);
  33419. return componentImage;
  33420. }
  33421. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33422. {
  33423. if (effect_ != effect)
  33424. {
  33425. effect_ = effect;
  33426. repaint();
  33427. }
  33428. }
  33429. LookAndFeel& Component::getLookAndFeel() const throw()
  33430. {
  33431. const Component* c = this;
  33432. do
  33433. {
  33434. if (c->lookAndFeel_ != 0)
  33435. return *(c->lookAndFeel_);
  33436. c = c->parentComponent_;
  33437. }
  33438. while (c != 0);
  33439. return LookAndFeel::getDefaultLookAndFeel();
  33440. }
  33441. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33442. {
  33443. if (lookAndFeel_ != newLookAndFeel)
  33444. {
  33445. lookAndFeel_ = newLookAndFeel;
  33446. sendLookAndFeelChange();
  33447. }
  33448. }
  33449. void Component::lookAndFeelChanged()
  33450. {
  33451. }
  33452. void Component::sendLookAndFeelChange()
  33453. {
  33454. repaint();
  33455. SafePointer<Component> safePointer (this);
  33456. lookAndFeelChanged();
  33457. if (safePointer != 0)
  33458. {
  33459. for (int i = childComponentList_.size(); --i >= 0;)
  33460. {
  33461. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33462. if (safePointer == 0)
  33463. return;
  33464. i = jmin (i, childComponentList_.size());
  33465. }
  33466. }
  33467. }
  33468. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33469. {
  33470. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33471. if (v != 0)
  33472. return Colour ((int) *v);
  33473. if (inheritFromParent && parentComponent_ != 0)
  33474. return parentComponent_->findColour (colourId, true);
  33475. return getLookAndFeel().findColour (colourId);
  33476. }
  33477. bool Component::isColourSpecified (const int colourId) const
  33478. {
  33479. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33480. }
  33481. void Component::removeColour (const int colourId)
  33482. {
  33483. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33484. colourChanged();
  33485. }
  33486. void Component::setColour (const int colourId, const Colour& colour)
  33487. {
  33488. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33489. colourChanged();
  33490. }
  33491. void Component::copyAllExplicitColoursTo (Component& target) const
  33492. {
  33493. bool changed = false;
  33494. for (int i = properties.size(); --i >= 0;)
  33495. {
  33496. const Identifier name (properties.getName(i));
  33497. if (name.toString().startsWith ("jcclr_"))
  33498. if (target.properties.set (name, properties [name]))
  33499. changed = true;
  33500. }
  33501. if (changed)
  33502. target.colourChanged();
  33503. }
  33504. void Component::colourChanged()
  33505. {
  33506. }
  33507. const Rectangle<int> Component::getLocalBounds() const throw()
  33508. {
  33509. return Rectangle<int> (getWidth(), getHeight());
  33510. }
  33511. const Rectangle<int> Component::getBoundsInParent() const throw()
  33512. {
  33513. return affineTransform_ == 0 ? bounds_
  33514. : bounds_.toFloat().transformed (*affineTransform_).getSmallestIntegerContainer();
  33515. }
  33516. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33517. {
  33518. result.clear();
  33519. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33520. if (! unclipped.isEmpty())
  33521. {
  33522. result.add (unclipped);
  33523. if (includeSiblings)
  33524. {
  33525. const Component* const c = getTopLevelComponent();
  33526. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33527. c->getLocalBounds(), this);
  33528. }
  33529. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33530. result.consolidate();
  33531. }
  33532. }
  33533. void Component::mouseEnter (const MouseEvent&)
  33534. {
  33535. // base class does nothing
  33536. }
  33537. void Component::mouseExit (const MouseEvent&)
  33538. {
  33539. // base class does nothing
  33540. }
  33541. void Component::mouseDown (const MouseEvent&)
  33542. {
  33543. // base class does nothing
  33544. }
  33545. void Component::mouseUp (const MouseEvent&)
  33546. {
  33547. // base class does nothing
  33548. }
  33549. void Component::mouseDrag (const MouseEvent&)
  33550. {
  33551. // base class does nothing
  33552. }
  33553. void Component::mouseMove (const MouseEvent&)
  33554. {
  33555. // base class does nothing
  33556. }
  33557. void Component::mouseDoubleClick (const MouseEvent&)
  33558. {
  33559. // base class does nothing
  33560. }
  33561. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33562. {
  33563. // the base class just passes this event up to its parent..
  33564. if (parentComponent_ != 0)
  33565. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33566. wheelIncrementX, wheelIncrementY);
  33567. }
  33568. void Component::resized()
  33569. {
  33570. // base class does nothing
  33571. }
  33572. void Component::moved()
  33573. {
  33574. // base class does nothing
  33575. }
  33576. void Component::childBoundsChanged (Component*)
  33577. {
  33578. // base class does nothing
  33579. }
  33580. void Component::parentSizeChanged()
  33581. {
  33582. // base class does nothing
  33583. }
  33584. void Component::addComponentListener (ComponentListener* const newListener)
  33585. {
  33586. componentListeners.add (newListener);
  33587. }
  33588. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33589. {
  33590. componentListeners.remove (listenerToRemove);
  33591. }
  33592. void Component::inputAttemptWhenModal()
  33593. {
  33594. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33595. getLookAndFeel().playAlertSound();
  33596. }
  33597. bool Component::canModalEventBeSentToComponent (const Component*)
  33598. {
  33599. return false;
  33600. }
  33601. void Component::internalModalInputAttempt()
  33602. {
  33603. Component* const current = getCurrentlyModalComponent();
  33604. if (current != 0)
  33605. current->inputAttemptWhenModal();
  33606. }
  33607. void Component::paint (Graphics&)
  33608. {
  33609. // all painting is done in the subclasses
  33610. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33611. }
  33612. void Component::paintOverChildren (Graphics&)
  33613. {
  33614. // all painting is done in the subclasses
  33615. }
  33616. void Component::postCommandMessage (const int commandId)
  33617. {
  33618. class CustomCommandMessage : public CallbackMessage
  33619. {
  33620. public:
  33621. CustomCommandMessage (Component* const target_, const int commandId_)
  33622. : target (target_), commandId (commandId_) {}
  33623. void messageCallback()
  33624. {
  33625. if (target != 0)
  33626. target->handleCommandMessage (commandId);
  33627. }
  33628. private:
  33629. Component::SafePointer<Component> target;
  33630. int commandId;
  33631. };
  33632. (new CustomCommandMessage (this, commandId))->post();
  33633. }
  33634. void Component::handleCommandMessage (int)
  33635. {
  33636. // used by subclasses
  33637. }
  33638. void Component::addMouseListener (MouseListener* const newListener,
  33639. const bool wantsEventsForAllNestedChildComponents)
  33640. {
  33641. // if component methods are being called from threads other than the message
  33642. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33643. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33644. // If you register a component as a mouselistener for itself, it'll receive all the events
  33645. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33646. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33647. if (mouseListeners_ == 0)
  33648. mouseListeners_ = new MouseListenerList();
  33649. mouseListeners_->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33650. }
  33651. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33652. {
  33653. // if component methods are being called from threads other than the message
  33654. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33655. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33656. if (mouseListeners_ != 0)
  33657. mouseListeners_->removeListener (listenerToRemove);
  33658. }
  33659. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33660. {
  33661. if (isCurrentlyBlockedByAnotherModalComponent())
  33662. {
  33663. // if something else is modal, always just show a normal mouse cursor
  33664. source.showMouseCursor (MouseCursor::NormalCursor);
  33665. return;
  33666. }
  33667. if (! flags.mouseInsideFlag)
  33668. {
  33669. flags.mouseInsideFlag = true;
  33670. flags.mouseOverFlag = true;
  33671. flags.mouseDownFlag = false;
  33672. BailOutChecker checker (this);
  33673. if (flags.repaintOnMouseActivityFlag)
  33674. repaint();
  33675. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33676. this, this, time, relativePos, time, 0, false);
  33677. mouseEnter (me);
  33678. if (checker.shouldBailOut())
  33679. return;
  33680. Desktop::getInstance().resetTimer();
  33681. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33682. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseEnter, me);
  33683. }
  33684. }
  33685. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33686. {
  33687. BailOutChecker checker (this);
  33688. if (flags.mouseDownFlag)
  33689. {
  33690. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33691. if (checker.shouldBailOut())
  33692. return;
  33693. }
  33694. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33695. {
  33696. flags.mouseInsideFlag = false;
  33697. flags.mouseOverFlag = false;
  33698. flags.mouseDownFlag = false;
  33699. if (flags.repaintOnMouseActivityFlag)
  33700. repaint();
  33701. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33702. this, this, time, relativePos, time, 0, false);
  33703. mouseExit (me);
  33704. if (checker.shouldBailOut())
  33705. return;
  33706. Desktop::getInstance().resetTimer();
  33707. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33708. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseExit, me);
  33709. }
  33710. }
  33711. class InternalDragRepeater : public Timer
  33712. {
  33713. public:
  33714. InternalDragRepeater()
  33715. {}
  33716. ~InternalDragRepeater()
  33717. {
  33718. clearSingletonInstance();
  33719. }
  33720. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33721. void timerCallback()
  33722. {
  33723. Desktop& desktop = Desktop::getInstance();
  33724. int numMiceDown = 0;
  33725. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33726. {
  33727. MouseInputSource* const source = desktop.getMouseSource(i);
  33728. if (source->isDragging())
  33729. {
  33730. source->triggerFakeMove();
  33731. ++numMiceDown;
  33732. }
  33733. }
  33734. if (numMiceDown == 0)
  33735. deleteInstance();
  33736. }
  33737. private:
  33738. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalDragRepeater);
  33739. };
  33740. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33741. void Component::beginDragAutoRepeat (const int interval)
  33742. {
  33743. if (interval > 0)
  33744. {
  33745. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33746. InternalDragRepeater::getInstance()->startTimer (interval);
  33747. }
  33748. else
  33749. {
  33750. InternalDragRepeater::deleteInstance();
  33751. }
  33752. }
  33753. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33754. {
  33755. Desktop& desktop = Desktop::getInstance();
  33756. BailOutChecker checker (this);
  33757. if (isCurrentlyBlockedByAnotherModalComponent())
  33758. {
  33759. internalModalInputAttempt();
  33760. if (checker.shouldBailOut())
  33761. return;
  33762. // If processing the input attempt has exited the modal loop, we'll allow the event
  33763. // to be delivered..
  33764. if (isCurrentlyBlockedByAnotherModalComponent())
  33765. {
  33766. // allow blocked mouse-events to go to global listeners..
  33767. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33768. this, this, time, relativePos, time,
  33769. source.getNumberOfMultipleClicks(), false);
  33770. desktop.resetTimer();
  33771. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33772. return;
  33773. }
  33774. }
  33775. {
  33776. Component* c = this;
  33777. while (c != 0)
  33778. {
  33779. if (c->isBroughtToFrontOnMouseClick())
  33780. {
  33781. c->toFront (true);
  33782. if (checker.shouldBailOut())
  33783. return;
  33784. }
  33785. c = c->parentComponent_;
  33786. }
  33787. }
  33788. if (! flags.dontFocusOnMouseClickFlag)
  33789. {
  33790. grabFocusInternal (focusChangedByMouseClick);
  33791. if (checker.shouldBailOut())
  33792. return;
  33793. }
  33794. flags.mouseDownFlag = true;
  33795. flags.mouseOverFlag = true;
  33796. if (flags.repaintOnMouseActivityFlag)
  33797. repaint();
  33798. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33799. this, this, time, relativePos, time,
  33800. source.getNumberOfMultipleClicks(), false);
  33801. mouseDown (me);
  33802. if (checker.shouldBailOut())
  33803. return;
  33804. desktop.resetTimer();
  33805. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33806. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDown, me);
  33807. }
  33808. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33809. {
  33810. if (flags.mouseDownFlag)
  33811. {
  33812. Desktop& desktop = Desktop::getInstance();
  33813. flags.mouseDownFlag = false;
  33814. BailOutChecker checker (this);
  33815. if (flags.repaintOnMouseActivityFlag)
  33816. repaint();
  33817. const MouseEvent me (source, relativePos,
  33818. oldModifiers, this, this, time,
  33819. getLocalPoint (0, source.getLastMouseDownPosition()),
  33820. source.getLastMouseDownTime(),
  33821. source.getNumberOfMultipleClicks(),
  33822. source.hasMouseMovedSignificantlySincePressed());
  33823. mouseUp (me);
  33824. if (checker.shouldBailOut())
  33825. return;
  33826. desktop.resetTimer();
  33827. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33828. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseUp, me);
  33829. if (checker.shouldBailOut())
  33830. return;
  33831. // check for double-click
  33832. if (me.getNumberOfClicks() >= 2)
  33833. {
  33834. mouseDoubleClick (me);
  33835. if (checker.shouldBailOut())
  33836. return;
  33837. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33838. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDoubleClick, me);
  33839. }
  33840. }
  33841. }
  33842. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33843. {
  33844. if (flags.mouseDownFlag)
  33845. {
  33846. Desktop& desktop = Desktop::getInstance();
  33847. flags.mouseOverFlag = reallyContains (relativePos, false);
  33848. BailOutChecker checker (this);
  33849. const MouseEvent me (source, relativePos,
  33850. source.getCurrentModifiers(), this, this, time,
  33851. getLocalPoint (0, source.getLastMouseDownPosition()),
  33852. source.getLastMouseDownTime(),
  33853. source.getNumberOfMultipleClicks(),
  33854. source.hasMouseMovedSignificantlySincePressed());
  33855. mouseDrag (me);
  33856. if (checker.shouldBailOut())
  33857. return;
  33858. desktop.resetTimer();
  33859. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33860. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDrag, me);
  33861. }
  33862. }
  33863. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33864. {
  33865. Desktop& desktop = Desktop::getInstance();
  33866. BailOutChecker checker (this);
  33867. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33868. this, this, time, relativePos, time, 0, false);
  33869. if (isCurrentlyBlockedByAnotherModalComponent())
  33870. {
  33871. // allow blocked mouse-events to go to global listeners..
  33872. desktop.sendMouseMove();
  33873. }
  33874. else
  33875. {
  33876. flags.mouseOverFlag = true;
  33877. mouseMove (me);
  33878. if (checker.shouldBailOut())
  33879. return;
  33880. desktop.resetTimer();
  33881. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33882. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseMove, me);
  33883. }
  33884. }
  33885. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33886. const Time& time, const float amountX, const float amountY)
  33887. {
  33888. Desktop& desktop = Desktop::getInstance();
  33889. BailOutChecker checker (this);
  33890. const float wheelIncrementX = amountX / 256.0f;
  33891. const float wheelIncrementY = amountY / 256.0f;
  33892. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33893. this, this, time, relativePos, time, 0, false);
  33894. if (isCurrentlyBlockedByAnotherModalComponent())
  33895. {
  33896. // allow blocked mouse-events to go to global listeners..
  33897. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33898. }
  33899. else
  33900. {
  33901. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33902. if (checker.shouldBailOut())
  33903. return;
  33904. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33905. MouseListenerList::sendWheelEvent (this, checker, me, wheelIncrementX, wheelIncrementY);
  33906. }
  33907. }
  33908. void Component::sendFakeMouseMove() const
  33909. {
  33910. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33911. }
  33912. void Component::broughtToFront()
  33913. {
  33914. }
  33915. void Component::internalBroughtToFront()
  33916. {
  33917. if (flags.hasHeavyweightPeerFlag)
  33918. Desktop::getInstance().componentBroughtToFront (this);
  33919. BailOutChecker checker (this);
  33920. broughtToFront();
  33921. if (checker.shouldBailOut())
  33922. return;
  33923. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33924. if (checker.shouldBailOut())
  33925. return;
  33926. // When brought to the front and there's a modal component blocking this one,
  33927. // we need to bring the modal one to the front instead..
  33928. Component* const cm = getCurrentlyModalComponent();
  33929. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33930. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33931. }
  33932. void Component::focusGained (FocusChangeType)
  33933. {
  33934. // base class does nothing
  33935. }
  33936. void Component::internalFocusGain (const FocusChangeType cause)
  33937. {
  33938. SafePointer<Component> safePointer (this);
  33939. focusGained (cause);
  33940. if (safePointer != 0)
  33941. internalChildFocusChange (cause);
  33942. }
  33943. void Component::focusLost (FocusChangeType)
  33944. {
  33945. // base class does nothing
  33946. }
  33947. void Component::internalFocusLoss (const FocusChangeType cause)
  33948. {
  33949. SafePointer<Component> safePointer (this);
  33950. focusLost (focusChangedDirectly);
  33951. if (safePointer != 0)
  33952. internalChildFocusChange (cause);
  33953. }
  33954. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33955. {
  33956. // base class does nothing
  33957. }
  33958. void Component::internalChildFocusChange (FocusChangeType cause)
  33959. {
  33960. const bool childIsNowFocused = hasKeyboardFocus (true);
  33961. if (flags.childCompFocusedFlag != childIsNowFocused)
  33962. {
  33963. flags.childCompFocusedFlag = childIsNowFocused;
  33964. SafePointer<Component> safePointer (this);
  33965. focusOfChildComponentChanged (cause);
  33966. if (safePointer == 0)
  33967. return;
  33968. }
  33969. if (parentComponent_ != 0)
  33970. parentComponent_->internalChildFocusChange (cause);
  33971. }
  33972. bool Component::isEnabled() const throw()
  33973. {
  33974. return (! flags.isDisabledFlag)
  33975. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33976. }
  33977. void Component::setEnabled (const bool shouldBeEnabled)
  33978. {
  33979. if (flags.isDisabledFlag == shouldBeEnabled)
  33980. {
  33981. flags.isDisabledFlag = ! shouldBeEnabled;
  33982. // if any parent components are disabled, setting our flag won't make a difference,
  33983. // so no need to send a change message
  33984. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33985. sendEnablementChangeMessage();
  33986. }
  33987. }
  33988. void Component::sendEnablementChangeMessage()
  33989. {
  33990. SafePointer<Component> safePointer (this);
  33991. enablementChanged();
  33992. if (safePointer == 0)
  33993. return;
  33994. for (int i = getNumChildComponents(); --i >= 0;)
  33995. {
  33996. Component* const c = getChildComponent (i);
  33997. if (c != 0)
  33998. {
  33999. c->sendEnablementChangeMessage();
  34000. if (safePointer == 0)
  34001. return;
  34002. }
  34003. }
  34004. }
  34005. void Component::enablementChanged()
  34006. {
  34007. }
  34008. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34009. {
  34010. flags.wantsFocusFlag = wantsFocus;
  34011. }
  34012. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34013. {
  34014. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34015. }
  34016. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34017. {
  34018. return ! flags.dontFocusOnMouseClickFlag;
  34019. }
  34020. bool Component::getWantsKeyboardFocus() const throw()
  34021. {
  34022. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34023. }
  34024. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34025. {
  34026. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34027. }
  34028. bool Component::isFocusContainer() const throw()
  34029. {
  34030. return flags.isFocusContainerFlag;
  34031. }
  34032. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34033. int Component::getExplicitFocusOrder() const
  34034. {
  34035. return properties [juce_explicitFocusOrderId];
  34036. }
  34037. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34038. {
  34039. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34040. }
  34041. KeyboardFocusTraverser* Component::createFocusTraverser()
  34042. {
  34043. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34044. return new KeyboardFocusTraverser();
  34045. return parentComponent_->createFocusTraverser();
  34046. }
  34047. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34048. {
  34049. // give the focus to this component
  34050. if (currentlyFocusedComponent != this)
  34051. {
  34052. JUCE_TRY
  34053. {
  34054. // get the focus onto our desktop window
  34055. ComponentPeer* const peer = getPeer();
  34056. if (peer != 0)
  34057. {
  34058. SafePointer<Component> safePointer (this);
  34059. peer->grabFocus();
  34060. if (peer->isFocused() && currentlyFocusedComponent != this)
  34061. {
  34062. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34063. currentlyFocusedComponent = this;
  34064. Desktop::getInstance().triggerFocusCallback();
  34065. // call this after setting currentlyFocusedComponent so that the one that's
  34066. // losing it has a chance to see where focus is going
  34067. if (componentLosingFocus != 0)
  34068. componentLosingFocus->internalFocusLoss (cause);
  34069. if (currentlyFocusedComponent == this)
  34070. {
  34071. focusGained (cause);
  34072. if (safePointer != 0)
  34073. internalChildFocusChange (cause);
  34074. }
  34075. }
  34076. }
  34077. }
  34078. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34079. catch (const std::exception& e)
  34080. {
  34081. currentlyFocusedComponent = 0;
  34082. Desktop::getInstance().triggerFocusCallback();
  34083. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34084. }
  34085. catch (...)
  34086. {
  34087. currentlyFocusedComponent = 0;
  34088. Desktop::getInstance().triggerFocusCallback();
  34089. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34090. }
  34091. #endif
  34092. }
  34093. }
  34094. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34095. {
  34096. if (isShowing())
  34097. {
  34098. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34099. {
  34100. takeKeyboardFocus (cause);
  34101. }
  34102. else
  34103. {
  34104. if (isParentOf (currentlyFocusedComponent)
  34105. && currentlyFocusedComponent->isShowing())
  34106. {
  34107. // do nothing if the focused component is actually a child of ours..
  34108. }
  34109. else
  34110. {
  34111. // find the default child component..
  34112. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34113. if (traverser != 0)
  34114. {
  34115. Component* const defaultComp = traverser->getDefaultComponent (this);
  34116. traverser = 0;
  34117. if (defaultComp != 0)
  34118. {
  34119. defaultComp->grabFocusInternal (cause, false);
  34120. return;
  34121. }
  34122. }
  34123. if (canTryParent && parentComponent_ != 0)
  34124. {
  34125. // if no children want it and we're allowed to try our parent comp,
  34126. // then pass up to parent, which will try our siblings.
  34127. parentComponent_->grabFocusInternal (cause, true);
  34128. }
  34129. }
  34130. }
  34131. }
  34132. }
  34133. void Component::grabKeyboardFocus()
  34134. {
  34135. // if component methods are being called from threads other than the message
  34136. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34137. CHECK_MESSAGE_MANAGER_IS_LOCKED
  34138. grabFocusInternal (focusChangedDirectly);
  34139. }
  34140. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34141. {
  34142. // if component methods are being called from threads other than the message
  34143. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34144. CHECK_MESSAGE_MANAGER_IS_LOCKED
  34145. if (parentComponent_ != 0)
  34146. {
  34147. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34148. if (traverser != 0)
  34149. {
  34150. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34151. : traverser->getPreviousComponent (this);
  34152. traverser = 0;
  34153. if (nextComp != 0)
  34154. {
  34155. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34156. {
  34157. SafePointer<Component> nextCompPointer (nextComp);
  34158. internalModalInputAttempt();
  34159. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34160. return;
  34161. }
  34162. nextComp->grabFocusInternal (focusChangedByTabKey);
  34163. return;
  34164. }
  34165. }
  34166. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34167. }
  34168. }
  34169. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34170. {
  34171. return (currentlyFocusedComponent == this)
  34172. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34173. }
  34174. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34175. {
  34176. return currentlyFocusedComponent;
  34177. }
  34178. void Component::giveAwayFocus()
  34179. {
  34180. // use a copy so we can clear the value before the call
  34181. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34182. currentlyFocusedComponent = 0;
  34183. Desktop::getInstance().triggerFocusCallback();
  34184. if (componentLosingFocus != 0)
  34185. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34186. }
  34187. bool Component::isMouseOver() const throw() { return flags.mouseOverFlag; }
  34188. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  34189. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  34190. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34191. {
  34192. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34193. }
  34194. const Point<int> Component::getMouseXYRelative() const
  34195. {
  34196. return getLocalPoint (0, Desktop::getMousePosition());
  34197. }
  34198. const Rectangle<int> Component::getParentMonitorArea() const
  34199. {
  34200. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  34201. }
  34202. void Component::addKeyListener (KeyListener* const newListener)
  34203. {
  34204. if (keyListeners_ == 0)
  34205. keyListeners_ = new Array <KeyListener*>();
  34206. keyListeners_->addIfNotAlreadyThere (newListener);
  34207. }
  34208. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34209. {
  34210. if (keyListeners_ != 0)
  34211. keyListeners_->removeValue (listenerToRemove);
  34212. }
  34213. bool Component::keyPressed (const KeyPress&)
  34214. {
  34215. return false;
  34216. }
  34217. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34218. {
  34219. return false;
  34220. }
  34221. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34222. {
  34223. if (parentComponent_ != 0)
  34224. parentComponent_->modifierKeysChanged (modifiers);
  34225. }
  34226. void Component::internalModifierKeysChanged()
  34227. {
  34228. sendFakeMouseMove();
  34229. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34230. }
  34231. ComponentPeer* Component::getPeer() const
  34232. {
  34233. if (flags.hasHeavyweightPeerFlag)
  34234. return ComponentPeer::getPeerFor (this);
  34235. else if (parentComponent_ != 0)
  34236. return parentComponent_->getPeer();
  34237. else
  34238. return 0;
  34239. }
  34240. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34241. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34242. {
  34243. jassert (component1 != 0);
  34244. }
  34245. bool Component::BailOutChecker::shouldBailOut() const throw()
  34246. {
  34247. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34248. }
  34249. END_JUCE_NAMESPACE
  34250. /*** End of inlined file: juce_Component.cpp ***/
  34251. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34252. BEGIN_JUCE_NAMESPACE
  34253. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34254. void ComponentListener::componentBroughtToFront (Component&) {}
  34255. void ComponentListener::componentVisibilityChanged (Component&) {}
  34256. void ComponentListener::componentChildrenChanged (Component&) {}
  34257. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34258. void ComponentListener::componentNameChanged (Component&) {}
  34259. void ComponentListener::componentBeingDeleted (Component&) {}
  34260. END_JUCE_NAMESPACE
  34261. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34262. /*** Start of inlined file: juce_Desktop.cpp ***/
  34263. BEGIN_JUCE_NAMESPACE
  34264. Desktop::Desktop()
  34265. : mouseClickCounter (0),
  34266. kioskModeComponent (0),
  34267. allowedOrientations (allOrientations)
  34268. {
  34269. createMouseInputSources();
  34270. refreshMonitorSizes();
  34271. }
  34272. Desktop::~Desktop()
  34273. {
  34274. jassert (instance == this);
  34275. instance = 0;
  34276. // doh! If you don't delete all your windows before exiting, you're going to
  34277. // be leaking memory!
  34278. jassert (desktopComponents.size() == 0);
  34279. }
  34280. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34281. {
  34282. if (instance == 0)
  34283. instance = new Desktop();
  34284. return *instance;
  34285. }
  34286. Desktop* Desktop::instance = 0;
  34287. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34288. const bool clipToWorkArea);
  34289. void Desktop::refreshMonitorSizes()
  34290. {
  34291. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34292. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34293. monitorCoordsClipped.clear();
  34294. monitorCoordsUnclipped.clear();
  34295. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34296. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34297. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34298. if (oldClipped != monitorCoordsClipped
  34299. || oldUnclipped != monitorCoordsUnclipped)
  34300. {
  34301. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34302. {
  34303. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34304. if (p != 0)
  34305. p->handleScreenSizeChange();
  34306. }
  34307. }
  34308. }
  34309. int Desktop::getNumDisplayMonitors() const throw()
  34310. {
  34311. return monitorCoordsClipped.size();
  34312. }
  34313. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34314. {
  34315. return clippedToWorkArea ? monitorCoordsClipped [index]
  34316. : monitorCoordsUnclipped [index];
  34317. }
  34318. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34319. {
  34320. RectangleList rl;
  34321. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34322. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34323. return rl;
  34324. }
  34325. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34326. {
  34327. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34328. }
  34329. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34330. {
  34331. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34332. double bestDistance = 1.0e10;
  34333. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34334. {
  34335. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34336. if (rect.contains (position))
  34337. return rect;
  34338. const double distance = rect.getCentre().getDistanceFrom (position);
  34339. if (distance < bestDistance)
  34340. {
  34341. bestDistance = distance;
  34342. best = rect;
  34343. }
  34344. }
  34345. return best;
  34346. }
  34347. int Desktop::getNumComponents() const throw()
  34348. {
  34349. return desktopComponents.size();
  34350. }
  34351. Component* Desktop::getComponent (const int index) const throw()
  34352. {
  34353. return desktopComponents [index];
  34354. }
  34355. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34356. {
  34357. for (int i = desktopComponents.size(); --i >= 0;)
  34358. {
  34359. Component* const c = desktopComponents.getUnchecked(i);
  34360. if (c->isVisible())
  34361. {
  34362. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34363. if (c->contains (relative))
  34364. return c->getComponentAt (relative);
  34365. }
  34366. }
  34367. return 0;
  34368. }
  34369. void Desktop::addDesktopComponent (Component* const c)
  34370. {
  34371. jassert (c != 0);
  34372. jassert (! desktopComponents.contains (c));
  34373. desktopComponents.addIfNotAlreadyThere (c);
  34374. }
  34375. void Desktop::removeDesktopComponent (Component* const c)
  34376. {
  34377. desktopComponents.removeValue (c);
  34378. }
  34379. void Desktop::componentBroughtToFront (Component* const c)
  34380. {
  34381. const int index = desktopComponents.indexOf (c);
  34382. jassert (index >= 0);
  34383. if (index >= 0)
  34384. {
  34385. int newIndex = -1;
  34386. if (! c->isAlwaysOnTop())
  34387. {
  34388. newIndex = desktopComponents.size();
  34389. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34390. --newIndex;
  34391. --newIndex;
  34392. }
  34393. desktopComponents.move (index, newIndex);
  34394. }
  34395. }
  34396. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34397. {
  34398. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34399. }
  34400. int Desktop::getMouseButtonClickCounter() throw()
  34401. {
  34402. return getInstance().mouseClickCounter;
  34403. }
  34404. void Desktop::incrementMouseClickCounter() throw()
  34405. {
  34406. ++mouseClickCounter;
  34407. }
  34408. int Desktop::getNumDraggingMouseSources() const throw()
  34409. {
  34410. int num = 0;
  34411. for (int i = mouseSources.size(); --i >= 0;)
  34412. if (mouseSources.getUnchecked(i)->isDragging())
  34413. ++num;
  34414. return num;
  34415. }
  34416. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34417. {
  34418. int num = 0;
  34419. for (int i = mouseSources.size(); --i >= 0;)
  34420. {
  34421. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34422. if (mi->isDragging())
  34423. {
  34424. if (index == num)
  34425. return mi;
  34426. ++num;
  34427. }
  34428. }
  34429. return 0;
  34430. }
  34431. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34432. {
  34433. focusListeners.add (listener);
  34434. }
  34435. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34436. {
  34437. focusListeners.remove (listener);
  34438. }
  34439. void Desktop::triggerFocusCallback()
  34440. {
  34441. triggerAsyncUpdate();
  34442. }
  34443. void Desktop::handleAsyncUpdate()
  34444. {
  34445. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34446. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34447. }
  34448. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34449. {
  34450. mouseListeners.add (listener);
  34451. resetTimer();
  34452. }
  34453. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34454. {
  34455. mouseListeners.remove (listener);
  34456. resetTimer();
  34457. }
  34458. void Desktop::timerCallback()
  34459. {
  34460. if (lastFakeMouseMove != getMousePosition())
  34461. sendMouseMove();
  34462. }
  34463. void Desktop::sendMouseMove()
  34464. {
  34465. if (! mouseListeners.isEmpty())
  34466. {
  34467. startTimer (20);
  34468. lastFakeMouseMove = getMousePosition();
  34469. Component* const target = findComponentAt (lastFakeMouseMove);
  34470. if (target != 0)
  34471. {
  34472. Component::BailOutChecker checker (target);
  34473. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34474. const Time now (Time::getCurrentTime());
  34475. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34476. target, target, now, pos, now, 0, false);
  34477. if (me.mods.isAnyMouseButtonDown())
  34478. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34479. else
  34480. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34481. }
  34482. }
  34483. }
  34484. void Desktop::resetTimer()
  34485. {
  34486. if (mouseListeners.size() == 0)
  34487. stopTimer();
  34488. else
  34489. startTimer (100);
  34490. lastFakeMouseMove = getMousePosition();
  34491. }
  34492. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34493. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34494. {
  34495. if (kioskModeComponent != componentToUse)
  34496. {
  34497. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34498. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34499. if (kioskModeComponent != 0)
  34500. {
  34501. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34502. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34503. }
  34504. kioskModeComponent = componentToUse;
  34505. if (kioskModeComponent != 0)
  34506. {
  34507. // Only components that are already on the desktop can be put into kiosk mode!
  34508. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34509. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34510. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34511. }
  34512. }
  34513. }
  34514. void Desktop::setOrientationsEnabled (const int newOrientations)
  34515. {
  34516. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34517. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34518. allowedOrientations = newOrientations;
  34519. }
  34520. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34521. {
  34522. // Make sure you only pass one valid flag in here...
  34523. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34524. return (allowedOrientations & orientation) != 0;
  34525. }
  34526. END_JUCE_NAMESPACE
  34527. /*** End of inlined file: juce_Desktop.cpp ***/
  34528. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34529. BEGIN_JUCE_NAMESPACE
  34530. class ModalComponentManager::ModalItem : public ComponentListener
  34531. {
  34532. public:
  34533. ModalItem (Component* const comp, Callback* const callback)
  34534. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34535. {
  34536. if (callback != 0)
  34537. callbacks.add (callback);
  34538. jassert (comp != 0);
  34539. component->addComponentListener (this);
  34540. }
  34541. ~ModalItem()
  34542. {
  34543. if (! isDeleted)
  34544. component->removeComponentListener (this);
  34545. }
  34546. void componentBeingDeleted (Component&)
  34547. {
  34548. isDeleted = true;
  34549. cancel();
  34550. }
  34551. void componentVisibilityChanged (Component&)
  34552. {
  34553. if (! component->isShowing())
  34554. cancel();
  34555. }
  34556. void componentParentHierarchyChanged (Component&)
  34557. {
  34558. if (! component->isShowing())
  34559. cancel();
  34560. }
  34561. void cancel()
  34562. {
  34563. if (isActive)
  34564. {
  34565. isActive = false;
  34566. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34567. }
  34568. }
  34569. Component* component;
  34570. OwnedArray<Callback> callbacks;
  34571. int returnValue;
  34572. bool isActive, isDeleted;
  34573. private:
  34574. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34575. };
  34576. ModalComponentManager::ModalComponentManager()
  34577. {
  34578. }
  34579. ModalComponentManager::~ModalComponentManager()
  34580. {
  34581. clearSingletonInstance();
  34582. }
  34583. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34584. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34585. {
  34586. if (component != 0)
  34587. stack.add (new ModalItem (component, callback));
  34588. }
  34589. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34590. {
  34591. if (callback != 0)
  34592. {
  34593. ScopedPointer<Callback> callbackDeleter (callback);
  34594. for (int i = stack.size(); --i >= 0;)
  34595. {
  34596. ModalItem* const item = stack.getUnchecked(i);
  34597. if (item->component == component)
  34598. {
  34599. item->callbacks.add (callback);
  34600. callbackDeleter.release();
  34601. break;
  34602. }
  34603. }
  34604. }
  34605. }
  34606. void ModalComponentManager::endModal (Component* component)
  34607. {
  34608. for (int i = stack.size(); --i >= 0;)
  34609. {
  34610. ModalItem* const item = stack.getUnchecked(i);
  34611. if (item->component == component)
  34612. item->cancel();
  34613. }
  34614. }
  34615. void ModalComponentManager::endModal (Component* component, int returnValue)
  34616. {
  34617. for (int i = stack.size(); --i >= 0;)
  34618. {
  34619. ModalItem* const item = stack.getUnchecked(i);
  34620. if (item->component == component)
  34621. {
  34622. item->returnValue = returnValue;
  34623. item->cancel();
  34624. }
  34625. }
  34626. }
  34627. int ModalComponentManager::getNumModalComponents() const
  34628. {
  34629. int n = 0;
  34630. for (int i = 0; i < stack.size(); ++i)
  34631. if (stack.getUnchecked(i)->isActive)
  34632. ++n;
  34633. return n;
  34634. }
  34635. Component* ModalComponentManager::getModalComponent (const int index) const
  34636. {
  34637. int n = 0;
  34638. for (int i = stack.size(); --i >= 0;)
  34639. {
  34640. const ModalItem* const item = stack.getUnchecked(i);
  34641. if (item->isActive)
  34642. if (n++ == index)
  34643. return item->component;
  34644. }
  34645. return 0;
  34646. }
  34647. bool ModalComponentManager::isModal (Component* const comp) const
  34648. {
  34649. for (int i = stack.size(); --i >= 0;)
  34650. {
  34651. const ModalItem* const item = stack.getUnchecked(i);
  34652. if (item->isActive && item->component == comp)
  34653. return true;
  34654. }
  34655. return false;
  34656. }
  34657. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34658. {
  34659. return comp == getModalComponent (0);
  34660. }
  34661. void ModalComponentManager::handleAsyncUpdate()
  34662. {
  34663. for (int i = stack.size(); --i >= 0;)
  34664. {
  34665. const ModalItem* const item = stack.getUnchecked(i);
  34666. if (! item->isActive)
  34667. {
  34668. for (int j = item->callbacks.size(); --j >= 0;)
  34669. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34670. stack.remove (i);
  34671. }
  34672. }
  34673. }
  34674. void ModalComponentManager::bringModalComponentsToFront()
  34675. {
  34676. ComponentPeer* lastOne = 0;
  34677. for (int i = 0; i < getNumModalComponents(); ++i)
  34678. {
  34679. Component* const c = getModalComponent (i);
  34680. if (c == 0)
  34681. break;
  34682. ComponentPeer* peer = c->getPeer();
  34683. if (peer != 0 && peer != lastOne)
  34684. {
  34685. if (lastOne == 0)
  34686. {
  34687. peer->toFront (true);
  34688. peer->grabFocus();
  34689. }
  34690. else
  34691. peer->toBehind (lastOne);
  34692. lastOne = peer;
  34693. }
  34694. }
  34695. }
  34696. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34697. {
  34698. public:
  34699. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34700. ~ReturnValueRetriever() {}
  34701. void modalStateFinished (int returnValue)
  34702. {
  34703. finished = true;
  34704. value = returnValue;
  34705. }
  34706. private:
  34707. int& value;
  34708. bool& finished;
  34709. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34710. };
  34711. int ModalComponentManager::runEventLoopForCurrentComponent()
  34712. {
  34713. // This can only be run from the message thread!
  34714. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34715. Component* currentlyModal = getModalComponent (0);
  34716. if (currentlyModal == 0)
  34717. return 0;
  34718. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34719. int returnValue = 0;
  34720. bool finished = false;
  34721. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34722. JUCE_TRY
  34723. {
  34724. while (! finished)
  34725. {
  34726. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34727. break;
  34728. }
  34729. }
  34730. JUCE_CATCH_EXCEPTION
  34731. if (prevFocused != 0)
  34732. prevFocused->grabKeyboardFocus();
  34733. return returnValue;
  34734. }
  34735. END_JUCE_NAMESPACE
  34736. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34737. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34738. BEGIN_JUCE_NAMESPACE
  34739. ArrowButton::ArrowButton (const String& name,
  34740. float arrowDirectionInRadians,
  34741. const Colour& arrowColour)
  34742. : Button (name),
  34743. colour (arrowColour)
  34744. {
  34745. path.lineTo (0.0f, 1.0f);
  34746. path.lineTo (1.0f, 0.5f);
  34747. path.closeSubPath();
  34748. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34749. 0.5f, 0.5f));
  34750. setComponentEffect (&shadow);
  34751. buttonStateChanged();
  34752. }
  34753. ArrowButton::~ArrowButton()
  34754. {
  34755. }
  34756. void ArrowButton::paintButton (Graphics& g,
  34757. bool /*isMouseOverButton*/,
  34758. bool /*isButtonDown*/)
  34759. {
  34760. g.setColour (colour);
  34761. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34762. (float) offset,
  34763. (float) (getWidth() - 3),
  34764. (float) (getHeight() - 3),
  34765. false));
  34766. }
  34767. void ArrowButton::buttonStateChanged()
  34768. {
  34769. offset = (isDown()) ? 1 : 0;
  34770. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34771. 0.3f, -1, 0);
  34772. }
  34773. END_JUCE_NAMESPACE
  34774. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34775. /*** Start of inlined file: juce_Button.cpp ***/
  34776. BEGIN_JUCE_NAMESPACE
  34777. class Button::RepeatTimer : public Timer
  34778. {
  34779. public:
  34780. RepeatTimer (Button& owner_) : owner (owner_) {}
  34781. void timerCallback() { owner.repeatTimerCallback(); }
  34782. private:
  34783. Button& owner;
  34784. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34785. };
  34786. Button::Button (const String& name)
  34787. : Component (name),
  34788. text (name),
  34789. buttonPressTime (0),
  34790. lastTimeCallbackTime (0),
  34791. commandManagerToUse (0),
  34792. autoRepeatDelay (-1),
  34793. autoRepeatSpeed (0),
  34794. autoRepeatMinimumDelay (-1),
  34795. radioGroupId (0),
  34796. commandID (0),
  34797. connectedEdgeFlags (0),
  34798. buttonState (buttonNormal),
  34799. lastToggleState (false),
  34800. clickTogglesState (false),
  34801. needsToRelease (false),
  34802. needsRepainting (false),
  34803. isKeyDown (false),
  34804. triggerOnMouseDown (false),
  34805. generateTooltip (false)
  34806. {
  34807. setWantsKeyboardFocus (true);
  34808. isOn.addListener (this);
  34809. }
  34810. Button::~Button()
  34811. {
  34812. isOn.removeListener (this);
  34813. if (commandManagerToUse != 0)
  34814. commandManagerToUse->removeListener (this);
  34815. repeatTimer = 0;
  34816. clearShortcuts();
  34817. }
  34818. void Button::setButtonText (const String& newText)
  34819. {
  34820. if (text != newText)
  34821. {
  34822. text = newText;
  34823. repaint();
  34824. }
  34825. }
  34826. void Button::setTooltip (const String& newTooltip)
  34827. {
  34828. SettableTooltipClient::setTooltip (newTooltip);
  34829. generateTooltip = false;
  34830. }
  34831. const String Button::getTooltip()
  34832. {
  34833. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34834. {
  34835. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34836. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34837. for (int i = 0; i < keyPresses.size(); ++i)
  34838. {
  34839. const String key (keyPresses.getReference(i).getTextDescription());
  34840. tt << " [";
  34841. if (key.length() == 1)
  34842. tt << TRANS("shortcut") << ": '" << key << "']";
  34843. else
  34844. tt << key << ']';
  34845. }
  34846. return tt;
  34847. }
  34848. return SettableTooltipClient::getTooltip();
  34849. }
  34850. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34851. {
  34852. if (connectedEdgeFlags != connectedEdgeFlags_)
  34853. {
  34854. connectedEdgeFlags = connectedEdgeFlags_;
  34855. repaint();
  34856. }
  34857. }
  34858. void Button::setToggleState (const bool shouldBeOn,
  34859. const bool sendChangeNotification)
  34860. {
  34861. if (shouldBeOn != lastToggleState)
  34862. {
  34863. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34864. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34865. lastToggleState = shouldBeOn;
  34866. repaint();
  34867. if (sendChangeNotification)
  34868. {
  34869. Component::SafePointer<Component> deletionWatcher (this);
  34870. sendClickMessage (ModifierKeys());
  34871. if (deletionWatcher == 0)
  34872. return;
  34873. }
  34874. if (lastToggleState)
  34875. turnOffOtherButtonsInGroup (sendChangeNotification);
  34876. }
  34877. }
  34878. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34879. {
  34880. clickTogglesState = shouldToggle;
  34881. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34882. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34883. // it is that this button represents, and the button will update its state to reflect this
  34884. // in the applicationCommandListChanged() method.
  34885. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34886. }
  34887. bool Button::getClickingTogglesState() const throw()
  34888. {
  34889. return clickTogglesState;
  34890. }
  34891. void Button::valueChanged (Value& value)
  34892. {
  34893. if (value.refersToSameSourceAs (isOn))
  34894. setToggleState (isOn.getValue(), true);
  34895. }
  34896. void Button::setRadioGroupId (const int newGroupId)
  34897. {
  34898. if (radioGroupId != newGroupId)
  34899. {
  34900. radioGroupId = newGroupId;
  34901. if (lastToggleState)
  34902. turnOffOtherButtonsInGroup (true);
  34903. }
  34904. }
  34905. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34906. {
  34907. Component* const p = getParentComponent();
  34908. if (p != 0 && radioGroupId != 0)
  34909. {
  34910. Component::SafePointer<Component> deletionWatcher (this);
  34911. for (int i = p->getNumChildComponents(); --i >= 0;)
  34912. {
  34913. Component* const c = p->getChildComponent (i);
  34914. if (c != this)
  34915. {
  34916. Button* const b = dynamic_cast <Button*> (c);
  34917. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34918. {
  34919. b->setToggleState (false, sendChangeNotification);
  34920. if (deletionWatcher == 0)
  34921. return;
  34922. }
  34923. }
  34924. }
  34925. }
  34926. }
  34927. void Button::enablementChanged()
  34928. {
  34929. updateState();
  34930. repaint();
  34931. }
  34932. Button::ButtonState Button::updateState()
  34933. {
  34934. return updateState (reallyContains (getMouseXYRelative(), true), isMouseButtonDown());
  34935. }
  34936. Button::ButtonState Button::updateState (const bool over, const bool down)
  34937. {
  34938. ButtonState newState = buttonNormal;
  34939. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34940. {
  34941. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34942. newState = buttonDown;
  34943. else if (over)
  34944. newState = buttonOver;
  34945. }
  34946. setState (newState);
  34947. return newState;
  34948. }
  34949. void Button::setState (const ButtonState newState)
  34950. {
  34951. if (buttonState != newState)
  34952. {
  34953. buttonState = newState;
  34954. repaint();
  34955. if (buttonState == buttonDown)
  34956. {
  34957. buttonPressTime = Time::getApproximateMillisecondCounter();
  34958. lastTimeCallbackTime = buttonPressTime;
  34959. }
  34960. sendStateMessage();
  34961. }
  34962. }
  34963. bool Button::isDown() const throw()
  34964. {
  34965. return buttonState == buttonDown;
  34966. }
  34967. bool Button::isOver() const throw()
  34968. {
  34969. return buttonState != buttonNormal;
  34970. }
  34971. void Button::buttonStateChanged()
  34972. {
  34973. }
  34974. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34975. {
  34976. const uint32 now = Time::getApproximateMillisecondCounter();
  34977. return now > buttonPressTime ? now - buttonPressTime : 0;
  34978. }
  34979. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34980. {
  34981. triggerOnMouseDown = isTriggeredOnMouseDown;
  34982. }
  34983. void Button::clicked()
  34984. {
  34985. }
  34986. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34987. {
  34988. clicked();
  34989. }
  34990. static const int clickMessageId = 0x2f3f4f99;
  34991. void Button::triggerClick()
  34992. {
  34993. postCommandMessage (clickMessageId);
  34994. }
  34995. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34996. {
  34997. if (clickTogglesState)
  34998. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34999. sendClickMessage (modifiers);
  35000. }
  35001. void Button::flashButtonState()
  35002. {
  35003. if (isEnabled())
  35004. {
  35005. needsToRelease = true;
  35006. setState (buttonDown);
  35007. getRepeatTimer().startTimer (100);
  35008. }
  35009. }
  35010. void Button::handleCommandMessage (int commandId)
  35011. {
  35012. if (commandId == clickMessageId)
  35013. {
  35014. if (isEnabled())
  35015. {
  35016. flashButtonState();
  35017. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35018. }
  35019. }
  35020. else
  35021. {
  35022. Component::handleCommandMessage (commandId);
  35023. }
  35024. }
  35025. void Button::addButtonListener (ButtonListener* const newListener)
  35026. {
  35027. buttonListeners.add (newListener);
  35028. }
  35029. void Button::removeButtonListener (ButtonListener* const listener)
  35030. {
  35031. buttonListeners.remove (listener);
  35032. }
  35033. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35034. {
  35035. Component::BailOutChecker checker (this);
  35036. if (commandManagerToUse != 0 && commandID != 0)
  35037. {
  35038. ApplicationCommandTarget::InvocationInfo info (commandID);
  35039. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35040. info.originatingComponent = this;
  35041. commandManagerToUse->invoke (info, true);
  35042. }
  35043. clicked (modifiers);
  35044. if (! checker.shouldBailOut())
  35045. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35046. }
  35047. void Button::sendStateMessage()
  35048. {
  35049. Component::BailOutChecker checker (this);
  35050. buttonStateChanged();
  35051. if (! checker.shouldBailOut())
  35052. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35053. }
  35054. void Button::paint (Graphics& g)
  35055. {
  35056. if (needsToRelease && isEnabled())
  35057. {
  35058. needsToRelease = false;
  35059. needsRepainting = true;
  35060. }
  35061. paintButton (g, isOver(), isDown());
  35062. }
  35063. void Button::mouseEnter (const MouseEvent&)
  35064. {
  35065. updateState (true, false);
  35066. }
  35067. void Button::mouseExit (const MouseEvent&)
  35068. {
  35069. updateState (false, false);
  35070. }
  35071. void Button::mouseDown (const MouseEvent& e)
  35072. {
  35073. updateState (true, true);
  35074. if (isDown())
  35075. {
  35076. if (autoRepeatDelay >= 0)
  35077. getRepeatTimer().startTimer (autoRepeatDelay);
  35078. if (triggerOnMouseDown)
  35079. internalClickCallback (e.mods);
  35080. }
  35081. }
  35082. void Button::mouseUp (const MouseEvent& e)
  35083. {
  35084. const bool wasDown = isDown();
  35085. updateState (isMouseOver(), false);
  35086. if (wasDown && isOver() && ! triggerOnMouseDown)
  35087. internalClickCallback (e.mods);
  35088. }
  35089. void Button::mouseDrag (const MouseEvent&)
  35090. {
  35091. const ButtonState oldState = buttonState;
  35092. updateState (isMouseOver(), true);
  35093. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35094. getRepeatTimer().startTimer (autoRepeatSpeed);
  35095. }
  35096. void Button::focusGained (FocusChangeType)
  35097. {
  35098. updateState();
  35099. repaint();
  35100. }
  35101. void Button::focusLost (FocusChangeType)
  35102. {
  35103. updateState();
  35104. repaint();
  35105. }
  35106. void Button::setVisible (bool shouldBeVisible)
  35107. {
  35108. if (shouldBeVisible != isVisible())
  35109. {
  35110. Component::setVisible (shouldBeVisible);
  35111. if (! shouldBeVisible)
  35112. needsToRelease = false;
  35113. updateState();
  35114. }
  35115. else
  35116. {
  35117. Component::setVisible (shouldBeVisible);
  35118. }
  35119. }
  35120. void Button::parentHierarchyChanged()
  35121. {
  35122. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35123. if (newKeySource != keySource.getComponent())
  35124. {
  35125. if (keySource != 0)
  35126. keySource->removeKeyListener (this);
  35127. keySource = newKeySource;
  35128. if (keySource != 0)
  35129. keySource->addKeyListener (this);
  35130. }
  35131. }
  35132. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35133. const int commandID_,
  35134. const bool generateTooltip_)
  35135. {
  35136. commandID = commandID_;
  35137. generateTooltip = generateTooltip_;
  35138. if (commandManagerToUse != commandManagerToUse_)
  35139. {
  35140. if (commandManagerToUse != 0)
  35141. commandManagerToUse->removeListener (this);
  35142. commandManagerToUse = commandManagerToUse_;
  35143. if (commandManagerToUse != 0)
  35144. commandManagerToUse->addListener (this);
  35145. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35146. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35147. // it is that this button represents, and the button will update its state to reflect this
  35148. // in the applicationCommandListChanged() method.
  35149. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35150. }
  35151. if (commandManagerToUse != 0)
  35152. applicationCommandListChanged();
  35153. else
  35154. setEnabled (true);
  35155. }
  35156. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35157. {
  35158. if (info.commandID == commandID
  35159. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35160. {
  35161. flashButtonState();
  35162. }
  35163. }
  35164. void Button::applicationCommandListChanged()
  35165. {
  35166. if (commandManagerToUse != 0)
  35167. {
  35168. ApplicationCommandInfo info (0);
  35169. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35170. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35171. if (target != 0)
  35172. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35173. }
  35174. }
  35175. void Button::addShortcut (const KeyPress& key)
  35176. {
  35177. if (key.isValid())
  35178. {
  35179. jassert (! isRegisteredForShortcut (key)); // already registered!
  35180. shortcuts.add (key);
  35181. parentHierarchyChanged();
  35182. }
  35183. }
  35184. void Button::clearShortcuts()
  35185. {
  35186. shortcuts.clear();
  35187. parentHierarchyChanged();
  35188. }
  35189. bool Button::isShortcutPressed() const
  35190. {
  35191. if (! isCurrentlyBlockedByAnotherModalComponent())
  35192. {
  35193. for (int i = shortcuts.size(); --i >= 0;)
  35194. if (shortcuts.getReference(i).isCurrentlyDown())
  35195. return true;
  35196. }
  35197. return false;
  35198. }
  35199. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35200. {
  35201. for (int i = shortcuts.size(); --i >= 0;)
  35202. if (key == shortcuts.getReference(i))
  35203. return true;
  35204. return false;
  35205. }
  35206. bool Button::keyStateChanged (const bool, Component*)
  35207. {
  35208. if (! isEnabled())
  35209. return false;
  35210. const bool wasDown = isKeyDown;
  35211. isKeyDown = isShortcutPressed();
  35212. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35213. getRepeatTimer().startTimer (autoRepeatDelay);
  35214. updateState();
  35215. if (isEnabled() && wasDown && ! isKeyDown)
  35216. {
  35217. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35218. // (return immediately - this button may now have been deleted)
  35219. return true;
  35220. }
  35221. return wasDown || isKeyDown;
  35222. }
  35223. bool Button::keyPressed (const KeyPress&, Component*)
  35224. {
  35225. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35226. return isShortcutPressed();
  35227. }
  35228. bool Button::keyPressed (const KeyPress& key)
  35229. {
  35230. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35231. {
  35232. triggerClick();
  35233. return true;
  35234. }
  35235. return false;
  35236. }
  35237. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35238. const int repeatMillisecs,
  35239. const int minimumDelayInMillisecs) throw()
  35240. {
  35241. autoRepeatDelay = initialDelayMillisecs;
  35242. autoRepeatSpeed = repeatMillisecs;
  35243. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35244. }
  35245. void Button::repeatTimerCallback()
  35246. {
  35247. if (needsRepainting)
  35248. {
  35249. getRepeatTimer().stopTimer();
  35250. updateState();
  35251. needsRepainting = false;
  35252. }
  35253. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  35254. {
  35255. int repeatSpeed = autoRepeatSpeed;
  35256. if (autoRepeatMinimumDelay >= 0)
  35257. {
  35258. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35259. timeHeldDown *= timeHeldDown;
  35260. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35261. }
  35262. repeatSpeed = jmax (1, repeatSpeed);
  35263. getRepeatTimer().startTimer (repeatSpeed);
  35264. const uint32 now = Time::getApproximateMillisecondCounter();
  35265. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35266. lastTimeCallbackTime = now;
  35267. Component::SafePointer<Component> deletionWatcher (this);
  35268. for (int i = numTimesToCallback; --i >= 0;)
  35269. {
  35270. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35271. if (deletionWatcher == 0 || ! isDown())
  35272. return;
  35273. }
  35274. }
  35275. else if (! needsToRelease)
  35276. {
  35277. getRepeatTimer().stopTimer();
  35278. }
  35279. }
  35280. Button::RepeatTimer& Button::getRepeatTimer()
  35281. {
  35282. if (repeatTimer == 0)
  35283. repeatTimer = new RepeatTimer (*this);
  35284. return *repeatTimer;
  35285. }
  35286. END_JUCE_NAMESPACE
  35287. /*** End of inlined file: juce_Button.cpp ***/
  35288. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35289. BEGIN_JUCE_NAMESPACE
  35290. DrawableButton::DrawableButton (const String& name,
  35291. const DrawableButton::ButtonStyle buttonStyle)
  35292. : Button (name),
  35293. style (buttonStyle),
  35294. currentImage (0),
  35295. edgeIndent (3)
  35296. {
  35297. if (buttonStyle == ImageOnButtonBackground)
  35298. {
  35299. backgroundOff = Colour (0xffbbbbff);
  35300. backgroundOn = Colour (0xff3333ff);
  35301. }
  35302. else
  35303. {
  35304. backgroundOff = Colours::transparentBlack;
  35305. backgroundOn = Colour (0xaabbbbff);
  35306. }
  35307. }
  35308. DrawableButton::~DrawableButton()
  35309. {
  35310. }
  35311. void DrawableButton::setImages (const Drawable* normal,
  35312. const Drawable* over,
  35313. const Drawable* down,
  35314. const Drawable* disabled,
  35315. const Drawable* normalOn,
  35316. const Drawable* overOn,
  35317. const Drawable* downOn,
  35318. const Drawable* disabledOn)
  35319. {
  35320. jassert (normal != 0); // you really need to give it at least a normal image..
  35321. if (normal != 0) normalImage = normal->createCopy();
  35322. if (over != 0) overImage = over->createCopy();
  35323. if (down != 0) downImage = down->createCopy();
  35324. if (disabled != 0) disabledImage = disabled->createCopy();
  35325. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35326. if (overOn != 0) overImageOn = overOn->createCopy();
  35327. if (downOn != 0) downImageOn = downOn->createCopy();
  35328. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35329. buttonStateChanged();
  35330. }
  35331. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35332. {
  35333. if (style != newStyle)
  35334. {
  35335. style = newStyle;
  35336. buttonStateChanged();
  35337. }
  35338. }
  35339. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35340. const Colour& toggledOnColour)
  35341. {
  35342. if (backgroundOff != toggledOffColour
  35343. || backgroundOn != toggledOnColour)
  35344. {
  35345. backgroundOff = toggledOffColour;
  35346. backgroundOn = toggledOnColour;
  35347. repaint();
  35348. }
  35349. }
  35350. const Colour& DrawableButton::getBackgroundColour() const throw()
  35351. {
  35352. return getToggleState() ? backgroundOn
  35353. : backgroundOff;
  35354. }
  35355. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35356. {
  35357. edgeIndent = numPixelsIndent;
  35358. repaint();
  35359. resized();
  35360. }
  35361. void DrawableButton::resized()
  35362. {
  35363. Button::resized();
  35364. if (style == ImageRaw)
  35365. {
  35366. currentImage->setOriginWithOriginalSize (Point<float>());
  35367. }
  35368. else if (currentImage != 0)
  35369. {
  35370. Rectangle<int> imageSpace;
  35371. if (style == ImageOnButtonBackground)
  35372. {
  35373. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35374. }
  35375. else
  35376. {
  35377. const int textH = (style == ImageAboveTextLabel)
  35378. ? jmin (16, proportionOfHeight (0.25f))
  35379. : 0;
  35380. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35381. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35382. imageSpace.setBounds (indentX, indentY,
  35383. getWidth() - indentX * 2,
  35384. getHeight() - indentY * 2 - textH);
  35385. }
  35386. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35387. }
  35388. }
  35389. void DrawableButton::buttonStateChanged()
  35390. {
  35391. repaint();
  35392. Drawable* imageToDraw = 0;
  35393. float opacity = 1.0f;
  35394. if (isEnabled())
  35395. {
  35396. imageToDraw = getCurrentImage();
  35397. }
  35398. else
  35399. {
  35400. imageToDraw = getToggleState() ? disabledImageOn
  35401. : disabledImage;
  35402. if (imageToDraw == 0)
  35403. {
  35404. opacity = 0.4f;
  35405. imageToDraw = getNormalImage();
  35406. }
  35407. }
  35408. if (imageToDraw != currentImage)
  35409. {
  35410. removeChildComponent (currentImage);
  35411. currentImage = imageToDraw;
  35412. if (currentImage != 0)
  35413. {
  35414. addAndMakeVisible (currentImage);
  35415. DrawableButton::resized();
  35416. }
  35417. }
  35418. if (currentImage != 0)
  35419. currentImage->setAlpha (opacity);
  35420. }
  35421. void DrawableButton::paintButton (Graphics& g,
  35422. bool isMouseOverButton,
  35423. bool isButtonDown)
  35424. {
  35425. if (style == ImageOnButtonBackground)
  35426. {
  35427. getLookAndFeel().drawButtonBackground (g, *this,
  35428. getBackgroundColour(),
  35429. isMouseOverButton,
  35430. isButtonDown);
  35431. }
  35432. else
  35433. {
  35434. g.fillAll (getBackgroundColour());
  35435. const int textH = (style == ImageAboveTextLabel)
  35436. ? jmin (16, proportionOfHeight (0.25f))
  35437. : 0;
  35438. if (textH > 0)
  35439. {
  35440. g.setFont ((float) textH);
  35441. g.setColour (findColour (DrawableButton::textColourId)
  35442. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35443. g.drawFittedText (getButtonText(),
  35444. 2, getHeight() - textH - 1,
  35445. getWidth() - 4, textH,
  35446. Justification::centred, 1);
  35447. }
  35448. }
  35449. }
  35450. Drawable* DrawableButton::getCurrentImage() const throw()
  35451. {
  35452. if (isDown())
  35453. return getDownImage();
  35454. if (isOver())
  35455. return getOverImage();
  35456. return getNormalImage();
  35457. }
  35458. Drawable* DrawableButton::getNormalImage() const throw()
  35459. {
  35460. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35461. : normalImage;
  35462. }
  35463. Drawable* DrawableButton::getOverImage() const throw()
  35464. {
  35465. Drawable* d = normalImage;
  35466. if (getToggleState())
  35467. {
  35468. if (overImageOn != 0)
  35469. d = overImageOn;
  35470. else if (normalImageOn != 0)
  35471. d = normalImageOn;
  35472. else if (overImage != 0)
  35473. d = overImage;
  35474. }
  35475. else
  35476. {
  35477. if (overImage != 0)
  35478. d = overImage;
  35479. }
  35480. return d;
  35481. }
  35482. Drawable* DrawableButton::getDownImage() const throw()
  35483. {
  35484. Drawable* d = normalImage;
  35485. if (getToggleState())
  35486. {
  35487. if (downImageOn != 0)
  35488. d = downImageOn;
  35489. else if (overImageOn != 0)
  35490. d = overImageOn;
  35491. else if (normalImageOn != 0)
  35492. d = normalImageOn;
  35493. else if (downImage != 0)
  35494. d = downImage;
  35495. else
  35496. d = getOverImage();
  35497. }
  35498. else
  35499. {
  35500. if (downImage != 0)
  35501. d = downImage;
  35502. else
  35503. d = getOverImage();
  35504. }
  35505. return d;
  35506. }
  35507. END_JUCE_NAMESPACE
  35508. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35509. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35510. BEGIN_JUCE_NAMESPACE
  35511. HyperlinkButton::HyperlinkButton (const String& linkText,
  35512. const URL& linkURL)
  35513. : Button (linkText),
  35514. url (linkURL),
  35515. font (14.0f, Font::underlined),
  35516. resizeFont (true),
  35517. justification (Justification::centred)
  35518. {
  35519. setMouseCursor (MouseCursor::PointingHandCursor);
  35520. setTooltip (linkURL.toString (false));
  35521. }
  35522. HyperlinkButton::~HyperlinkButton()
  35523. {
  35524. }
  35525. void HyperlinkButton::setFont (const Font& newFont,
  35526. const bool resizeToMatchComponentHeight,
  35527. const Justification& justificationType)
  35528. {
  35529. font = newFont;
  35530. resizeFont = resizeToMatchComponentHeight;
  35531. justification = justificationType;
  35532. repaint();
  35533. }
  35534. void HyperlinkButton::setURL (const URL& newURL) throw()
  35535. {
  35536. url = newURL;
  35537. setTooltip (newURL.toString (false));
  35538. }
  35539. const Font HyperlinkButton::getFontToUse() const
  35540. {
  35541. Font f (font);
  35542. if (resizeFont)
  35543. f.setHeight (getHeight() * 0.7f);
  35544. return f;
  35545. }
  35546. void HyperlinkButton::changeWidthToFitText()
  35547. {
  35548. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35549. }
  35550. void HyperlinkButton::colourChanged()
  35551. {
  35552. repaint();
  35553. }
  35554. void HyperlinkButton::clicked()
  35555. {
  35556. if (url.isWellFormed())
  35557. url.launchInDefaultBrowser();
  35558. }
  35559. void HyperlinkButton::paintButton (Graphics& g,
  35560. bool isMouseOverButton,
  35561. bool isButtonDown)
  35562. {
  35563. const Colour textColour (findColour (textColourId));
  35564. if (isEnabled())
  35565. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35566. : textColour);
  35567. else
  35568. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35569. g.setFont (getFontToUse());
  35570. g.drawText (getButtonText(),
  35571. 2, 0, getWidth() - 2, getHeight(),
  35572. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35573. true);
  35574. }
  35575. END_JUCE_NAMESPACE
  35576. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35577. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35578. BEGIN_JUCE_NAMESPACE
  35579. ImageButton::ImageButton (const String& text_)
  35580. : Button (text_),
  35581. scaleImageToFit (true),
  35582. preserveProportions (true),
  35583. alphaThreshold (0),
  35584. imageX (0),
  35585. imageY (0),
  35586. imageW (0),
  35587. imageH (0),
  35588. normalImage (0),
  35589. overImage (0),
  35590. downImage (0)
  35591. {
  35592. }
  35593. ImageButton::~ImageButton()
  35594. {
  35595. }
  35596. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35597. const bool rescaleImagesWhenButtonSizeChanges,
  35598. const bool preserveImageProportions,
  35599. const Image& normalImage_,
  35600. const float imageOpacityWhenNormal,
  35601. const Colour& overlayColourWhenNormal,
  35602. const Image& overImage_,
  35603. const float imageOpacityWhenOver,
  35604. const Colour& overlayColourWhenOver,
  35605. const Image& downImage_,
  35606. const float imageOpacityWhenDown,
  35607. const Colour& overlayColourWhenDown,
  35608. const float hitTestAlphaThreshold)
  35609. {
  35610. normalImage = normalImage_;
  35611. overImage = overImage_;
  35612. downImage = downImage_;
  35613. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35614. {
  35615. imageW = normalImage.getWidth();
  35616. imageH = normalImage.getHeight();
  35617. setSize (imageW, imageH);
  35618. }
  35619. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35620. preserveProportions = preserveImageProportions;
  35621. normalOpacity = imageOpacityWhenNormal;
  35622. normalOverlay = overlayColourWhenNormal;
  35623. overOpacity = imageOpacityWhenOver;
  35624. overOverlay = overlayColourWhenOver;
  35625. downOpacity = imageOpacityWhenDown;
  35626. downOverlay = overlayColourWhenDown;
  35627. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35628. repaint();
  35629. }
  35630. const Image ImageButton::getCurrentImage() const
  35631. {
  35632. if (isDown() || getToggleState())
  35633. return getDownImage();
  35634. if (isOver())
  35635. return getOverImage();
  35636. return getNormalImage();
  35637. }
  35638. const Image ImageButton::getNormalImage() const
  35639. {
  35640. return normalImage;
  35641. }
  35642. const Image ImageButton::getOverImage() const
  35643. {
  35644. return overImage.isValid() ? overImage
  35645. : normalImage;
  35646. }
  35647. const Image ImageButton::getDownImage() const
  35648. {
  35649. return downImage.isValid() ? downImage
  35650. : getOverImage();
  35651. }
  35652. void ImageButton::paintButton (Graphics& g,
  35653. bool isMouseOverButton,
  35654. bool isButtonDown)
  35655. {
  35656. if (! isEnabled())
  35657. {
  35658. isMouseOverButton = false;
  35659. isButtonDown = false;
  35660. }
  35661. Image im (getCurrentImage());
  35662. if (im.isValid())
  35663. {
  35664. const int iw = im.getWidth();
  35665. const int ih = im.getHeight();
  35666. imageW = getWidth();
  35667. imageH = getHeight();
  35668. imageX = (imageW - iw) >> 1;
  35669. imageY = (imageH - ih) >> 1;
  35670. if (scaleImageToFit)
  35671. {
  35672. if (preserveProportions)
  35673. {
  35674. int newW, newH;
  35675. const float imRatio = ih / (float)iw;
  35676. const float destRatio = imageH / (float)imageW;
  35677. if (imRatio > destRatio)
  35678. {
  35679. newW = roundToInt (imageH / imRatio);
  35680. newH = imageH;
  35681. }
  35682. else
  35683. {
  35684. newW = imageW;
  35685. newH = roundToInt (imageW * imRatio);
  35686. }
  35687. imageX = (imageW - newW) / 2;
  35688. imageY = (imageH - newH) / 2;
  35689. imageW = newW;
  35690. imageH = newH;
  35691. }
  35692. else
  35693. {
  35694. imageX = 0;
  35695. imageY = 0;
  35696. }
  35697. }
  35698. if (! scaleImageToFit)
  35699. {
  35700. imageW = iw;
  35701. imageH = ih;
  35702. }
  35703. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35704. isButtonDown ? downOverlay
  35705. : (isMouseOverButton ? overOverlay
  35706. : normalOverlay),
  35707. isButtonDown ? downOpacity
  35708. : (isMouseOverButton ? overOpacity
  35709. : normalOpacity),
  35710. *this);
  35711. }
  35712. }
  35713. bool ImageButton::hitTest (int x, int y)
  35714. {
  35715. if (alphaThreshold == 0)
  35716. return true;
  35717. Image im (getCurrentImage());
  35718. return im.isNull() || (imageW > 0 && imageH > 0
  35719. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35720. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35721. }
  35722. END_JUCE_NAMESPACE
  35723. /*** End of inlined file: juce_ImageButton.cpp ***/
  35724. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35725. BEGIN_JUCE_NAMESPACE
  35726. ShapeButton::ShapeButton (const String& text_,
  35727. const Colour& normalColour_,
  35728. const Colour& overColour_,
  35729. const Colour& downColour_)
  35730. : Button (text_),
  35731. normalColour (normalColour_),
  35732. overColour (overColour_),
  35733. downColour (downColour_),
  35734. maintainShapeProportions (false),
  35735. outlineWidth (0.0f)
  35736. {
  35737. }
  35738. ShapeButton::~ShapeButton()
  35739. {
  35740. }
  35741. void ShapeButton::setColours (const Colour& newNormalColour,
  35742. const Colour& newOverColour,
  35743. const Colour& newDownColour)
  35744. {
  35745. normalColour = newNormalColour;
  35746. overColour = newOverColour;
  35747. downColour = newDownColour;
  35748. }
  35749. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35750. const float newOutlineWidth)
  35751. {
  35752. outlineColour = newOutlineColour;
  35753. outlineWidth = newOutlineWidth;
  35754. }
  35755. void ShapeButton::setShape (const Path& newShape,
  35756. const bool resizeNowToFitThisShape,
  35757. const bool maintainShapeProportions_,
  35758. const bool hasShadow)
  35759. {
  35760. shape = newShape;
  35761. maintainShapeProportions = maintainShapeProportions_;
  35762. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35763. setComponentEffect ((hasShadow) ? &shadow : 0);
  35764. if (resizeNowToFitThisShape)
  35765. {
  35766. Rectangle<float> bounds (shape.getBounds());
  35767. if (hasShadow)
  35768. bounds.expand (4.0f, 4.0f);
  35769. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35770. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35771. 1 + (int) (bounds.getHeight() + outlineWidth));
  35772. }
  35773. }
  35774. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35775. {
  35776. if (! isEnabled())
  35777. {
  35778. isMouseOverButton = false;
  35779. isButtonDown = false;
  35780. }
  35781. g.setColour ((isButtonDown) ? downColour
  35782. : (isMouseOverButton) ? overColour
  35783. : normalColour);
  35784. int w = getWidth();
  35785. int h = getHeight();
  35786. if (getComponentEffect() != 0)
  35787. {
  35788. w -= 4;
  35789. h -= 4;
  35790. }
  35791. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35792. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35793. w - offset - outlineWidth,
  35794. h - offset - outlineWidth,
  35795. maintainShapeProportions));
  35796. g.fillPath (shape, trans);
  35797. if (outlineWidth > 0.0f)
  35798. {
  35799. g.setColour (outlineColour);
  35800. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35801. }
  35802. }
  35803. END_JUCE_NAMESPACE
  35804. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35805. /*** Start of inlined file: juce_TextButton.cpp ***/
  35806. BEGIN_JUCE_NAMESPACE
  35807. TextButton::TextButton (const String& name,
  35808. const String& toolTip)
  35809. : Button (name)
  35810. {
  35811. setTooltip (toolTip);
  35812. }
  35813. TextButton::~TextButton()
  35814. {
  35815. }
  35816. void TextButton::paintButton (Graphics& g,
  35817. bool isMouseOverButton,
  35818. bool isButtonDown)
  35819. {
  35820. getLookAndFeel().drawButtonBackground (g, *this,
  35821. findColour (getToggleState() ? buttonOnColourId
  35822. : buttonColourId),
  35823. isMouseOverButton,
  35824. isButtonDown);
  35825. getLookAndFeel().drawButtonText (g, *this,
  35826. isMouseOverButton,
  35827. isButtonDown);
  35828. }
  35829. void TextButton::colourChanged()
  35830. {
  35831. repaint();
  35832. }
  35833. const Font TextButton::getFont()
  35834. {
  35835. return Font (jmin (15.0f, getHeight() * 0.6f));
  35836. }
  35837. void TextButton::changeWidthToFitText (const int newHeight)
  35838. {
  35839. if (newHeight >= 0)
  35840. setSize (jmax (1, getWidth()), newHeight);
  35841. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35842. getHeight());
  35843. }
  35844. END_JUCE_NAMESPACE
  35845. /*** End of inlined file: juce_TextButton.cpp ***/
  35846. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35847. BEGIN_JUCE_NAMESPACE
  35848. ToggleButton::ToggleButton (const String& buttonText)
  35849. : Button (buttonText)
  35850. {
  35851. setClickingTogglesState (true);
  35852. }
  35853. ToggleButton::~ToggleButton()
  35854. {
  35855. }
  35856. void ToggleButton::paintButton (Graphics& g,
  35857. bool isMouseOverButton,
  35858. bool isButtonDown)
  35859. {
  35860. getLookAndFeel().drawToggleButton (g, *this,
  35861. isMouseOverButton,
  35862. isButtonDown);
  35863. }
  35864. void ToggleButton::changeWidthToFitText()
  35865. {
  35866. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35867. }
  35868. void ToggleButton::colourChanged()
  35869. {
  35870. repaint();
  35871. }
  35872. END_JUCE_NAMESPACE
  35873. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35874. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35875. BEGIN_JUCE_NAMESPACE
  35876. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35877. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35878. : ToolbarItemComponent (itemId_, buttonText, true),
  35879. normalImage (normalImage_),
  35880. toggledOnImage (toggledOnImage_),
  35881. currentImage (0)
  35882. {
  35883. jassert (normalImage_ != 0);
  35884. }
  35885. ToolbarButton::~ToolbarButton()
  35886. {
  35887. }
  35888. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35889. {
  35890. preferredSize = minSize = maxSize = toolbarDepth;
  35891. return true;
  35892. }
  35893. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35894. {
  35895. }
  35896. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35897. {
  35898. buttonStateChanged();
  35899. }
  35900. void ToolbarButton::updateDrawable()
  35901. {
  35902. if (currentImage != 0)
  35903. {
  35904. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35905. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35906. }
  35907. }
  35908. void ToolbarButton::resized()
  35909. {
  35910. ToolbarItemComponent::resized();
  35911. updateDrawable();
  35912. }
  35913. void ToolbarButton::enablementChanged()
  35914. {
  35915. ToolbarItemComponent::enablementChanged();
  35916. updateDrawable();
  35917. }
  35918. void ToolbarButton::buttonStateChanged()
  35919. {
  35920. Drawable* d = normalImage;
  35921. if (getToggleState() && toggledOnImage != 0)
  35922. d = toggledOnImage;
  35923. if (d != currentImage)
  35924. {
  35925. removeChildComponent (currentImage);
  35926. currentImage = d;
  35927. if (d != 0)
  35928. {
  35929. enablementChanged();
  35930. addAndMakeVisible (d);
  35931. updateDrawable();
  35932. }
  35933. }
  35934. }
  35935. END_JUCE_NAMESPACE
  35936. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35937. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35938. BEGIN_JUCE_NAMESPACE
  35939. class CodeDocumentLine
  35940. {
  35941. public:
  35942. CodeDocumentLine (const juce_wchar* const line_,
  35943. const int lineLength_,
  35944. const int numNewLineChars,
  35945. const int lineStartInFile_)
  35946. : line (line_, lineLength_),
  35947. lineStartInFile (lineStartInFile_),
  35948. lineLength (lineLength_),
  35949. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35950. {
  35951. }
  35952. ~CodeDocumentLine()
  35953. {
  35954. }
  35955. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35956. {
  35957. const juce_wchar* const t = text;
  35958. int pos = 0;
  35959. while (t [pos] != 0)
  35960. {
  35961. const int startOfLine = pos;
  35962. int numNewLineChars = 0;
  35963. while (t[pos] != 0)
  35964. {
  35965. if (t[pos] == '\r')
  35966. {
  35967. ++numNewLineChars;
  35968. ++pos;
  35969. if (t[pos] == '\n')
  35970. {
  35971. ++numNewLineChars;
  35972. ++pos;
  35973. }
  35974. break;
  35975. }
  35976. if (t[pos] == '\n')
  35977. {
  35978. ++numNewLineChars;
  35979. ++pos;
  35980. break;
  35981. }
  35982. ++pos;
  35983. }
  35984. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35985. numNewLineChars, startOfLine));
  35986. }
  35987. jassert (pos == text.length());
  35988. }
  35989. bool endsWithLineBreak() const throw()
  35990. {
  35991. return lineLengthWithoutNewLines != lineLength;
  35992. }
  35993. void updateLength() throw()
  35994. {
  35995. lineLengthWithoutNewLines = lineLength = line.length();
  35996. while (lineLengthWithoutNewLines > 0
  35997. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35998. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35999. {
  36000. --lineLengthWithoutNewLines;
  36001. }
  36002. }
  36003. String line;
  36004. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36005. };
  36006. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36007. : document (document_),
  36008. currentLine (document_->lines[0]),
  36009. line (0),
  36010. position (0)
  36011. {
  36012. }
  36013. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36014. : document (other.document),
  36015. currentLine (other.currentLine),
  36016. line (other.line),
  36017. position (other.position)
  36018. {
  36019. }
  36020. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36021. {
  36022. document = other.document;
  36023. currentLine = other.currentLine;
  36024. line = other.line;
  36025. position = other.position;
  36026. return *this;
  36027. }
  36028. CodeDocument::Iterator::~Iterator() throw()
  36029. {
  36030. }
  36031. juce_wchar CodeDocument::Iterator::nextChar()
  36032. {
  36033. if (currentLine == 0)
  36034. return 0;
  36035. jassert (currentLine == document->lines.getUnchecked (line));
  36036. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36037. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36038. {
  36039. ++line;
  36040. currentLine = document->lines [line];
  36041. }
  36042. return result;
  36043. }
  36044. void CodeDocument::Iterator::skip()
  36045. {
  36046. if (currentLine != 0)
  36047. {
  36048. jassert (currentLine == document->lines.getUnchecked (line));
  36049. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36050. {
  36051. ++line;
  36052. currentLine = document->lines [line];
  36053. }
  36054. }
  36055. }
  36056. void CodeDocument::Iterator::skipToEndOfLine()
  36057. {
  36058. if (currentLine != 0)
  36059. {
  36060. jassert (currentLine == document->lines.getUnchecked (line));
  36061. ++line;
  36062. currentLine = document->lines [line];
  36063. if (currentLine != 0)
  36064. position = currentLine->lineStartInFile;
  36065. else
  36066. position = document->getNumCharacters();
  36067. }
  36068. }
  36069. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36070. {
  36071. if (currentLine == 0)
  36072. return 0;
  36073. jassert (currentLine == document->lines.getUnchecked (line));
  36074. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36075. }
  36076. void CodeDocument::Iterator::skipWhitespace()
  36077. {
  36078. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36079. skip();
  36080. }
  36081. bool CodeDocument::Iterator::isEOF() const throw()
  36082. {
  36083. return currentLine == 0;
  36084. }
  36085. CodeDocument::Position::Position() throw()
  36086. : owner (0), characterPos (0), line (0),
  36087. indexInLine (0), positionMaintained (false)
  36088. {
  36089. }
  36090. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36091. const int line_, const int indexInLine_) throw()
  36092. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36093. characterPos (0), line (line_),
  36094. indexInLine (indexInLine_), positionMaintained (false)
  36095. {
  36096. setLineAndIndex (line_, indexInLine_);
  36097. }
  36098. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36099. const int characterPos_) throw()
  36100. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36101. positionMaintained (false)
  36102. {
  36103. setPosition (characterPos_);
  36104. }
  36105. CodeDocument::Position::Position (const Position& other) throw()
  36106. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36107. indexInLine (other.indexInLine), positionMaintained (false)
  36108. {
  36109. jassert (*this == other);
  36110. }
  36111. CodeDocument::Position::~Position()
  36112. {
  36113. setPositionMaintained (false);
  36114. }
  36115. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36116. {
  36117. if (this != &other)
  36118. {
  36119. const bool wasPositionMaintained = positionMaintained;
  36120. if (owner != other.owner)
  36121. setPositionMaintained (false);
  36122. owner = other.owner;
  36123. line = other.line;
  36124. indexInLine = other.indexInLine;
  36125. characterPos = other.characterPos;
  36126. setPositionMaintained (wasPositionMaintained);
  36127. jassert (*this == other);
  36128. }
  36129. return *this;
  36130. }
  36131. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36132. {
  36133. jassert ((characterPos == other.characterPos)
  36134. == (line == other.line && indexInLine == other.indexInLine));
  36135. return characterPos == other.characterPos
  36136. && line == other.line
  36137. && indexInLine == other.indexInLine
  36138. && owner == other.owner;
  36139. }
  36140. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36141. {
  36142. return ! operator== (other);
  36143. }
  36144. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36145. {
  36146. jassert (owner != 0);
  36147. if (owner->lines.size() == 0)
  36148. {
  36149. line = 0;
  36150. indexInLine = 0;
  36151. characterPos = 0;
  36152. }
  36153. else
  36154. {
  36155. if (newLine >= owner->lines.size())
  36156. {
  36157. line = owner->lines.size() - 1;
  36158. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36159. jassert (l != 0);
  36160. indexInLine = l->lineLengthWithoutNewLines;
  36161. characterPos = l->lineStartInFile + indexInLine;
  36162. }
  36163. else
  36164. {
  36165. line = jmax (0, newLine);
  36166. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36167. jassert (l != 0);
  36168. if (l->lineLengthWithoutNewLines > 0)
  36169. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36170. else
  36171. indexInLine = 0;
  36172. characterPos = l->lineStartInFile + indexInLine;
  36173. }
  36174. }
  36175. }
  36176. void CodeDocument::Position::setPosition (const int newPosition)
  36177. {
  36178. jassert (owner != 0);
  36179. line = 0;
  36180. indexInLine = 0;
  36181. characterPos = 0;
  36182. if (newPosition > 0)
  36183. {
  36184. int lineStart = 0;
  36185. int lineEnd = owner->lines.size();
  36186. for (;;)
  36187. {
  36188. if (lineEnd - lineStart < 4)
  36189. {
  36190. for (int i = lineStart; i < lineEnd; ++i)
  36191. {
  36192. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36193. int index = newPosition - l->lineStartInFile;
  36194. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36195. {
  36196. line = i;
  36197. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36198. characterPos = l->lineStartInFile + indexInLine;
  36199. }
  36200. }
  36201. break;
  36202. }
  36203. else
  36204. {
  36205. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36206. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36207. if (newPosition >= mid->lineStartInFile)
  36208. lineStart = midIndex;
  36209. else
  36210. lineEnd = midIndex;
  36211. }
  36212. }
  36213. }
  36214. }
  36215. void CodeDocument::Position::moveBy (int characterDelta)
  36216. {
  36217. jassert (owner != 0);
  36218. if (characterDelta == 1)
  36219. {
  36220. setPosition (getPosition());
  36221. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36222. if (line < owner->lines.size())
  36223. {
  36224. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36225. if (indexInLine + characterDelta < l->lineLength
  36226. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36227. ++characterDelta;
  36228. }
  36229. }
  36230. setPosition (characterPos + characterDelta);
  36231. }
  36232. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36233. {
  36234. CodeDocument::Position p (*this);
  36235. p.moveBy (characterDelta);
  36236. return p;
  36237. }
  36238. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36239. {
  36240. CodeDocument::Position p (*this);
  36241. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36242. return p;
  36243. }
  36244. const juce_wchar CodeDocument::Position::getCharacter() const
  36245. {
  36246. const CodeDocumentLine* const l = owner->lines [line];
  36247. return l == 0 ? 0 : l->line [getIndexInLine()];
  36248. }
  36249. const String CodeDocument::Position::getLineText() const
  36250. {
  36251. const CodeDocumentLine* const l = owner->lines [line];
  36252. return l == 0 ? String::empty : l->line;
  36253. }
  36254. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36255. {
  36256. if (isMaintained != positionMaintained)
  36257. {
  36258. positionMaintained = isMaintained;
  36259. if (owner != 0)
  36260. {
  36261. if (isMaintained)
  36262. {
  36263. jassert (! owner->positionsToMaintain.contains (this));
  36264. owner->positionsToMaintain.add (this);
  36265. }
  36266. else
  36267. {
  36268. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36269. jassert (owner->positionsToMaintain.contains (this));
  36270. owner->positionsToMaintain.removeValue (this);
  36271. }
  36272. }
  36273. }
  36274. }
  36275. CodeDocument::CodeDocument()
  36276. : undoManager (std::numeric_limits<int>::max(), 10000),
  36277. currentActionIndex (0),
  36278. indexOfSavedState (-1),
  36279. maximumLineLength (-1),
  36280. newLineChars ("\r\n")
  36281. {
  36282. }
  36283. CodeDocument::~CodeDocument()
  36284. {
  36285. }
  36286. const String CodeDocument::getAllContent() const
  36287. {
  36288. return getTextBetween (Position (this, 0),
  36289. Position (this, lines.size(), 0));
  36290. }
  36291. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36292. {
  36293. if (end.getPosition() <= start.getPosition())
  36294. return String::empty;
  36295. const int startLine = start.getLineNumber();
  36296. const int endLine = end.getLineNumber();
  36297. if (startLine == endLine)
  36298. {
  36299. CodeDocumentLine* const line = lines [startLine];
  36300. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36301. }
  36302. String result;
  36303. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36304. String::Concatenator concatenator (result);
  36305. const int maxLine = jmin (lines.size() - 1, endLine);
  36306. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36307. {
  36308. const CodeDocumentLine* line = lines.getUnchecked(i);
  36309. int len = line->lineLength;
  36310. if (i == startLine)
  36311. {
  36312. const int index = start.getIndexInLine();
  36313. concatenator.append (line->line.substring (index, len));
  36314. }
  36315. else if (i == endLine)
  36316. {
  36317. len = end.getIndexInLine();
  36318. concatenator.append (line->line.substring (0, len));
  36319. }
  36320. else
  36321. {
  36322. concatenator.append (line->line);
  36323. }
  36324. }
  36325. return result;
  36326. }
  36327. int CodeDocument::getNumCharacters() const throw()
  36328. {
  36329. const CodeDocumentLine* const lastLine = lines.getLast();
  36330. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36331. }
  36332. const String CodeDocument::getLine (const int lineIndex) const throw()
  36333. {
  36334. const CodeDocumentLine* const line = lines [lineIndex];
  36335. return (line == 0) ? String::empty : line->line;
  36336. }
  36337. int CodeDocument::getMaximumLineLength() throw()
  36338. {
  36339. if (maximumLineLength < 0)
  36340. {
  36341. maximumLineLength = 0;
  36342. for (int i = lines.size(); --i >= 0;)
  36343. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36344. }
  36345. return maximumLineLength;
  36346. }
  36347. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36348. {
  36349. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36350. }
  36351. void CodeDocument::insertText (const Position& position, const String& text)
  36352. {
  36353. insert (text, position.getPosition(), true);
  36354. }
  36355. void CodeDocument::replaceAllContent (const String& newContent)
  36356. {
  36357. remove (0, getNumCharacters(), true);
  36358. insert (newContent, 0, true);
  36359. }
  36360. bool CodeDocument::loadFromStream (InputStream& stream)
  36361. {
  36362. replaceAllContent (stream.readEntireStreamAsString());
  36363. setSavePoint();
  36364. clearUndoHistory();
  36365. return true;
  36366. }
  36367. bool CodeDocument::writeToStream (OutputStream& stream)
  36368. {
  36369. for (int i = 0; i < lines.size(); ++i)
  36370. {
  36371. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36372. const char* utf8 = temp.toUTF8();
  36373. if (! stream.write (utf8, (int) strlen (utf8)))
  36374. return false;
  36375. }
  36376. return true;
  36377. }
  36378. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36379. {
  36380. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36381. newLineChars = newLine;
  36382. }
  36383. void CodeDocument::newTransaction()
  36384. {
  36385. undoManager.beginNewTransaction (String::empty);
  36386. }
  36387. void CodeDocument::undo()
  36388. {
  36389. newTransaction();
  36390. undoManager.undo();
  36391. }
  36392. void CodeDocument::redo()
  36393. {
  36394. undoManager.redo();
  36395. }
  36396. void CodeDocument::clearUndoHistory()
  36397. {
  36398. undoManager.clearUndoHistory();
  36399. }
  36400. void CodeDocument::setSavePoint() throw()
  36401. {
  36402. indexOfSavedState = currentActionIndex;
  36403. }
  36404. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36405. {
  36406. return currentActionIndex != indexOfSavedState;
  36407. }
  36408. namespace CodeDocumentHelpers
  36409. {
  36410. int getCharacterType (const juce_wchar character) throw()
  36411. {
  36412. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36413. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36414. }
  36415. }
  36416. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36417. {
  36418. Position p (position);
  36419. const int maxDistance = 256;
  36420. int i = 0;
  36421. while (i < maxDistance
  36422. && CharacterFunctions::isWhitespace (p.getCharacter())
  36423. && (i == 0 || (p.getCharacter() != '\n'
  36424. && p.getCharacter() != '\r')))
  36425. {
  36426. ++i;
  36427. p.moveBy (1);
  36428. }
  36429. if (i == 0)
  36430. {
  36431. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36432. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36433. {
  36434. ++i;
  36435. p.moveBy (1);
  36436. }
  36437. while (i < maxDistance
  36438. && CharacterFunctions::isWhitespace (p.getCharacter())
  36439. && (i == 0 || (p.getCharacter() != '\n'
  36440. && p.getCharacter() != '\r')))
  36441. {
  36442. ++i;
  36443. p.moveBy (1);
  36444. }
  36445. }
  36446. return p;
  36447. }
  36448. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36449. {
  36450. Position p (position);
  36451. const int maxDistance = 256;
  36452. int i = 0;
  36453. bool stoppedAtLineStart = false;
  36454. while (i < maxDistance)
  36455. {
  36456. const juce_wchar c = p.movedBy (-1).getCharacter();
  36457. if (c == '\r' || c == '\n')
  36458. {
  36459. stoppedAtLineStart = true;
  36460. if (i > 0)
  36461. break;
  36462. }
  36463. if (! CharacterFunctions::isWhitespace (c))
  36464. break;
  36465. p.moveBy (-1);
  36466. ++i;
  36467. }
  36468. if (i < maxDistance && ! stoppedAtLineStart)
  36469. {
  36470. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36471. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36472. {
  36473. p.moveBy (-1);
  36474. ++i;
  36475. }
  36476. }
  36477. return p;
  36478. }
  36479. void CodeDocument::checkLastLineStatus()
  36480. {
  36481. while (lines.size() > 0
  36482. && lines.getLast()->lineLength == 0
  36483. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36484. {
  36485. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36486. lines.removeLast();
  36487. }
  36488. const CodeDocumentLine* const lastLine = lines.getLast();
  36489. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36490. {
  36491. // check that there's an empty line at the end if the preceding one ends in a newline..
  36492. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36493. }
  36494. }
  36495. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36496. {
  36497. listeners.add (listener);
  36498. }
  36499. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36500. {
  36501. listeners.remove (listener);
  36502. }
  36503. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36504. {
  36505. Position startPos (this, startLine, 0);
  36506. Position endPos (this, endLine, 0);
  36507. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36508. }
  36509. class CodeDocumentInsertAction : public UndoableAction
  36510. {
  36511. public:
  36512. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36513. : owner (owner_),
  36514. text (text_),
  36515. insertPos (insertPos_)
  36516. {
  36517. }
  36518. bool perform()
  36519. {
  36520. owner.currentActionIndex++;
  36521. owner.insert (text, insertPos, false);
  36522. return true;
  36523. }
  36524. bool undo()
  36525. {
  36526. owner.currentActionIndex--;
  36527. owner.remove (insertPos, insertPos + text.length(), false);
  36528. return true;
  36529. }
  36530. int getSizeInUnits() { return text.length() + 32; }
  36531. private:
  36532. CodeDocument& owner;
  36533. const String text;
  36534. int insertPos;
  36535. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36536. };
  36537. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36538. {
  36539. if (text.isEmpty())
  36540. return;
  36541. if (undoable)
  36542. {
  36543. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36544. }
  36545. else
  36546. {
  36547. Position pos (this, insertPos);
  36548. const int firstAffectedLine = pos.getLineNumber();
  36549. int lastAffectedLine = firstAffectedLine + 1;
  36550. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36551. String textInsideOriginalLine (text);
  36552. if (firstLine != 0)
  36553. {
  36554. const int index = pos.getIndexInLine();
  36555. textInsideOriginalLine = firstLine->line.substring (0, index)
  36556. + textInsideOriginalLine
  36557. + firstLine->line.substring (index);
  36558. }
  36559. maximumLineLength = -1;
  36560. Array <CodeDocumentLine*> newLines;
  36561. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36562. jassert (newLines.size() > 0);
  36563. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36564. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36565. lines.set (firstAffectedLine, newFirstLine);
  36566. if (newLines.size() > 1)
  36567. {
  36568. for (int i = 1; i < newLines.size(); ++i)
  36569. {
  36570. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36571. lines.insert (firstAffectedLine + i, l);
  36572. }
  36573. lastAffectedLine = lines.size();
  36574. }
  36575. int i, lineStart = newFirstLine->lineStartInFile;
  36576. for (i = firstAffectedLine; i < lines.size(); ++i)
  36577. {
  36578. CodeDocumentLine* const l = lines.getUnchecked (i);
  36579. l->lineStartInFile = lineStart;
  36580. lineStart += l->lineLength;
  36581. }
  36582. checkLastLineStatus();
  36583. const int newTextLength = text.length();
  36584. for (i = 0; i < positionsToMaintain.size(); ++i)
  36585. {
  36586. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36587. if (p->getPosition() >= insertPos)
  36588. p->setPosition (p->getPosition() + newTextLength);
  36589. }
  36590. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36591. }
  36592. }
  36593. class CodeDocumentDeleteAction : public UndoableAction
  36594. {
  36595. public:
  36596. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36597. : owner (owner_),
  36598. startPos (startPos_),
  36599. endPos (endPos_)
  36600. {
  36601. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36602. CodeDocument::Position (&owner, endPos));
  36603. }
  36604. bool perform()
  36605. {
  36606. owner.currentActionIndex++;
  36607. owner.remove (startPos, endPos, false);
  36608. return true;
  36609. }
  36610. bool undo()
  36611. {
  36612. owner.currentActionIndex--;
  36613. owner.insert (removedText, startPos, false);
  36614. return true;
  36615. }
  36616. int getSizeInUnits() { return removedText.length() + 32; }
  36617. private:
  36618. CodeDocument& owner;
  36619. int startPos, endPos;
  36620. String removedText;
  36621. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36622. };
  36623. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36624. {
  36625. if (endPos <= startPos)
  36626. return;
  36627. if (undoable)
  36628. {
  36629. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36630. }
  36631. else
  36632. {
  36633. Position startPosition (this, startPos);
  36634. Position endPosition (this, endPos);
  36635. maximumLineLength = -1;
  36636. const int firstAffectedLine = startPosition.getLineNumber();
  36637. const int endLine = endPosition.getLineNumber();
  36638. int lastAffectedLine = firstAffectedLine + 1;
  36639. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36640. if (firstAffectedLine == endLine)
  36641. {
  36642. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36643. + firstLine->line.substring (endPosition.getIndexInLine());
  36644. firstLine->updateLength();
  36645. }
  36646. else
  36647. {
  36648. lastAffectedLine = lines.size();
  36649. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36650. jassert (lastLine != 0);
  36651. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36652. + lastLine->line.substring (endPosition.getIndexInLine());
  36653. firstLine->updateLength();
  36654. int numLinesToRemove = endLine - firstAffectedLine;
  36655. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36656. }
  36657. int i;
  36658. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36659. {
  36660. CodeDocumentLine* const l = lines.getUnchecked (i);
  36661. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36662. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36663. }
  36664. checkLastLineStatus();
  36665. const int totalChars = getNumCharacters();
  36666. for (i = 0; i < positionsToMaintain.size(); ++i)
  36667. {
  36668. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36669. if (p->getPosition() > startPosition.getPosition())
  36670. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36671. if (p->getPosition() > totalChars)
  36672. p->setPosition (totalChars);
  36673. }
  36674. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36675. }
  36676. }
  36677. END_JUCE_NAMESPACE
  36678. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36679. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36680. BEGIN_JUCE_NAMESPACE
  36681. class CodeEditorComponent::CaretComponent : public Component,
  36682. public Timer
  36683. {
  36684. public:
  36685. CaretComponent (CodeEditorComponent& owner_)
  36686. : owner (owner_)
  36687. {
  36688. setAlwaysOnTop (true);
  36689. setInterceptsMouseClicks (false, false);
  36690. }
  36691. void paint (Graphics& g)
  36692. {
  36693. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36694. }
  36695. void timerCallback()
  36696. {
  36697. setVisible (shouldBeShown() && ! isVisible());
  36698. }
  36699. void updatePosition()
  36700. {
  36701. startTimer (400);
  36702. setVisible (shouldBeShown());
  36703. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36704. }
  36705. private:
  36706. CodeEditorComponent& owner;
  36707. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36708. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36709. };
  36710. class CodeEditorComponent::CodeEditorLine
  36711. {
  36712. public:
  36713. CodeEditorLine() throw()
  36714. : highlightColumnStart (0), highlightColumnEnd (0)
  36715. {
  36716. }
  36717. bool update (CodeDocument& document, int lineNum,
  36718. CodeDocument::Iterator& source,
  36719. CodeTokeniser* analyser, const int spacesPerTab,
  36720. const CodeDocument::Position& selectionStart,
  36721. const CodeDocument::Position& selectionEnd)
  36722. {
  36723. Array <SyntaxToken> newTokens;
  36724. newTokens.ensureStorageAllocated (8);
  36725. if (analyser == 0)
  36726. {
  36727. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36728. }
  36729. else if (lineNum < document.getNumLines())
  36730. {
  36731. const CodeDocument::Position pos (&document, lineNum, 0);
  36732. createTokens (pos.getPosition(), pos.getLineText(),
  36733. source, analyser, newTokens);
  36734. }
  36735. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36736. int newHighlightStart = 0;
  36737. int newHighlightEnd = 0;
  36738. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36739. {
  36740. const String line (document.getLine (lineNum));
  36741. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36742. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36743. line, spacesPerTab);
  36744. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36745. line, spacesPerTab);
  36746. }
  36747. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36748. {
  36749. highlightColumnStart = newHighlightStart;
  36750. highlightColumnEnd = newHighlightEnd;
  36751. }
  36752. else
  36753. {
  36754. if (tokens.size() == newTokens.size())
  36755. {
  36756. bool allTheSame = true;
  36757. for (int i = newTokens.size(); --i >= 0;)
  36758. {
  36759. if (tokens.getReference(i) != newTokens.getReference(i))
  36760. {
  36761. allTheSame = false;
  36762. break;
  36763. }
  36764. }
  36765. if (allTheSame)
  36766. return false;
  36767. }
  36768. }
  36769. tokens.swapWithArray (newTokens);
  36770. return true;
  36771. }
  36772. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36773. float x, const int y, const int baselineOffset, const int lineHeight,
  36774. const Colour& highlightColour) const
  36775. {
  36776. if (highlightColumnStart < highlightColumnEnd)
  36777. {
  36778. g.setColour (highlightColour);
  36779. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36780. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36781. }
  36782. int lastType = std::numeric_limits<int>::min();
  36783. for (int i = 0; i < tokens.size(); ++i)
  36784. {
  36785. SyntaxToken& token = tokens.getReference(i);
  36786. if (lastType != token.tokenType)
  36787. {
  36788. lastType = token.tokenType;
  36789. g.setColour (owner.getColourForTokenType (lastType));
  36790. }
  36791. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36792. if (i < tokens.size() - 1)
  36793. {
  36794. if (token.width < 0)
  36795. token.width = font.getStringWidthFloat (token.text);
  36796. x += token.width;
  36797. }
  36798. }
  36799. }
  36800. private:
  36801. struct SyntaxToken
  36802. {
  36803. String text;
  36804. int tokenType;
  36805. float width;
  36806. SyntaxToken (const String& text_, const int type) throw()
  36807. : text (text_), tokenType (type), width (-1.0f)
  36808. {
  36809. }
  36810. bool operator!= (const SyntaxToken& other) const throw()
  36811. {
  36812. return text != other.text || tokenType != other.tokenType;
  36813. }
  36814. };
  36815. Array <SyntaxToken> tokens;
  36816. int highlightColumnStart, highlightColumnEnd;
  36817. static void createTokens (int startPosition, const String& lineText,
  36818. CodeDocument::Iterator& source,
  36819. CodeTokeniser* analyser,
  36820. Array <SyntaxToken>& newTokens)
  36821. {
  36822. CodeDocument::Iterator lastIterator (source);
  36823. const int lineLength = lineText.length();
  36824. for (;;)
  36825. {
  36826. int tokenType = analyser->readNextToken (source);
  36827. int tokenStart = lastIterator.getPosition();
  36828. int tokenEnd = source.getPosition();
  36829. if (tokenEnd <= tokenStart)
  36830. break;
  36831. tokenEnd -= startPosition;
  36832. if (tokenEnd > 0)
  36833. {
  36834. tokenStart -= startPosition;
  36835. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36836. tokenType));
  36837. if (tokenEnd >= lineLength)
  36838. break;
  36839. }
  36840. lastIterator = source;
  36841. }
  36842. source = lastIterator;
  36843. }
  36844. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36845. {
  36846. int x = 0;
  36847. for (int i = 0; i < tokens.size(); ++i)
  36848. {
  36849. SyntaxToken& t = tokens.getReference(i);
  36850. for (;;)
  36851. {
  36852. int tabPos = t.text.indexOfChar ('\t');
  36853. if (tabPos < 0)
  36854. break;
  36855. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36856. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36857. }
  36858. x += t.text.length();
  36859. }
  36860. }
  36861. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36862. {
  36863. jassert (index <= line.length());
  36864. int col = 0;
  36865. for (int i = 0; i < index; ++i)
  36866. {
  36867. if (line[i] != '\t')
  36868. ++col;
  36869. else
  36870. col += spacesPerTab - (col % spacesPerTab);
  36871. }
  36872. return col;
  36873. }
  36874. };
  36875. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36876. CodeTokeniser* const codeTokeniser_)
  36877. : document (document_),
  36878. firstLineOnScreen (0),
  36879. gutter (5),
  36880. spacesPerTab (4),
  36881. lineHeight (0),
  36882. linesOnScreen (0),
  36883. columnsOnScreen (0),
  36884. scrollbarThickness (16),
  36885. columnToTryToMaintain (-1),
  36886. useSpacesForTabs (false),
  36887. xOffset (0),
  36888. verticalScrollBar (true),
  36889. horizontalScrollBar (false),
  36890. codeTokeniser (codeTokeniser_)
  36891. {
  36892. caretPos = CodeDocument::Position (&document_, 0, 0);
  36893. caretPos.setPositionMaintained (true);
  36894. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36895. selectionStart.setPositionMaintained (true);
  36896. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36897. selectionEnd.setPositionMaintained (true);
  36898. setOpaque (true);
  36899. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36900. setWantsKeyboardFocus (true);
  36901. addAndMakeVisible (&verticalScrollBar);
  36902. verticalScrollBar.setSingleStepSize (1.0);
  36903. addAndMakeVisible (&horizontalScrollBar);
  36904. horizontalScrollBar.setSingleStepSize (1.0);
  36905. addAndMakeVisible (caret = new CaretComponent (*this));
  36906. Font f (12.0f);
  36907. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36908. setFont (f);
  36909. resetToDefaultColours();
  36910. verticalScrollBar.addListener (this);
  36911. horizontalScrollBar.addListener (this);
  36912. document.addListener (this);
  36913. }
  36914. CodeEditorComponent::~CodeEditorComponent()
  36915. {
  36916. document.removeListener (this);
  36917. }
  36918. void CodeEditorComponent::loadContent (const String& newContent)
  36919. {
  36920. clearCachedIterators (0);
  36921. document.replaceAllContent (newContent);
  36922. document.clearUndoHistory();
  36923. document.setSavePoint();
  36924. caretPos.setPosition (0);
  36925. selectionStart.setPosition (0);
  36926. selectionEnd.setPosition (0);
  36927. scrollToLine (0);
  36928. }
  36929. bool CodeEditorComponent::isTextInputActive() const
  36930. {
  36931. return true;
  36932. }
  36933. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36934. const CodeDocument::Position& affectedTextEnd)
  36935. {
  36936. clearCachedIterators (affectedTextStart.getLineNumber());
  36937. triggerAsyncUpdate();
  36938. caret->updatePosition();
  36939. columnToTryToMaintain = -1;
  36940. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36941. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36942. deselectAll();
  36943. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36944. || caretPos.getPosition() < affectedTextStart.getPosition())
  36945. moveCaretTo (affectedTextStart, false);
  36946. updateScrollBars();
  36947. }
  36948. void CodeEditorComponent::resized()
  36949. {
  36950. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36951. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36952. lines.clear();
  36953. rebuildLineTokens();
  36954. caret->updatePosition();
  36955. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36956. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36957. updateScrollBars();
  36958. }
  36959. void CodeEditorComponent::paint (Graphics& g)
  36960. {
  36961. handleUpdateNowIfNeeded();
  36962. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36963. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36964. g.setFont (font);
  36965. const int baselineOffset = (int) font.getAscent();
  36966. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36967. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36968. const Rectangle<int> clip (g.getClipBounds());
  36969. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36970. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36971. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36972. {
  36973. lines.getUnchecked(j)->draw (*this, g, font,
  36974. (float) (gutter - xOffset * charWidth),
  36975. lineHeight * j, baselineOffset, lineHeight,
  36976. highlightColour);
  36977. }
  36978. }
  36979. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36980. {
  36981. if (scrollbarThickness != thickness)
  36982. {
  36983. scrollbarThickness = thickness;
  36984. resized();
  36985. }
  36986. }
  36987. void CodeEditorComponent::handleAsyncUpdate()
  36988. {
  36989. rebuildLineTokens();
  36990. }
  36991. void CodeEditorComponent::rebuildLineTokens()
  36992. {
  36993. cancelPendingUpdate();
  36994. const int numNeeded = linesOnScreen + 1;
  36995. int minLineToRepaint = numNeeded;
  36996. int maxLineToRepaint = 0;
  36997. if (numNeeded != lines.size())
  36998. {
  36999. lines.clear();
  37000. for (int i = numNeeded; --i >= 0;)
  37001. lines.add (new CodeEditorLine());
  37002. minLineToRepaint = 0;
  37003. maxLineToRepaint = numNeeded;
  37004. }
  37005. jassert (numNeeded == lines.size());
  37006. CodeDocument::Iterator source (&document);
  37007. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37008. for (int i = 0; i < numNeeded; ++i)
  37009. {
  37010. CodeEditorLine* const line = lines.getUnchecked(i);
  37011. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37012. selectionStart, selectionEnd))
  37013. {
  37014. minLineToRepaint = jmin (minLineToRepaint, i);
  37015. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37016. }
  37017. }
  37018. if (minLineToRepaint <= maxLineToRepaint)
  37019. {
  37020. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37021. verticalScrollBar.getX() - gutter,
  37022. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37023. }
  37024. }
  37025. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37026. {
  37027. caretPos = newPos;
  37028. columnToTryToMaintain = -1;
  37029. if (highlighting)
  37030. {
  37031. if (dragType == notDragging)
  37032. {
  37033. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37034. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37035. dragType = draggingSelectionStart;
  37036. else
  37037. dragType = draggingSelectionEnd;
  37038. }
  37039. if (dragType == draggingSelectionStart)
  37040. {
  37041. selectionStart = caretPos;
  37042. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37043. {
  37044. const CodeDocument::Position temp (selectionStart);
  37045. selectionStart = selectionEnd;
  37046. selectionEnd = temp;
  37047. dragType = draggingSelectionEnd;
  37048. }
  37049. }
  37050. else
  37051. {
  37052. selectionEnd = caretPos;
  37053. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37054. {
  37055. const CodeDocument::Position temp (selectionStart);
  37056. selectionStart = selectionEnd;
  37057. selectionEnd = temp;
  37058. dragType = draggingSelectionStart;
  37059. }
  37060. }
  37061. triggerAsyncUpdate();
  37062. }
  37063. else
  37064. {
  37065. deselectAll();
  37066. }
  37067. caret->updatePosition();
  37068. scrollToKeepCaretOnScreen();
  37069. updateScrollBars();
  37070. }
  37071. void CodeEditorComponent::deselectAll()
  37072. {
  37073. if (selectionStart != selectionEnd)
  37074. triggerAsyncUpdate();
  37075. selectionStart = caretPos;
  37076. selectionEnd = caretPos;
  37077. }
  37078. void CodeEditorComponent::updateScrollBars()
  37079. {
  37080. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37081. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  37082. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37083. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  37084. }
  37085. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37086. {
  37087. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37088. newFirstLineOnScreen);
  37089. if (newFirstLineOnScreen != firstLineOnScreen)
  37090. {
  37091. firstLineOnScreen = newFirstLineOnScreen;
  37092. caret->updatePosition();
  37093. updateCachedIterators (firstLineOnScreen);
  37094. triggerAsyncUpdate();
  37095. }
  37096. }
  37097. void CodeEditorComponent::scrollToColumnInternal (double column)
  37098. {
  37099. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37100. if (xOffset != newOffset)
  37101. {
  37102. xOffset = newOffset;
  37103. caret->updatePosition();
  37104. repaint();
  37105. }
  37106. }
  37107. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37108. {
  37109. scrollToLineInternal (newFirstLineOnScreen);
  37110. updateScrollBars();
  37111. }
  37112. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37113. {
  37114. scrollToColumnInternal (newFirstColumnOnScreen);
  37115. updateScrollBars();
  37116. }
  37117. void CodeEditorComponent::scrollBy (int deltaLines)
  37118. {
  37119. scrollToLine (firstLineOnScreen + deltaLines);
  37120. }
  37121. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37122. {
  37123. if (caretPos.getLineNumber() < firstLineOnScreen)
  37124. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37125. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37126. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37127. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37128. if (column >= xOffset + columnsOnScreen - 1)
  37129. scrollToColumn (column + 1 - columnsOnScreen);
  37130. else if (column < xOffset)
  37131. scrollToColumn (column);
  37132. }
  37133. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37134. {
  37135. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37136. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37137. roundToInt (charWidth),
  37138. lineHeight);
  37139. }
  37140. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37141. {
  37142. const int line = y / lineHeight + firstLineOnScreen;
  37143. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37144. const int index = columnToIndex (line, column);
  37145. return CodeDocument::Position (&document, line, index);
  37146. }
  37147. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37148. {
  37149. document.deleteSection (selectionStart, selectionEnd);
  37150. if (newText.isNotEmpty())
  37151. document.insertText (caretPos, newText);
  37152. scrollToKeepCaretOnScreen();
  37153. }
  37154. void CodeEditorComponent::insertTabAtCaret()
  37155. {
  37156. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37157. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37158. {
  37159. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37160. }
  37161. if (useSpacesForTabs)
  37162. {
  37163. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37164. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37165. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37166. }
  37167. else
  37168. {
  37169. insertTextAtCaret ("\t");
  37170. }
  37171. }
  37172. void CodeEditorComponent::cut()
  37173. {
  37174. insertTextAtCaret (String::empty);
  37175. }
  37176. void CodeEditorComponent::copy()
  37177. {
  37178. newTransaction();
  37179. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37180. if (selection.isNotEmpty())
  37181. SystemClipboard::copyTextToClipboard (selection);
  37182. }
  37183. void CodeEditorComponent::copyThenCut()
  37184. {
  37185. copy();
  37186. cut();
  37187. newTransaction();
  37188. }
  37189. void CodeEditorComponent::paste()
  37190. {
  37191. newTransaction();
  37192. const String clip (SystemClipboard::getTextFromClipboard());
  37193. if (clip.isNotEmpty())
  37194. insertTextAtCaret (clip);
  37195. newTransaction();
  37196. }
  37197. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37198. {
  37199. newTransaction();
  37200. if (moveInWholeWordSteps)
  37201. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37202. else
  37203. moveCaretTo (caretPos.movedBy (-1), selecting);
  37204. }
  37205. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37206. {
  37207. newTransaction();
  37208. if (moveInWholeWordSteps)
  37209. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37210. else
  37211. moveCaretTo (caretPos.movedBy (1), selecting);
  37212. }
  37213. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37214. {
  37215. CodeDocument::Position pos (caretPos);
  37216. const int newLineNum = pos.getLineNumber() + delta;
  37217. if (columnToTryToMaintain < 0)
  37218. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37219. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37220. const int colToMaintain = columnToTryToMaintain;
  37221. moveCaretTo (pos, selecting);
  37222. columnToTryToMaintain = colToMaintain;
  37223. }
  37224. void CodeEditorComponent::cursorDown (const bool selecting)
  37225. {
  37226. newTransaction();
  37227. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37228. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37229. else
  37230. moveLineDelta (1, selecting);
  37231. }
  37232. void CodeEditorComponent::cursorUp (const bool selecting)
  37233. {
  37234. newTransaction();
  37235. if (caretPos.getLineNumber() == 0)
  37236. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37237. else
  37238. moveLineDelta (-1, selecting);
  37239. }
  37240. void CodeEditorComponent::pageDown (const bool selecting)
  37241. {
  37242. newTransaction();
  37243. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37244. moveLineDelta (linesOnScreen, selecting);
  37245. }
  37246. void CodeEditorComponent::pageUp (const bool selecting)
  37247. {
  37248. newTransaction();
  37249. scrollBy (-linesOnScreen);
  37250. moveLineDelta (-linesOnScreen, selecting);
  37251. }
  37252. void CodeEditorComponent::scrollUp()
  37253. {
  37254. newTransaction();
  37255. scrollBy (1);
  37256. if (caretPos.getLineNumber() < firstLineOnScreen)
  37257. moveLineDelta (1, false);
  37258. }
  37259. void CodeEditorComponent::scrollDown()
  37260. {
  37261. newTransaction();
  37262. scrollBy (-1);
  37263. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37264. moveLineDelta (-1, false);
  37265. }
  37266. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37267. {
  37268. newTransaction();
  37269. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37270. }
  37271. namespace CodeEditorHelpers
  37272. {
  37273. int findFirstNonWhitespaceChar (const String& line) throw()
  37274. {
  37275. const int len = line.length();
  37276. for (int i = 0; i < len; ++i)
  37277. if (! CharacterFunctions::isWhitespace (line [i]))
  37278. return i;
  37279. return 0;
  37280. }
  37281. }
  37282. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37283. {
  37284. newTransaction();
  37285. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37286. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37287. index = 0;
  37288. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37289. }
  37290. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37291. {
  37292. newTransaction();
  37293. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37294. }
  37295. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37296. {
  37297. newTransaction();
  37298. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37299. }
  37300. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37301. {
  37302. if (moveInWholeWordSteps)
  37303. {
  37304. cut(); // in case something is already highlighted
  37305. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37306. }
  37307. else
  37308. {
  37309. if (selectionStart == selectionEnd)
  37310. selectionStart.moveBy (-1);
  37311. }
  37312. cut();
  37313. }
  37314. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37315. {
  37316. if (moveInWholeWordSteps)
  37317. {
  37318. cut(); // in case something is already highlighted
  37319. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37320. }
  37321. else
  37322. {
  37323. if (selectionStart == selectionEnd)
  37324. selectionEnd.moveBy (1);
  37325. else
  37326. newTransaction();
  37327. }
  37328. cut();
  37329. }
  37330. void CodeEditorComponent::selectAll()
  37331. {
  37332. newTransaction();
  37333. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37334. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37335. }
  37336. void CodeEditorComponent::undo()
  37337. {
  37338. document.undo();
  37339. scrollToKeepCaretOnScreen();
  37340. }
  37341. void CodeEditorComponent::redo()
  37342. {
  37343. document.redo();
  37344. scrollToKeepCaretOnScreen();
  37345. }
  37346. void CodeEditorComponent::newTransaction()
  37347. {
  37348. document.newTransaction();
  37349. startTimer (600);
  37350. }
  37351. void CodeEditorComponent::timerCallback()
  37352. {
  37353. newTransaction();
  37354. }
  37355. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37356. {
  37357. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37358. }
  37359. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37360. {
  37361. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37362. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37363. }
  37364. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37365. {
  37366. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37367. CodeDocument::Position (&document, range.getEnd()));
  37368. }
  37369. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37370. {
  37371. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37372. const bool shiftDown = key.getModifiers().isShiftDown();
  37373. if (key.isKeyCode (KeyPress::leftKey))
  37374. {
  37375. cursorLeft (moveInWholeWordSteps, shiftDown);
  37376. }
  37377. else if (key.isKeyCode (KeyPress::rightKey))
  37378. {
  37379. cursorRight (moveInWholeWordSteps, shiftDown);
  37380. }
  37381. else if (key.isKeyCode (KeyPress::upKey))
  37382. {
  37383. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37384. scrollDown();
  37385. #if JUCE_MAC
  37386. else if (key.getModifiers().isCommandDown())
  37387. goToStartOfDocument (shiftDown);
  37388. #endif
  37389. else
  37390. cursorUp (shiftDown);
  37391. }
  37392. else if (key.isKeyCode (KeyPress::downKey))
  37393. {
  37394. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37395. scrollUp();
  37396. #if JUCE_MAC
  37397. else if (key.getModifiers().isCommandDown())
  37398. goToEndOfDocument (shiftDown);
  37399. #endif
  37400. else
  37401. cursorDown (shiftDown);
  37402. }
  37403. else if (key.isKeyCode (KeyPress::pageDownKey))
  37404. {
  37405. pageDown (shiftDown);
  37406. }
  37407. else if (key.isKeyCode (KeyPress::pageUpKey))
  37408. {
  37409. pageUp (shiftDown);
  37410. }
  37411. else if (key.isKeyCode (KeyPress::homeKey))
  37412. {
  37413. if (moveInWholeWordSteps)
  37414. goToStartOfDocument (shiftDown);
  37415. else
  37416. goToStartOfLine (shiftDown);
  37417. }
  37418. else if (key.isKeyCode (KeyPress::endKey))
  37419. {
  37420. if (moveInWholeWordSteps)
  37421. goToEndOfDocument (shiftDown);
  37422. else
  37423. goToEndOfLine (shiftDown);
  37424. }
  37425. else if (key.isKeyCode (KeyPress::backspaceKey))
  37426. {
  37427. backspace (moveInWholeWordSteps);
  37428. }
  37429. else if (key.isKeyCode (KeyPress::deleteKey))
  37430. {
  37431. deleteForward (moveInWholeWordSteps);
  37432. }
  37433. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37434. {
  37435. copy();
  37436. }
  37437. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37438. {
  37439. copyThenCut();
  37440. }
  37441. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37442. {
  37443. paste();
  37444. }
  37445. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37446. {
  37447. undo();
  37448. }
  37449. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37450. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37451. {
  37452. redo();
  37453. }
  37454. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37455. {
  37456. selectAll();
  37457. }
  37458. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37459. {
  37460. insertTabAtCaret();
  37461. }
  37462. else if (key == KeyPress::returnKey)
  37463. {
  37464. newTransaction();
  37465. insertTextAtCaret (document.getNewLineCharacters());
  37466. }
  37467. else if (key.isKeyCode (KeyPress::escapeKey))
  37468. {
  37469. newTransaction();
  37470. }
  37471. else if (key.getTextCharacter() >= ' ')
  37472. {
  37473. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37474. }
  37475. else
  37476. {
  37477. return false;
  37478. }
  37479. return true;
  37480. }
  37481. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37482. {
  37483. newTransaction();
  37484. dragType = notDragging;
  37485. if (! e.mods.isPopupMenu())
  37486. {
  37487. beginDragAutoRepeat (100);
  37488. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37489. }
  37490. else
  37491. {
  37492. /*PopupMenu m;
  37493. addPopupMenuItems (m, &e);
  37494. const int result = m.show();
  37495. if (result != 0)
  37496. performPopupMenuAction (result);
  37497. */
  37498. }
  37499. }
  37500. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37501. {
  37502. if (! e.mods.isPopupMenu())
  37503. moveCaretTo (getPositionAt (e.x, e.y), true);
  37504. }
  37505. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37506. {
  37507. newTransaction();
  37508. beginDragAutoRepeat (0);
  37509. dragType = notDragging;
  37510. }
  37511. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37512. {
  37513. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37514. CodeDocument::Position tokenEnd (tokenStart);
  37515. if (e.getNumberOfClicks() > 2)
  37516. {
  37517. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37518. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37519. }
  37520. else
  37521. {
  37522. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37523. tokenEnd.moveBy (1);
  37524. tokenStart = tokenEnd;
  37525. while (tokenStart.getIndexInLine() > 0
  37526. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37527. tokenStart.moveBy (-1);
  37528. }
  37529. moveCaretTo (tokenEnd, false);
  37530. moveCaretTo (tokenStart, true);
  37531. }
  37532. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37533. {
  37534. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37535. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37536. {
  37537. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37538. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37539. }
  37540. else
  37541. {
  37542. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37543. }
  37544. }
  37545. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37546. {
  37547. if (scrollBarThatHasMoved == &verticalScrollBar)
  37548. scrollToLineInternal ((int) newRangeStart);
  37549. else
  37550. scrollToColumnInternal (newRangeStart);
  37551. }
  37552. void CodeEditorComponent::focusGained (FocusChangeType)
  37553. {
  37554. caret->updatePosition();
  37555. }
  37556. void CodeEditorComponent::focusLost (FocusChangeType)
  37557. {
  37558. caret->updatePosition();
  37559. }
  37560. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37561. {
  37562. useSpacesForTabs = insertSpaces;
  37563. if (spacesPerTab != numSpaces)
  37564. {
  37565. spacesPerTab = numSpaces;
  37566. triggerAsyncUpdate();
  37567. }
  37568. }
  37569. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37570. {
  37571. const String line (document.getLine (lineNum));
  37572. jassert (index <= line.length());
  37573. int col = 0;
  37574. for (int i = 0; i < index; ++i)
  37575. {
  37576. if (line[i] != '\t')
  37577. ++col;
  37578. else
  37579. col += getTabSize() - (col % getTabSize());
  37580. }
  37581. return col;
  37582. }
  37583. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37584. {
  37585. const String line (document.getLine (lineNum));
  37586. const int lineLength = line.length();
  37587. int i, col = 0;
  37588. for (i = 0; i < lineLength; ++i)
  37589. {
  37590. if (line[i] != '\t')
  37591. ++col;
  37592. else
  37593. col += getTabSize() - (col % getTabSize());
  37594. if (col > column)
  37595. break;
  37596. }
  37597. return i;
  37598. }
  37599. void CodeEditorComponent::setFont (const Font& newFont)
  37600. {
  37601. font = newFont;
  37602. charWidth = font.getStringWidthFloat ("0");
  37603. lineHeight = roundToInt (font.getHeight());
  37604. resized();
  37605. }
  37606. void CodeEditorComponent::resetToDefaultColours()
  37607. {
  37608. coloursForTokenCategories.clear();
  37609. if (codeTokeniser != 0)
  37610. {
  37611. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37612. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37613. }
  37614. }
  37615. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37616. {
  37617. jassert (tokenType < 256);
  37618. while (coloursForTokenCategories.size() < tokenType)
  37619. coloursForTokenCategories.add (Colours::black);
  37620. coloursForTokenCategories.set (tokenType, colour);
  37621. repaint();
  37622. }
  37623. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37624. {
  37625. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37626. return findColour (CodeEditorComponent::defaultTextColourId);
  37627. return coloursForTokenCategories.getReference (tokenType);
  37628. }
  37629. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37630. {
  37631. int i;
  37632. for (i = cachedIterators.size(); --i >= 0;)
  37633. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37634. break;
  37635. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37636. }
  37637. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37638. {
  37639. const int maxNumCachedPositions = 5000;
  37640. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37641. if (cachedIterators.size() == 0)
  37642. cachedIterators.add (new CodeDocument::Iterator (&document));
  37643. if (codeTokeniser == 0)
  37644. return;
  37645. for (;;)
  37646. {
  37647. CodeDocument::Iterator* last = cachedIterators.getLast();
  37648. if (last->getLine() >= maxLineNum)
  37649. break;
  37650. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37651. cachedIterators.add (t);
  37652. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37653. for (;;)
  37654. {
  37655. codeTokeniser->readNextToken (*t);
  37656. if (t->getLine() >= targetLine)
  37657. break;
  37658. if (t->isEOF())
  37659. return;
  37660. }
  37661. }
  37662. }
  37663. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37664. {
  37665. if (codeTokeniser == 0)
  37666. return;
  37667. for (int i = cachedIterators.size(); --i >= 0;)
  37668. {
  37669. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37670. if (t->getPosition() <= position)
  37671. {
  37672. source = *t;
  37673. break;
  37674. }
  37675. }
  37676. while (source.getPosition() < position)
  37677. {
  37678. const CodeDocument::Iterator original (source);
  37679. codeTokeniser->readNextToken (source);
  37680. if (source.getPosition() > position || source.isEOF())
  37681. {
  37682. source = original;
  37683. break;
  37684. }
  37685. }
  37686. }
  37687. END_JUCE_NAMESPACE
  37688. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37689. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37690. BEGIN_JUCE_NAMESPACE
  37691. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37692. {
  37693. }
  37694. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37695. {
  37696. }
  37697. namespace CppTokeniser
  37698. {
  37699. bool isIdentifierStart (const juce_wchar c) throw()
  37700. {
  37701. return CharacterFunctions::isLetter (c)
  37702. || c == '_' || c == '@';
  37703. }
  37704. bool isIdentifierBody (const juce_wchar c) throw()
  37705. {
  37706. return CharacterFunctions::isLetterOrDigit (c)
  37707. || c == '_' || c == '@';
  37708. }
  37709. bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37710. {
  37711. static const juce_wchar* const keywords2Char[] =
  37712. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37713. static const juce_wchar* const keywords3Char[] =
  37714. { JUCE_T("for"), JUCE_T("int"), JUCE_T("new"), JUCE_T("try"), JUCE_T("xor"), JUCE_T("and"), JUCE_T("asm"), JUCE_T("not"), 0 };
  37715. static const juce_wchar* const keywords4Char[] =
  37716. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37717. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37718. static const juce_wchar* const keywords5Char[] =
  37719. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37720. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37721. static const juce_wchar* const keywords6Char[] =
  37722. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37723. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37724. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37725. static const juce_wchar* const keywordsOther[] =
  37726. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37727. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37728. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37729. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37730. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37731. const juce_wchar* const* k;
  37732. switch (tokenLength)
  37733. {
  37734. case 2: k = keywords2Char; break;
  37735. case 3: k = keywords3Char; break;
  37736. case 4: k = keywords4Char; break;
  37737. case 5: k = keywords5Char; break;
  37738. case 6: k = keywords6Char; break;
  37739. default:
  37740. if (tokenLength < 2 || tokenLength > 16)
  37741. return false;
  37742. k = keywordsOther;
  37743. break;
  37744. }
  37745. int i = 0;
  37746. while (k[i] != 0)
  37747. {
  37748. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37749. return true;
  37750. ++i;
  37751. }
  37752. return false;
  37753. }
  37754. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37755. {
  37756. int tokenLength = 0;
  37757. juce_wchar possibleIdentifier [19];
  37758. while (isIdentifierBody (source.peekNextChar()))
  37759. {
  37760. const juce_wchar c = source.nextChar();
  37761. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37762. possibleIdentifier [tokenLength] = c;
  37763. ++tokenLength;
  37764. }
  37765. if (tokenLength > 1 && tokenLength <= 16)
  37766. {
  37767. possibleIdentifier [tokenLength] = 0;
  37768. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37769. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37770. }
  37771. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37772. }
  37773. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37774. {
  37775. const juce_wchar c = source.peekNextChar();
  37776. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37777. source.skip();
  37778. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37779. return false;
  37780. return true;
  37781. }
  37782. bool isHexDigit (const juce_wchar c) throw()
  37783. {
  37784. return (c >= '0' && c <= '9')
  37785. || (c >= 'a' && c <= 'f')
  37786. || (c >= 'A' && c <= 'F');
  37787. }
  37788. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37789. {
  37790. if (source.nextChar() != '0')
  37791. return false;
  37792. juce_wchar c = source.nextChar();
  37793. if (c != 'x' && c != 'X')
  37794. return false;
  37795. int numDigits = 0;
  37796. while (isHexDigit (source.peekNextChar()))
  37797. {
  37798. ++numDigits;
  37799. source.skip();
  37800. }
  37801. if (numDigits == 0)
  37802. return false;
  37803. return skipNumberSuffix (source);
  37804. }
  37805. bool isOctalDigit (const juce_wchar c) throw()
  37806. {
  37807. return c >= '0' && c <= '7';
  37808. }
  37809. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37810. {
  37811. if (source.nextChar() != '0')
  37812. return false;
  37813. if (! isOctalDigit (source.nextChar()))
  37814. return false;
  37815. while (isOctalDigit (source.peekNextChar()))
  37816. source.skip();
  37817. return skipNumberSuffix (source);
  37818. }
  37819. bool isDecimalDigit (const juce_wchar c) throw()
  37820. {
  37821. return c >= '0' && c <= '9';
  37822. }
  37823. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37824. {
  37825. int numChars = 0;
  37826. while (isDecimalDigit (source.peekNextChar()))
  37827. {
  37828. ++numChars;
  37829. source.skip();
  37830. }
  37831. if (numChars == 0)
  37832. return false;
  37833. return skipNumberSuffix (source);
  37834. }
  37835. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37836. {
  37837. int numDigits = 0;
  37838. while (isDecimalDigit (source.peekNextChar()))
  37839. {
  37840. source.skip();
  37841. ++numDigits;
  37842. }
  37843. const bool hasPoint = (source.peekNextChar() == '.');
  37844. if (hasPoint)
  37845. {
  37846. source.skip();
  37847. while (isDecimalDigit (source.peekNextChar()))
  37848. {
  37849. source.skip();
  37850. ++numDigits;
  37851. }
  37852. }
  37853. if (numDigits == 0)
  37854. return false;
  37855. juce_wchar c = source.peekNextChar();
  37856. const bool hasExponent = (c == 'e' || c == 'E');
  37857. if (hasExponent)
  37858. {
  37859. source.skip();
  37860. c = source.peekNextChar();
  37861. if (c == '+' || c == '-')
  37862. source.skip();
  37863. int numExpDigits = 0;
  37864. while (isDecimalDigit (source.peekNextChar()))
  37865. {
  37866. source.skip();
  37867. ++numExpDigits;
  37868. }
  37869. if (numExpDigits == 0)
  37870. return false;
  37871. }
  37872. c = source.peekNextChar();
  37873. if (c == 'f' || c == 'F')
  37874. source.skip();
  37875. else if (! (hasExponent || hasPoint))
  37876. return false;
  37877. return true;
  37878. }
  37879. int parseNumber (CodeDocument::Iterator& source)
  37880. {
  37881. const CodeDocument::Iterator original (source);
  37882. if (parseFloatLiteral (source))
  37883. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37884. source = original;
  37885. if (parseHexLiteral (source))
  37886. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37887. source = original;
  37888. if (parseOctalLiteral (source))
  37889. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37890. source = original;
  37891. if (parseDecimalLiteral (source))
  37892. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37893. source = original;
  37894. source.skip();
  37895. return CPlusPlusCodeTokeniser::tokenType_error;
  37896. }
  37897. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37898. {
  37899. const juce_wchar quote = source.nextChar();
  37900. for (;;)
  37901. {
  37902. const juce_wchar c = source.nextChar();
  37903. if (c == quote || c == 0)
  37904. break;
  37905. if (c == '\\')
  37906. source.skip();
  37907. }
  37908. }
  37909. void skipComment (CodeDocument::Iterator& source) throw()
  37910. {
  37911. bool lastWasStar = false;
  37912. for (;;)
  37913. {
  37914. const juce_wchar c = source.nextChar();
  37915. if (c == 0 || (c == '/' && lastWasStar))
  37916. break;
  37917. lastWasStar = (c == '*');
  37918. }
  37919. }
  37920. }
  37921. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37922. {
  37923. int result = tokenType_error;
  37924. source.skipWhitespace();
  37925. juce_wchar firstChar = source.peekNextChar();
  37926. switch (firstChar)
  37927. {
  37928. case 0:
  37929. source.skip();
  37930. break;
  37931. case '0':
  37932. case '1':
  37933. case '2':
  37934. case '3':
  37935. case '4':
  37936. case '5':
  37937. case '6':
  37938. case '7':
  37939. case '8':
  37940. case '9':
  37941. result = CppTokeniser::parseNumber (source);
  37942. break;
  37943. case '.':
  37944. result = CppTokeniser::parseNumber (source);
  37945. if (result == tokenType_error)
  37946. result = tokenType_punctuation;
  37947. break;
  37948. case ',':
  37949. case ';':
  37950. case ':':
  37951. source.skip();
  37952. result = tokenType_punctuation;
  37953. break;
  37954. case '(':
  37955. case ')':
  37956. case '{':
  37957. case '}':
  37958. case '[':
  37959. case ']':
  37960. source.skip();
  37961. result = tokenType_bracket;
  37962. break;
  37963. case '"':
  37964. case '\'':
  37965. CppTokeniser::skipQuotedString (source);
  37966. result = tokenType_stringLiteral;
  37967. break;
  37968. case '+':
  37969. result = tokenType_operator;
  37970. source.skip();
  37971. if (source.peekNextChar() == '+')
  37972. source.skip();
  37973. else if (source.peekNextChar() == '=')
  37974. source.skip();
  37975. break;
  37976. case '-':
  37977. source.skip();
  37978. result = CppTokeniser::parseNumber (source);
  37979. if (result == tokenType_error)
  37980. {
  37981. result = tokenType_operator;
  37982. if (source.peekNextChar() == '-')
  37983. source.skip();
  37984. else if (source.peekNextChar() == '=')
  37985. source.skip();
  37986. }
  37987. break;
  37988. case '*':
  37989. case '%':
  37990. case '=':
  37991. case '!':
  37992. result = tokenType_operator;
  37993. source.skip();
  37994. if (source.peekNextChar() == '=')
  37995. source.skip();
  37996. break;
  37997. case '/':
  37998. result = tokenType_operator;
  37999. source.skip();
  38000. if (source.peekNextChar() == '=')
  38001. {
  38002. source.skip();
  38003. }
  38004. else if (source.peekNextChar() == '/')
  38005. {
  38006. result = tokenType_comment;
  38007. source.skipToEndOfLine();
  38008. }
  38009. else if (source.peekNextChar() == '*')
  38010. {
  38011. source.skip();
  38012. result = tokenType_comment;
  38013. CppTokeniser::skipComment (source);
  38014. }
  38015. break;
  38016. case '?':
  38017. case '~':
  38018. source.skip();
  38019. result = tokenType_operator;
  38020. break;
  38021. case '<':
  38022. source.skip();
  38023. result = tokenType_operator;
  38024. if (source.peekNextChar() == '=')
  38025. {
  38026. source.skip();
  38027. }
  38028. else if (source.peekNextChar() == '<')
  38029. {
  38030. source.skip();
  38031. if (source.peekNextChar() == '=')
  38032. source.skip();
  38033. }
  38034. break;
  38035. case '>':
  38036. source.skip();
  38037. result = tokenType_operator;
  38038. if (source.peekNextChar() == '=')
  38039. {
  38040. source.skip();
  38041. }
  38042. else if (source.peekNextChar() == '<')
  38043. {
  38044. source.skip();
  38045. if (source.peekNextChar() == '=')
  38046. source.skip();
  38047. }
  38048. break;
  38049. case '|':
  38050. source.skip();
  38051. result = tokenType_operator;
  38052. if (source.peekNextChar() == '=')
  38053. {
  38054. source.skip();
  38055. }
  38056. else if (source.peekNextChar() == '|')
  38057. {
  38058. source.skip();
  38059. if (source.peekNextChar() == '=')
  38060. source.skip();
  38061. }
  38062. break;
  38063. case '&':
  38064. source.skip();
  38065. result = tokenType_operator;
  38066. if (source.peekNextChar() == '=')
  38067. {
  38068. source.skip();
  38069. }
  38070. else if (source.peekNextChar() == '&')
  38071. {
  38072. source.skip();
  38073. if (source.peekNextChar() == '=')
  38074. source.skip();
  38075. }
  38076. break;
  38077. case '^':
  38078. source.skip();
  38079. result = tokenType_operator;
  38080. if (source.peekNextChar() == '=')
  38081. {
  38082. source.skip();
  38083. }
  38084. else if (source.peekNextChar() == '^')
  38085. {
  38086. source.skip();
  38087. if (source.peekNextChar() == '=')
  38088. source.skip();
  38089. }
  38090. break;
  38091. case '#':
  38092. result = tokenType_preprocessor;
  38093. source.skipToEndOfLine();
  38094. break;
  38095. default:
  38096. if (CppTokeniser::isIdentifierStart (firstChar))
  38097. result = CppTokeniser::parseIdentifier (source);
  38098. else
  38099. source.skip();
  38100. break;
  38101. }
  38102. return result;
  38103. }
  38104. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38105. {
  38106. const char* const types[] =
  38107. {
  38108. "Error",
  38109. "Comment",
  38110. "C++ keyword",
  38111. "Identifier",
  38112. "Integer literal",
  38113. "Float literal",
  38114. "String literal",
  38115. "Operator",
  38116. "Bracket",
  38117. "Punctuation",
  38118. "Preprocessor line",
  38119. 0
  38120. };
  38121. return StringArray (types);
  38122. }
  38123. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38124. {
  38125. const uint32 colours[] =
  38126. {
  38127. 0xffcc0000, // error
  38128. 0xff00aa00, // comment
  38129. 0xff0000cc, // keyword
  38130. 0xff000000, // identifier
  38131. 0xff880000, // int literal
  38132. 0xff885500, // float literal
  38133. 0xff990099, // string literal
  38134. 0xff225500, // operator
  38135. 0xff000055, // bracket
  38136. 0xff004400, // punctuation
  38137. 0xff660000 // preprocessor
  38138. };
  38139. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38140. return Colour (colours [tokenType]);
  38141. return Colours::black;
  38142. }
  38143. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38144. {
  38145. return CppTokeniser::isReservedKeyword (token, token.length());
  38146. }
  38147. END_JUCE_NAMESPACE
  38148. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38149. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38150. BEGIN_JUCE_NAMESPACE
  38151. ComboBox::ComboBox (const String& name)
  38152. : Component (name),
  38153. lastCurrentId (0),
  38154. isButtonDown (false),
  38155. separatorPending (false),
  38156. menuActive (false),
  38157. noChoicesMessage (TRANS("(no choices)"))
  38158. {
  38159. setRepaintsOnMouseActivity (true);
  38160. lookAndFeelChanged();
  38161. currentId.addListener (this);
  38162. }
  38163. ComboBox::~ComboBox()
  38164. {
  38165. currentId.removeListener (this);
  38166. if (menuActive)
  38167. PopupMenu::dismissAllActiveMenus();
  38168. label = 0;
  38169. }
  38170. void ComboBox::setEditableText (const bool isEditable)
  38171. {
  38172. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38173. {
  38174. label->setEditable (isEditable, isEditable, false);
  38175. setWantsKeyboardFocus (! isEditable);
  38176. resized();
  38177. }
  38178. }
  38179. bool ComboBox::isTextEditable() const throw()
  38180. {
  38181. return label->isEditable();
  38182. }
  38183. void ComboBox::setJustificationType (const Justification& justification)
  38184. {
  38185. label->setJustificationType (justification);
  38186. }
  38187. const Justification ComboBox::getJustificationType() const throw()
  38188. {
  38189. return label->getJustificationType();
  38190. }
  38191. void ComboBox::setTooltip (const String& newTooltip)
  38192. {
  38193. SettableTooltipClient::setTooltip (newTooltip);
  38194. label->setTooltip (newTooltip);
  38195. }
  38196. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38197. {
  38198. // you can't add empty strings to the list..
  38199. jassert (newItemText.isNotEmpty());
  38200. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38201. jassert (newItemId != 0);
  38202. // you shouldn't use duplicate item IDs!
  38203. jassert (getItemForId (newItemId) == 0);
  38204. if (newItemText.isNotEmpty() && newItemId != 0)
  38205. {
  38206. if (separatorPending)
  38207. {
  38208. separatorPending = false;
  38209. ItemInfo* const item = new ItemInfo();
  38210. item->itemId = 0;
  38211. item->isEnabled = false;
  38212. item->isHeading = false;
  38213. items.add (item);
  38214. }
  38215. ItemInfo* const item = new ItemInfo();
  38216. item->name = newItemText;
  38217. item->itemId = newItemId;
  38218. item->isEnabled = true;
  38219. item->isHeading = false;
  38220. items.add (item);
  38221. }
  38222. }
  38223. void ComboBox::addSeparator()
  38224. {
  38225. separatorPending = (items.size() > 0);
  38226. }
  38227. void ComboBox::addSectionHeading (const String& headingName)
  38228. {
  38229. // you can't add empty strings to the list..
  38230. jassert (headingName.isNotEmpty());
  38231. if (headingName.isNotEmpty())
  38232. {
  38233. if (separatorPending)
  38234. {
  38235. separatorPending = false;
  38236. ItemInfo* const item = new ItemInfo();
  38237. item->itemId = 0;
  38238. item->isEnabled = false;
  38239. item->isHeading = false;
  38240. items.add (item);
  38241. }
  38242. ItemInfo* const item = new ItemInfo();
  38243. item->name = headingName;
  38244. item->itemId = 0;
  38245. item->isEnabled = true;
  38246. item->isHeading = true;
  38247. items.add (item);
  38248. }
  38249. }
  38250. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38251. {
  38252. ItemInfo* const item = getItemForId (itemId);
  38253. if (item != 0)
  38254. item->isEnabled = shouldBeEnabled;
  38255. }
  38256. void ComboBox::changeItemText (const int itemId, const String& newText)
  38257. {
  38258. ItemInfo* const item = getItemForId (itemId);
  38259. jassert (item != 0);
  38260. if (item != 0)
  38261. item->name = newText;
  38262. }
  38263. void ComboBox::clear (const bool dontSendChangeMessage)
  38264. {
  38265. items.clear();
  38266. separatorPending = false;
  38267. if (! label->isEditable())
  38268. setSelectedItemIndex (-1, dontSendChangeMessage);
  38269. }
  38270. bool ComboBox::ItemInfo::isSeparator() const throw()
  38271. {
  38272. return name.isEmpty();
  38273. }
  38274. bool ComboBox::ItemInfo::isRealItem() const throw()
  38275. {
  38276. return ! (isHeading || name.isEmpty());
  38277. }
  38278. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38279. {
  38280. if (itemId != 0)
  38281. {
  38282. for (int i = items.size(); --i >= 0;)
  38283. if (items.getUnchecked(i)->itemId == itemId)
  38284. return items.getUnchecked(i);
  38285. }
  38286. return 0;
  38287. }
  38288. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38289. {
  38290. int n = 0;
  38291. for (int i = 0; i < items.size(); ++i)
  38292. {
  38293. ItemInfo* const item = items.getUnchecked(i);
  38294. if (item->isRealItem())
  38295. if (n++ == index)
  38296. return item;
  38297. }
  38298. return 0;
  38299. }
  38300. int ComboBox::getNumItems() const throw()
  38301. {
  38302. int n = 0;
  38303. for (int i = items.size(); --i >= 0;)
  38304. if (items.getUnchecked(i)->isRealItem())
  38305. ++n;
  38306. return n;
  38307. }
  38308. const String ComboBox::getItemText (const int index) const
  38309. {
  38310. const ItemInfo* const item = getItemForIndex (index);
  38311. if (item != 0)
  38312. return item->name;
  38313. return String::empty;
  38314. }
  38315. int ComboBox::getItemId (const int index) const throw()
  38316. {
  38317. const ItemInfo* const item = getItemForIndex (index);
  38318. return (item != 0) ? item->itemId : 0;
  38319. }
  38320. int ComboBox::indexOfItemId (const int itemId) const throw()
  38321. {
  38322. int n = 0;
  38323. for (int i = 0; i < items.size(); ++i)
  38324. {
  38325. const ItemInfo* const item = items.getUnchecked(i);
  38326. if (item->isRealItem())
  38327. {
  38328. if (item->itemId == itemId)
  38329. return n;
  38330. ++n;
  38331. }
  38332. }
  38333. return -1;
  38334. }
  38335. int ComboBox::getSelectedItemIndex() const
  38336. {
  38337. int index = indexOfItemId (currentId.getValue());
  38338. if (getText() != getItemText (index))
  38339. index = -1;
  38340. return index;
  38341. }
  38342. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38343. {
  38344. setSelectedId (getItemId (index), dontSendChangeMessage);
  38345. }
  38346. int ComboBox::getSelectedId() const throw()
  38347. {
  38348. const ItemInfo* const item = getItemForId (currentId.getValue());
  38349. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38350. }
  38351. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38352. {
  38353. const ItemInfo* const item = getItemForId (newItemId);
  38354. const String newItemText (item != 0 ? item->name : String::empty);
  38355. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38356. {
  38357. if (! dontSendChangeMessage)
  38358. triggerAsyncUpdate();
  38359. label->setText (newItemText, false);
  38360. lastCurrentId = newItemId;
  38361. currentId = newItemId;
  38362. repaint(); // for the benefit of the 'none selected' text
  38363. }
  38364. }
  38365. void ComboBox::valueChanged (Value&)
  38366. {
  38367. if (lastCurrentId != (int) currentId.getValue())
  38368. setSelectedId (currentId.getValue(), false);
  38369. }
  38370. const String ComboBox::getText() const
  38371. {
  38372. return label->getText();
  38373. }
  38374. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38375. {
  38376. for (int i = items.size(); --i >= 0;)
  38377. {
  38378. const ItemInfo* const item = items.getUnchecked(i);
  38379. if (item->isRealItem()
  38380. && item->name == newText)
  38381. {
  38382. setSelectedId (item->itemId, dontSendChangeMessage);
  38383. return;
  38384. }
  38385. }
  38386. lastCurrentId = 0;
  38387. currentId = 0;
  38388. if (label->getText() != newText)
  38389. {
  38390. label->setText (newText, false);
  38391. if (! dontSendChangeMessage)
  38392. triggerAsyncUpdate();
  38393. }
  38394. repaint();
  38395. }
  38396. void ComboBox::showEditor()
  38397. {
  38398. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38399. label->showEditor();
  38400. }
  38401. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38402. {
  38403. if (textWhenNothingSelected != newMessage)
  38404. {
  38405. textWhenNothingSelected = newMessage;
  38406. repaint();
  38407. }
  38408. }
  38409. const String ComboBox::getTextWhenNothingSelected() const
  38410. {
  38411. return textWhenNothingSelected;
  38412. }
  38413. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38414. {
  38415. noChoicesMessage = newMessage;
  38416. }
  38417. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38418. {
  38419. return noChoicesMessage;
  38420. }
  38421. void ComboBox::paint (Graphics& g)
  38422. {
  38423. getLookAndFeel().drawComboBox (g,
  38424. getWidth(),
  38425. getHeight(),
  38426. isButtonDown,
  38427. label->getRight(),
  38428. 0,
  38429. getWidth() - label->getRight(),
  38430. getHeight(),
  38431. *this);
  38432. if (textWhenNothingSelected.isNotEmpty()
  38433. && label->getText().isEmpty()
  38434. && ! label->isBeingEdited())
  38435. {
  38436. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38437. g.setFont (label->getFont());
  38438. g.drawFittedText (textWhenNothingSelected,
  38439. label->getX() + 2, label->getY() + 1,
  38440. label->getWidth() - 4, label->getHeight() - 2,
  38441. label->getJustificationType(),
  38442. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38443. }
  38444. }
  38445. void ComboBox::resized()
  38446. {
  38447. if (getHeight() > 0 && getWidth() > 0)
  38448. getLookAndFeel().positionComboBoxText (*this, *label);
  38449. }
  38450. void ComboBox::enablementChanged()
  38451. {
  38452. repaint();
  38453. }
  38454. void ComboBox::lookAndFeelChanged()
  38455. {
  38456. repaint();
  38457. {
  38458. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38459. jassert (newLabel != 0);
  38460. if (label != 0)
  38461. {
  38462. newLabel->setEditable (label->isEditable());
  38463. newLabel->setJustificationType (label->getJustificationType());
  38464. newLabel->setTooltip (label->getTooltip());
  38465. newLabel->setText (label->getText(), false);
  38466. }
  38467. label = newLabel;
  38468. }
  38469. addAndMakeVisible (label);
  38470. label->addListener (this);
  38471. label->addMouseListener (this, false);
  38472. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38473. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38474. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38475. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38476. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38477. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38478. resized();
  38479. }
  38480. void ComboBox::colourChanged()
  38481. {
  38482. lookAndFeelChanged();
  38483. }
  38484. bool ComboBox::keyPressed (const KeyPress& key)
  38485. {
  38486. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38487. {
  38488. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38489. return true;
  38490. }
  38491. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38492. {
  38493. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38494. return true;
  38495. }
  38496. else if (key.isKeyCode (KeyPress::returnKey))
  38497. {
  38498. showPopup();
  38499. return true;
  38500. }
  38501. return false;
  38502. }
  38503. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38504. {
  38505. // only forward key events that aren't used by this component
  38506. return isKeyDown
  38507. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38508. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38509. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38510. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38511. }
  38512. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38513. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38514. void ComboBox::labelTextChanged (Label*)
  38515. {
  38516. triggerAsyncUpdate();
  38517. }
  38518. class ComboBox::Callback : public ModalComponentManager::Callback
  38519. {
  38520. public:
  38521. Callback (ComboBox* const box_)
  38522. : box (box_)
  38523. {
  38524. }
  38525. void modalStateFinished (int returnValue)
  38526. {
  38527. if (box != 0)
  38528. {
  38529. box->menuActive = false;
  38530. if (returnValue != 0)
  38531. box->setSelectedId (returnValue);
  38532. }
  38533. }
  38534. private:
  38535. Component::SafePointer<ComboBox> box;
  38536. JUCE_DECLARE_NON_COPYABLE (Callback);
  38537. };
  38538. void ComboBox::showPopup()
  38539. {
  38540. if (! menuActive)
  38541. {
  38542. const int selectedId = getSelectedId();
  38543. PopupMenu menu;
  38544. menu.setLookAndFeel (&getLookAndFeel());
  38545. for (int i = 0; i < items.size(); ++i)
  38546. {
  38547. const ItemInfo* const item = items.getUnchecked(i);
  38548. if (item->isSeparator())
  38549. menu.addSeparator();
  38550. else if (item->isHeading)
  38551. menu.addSectionHeader (item->name);
  38552. else
  38553. menu.addItem (item->itemId, item->name,
  38554. item->isEnabled, item->itemId == selectedId);
  38555. }
  38556. if (items.size() == 0)
  38557. menu.addItem (1, noChoicesMessage, false);
  38558. menuActive = true;
  38559. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38560. new Callback (this));
  38561. }
  38562. }
  38563. void ComboBox::mouseDown (const MouseEvent& e)
  38564. {
  38565. beginDragAutoRepeat (300);
  38566. isButtonDown = isEnabled();
  38567. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38568. showPopup();
  38569. }
  38570. void ComboBox::mouseDrag (const MouseEvent& e)
  38571. {
  38572. beginDragAutoRepeat (50);
  38573. if (isButtonDown && ! e.mouseWasClicked())
  38574. showPopup();
  38575. }
  38576. void ComboBox::mouseUp (const MouseEvent& e2)
  38577. {
  38578. if (isButtonDown)
  38579. {
  38580. isButtonDown = false;
  38581. repaint();
  38582. const MouseEvent e (e2.getEventRelativeTo (this));
  38583. if (reallyContains (e.getPosition(), true)
  38584. && (e2.eventComponent == this || ! label->isEditable()))
  38585. {
  38586. showPopup();
  38587. }
  38588. }
  38589. }
  38590. void ComboBox::addListener (ComboBoxListener* const listener)
  38591. {
  38592. listeners.add (listener);
  38593. }
  38594. void ComboBox::removeListener (ComboBoxListener* const listener)
  38595. {
  38596. listeners.remove (listener);
  38597. }
  38598. void ComboBox::handleAsyncUpdate()
  38599. {
  38600. Component::BailOutChecker checker (this);
  38601. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38602. }
  38603. END_JUCE_NAMESPACE
  38604. /*** End of inlined file: juce_ComboBox.cpp ***/
  38605. /*** Start of inlined file: juce_Label.cpp ***/
  38606. BEGIN_JUCE_NAMESPACE
  38607. Label::Label (const String& componentName,
  38608. const String& labelText)
  38609. : Component (componentName),
  38610. textValue (labelText),
  38611. lastTextValue (labelText),
  38612. font (15.0f),
  38613. justification (Justification::centredLeft),
  38614. ownerComponent (0),
  38615. horizontalBorderSize (5),
  38616. verticalBorderSize (1),
  38617. minimumHorizontalScale (0.7f),
  38618. editSingleClick (false),
  38619. editDoubleClick (false),
  38620. lossOfFocusDiscardsChanges (false)
  38621. {
  38622. setColour (TextEditor::textColourId, Colours::black);
  38623. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38624. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38625. textValue.addListener (this);
  38626. }
  38627. Label::~Label()
  38628. {
  38629. textValue.removeListener (this);
  38630. if (ownerComponent != 0)
  38631. ownerComponent->removeComponentListener (this);
  38632. editor = 0;
  38633. }
  38634. void Label::setText (const String& newText,
  38635. const bool broadcastChangeMessage)
  38636. {
  38637. hideEditor (true);
  38638. if (lastTextValue != newText)
  38639. {
  38640. lastTextValue = newText;
  38641. textValue = newText;
  38642. repaint();
  38643. textWasChanged();
  38644. if (ownerComponent != 0)
  38645. componentMovedOrResized (*ownerComponent, true, true);
  38646. if (broadcastChangeMessage)
  38647. callChangeListeners();
  38648. }
  38649. }
  38650. const String Label::getText (const bool returnActiveEditorContents) const
  38651. {
  38652. return (returnActiveEditorContents && isBeingEdited())
  38653. ? editor->getText()
  38654. : textValue.toString();
  38655. }
  38656. void Label::valueChanged (Value&)
  38657. {
  38658. if (lastTextValue != textValue.toString())
  38659. setText (textValue.toString(), true);
  38660. }
  38661. void Label::setFont (const Font& newFont)
  38662. {
  38663. if (font != newFont)
  38664. {
  38665. font = newFont;
  38666. repaint();
  38667. }
  38668. }
  38669. const Font& Label::getFont() const throw()
  38670. {
  38671. return font;
  38672. }
  38673. void Label::setEditable (const bool editOnSingleClick,
  38674. const bool editOnDoubleClick,
  38675. const bool lossOfFocusDiscardsChanges_)
  38676. {
  38677. editSingleClick = editOnSingleClick;
  38678. editDoubleClick = editOnDoubleClick;
  38679. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38680. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38681. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38682. }
  38683. void Label::setJustificationType (const Justification& newJustification)
  38684. {
  38685. if (justification != newJustification)
  38686. {
  38687. justification = newJustification;
  38688. repaint();
  38689. }
  38690. }
  38691. void Label::setBorderSize (int h, int v)
  38692. {
  38693. if (horizontalBorderSize != h || verticalBorderSize != v)
  38694. {
  38695. horizontalBorderSize = h;
  38696. verticalBorderSize = v;
  38697. repaint();
  38698. }
  38699. }
  38700. Component* Label::getAttachedComponent() const
  38701. {
  38702. return static_cast<Component*> (ownerComponent);
  38703. }
  38704. void Label::attachToComponent (Component* owner,
  38705. const bool onLeft)
  38706. {
  38707. if (ownerComponent != 0)
  38708. ownerComponent->removeComponentListener (this);
  38709. ownerComponent = owner;
  38710. leftOfOwnerComp = onLeft;
  38711. if (ownerComponent != 0)
  38712. {
  38713. setVisible (owner->isVisible());
  38714. ownerComponent->addComponentListener (this);
  38715. componentParentHierarchyChanged (*ownerComponent);
  38716. componentMovedOrResized (*ownerComponent, true, true);
  38717. }
  38718. }
  38719. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38720. {
  38721. if (leftOfOwnerComp)
  38722. {
  38723. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38724. component.getHeight());
  38725. setTopRightPosition (component.getX(), component.getY());
  38726. }
  38727. else
  38728. {
  38729. setSize (component.getWidth(),
  38730. 8 + roundToInt (getFont().getHeight()));
  38731. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38732. }
  38733. }
  38734. void Label::componentParentHierarchyChanged (Component& component)
  38735. {
  38736. if (component.getParentComponent() != 0)
  38737. component.getParentComponent()->addChildComponent (this);
  38738. }
  38739. void Label::componentVisibilityChanged (Component& component)
  38740. {
  38741. setVisible (component.isVisible());
  38742. }
  38743. void Label::textWasEdited()
  38744. {
  38745. }
  38746. void Label::textWasChanged()
  38747. {
  38748. }
  38749. void Label::showEditor()
  38750. {
  38751. if (editor == 0)
  38752. {
  38753. addAndMakeVisible (editor = createEditorComponent());
  38754. editor->setText (getText(), false);
  38755. editor->addListener (this);
  38756. editor->grabKeyboardFocus();
  38757. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38758. editor->addListener (this);
  38759. resized();
  38760. repaint();
  38761. editorShown (editor);
  38762. enterModalState (false);
  38763. editor->grabKeyboardFocus();
  38764. }
  38765. }
  38766. void Label::editorShown (TextEditor* /*editorComponent*/)
  38767. {
  38768. }
  38769. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38770. {
  38771. }
  38772. bool Label::updateFromTextEditorContents()
  38773. {
  38774. jassert (editor != 0);
  38775. const String newText (editor->getText());
  38776. if (textValue.toString() != newText)
  38777. {
  38778. lastTextValue = newText;
  38779. textValue = newText;
  38780. repaint();
  38781. textWasChanged();
  38782. if (ownerComponent != 0)
  38783. componentMovedOrResized (*ownerComponent, true, true);
  38784. return true;
  38785. }
  38786. return false;
  38787. }
  38788. void Label::hideEditor (const bool discardCurrentEditorContents)
  38789. {
  38790. if (editor != 0)
  38791. {
  38792. Component::SafePointer<Component> deletionChecker (this);
  38793. editorAboutToBeHidden (editor);
  38794. const bool changed = (! discardCurrentEditorContents)
  38795. && updateFromTextEditorContents();
  38796. editor = 0;
  38797. repaint();
  38798. if (changed)
  38799. textWasEdited();
  38800. if (deletionChecker != 0)
  38801. exitModalState (0);
  38802. if (changed && deletionChecker != 0)
  38803. callChangeListeners();
  38804. }
  38805. }
  38806. void Label::inputAttemptWhenModal()
  38807. {
  38808. if (editor != 0)
  38809. {
  38810. if (lossOfFocusDiscardsChanges)
  38811. textEditorEscapeKeyPressed (*editor);
  38812. else
  38813. textEditorReturnKeyPressed (*editor);
  38814. }
  38815. }
  38816. bool Label::isBeingEdited() const throw()
  38817. {
  38818. return editor != 0;
  38819. }
  38820. TextEditor* Label::createEditorComponent()
  38821. {
  38822. TextEditor* const ed = new TextEditor (getName());
  38823. ed->setFont (font);
  38824. // copy these colours from our own settings..
  38825. const int cols[] = { TextEditor::backgroundColourId,
  38826. TextEditor::textColourId,
  38827. TextEditor::highlightColourId,
  38828. TextEditor::highlightedTextColourId,
  38829. TextEditor::caretColourId,
  38830. TextEditor::outlineColourId,
  38831. TextEditor::focusedOutlineColourId,
  38832. TextEditor::shadowColourId };
  38833. for (int i = 0; i < numElementsInArray (cols); ++i)
  38834. ed->setColour (cols[i], findColour (cols[i]));
  38835. return ed;
  38836. }
  38837. void Label::paint (Graphics& g)
  38838. {
  38839. getLookAndFeel().drawLabel (g, *this);
  38840. }
  38841. void Label::mouseUp (const MouseEvent& e)
  38842. {
  38843. if (editSingleClick
  38844. && e.mouseWasClicked()
  38845. && contains (e.getPosition())
  38846. && ! e.mods.isPopupMenu())
  38847. {
  38848. showEditor();
  38849. }
  38850. }
  38851. void Label::mouseDoubleClick (const MouseEvent& e)
  38852. {
  38853. if (editDoubleClick && ! e.mods.isPopupMenu())
  38854. showEditor();
  38855. }
  38856. void Label::resized()
  38857. {
  38858. if (editor != 0)
  38859. editor->setBoundsInset (BorderSize (0));
  38860. }
  38861. void Label::focusGained (FocusChangeType cause)
  38862. {
  38863. if (editSingleClick && cause == focusChangedByTabKey)
  38864. showEditor();
  38865. }
  38866. void Label::enablementChanged()
  38867. {
  38868. repaint();
  38869. }
  38870. void Label::colourChanged()
  38871. {
  38872. repaint();
  38873. }
  38874. void Label::setMinimumHorizontalScale (const float newScale)
  38875. {
  38876. if (minimumHorizontalScale != newScale)
  38877. {
  38878. minimumHorizontalScale = newScale;
  38879. repaint();
  38880. }
  38881. }
  38882. // We'll use a custom focus traverser here to make sure focus goes from the
  38883. // text editor to another component rather than back to the label itself.
  38884. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38885. {
  38886. public:
  38887. LabelKeyboardFocusTraverser() {}
  38888. Component* getNextComponent (Component* current)
  38889. {
  38890. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38891. ? current->getParentComponent() : current);
  38892. }
  38893. Component* getPreviousComponent (Component* current)
  38894. {
  38895. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38896. ? current->getParentComponent() : current);
  38897. }
  38898. };
  38899. KeyboardFocusTraverser* Label::createFocusTraverser()
  38900. {
  38901. return new LabelKeyboardFocusTraverser();
  38902. }
  38903. void Label::addListener (LabelListener* const listener)
  38904. {
  38905. listeners.add (listener);
  38906. }
  38907. void Label::removeListener (LabelListener* const listener)
  38908. {
  38909. listeners.remove (listener);
  38910. }
  38911. void Label::callChangeListeners()
  38912. {
  38913. Component::BailOutChecker checker (this);
  38914. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38915. }
  38916. void Label::textEditorTextChanged (TextEditor& ed)
  38917. {
  38918. if (editor != 0)
  38919. {
  38920. jassert (&ed == editor);
  38921. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38922. {
  38923. if (lossOfFocusDiscardsChanges)
  38924. textEditorEscapeKeyPressed (ed);
  38925. else
  38926. textEditorReturnKeyPressed (ed);
  38927. }
  38928. }
  38929. }
  38930. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38931. {
  38932. if (editor != 0)
  38933. {
  38934. jassert (&ed == editor);
  38935. (void) ed;
  38936. const bool changed = updateFromTextEditorContents();
  38937. hideEditor (true);
  38938. if (changed)
  38939. {
  38940. Component::SafePointer<Component> deletionChecker (this);
  38941. textWasEdited();
  38942. if (deletionChecker != 0)
  38943. callChangeListeners();
  38944. }
  38945. }
  38946. }
  38947. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38948. {
  38949. if (editor != 0)
  38950. {
  38951. jassert (&ed == editor);
  38952. (void) ed;
  38953. editor->setText (textValue.toString(), false);
  38954. hideEditor (true);
  38955. }
  38956. }
  38957. void Label::textEditorFocusLost (TextEditor& ed)
  38958. {
  38959. textEditorTextChanged (ed);
  38960. }
  38961. END_JUCE_NAMESPACE
  38962. /*** End of inlined file: juce_Label.cpp ***/
  38963. /*** Start of inlined file: juce_ListBox.cpp ***/
  38964. BEGIN_JUCE_NAMESPACE
  38965. class ListBoxRowComponent : public Component,
  38966. public TooltipClient
  38967. {
  38968. public:
  38969. ListBoxRowComponent (ListBox& owner_)
  38970. : owner (owner_), row (-1),
  38971. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38972. {
  38973. }
  38974. void paint (Graphics& g)
  38975. {
  38976. if (owner.getModel() != 0)
  38977. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38978. }
  38979. void update (const int row_, const bool selected_)
  38980. {
  38981. if (row != row_ || selected != selected_)
  38982. {
  38983. repaint();
  38984. row = row_;
  38985. selected = selected_;
  38986. }
  38987. if (owner.getModel() != 0)
  38988. {
  38989. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  38990. if (customComponent != 0)
  38991. {
  38992. addAndMakeVisible (customComponent);
  38993. customComponent->setBounds (getLocalBounds());
  38994. }
  38995. }
  38996. }
  38997. void mouseDown (const MouseEvent& e)
  38998. {
  38999. isDragging = false;
  39000. selectRowOnMouseUp = false;
  39001. if (isEnabled())
  39002. {
  39003. if (! selected)
  39004. {
  39005. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39006. if (owner.getModel() != 0)
  39007. owner.getModel()->listBoxItemClicked (row, e);
  39008. }
  39009. else
  39010. {
  39011. selectRowOnMouseUp = true;
  39012. }
  39013. }
  39014. }
  39015. void mouseUp (const MouseEvent& e)
  39016. {
  39017. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39018. {
  39019. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39020. if (owner.getModel() != 0)
  39021. owner.getModel()->listBoxItemClicked (row, e);
  39022. }
  39023. }
  39024. void mouseDoubleClick (const MouseEvent& e)
  39025. {
  39026. if (owner.getModel() != 0 && isEnabled())
  39027. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39028. }
  39029. void mouseDrag (const MouseEvent& e)
  39030. {
  39031. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39032. {
  39033. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39034. if (selectedRows.size() > 0)
  39035. {
  39036. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39037. if (dragDescription.isNotEmpty())
  39038. {
  39039. isDragging = true;
  39040. owner.startDragAndDrop (e, dragDescription);
  39041. }
  39042. }
  39043. }
  39044. }
  39045. void resized()
  39046. {
  39047. if (customComponent != 0)
  39048. customComponent->setBounds (getLocalBounds());
  39049. }
  39050. const String getTooltip()
  39051. {
  39052. if (owner.getModel() != 0)
  39053. return owner.getModel()->getTooltipForRow (row);
  39054. return String::empty;
  39055. }
  39056. ScopedPointer<Component> customComponent;
  39057. private:
  39058. ListBox& owner;
  39059. int row;
  39060. bool selected, isDragging, selectRowOnMouseUp;
  39061. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  39062. };
  39063. class ListViewport : public Viewport
  39064. {
  39065. public:
  39066. ListViewport (ListBox& owner_)
  39067. : owner (owner_)
  39068. {
  39069. setWantsKeyboardFocus (false);
  39070. Component* const content = new Component();
  39071. setViewedComponent (content);
  39072. content->addMouseListener (this, false);
  39073. content->setWantsKeyboardFocus (false);
  39074. }
  39075. ~ListViewport()
  39076. {
  39077. }
  39078. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39079. {
  39080. return rows [row % jmax (1, rows.size())];
  39081. }
  39082. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  39083. {
  39084. return (row >= firstIndex && row < firstIndex + rows.size())
  39085. ? getComponentForRow (row) : 0;
  39086. }
  39087. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39088. {
  39089. const int index = getIndexOfChildComponent (rowComponent);
  39090. const int num = rows.size();
  39091. for (int i = num; --i >= 0;)
  39092. if (((firstIndex + i) % jmax (1, num)) == index)
  39093. return firstIndex + i;
  39094. return -1;
  39095. }
  39096. void visibleAreaChanged (int, int, int, int)
  39097. {
  39098. updateVisibleArea (true);
  39099. if (owner.getModel() != 0)
  39100. owner.getModel()->listWasScrolled();
  39101. }
  39102. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39103. {
  39104. hasUpdated = false;
  39105. const int newX = getViewedComponent()->getX();
  39106. int newY = getViewedComponent()->getY();
  39107. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39108. const int newH = owner.totalItems * owner.getRowHeight();
  39109. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39110. newY = getMaximumVisibleHeight() - newH;
  39111. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39112. if (makeSureItUpdatesContent && ! hasUpdated)
  39113. updateContents();
  39114. }
  39115. void updateContents()
  39116. {
  39117. hasUpdated = true;
  39118. const int rowHeight = owner.getRowHeight();
  39119. if (rowHeight > 0)
  39120. {
  39121. const int y = getViewPositionY();
  39122. const int w = getViewedComponent()->getWidth();
  39123. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39124. rows.removeRange (numNeeded, rows.size());
  39125. while (numNeeded > rows.size())
  39126. {
  39127. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  39128. rows.add (newRow);
  39129. getViewedComponent()->addAndMakeVisible (newRow);
  39130. }
  39131. firstIndex = y / rowHeight;
  39132. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39133. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39134. for (int i = 0; i < numNeeded; ++i)
  39135. {
  39136. const int row = i + firstIndex;
  39137. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39138. if (rowComp != 0)
  39139. {
  39140. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39141. rowComp->update (row, owner.isRowSelected (row));
  39142. }
  39143. }
  39144. }
  39145. if (owner.headerComponent != 0)
  39146. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39147. owner.outlineThickness,
  39148. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39149. getViewedComponent()->getWidth()),
  39150. owner.headerComponent->getHeight());
  39151. }
  39152. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  39153. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  39154. {
  39155. hasUpdated = false;
  39156. if (row < firstWholeIndex && ! dontScroll)
  39157. {
  39158. setViewPosition (getViewPositionX(), row * rowHeight);
  39159. }
  39160. else if (row >= lastWholeIndex && ! dontScroll)
  39161. {
  39162. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  39163. if (row >= lastRowSelected + rowsOnScreen
  39164. && rowsOnScreen < totalItems - 1
  39165. && ! isMouseClick)
  39166. {
  39167. setViewPosition (getViewPositionX(),
  39168. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  39169. }
  39170. else
  39171. {
  39172. setViewPosition (getViewPositionX(),
  39173. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39174. }
  39175. }
  39176. if (! hasUpdated)
  39177. updateContents();
  39178. }
  39179. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  39180. {
  39181. if (row < firstWholeIndex)
  39182. {
  39183. setViewPosition (getViewPositionX(), row * rowHeight);
  39184. }
  39185. else if (row >= lastWholeIndex)
  39186. {
  39187. setViewPosition (getViewPositionX(),
  39188. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39189. }
  39190. }
  39191. void paint (Graphics& g)
  39192. {
  39193. if (isOpaque())
  39194. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39195. }
  39196. bool keyPressed (const KeyPress& key)
  39197. {
  39198. if (key.isKeyCode (KeyPress::upKey)
  39199. || key.isKeyCode (KeyPress::downKey)
  39200. || key.isKeyCode (KeyPress::pageUpKey)
  39201. || key.isKeyCode (KeyPress::pageDownKey)
  39202. || key.isKeyCode (KeyPress::homeKey)
  39203. || key.isKeyCode (KeyPress::endKey))
  39204. {
  39205. // we want to avoid these keypresses going to the viewport, and instead allow
  39206. // them to pass up to our listbox..
  39207. return false;
  39208. }
  39209. return Viewport::keyPressed (key);
  39210. }
  39211. private:
  39212. ListBox& owner;
  39213. OwnedArray<ListBoxRowComponent> rows;
  39214. int firstIndex, firstWholeIndex, lastWholeIndex;
  39215. bool hasUpdated;
  39216. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  39217. };
  39218. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39219. : Component (name),
  39220. model (model_),
  39221. totalItems (0),
  39222. rowHeight (22),
  39223. minimumRowWidth (0),
  39224. outlineThickness (0),
  39225. lastRowSelected (-1),
  39226. mouseMoveSelects (false),
  39227. multipleSelection (false),
  39228. hasDoneInitialUpdate (false)
  39229. {
  39230. addAndMakeVisible (viewport = new ListViewport (*this));
  39231. setWantsKeyboardFocus (true);
  39232. colourChanged();
  39233. }
  39234. ListBox::~ListBox()
  39235. {
  39236. headerComponent = 0;
  39237. viewport = 0;
  39238. }
  39239. void ListBox::setModel (ListBoxModel* const newModel)
  39240. {
  39241. if (model != newModel)
  39242. {
  39243. model = newModel;
  39244. repaint();
  39245. updateContent();
  39246. }
  39247. }
  39248. void ListBox::setMultipleSelectionEnabled (bool b)
  39249. {
  39250. multipleSelection = b;
  39251. }
  39252. void ListBox::setMouseMoveSelectsRows (bool b)
  39253. {
  39254. mouseMoveSelects = b;
  39255. if (b)
  39256. addMouseListener (this, true);
  39257. }
  39258. void ListBox::paint (Graphics& g)
  39259. {
  39260. if (! hasDoneInitialUpdate)
  39261. updateContent();
  39262. g.fillAll (findColour (backgroundColourId));
  39263. }
  39264. void ListBox::paintOverChildren (Graphics& g)
  39265. {
  39266. if (outlineThickness > 0)
  39267. {
  39268. g.setColour (findColour (outlineColourId));
  39269. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39270. }
  39271. }
  39272. void ListBox::resized()
  39273. {
  39274. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39275. outlineThickness,
  39276. outlineThickness,
  39277. outlineThickness));
  39278. viewport->setSingleStepSizes (20, getRowHeight());
  39279. viewport->updateVisibleArea (false);
  39280. }
  39281. void ListBox::visibilityChanged()
  39282. {
  39283. viewport->updateVisibleArea (true);
  39284. }
  39285. Viewport* ListBox::getViewport() const throw()
  39286. {
  39287. return viewport;
  39288. }
  39289. void ListBox::updateContent()
  39290. {
  39291. hasDoneInitialUpdate = true;
  39292. totalItems = (model != 0) ? model->getNumRows() : 0;
  39293. bool selectionChanged = false;
  39294. if (selected [selected.size() - 1] >= totalItems)
  39295. {
  39296. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39297. lastRowSelected = getSelectedRow (0);
  39298. selectionChanged = true;
  39299. }
  39300. viewport->updateVisibleArea (isVisible());
  39301. viewport->resized();
  39302. if (selectionChanged && model != 0)
  39303. model->selectedRowsChanged (lastRowSelected);
  39304. }
  39305. void ListBox::selectRow (const int row,
  39306. bool dontScroll,
  39307. bool deselectOthersFirst)
  39308. {
  39309. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39310. }
  39311. void ListBox::selectRowInternal (const int row,
  39312. bool dontScroll,
  39313. bool deselectOthersFirst,
  39314. bool isMouseClick)
  39315. {
  39316. if (! multipleSelection)
  39317. deselectOthersFirst = true;
  39318. if ((! isRowSelected (row))
  39319. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39320. {
  39321. if (((unsigned int) row) < (unsigned int) totalItems)
  39322. {
  39323. if (deselectOthersFirst)
  39324. selected.clear();
  39325. selected.addRange (Range<int> (row, row + 1));
  39326. if (getHeight() == 0 || getWidth() == 0)
  39327. dontScroll = true;
  39328. viewport->selectRow (row, getRowHeight(), dontScroll,
  39329. lastRowSelected, totalItems, isMouseClick);
  39330. lastRowSelected = row;
  39331. model->selectedRowsChanged (row);
  39332. }
  39333. else
  39334. {
  39335. if (deselectOthersFirst)
  39336. deselectAllRows();
  39337. }
  39338. }
  39339. }
  39340. void ListBox::deselectRow (const int row)
  39341. {
  39342. if (selected.contains (row))
  39343. {
  39344. selected.removeRange (Range <int> (row, row + 1));
  39345. if (row == lastRowSelected)
  39346. lastRowSelected = getSelectedRow (0);
  39347. viewport->updateContents();
  39348. model->selectedRowsChanged (lastRowSelected);
  39349. }
  39350. }
  39351. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39352. const bool sendNotificationEventToModel)
  39353. {
  39354. selected = setOfRowsToBeSelected;
  39355. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39356. if (! isRowSelected (lastRowSelected))
  39357. lastRowSelected = getSelectedRow (0);
  39358. viewport->updateContents();
  39359. if ((model != 0) && sendNotificationEventToModel)
  39360. model->selectedRowsChanged (lastRowSelected);
  39361. }
  39362. const SparseSet<int> ListBox::getSelectedRows() const
  39363. {
  39364. return selected;
  39365. }
  39366. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39367. {
  39368. if (multipleSelection && (firstRow != lastRow))
  39369. {
  39370. const int numRows = totalItems - 1;
  39371. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39372. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39373. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39374. jmax (firstRow, lastRow) + 1));
  39375. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39376. }
  39377. selectRowInternal (lastRow, false, false, true);
  39378. }
  39379. void ListBox::flipRowSelection (const int row)
  39380. {
  39381. if (isRowSelected (row))
  39382. deselectRow (row);
  39383. else
  39384. selectRowInternal (row, false, false, true);
  39385. }
  39386. void ListBox::deselectAllRows()
  39387. {
  39388. if (! selected.isEmpty())
  39389. {
  39390. selected.clear();
  39391. lastRowSelected = -1;
  39392. viewport->updateContents();
  39393. if (model != 0)
  39394. model->selectedRowsChanged (lastRowSelected);
  39395. }
  39396. }
  39397. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39398. const ModifierKeys& mods)
  39399. {
  39400. if (multipleSelection && mods.isCommandDown())
  39401. {
  39402. flipRowSelection (row);
  39403. }
  39404. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39405. {
  39406. selectRangeOfRows (lastRowSelected, row);
  39407. }
  39408. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39409. {
  39410. selectRowInternal (row, false, true, true);
  39411. }
  39412. }
  39413. int ListBox::getNumSelectedRows() const
  39414. {
  39415. return selected.size();
  39416. }
  39417. int ListBox::getSelectedRow (const int index) const
  39418. {
  39419. return (((unsigned int) index) < (unsigned int) selected.size())
  39420. ? selected [index] : -1;
  39421. }
  39422. bool ListBox::isRowSelected (const int row) const
  39423. {
  39424. return selected.contains (row);
  39425. }
  39426. int ListBox::getLastRowSelected() const
  39427. {
  39428. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39429. }
  39430. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39431. {
  39432. if (((unsigned int) x) < (unsigned int) getWidth())
  39433. {
  39434. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39435. if (((unsigned int) row) < (unsigned int) totalItems)
  39436. return row;
  39437. }
  39438. return -1;
  39439. }
  39440. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39441. {
  39442. if (((unsigned int) x) < (unsigned int) getWidth())
  39443. {
  39444. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39445. return jlimit (0, totalItems, row);
  39446. }
  39447. return -1;
  39448. }
  39449. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39450. {
  39451. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39452. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39453. }
  39454. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39455. {
  39456. return viewport->getRowNumberOfComponent (rowComponent);
  39457. }
  39458. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39459. const bool relativeToComponentTopLeft) const throw()
  39460. {
  39461. int y = viewport->getY() + rowHeight * rowNumber;
  39462. if (relativeToComponentTopLeft)
  39463. y -= viewport->getViewPositionY();
  39464. return Rectangle<int> (viewport->getX(), y,
  39465. viewport->getViewedComponent()->getWidth(), rowHeight);
  39466. }
  39467. void ListBox::setVerticalPosition (const double proportion)
  39468. {
  39469. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39470. viewport->setViewPosition (viewport->getViewPositionX(),
  39471. jmax (0, roundToInt (proportion * offscreen)));
  39472. }
  39473. double ListBox::getVerticalPosition() const
  39474. {
  39475. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39476. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39477. : 0;
  39478. }
  39479. int ListBox::getVisibleRowWidth() const throw()
  39480. {
  39481. return viewport->getViewWidth();
  39482. }
  39483. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39484. {
  39485. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39486. }
  39487. bool ListBox::keyPressed (const KeyPress& key)
  39488. {
  39489. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39490. const bool multiple = multipleSelection
  39491. && (lastRowSelected >= 0)
  39492. && (key.getModifiers().isShiftDown()
  39493. || key.getModifiers().isCtrlDown()
  39494. || key.getModifiers().isCommandDown());
  39495. if (key.isKeyCode (KeyPress::upKey))
  39496. {
  39497. if (multiple)
  39498. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39499. else
  39500. selectRow (jmax (0, lastRowSelected - 1));
  39501. }
  39502. else if (key.isKeyCode (KeyPress::returnKey)
  39503. && isRowSelected (lastRowSelected))
  39504. {
  39505. if (model != 0)
  39506. model->returnKeyPressed (lastRowSelected);
  39507. }
  39508. else if (key.isKeyCode (KeyPress::pageUpKey))
  39509. {
  39510. if (multiple)
  39511. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39512. else
  39513. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39514. }
  39515. else if (key.isKeyCode (KeyPress::pageDownKey))
  39516. {
  39517. if (multiple)
  39518. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39519. else
  39520. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39521. }
  39522. else if (key.isKeyCode (KeyPress::homeKey))
  39523. {
  39524. if (multiple && key.getModifiers().isShiftDown())
  39525. selectRangeOfRows (lastRowSelected, 0);
  39526. else
  39527. selectRow (0);
  39528. }
  39529. else if (key.isKeyCode (KeyPress::endKey))
  39530. {
  39531. if (multiple && key.getModifiers().isShiftDown())
  39532. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39533. else
  39534. selectRow (totalItems - 1);
  39535. }
  39536. else if (key.isKeyCode (KeyPress::downKey))
  39537. {
  39538. if (multiple)
  39539. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39540. else
  39541. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39542. }
  39543. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39544. && isRowSelected (lastRowSelected))
  39545. {
  39546. if (model != 0)
  39547. model->deleteKeyPressed (lastRowSelected);
  39548. }
  39549. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39550. {
  39551. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39552. }
  39553. else
  39554. {
  39555. return false;
  39556. }
  39557. return true;
  39558. }
  39559. bool ListBox::keyStateChanged (const bool isKeyDown)
  39560. {
  39561. return isKeyDown
  39562. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39563. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39564. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39565. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39566. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39567. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39568. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39569. }
  39570. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39571. {
  39572. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39573. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39574. }
  39575. void ListBox::mouseMove (const MouseEvent& e)
  39576. {
  39577. if (mouseMoveSelects)
  39578. {
  39579. const MouseEvent e2 (e.getEventRelativeTo (this));
  39580. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39581. }
  39582. }
  39583. void ListBox::mouseExit (const MouseEvent& e)
  39584. {
  39585. mouseMove (e);
  39586. }
  39587. void ListBox::mouseUp (const MouseEvent& e)
  39588. {
  39589. if (e.mouseWasClicked() && model != 0)
  39590. model->backgroundClicked();
  39591. }
  39592. void ListBox::setRowHeight (const int newHeight)
  39593. {
  39594. rowHeight = jmax (1, newHeight);
  39595. viewport->setSingleStepSizes (20, rowHeight);
  39596. updateContent();
  39597. }
  39598. int ListBox::getNumRowsOnScreen() const throw()
  39599. {
  39600. return viewport->getMaximumVisibleHeight() / rowHeight;
  39601. }
  39602. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39603. {
  39604. minimumRowWidth = newMinimumWidth;
  39605. updateContent();
  39606. }
  39607. int ListBox::getVisibleContentWidth() const throw()
  39608. {
  39609. return viewport->getMaximumVisibleWidth();
  39610. }
  39611. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39612. {
  39613. return viewport->getVerticalScrollBar();
  39614. }
  39615. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39616. {
  39617. return viewport->getHorizontalScrollBar();
  39618. }
  39619. void ListBox::colourChanged()
  39620. {
  39621. setOpaque (findColour (backgroundColourId).isOpaque());
  39622. viewport->setOpaque (isOpaque());
  39623. repaint();
  39624. }
  39625. void ListBox::setOutlineThickness (const int outlineThickness_)
  39626. {
  39627. outlineThickness = outlineThickness_;
  39628. resized();
  39629. }
  39630. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39631. {
  39632. if (headerComponent != newHeaderComponent)
  39633. {
  39634. headerComponent = newHeaderComponent;
  39635. addAndMakeVisible (newHeaderComponent);
  39636. ListBox::resized();
  39637. }
  39638. }
  39639. void ListBox::repaintRow (const int rowNumber) throw()
  39640. {
  39641. repaint (getRowPosition (rowNumber, true));
  39642. }
  39643. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39644. {
  39645. Rectangle<int> imageArea;
  39646. const int firstRow = getRowContainingPosition (0, 0);
  39647. int i;
  39648. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39649. {
  39650. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39651. if (rowComp != 0 && isRowSelected (firstRow + i))
  39652. {
  39653. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39654. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39655. imageArea = imageArea.getUnion (rowRect);
  39656. }
  39657. }
  39658. imageArea = imageArea.getIntersection (getLocalBounds());
  39659. imageX = imageArea.getX();
  39660. imageY = imageArea.getY();
  39661. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39662. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39663. {
  39664. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39665. if (rowComp != 0 && isRowSelected (firstRow + i))
  39666. {
  39667. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39668. Graphics g (snapshot);
  39669. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39670. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39671. rowComp->paintEntireComponent (g, false);
  39672. }
  39673. }
  39674. return snapshot;
  39675. }
  39676. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39677. {
  39678. DragAndDropContainer* const dragContainer
  39679. = DragAndDropContainer::findParentDragContainerFor (this);
  39680. if (dragContainer != 0)
  39681. {
  39682. int x, y;
  39683. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39684. dragImage.multiplyAllAlphas (0.6f);
  39685. MouseEvent e2 (e.getEventRelativeTo (this));
  39686. const Point<int> p (x - e2.x, y - e2.y);
  39687. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39688. }
  39689. else
  39690. {
  39691. // to be able to do a drag-and-drop operation, the listbox needs to
  39692. // be inside a component which is also a DragAndDropContainer.
  39693. jassertfalse;
  39694. }
  39695. }
  39696. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39697. {
  39698. (void) existingComponentToUpdate;
  39699. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39700. return 0;
  39701. }
  39702. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39703. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39704. void ListBoxModel::backgroundClicked() {}
  39705. void ListBoxModel::selectedRowsChanged (int) {}
  39706. void ListBoxModel::deleteKeyPressed (int) {}
  39707. void ListBoxModel::returnKeyPressed (int) {}
  39708. void ListBoxModel::listWasScrolled() {}
  39709. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39710. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39711. END_JUCE_NAMESPACE
  39712. /*** End of inlined file: juce_ListBox.cpp ***/
  39713. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39714. BEGIN_JUCE_NAMESPACE
  39715. ProgressBar::ProgressBar (double& progress_)
  39716. : progress (progress_),
  39717. displayPercentage (true),
  39718. lastCallbackTime (0)
  39719. {
  39720. currentValue = jlimit (0.0, 1.0, progress);
  39721. }
  39722. ProgressBar::~ProgressBar()
  39723. {
  39724. }
  39725. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39726. {
  39727. displayPercentage = shouldDisplayPercentage;
  39728. repaint();
  39729. }
  39730. void ProgressBar::setTextToDisplay (const String& text)
  39731. {
  39732. displayPercentage = false;
  39733. displayedMessage = text;
  39734. }
  39735. void ProgressBar::lookAndFeelChanged()
  39736. {
  39737. setOpaque (findColour (backgroundColourId).isOpaque());
  39738. }
  39739. void ProgressBar::colourChanged()
  39740. {
  39741. lookAndFeelChanged();
  39742. }
  39743. void ProgressBar::paint (Graphics& g)
  39744. {
  39745. String text;
  39746. if (displayPercentage)
  39747. {
  39748. if (currentValue >= 0 && currentValue <= 1.0)
  39749. text << roundToInt (currentValue * 100.0) << '%';
  39750. }
  39751. else
  39752. {
  39753. text = displayedMessage;
  39754. }
  39755. getLookAndFeel().drawProgressBar (g, *this,
  39756. getWidth(), getHeight(),
  39757. currentValue, text);
  39758. }
  39759. void ProgressBar::visibilityChanged()
  39760. {
  39761. if (isVisible())
  39762. startTimer (30);
  39763. else
  39764. stopTimer();
  39765. }
  39766. void ProgressBar::timerCallback()
  39767. {
  39768. double newProgress = progress;
  39769. const uint32 now = Time::getMillisecondCounter();
  39770. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39771. lastCallbackTime = now;
  39772. if (currentValue != newProgress
  39773. || newProgress < 0 || newProgress >= 1.0
  39774. || currentMessage != displayedMessage)
  39775. {
  39776. if (currentValue < newProgress
  39777. && newProgress >= 0 && newProgress < 1.0
  39778. && currentValue >= 0 && currentValue < 1.0)
  39779. {
  39780. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39781. newProgress);
  39782. }
  39783. currentValue = newProgress;
  39784. currentMessage = displayedMessage;
  39785. repaint();
  39786. }
  39787. }
  39788. END_JUCE_NAMESPACE
  39789. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39790. /*** Start of inlined file: juce_Slider.cpp ***/
  39791. BEGIN_JUCE_NAMESPACE
  39792. class SliderPopupDisplayComponent : public BubbleComponent
  39793. {
  39794. public:
  39795. SliderPopupDisplayComponent (Slider* const owner_)
  39796. : owner (owner_),
  39797. font (15.0f, Font::bold)
  39798. {
  39799. setAlwaysOnTop (true);
  39800. }
  39801. ~SliderPopupDisplayComponent()
  39802. {
  39803. }
  39804. void paintContent (Graphics& g, int w, int h)
  39805. {
  39806. g.setFont (font);
  39807. g.setColour (Colours::black);
  39808. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39809. }
  39810. void getContentSize (int& w, int& h)
  39811. {
  39812. w = font.getStringWidth (text) + 18;
  39813. h = (int) (font.getHeight() * 1.6f);
  39814. }
  39815. void updatePosition (const String& newText)
  39816. {
  39817. if (text != newText)
  39818. {
  39819. text = newText;
  39820. repaint();
  39821. }
  39822. BubbleComponent::setPosition (owner);
  39823. }
  39824. private:
  39825. Slider* owner;
  39826. Font font;
  39827. String text;
  39828. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39829. };
  39830. Slider::Slider (const String& name)
  39831. : Component (name),
  39832. lastCurrentValue (0),
  39833. lastValueMin (0),
  39834. lastValueMax (0),
  39835. minimum (0),
  39836. maximum (10),
  39837. interval (0),
  39838. skewFactor (1.0),
  39839. velocityModeSensitivity (1.0),
  39840. velocityModeOffset (0.0),
  39841. velocityModeThreshold (1),
  39842. rotaryStart (float_Pi * 1.2f),
  39843. rotaryEnd (float_Pi * 2.8f),
  39844. numDecimalPlaces (7),
  39845. sliderRegionStart (0),
  39846. sliderRegionSize (1),
  39847. sliderBeingDragged (-1),
  39848. pixelsForFullDragExtent (250),
  39849. style (LinearHorizontal),
  39850. textBoxPos (TextBoxLeft),
  39851. textBoxWidth (80),
  39852. textBoxHeight (20),
  39853. incDecButtonMode (incDecButtonsNotDraggable),
  39854. editableText (true),
  39855. doubleClickToValue (false),
  39856. isVelocityBased (false),
  39857. userKeyOverridesVelocity (true),
  39858. rotaryStop (true),
  39859. incDecButtonsSideBySide (false),
  39860. sendChangeOnlyOnRelease (false),
  39861. popupDisplayEnabled (false),
  39862. menuEnabled (false),
  39863. menuShown (false),
  39864. scrollWheelEnabled (true),
  39865. snapsToMousePos (true),
  39866. popupDisplay (0),
  39867. parentForPopupDisplay (0)
  39868. {
  39869. setWantsKeyboardFocus (false);
  39870. setRepaintsOnMouseActivity (true);
  39871. lookAndFeelChanged();
  39872. updateText();
  39873. currentValue.addListener (this);
  39874. valueMin.addListener (this);
  39875. valueMax.addListener (this);
  39876. }
  39877. Slider::~Slider()
  39878. {
  39879. currentValue.removeListener (this);
  39880. valueMin.removeListener (this);
  39881. valueMax.removeListener (this);
  39882. popupDisplay = 0;
  39883. }
  39884. void Slider::handleAsyncUpdate()
  39885. {
  39886. cancelPendingUpdate();
  39887. Component::BailOutChecker checker (this);
  39888. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39889. }
  39890. void Slider::sendDragStart()
  39891. {
  39892. startedDragging();
  39893. Component::BailOutChecker checker (this);
  39894. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39895. }
  39896. void Slider::sendDragEnd()
  39897. {
  39898. stoppedDragging();
  39899. sliderBeingDragged = -1;
  39900. Component::BailOutChecker checker (this);
  39901. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39902. }
  39903. void Slider::addListener (SliderListener* const listener)
  39904. {
  39905. listeners.add (listener);
  39906. }
  39907. void Slider::removeListener (SliderListener* const listener)
  39908. {
  39909. listeners.remove (listener);
  39910. }
  39911. void Slider::setSliderStyle (const SliderStyle newStyle)
  39912. {
  39913. if (style != newStyle)
  39914. {
  39915. style = newStyle;
  39916. repaint();
  39917. lookAndFeelChanged();
  39918. }
  39919. }
  39920. void Slider::setRotaryParameters (const float startAngleRadians,
  39921. const float endAngleRadians,
  39922. const bool stopAtEnd)
  39923. {
  39924. // make sure the values are sensible..
  39925. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39926. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39927. jassert (rotaryStart < rotaryEnd);
  39928. rotaryStart = startAngleRadians;
  39929. rotaryEnd = endAngleRadians;
  39930. rotaryStop = stopAtEnd;
  39931. }
  39932. void Slider::setVelocityBasedMode (const bool velBased)
  39933. {
  39934. isVelocityBased = velBased;
  39935. }
  39936. void Slider::setVelocityModeParameters (const double sensitivity,
  39937. const int threshold,
  39938. const double offset,
  39939. const bool userCanPressKeyToSwapMode)
  39940. {
  39941. jassert (threshold >= 0);
  39942. jassert (sensitivity > 0);
  39943. jassert (offset >= 0);
  39944. velocityModeSensitivity = sensitivity;
  39945. velocityModeOffset = offset;
  39946. velocityModeThreshold = threshold;
  39947. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39948. }
  39949. void Slider::setSkewFactor (const double factor)
  39950. {
  39951. skewFactor = factor;
  39952. }
  39953. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39954. {
  39955. if (maximum > minimum)
  39956. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39957. / (maximum - minimum));
  39958. }
  39959. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39960. {
  39961. jassert (distanceForFullScaleDrag > 0);
  39962. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39963. }
  39964. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39965. {
  39966. if (incDecButtonMode != mode)
  39967. {
  39968. incDecButtonMode = mode;
  39969. lookAndFeelChanged();
  39970. }
  39971. }
  39972. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39973. const bool isReadOnly,
  39974. const int textEntryBoxWidth,
  39975. const int textEntryBoxHeight)
  39976. {
  39977. if (textBoxPos != newPosition
  39978. || editableText != (! isReadOnly)
  39979. || textBoxWidth != textEntryBoxWidth
  39980. || textBoxHeight != textEntryBoxHeight)
  39981. {
  39982. textBoxPos = newPosition;
  39983. editableText = ! isReadOnly;
  39984. textBoxWidth = textEntryBoxWidth;
  39985. textBoxHeight = textEntryBoxHeight;
  39986. repaint();
  39987. lookAndFeelChanged();
  39988. }
  39989. }
  39990. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39991. {
  39992. editableText = shouldBeEditable;
  39993. if (valueBox != 0)
  39994. valueBox->setEditable (shouldBeEditable && isEnabled());
  39995. }
  39996. void Slider::showTextBox()
  39997. {
  39998. jassert (editableText); // this should probably be avoided in read-only sliders.
  39999. if (valueBox != 0)
  40000. valueBox->showEditor();
  40001. }
  40002. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40003. {
  40004. if (valueBox != 0)
  40005. {
  40006. valueBox->hideEditor (discardCurrentEditorContents);
  40007. if (discardCurrentEditorContents)
  40008. updateText();
  40009. }
  40010. }
  40011. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40012. {
  40013. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40014. }
  40015. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40016. {
  40017. snapsToMousePos = shouldSnapToMouse;
  40018. }
  40019. void Slider::setPopupDisplayEnabled (const bool enabled,
  40020. Component* const parentComponentToUse)
  40021. {
  40022. popupDisplayEnabled = enabled;
  40023. parentForPopupDisplay = parentComponentToUse;
  40024. }
  40025. void Slider::colourChanged()
  40026. {
  40027. lookAndFeelChanged();
  40028. }
  40029. void Slider::lookAndFeelChanged()
  40030. {
  40031. LookAndFeel& lf = getLookAndFeel();
  40032. if (textBoxPos != NoTextBox)
  40033. {
  40034. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40035. : getTextFromValue (currentValue.getValue()));
  40036. valueBox = 0;
  40037. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40038. valueBox->setWantsKeyboardFocus (false);
  40039. valueBox->setText (previousTextBoxContent, false);
  40040. valueBox->setEditable (editableText && isEnabled());
  40041. valueBox->addListener (this);
  40042. if (style == LinearBar)
  40043. valueBox->addMouseListener (this, false);
  40044. valueBox->setTooltip (getTooltip());
  40045. }
  40046. else
  40047. {
  40048. valueBox = 0;
  40049. }
  40050. if (style == IncDecButtons)
  40051. {
  40052. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40053. incButton->addButtonListener (this);
  40054. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40055. decButton->addButtonListener (this);
  40056. if (incDecButtonMode != incDecButtonsNotDraggable)
  40057. {
  40058. incButton->addMouseListener (this, false);
  40059. decButton->addMouseListener (this, false);
  40060. }
  40061. else
  40062. {
  40063. incButton->setRepeatSpeed (300, 100, 20);
  40064. incButton->addMouseListener (decButton, false);
  40065. decButton->setRepeatSpeed (300, 100, 20);
  40066. decButton->addMouseListener (incButton, false);
  40067. }
  40068. incButton->setTooltip (getTooltip());
  40069. decButton->setTooltip (getTooltip());
  40070. }
  40071. else
  40072. {
  40073. incButton = 0;
  40074. decButton = 0;
  40075. }
  40076. setComponentEffect (lf.getSliderEffect());
  40077. resized();
  40078. repaint();
  40079. }
  40080. void Slider::setRange (const double newMin,
  40081. const double newMax,
  40082. const double newInt)
  40083. {
  40084. if (minimum != newMin
  40085. || maximum != newMax
  40086. || interval != newInt)
  40087. {
  40088. minimum = newMin;
  40089. maximum = newMax;
  40090. interval = newInt;
  40091. // figure out the number of DPs needed to display all values at this
  40092. // interval setting.
  40093. numDecimalPlaces = 7;
  40094. if (newInt != 0)
  40095. {
  40096. int v = abs ((int) (newInt * 10000000));
  40097. while ((v % 10) == 0)
  40098. {
  40099. --numDecimalPlaces;
  40100. v /= 10;
  40101. }
  40102. }
  40103. // keep the current values inside the new range..
  40104. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40105. {
  40106. setValue (getValue(), false, false);
  40107. }
  40108. else
  40109. {
  40110. setMinValue (getMinValue(), false, false);
  40111. setMaxValue (getMaxValue(), false, false);
  40112. }
  40113. updateText();
  40114. }
  40115. }
  40116. void Slider::triggerChangeMessage (const bool synchronous)
  40117. {
  40118. if (synchronous)
  40119. handleAsyncUpdate();
  40120. else
  40121. triggerAsyncUpdate();
  40122. valueChanged();
  40123. }
  40124. void Slider::valueChanged (Value& value)
  40125. {
  40126. if (value.refersToSameSourceAs (currentValue))
  40127. {
  40128. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40129. setValue (currentValue.getValue(), false, false);
  40130. }
  40131. else if (value.refersToSameSourceAs (valueMin))
  40132. setMinValue (valueMin.getValue(), false, false, true);
  40133. else if (value.refersToSameSourceAs (valueMax))
  40134. setMaxValue (valueMax.getValue(), false, false, true);
  40135. }
  40136. double Slider::getValue() const
  40137. {
  40138. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40139. // methods to get the two values.
  40140. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40141. return currentValue.getValue();
  40142. }
  40143. void Slider::setValue (double newValue,
  40144. const bool sendUpdateMessage,
  40145. const bool sendMessageSynchronously)
  40146. {
  40147. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40148. // methods to set the two values.
  40149. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40150. newValue = constrainedValue (newValue);
  40151. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40152. {
  40153. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40154. newValue = jlimit ((double) valueMin.getValue(),
  40155. (double) valueMax.getValue(),
  40156. newValue);
  40157. }
  40158. if (newValue != lastCurrentValue)
  40159. {
  40160. if (valueBox != 0)
  40161. valueBox->hideEditor (true);
  40162. lastCurrentValue = newValue;
  40163. currentValue = newValue;
  40164. updateText();
  40165. repaint();
  40166. if (popupDisplay != 0)
  40167. {
  40168. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40169. ->updatePosition (getTextFromValue (newValue));
  40170. popupDisplay->repaint();
  40171. }
  40172. if (sendUpdateMessage)
  40173. triggerChangeMessage (sendMessageSynchronously);
  40174. }
  40175. }
  40176. double Slider::getMinValue() const
  40177. {
  40178. // The minimum value only applies to sliders that are in two- or three-value mode.
  40179. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40180. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40181. return valueMin.getValue();
  40182. }
  40183. double Slider::getMaxValue() const
  40184. {
  40185. // The maximum value only applies to sliders that are in two- or three-value mode.
  40186. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40187. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40188. return valueMax.getValue();
  40189. }
  40190. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40191. {
  40192. // The minimum value only applies to sliders that are in two- or three-value mode.
  40193. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40194. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40195. newValue = constrainedValue (newValue);
  40196. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40197. {
  40198. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40199. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40200. newValue = jmin ((double) valueMax.getValue(), newValue);
  40201. }
  40202. else
  40203. {
  40204. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40205. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40206. newValue = jmin (lastCurrentValue, newValue);
  40207. }
  40208. if (lastValueMin != newValue)
  40209. {
  40210. lastValueMin = newValue;
  40211. valueMin = newValue;
  40212. repaint();
  40213. if (popupDisplay != 0)
  40214. {
  40215. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40216. ->updatePosition (getTextFromValue (newValue));
  40217. popupDisplay->repaint();
  40218. }
  40219. if (sendUpdateMessage)
  40220. triggerChangeMessage (sendMessageSynchronously);
  40221. }
  40222. }
  40223. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40224. {
  40225. // The maximum value only applies to sliders that are in two- or three-value mode.
  40226. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40227. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40228. newValue = constrainedValue (newValue);
  40229. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40230. {
  40231. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40232. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40233. newValue = jmax ((double) valueMin.getValue(), newValue);
  40234. }
  40235. else
  40236. {
  40237. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40238. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40239. newValue = jmax (lastCurrentValue, newValue);
  40240. }
  40241. if (lastValueMax != newValue)
  40242. {
  40243. lastValueMax = newValue;
  40244. valueMax = newValue;
  40245. repaint();
  40246. if (popupDisplay != 0)
  40247. {
  40248. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40249. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40250. popupDisplay->repaint();
  40251. }
  40252. if (sendUpdateMessage)
  40253. triggerChangeMessage (sendMessageSynchronously);
  40254. }
  40255. }
  40256. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40257. const double valueToSetOnDoubleClick)
  40258. {
  40259. doubleClickToValue = isDoubleClickEnabled;
  40260. doubleClickReturnValue = valueToSetOnDoubleClick;
  40261. }
  40262. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40263. {
  40264. isEnabled_ = doubleClickToValue;
  40265. return doubleClickReturnValue;
  40266. }
  40267. void Slider::updateText()
  40268. {
  40269. if (valueBox != 0)
  40270. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40271. }
  40272. void Slider::setTextValueSuffix (const String& suffix)
  40273. {
  40274. if (textSuffix != suffix)
  40275. {
  40276. textSuffix = suffix;
  40277. updateText();
  40278. }
  40279. }
  40280. const String Slider::getTextValueSuffix() const
  40281. {
  40282. return textSuffix;
  40283. }
  40284. const String Slider::getTextFromValue (double v)
  40285. {
  40286. if (getNumDecimalPlacesToDisplay() > 0)
  40287. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40288. else
  40289. return String (roundToInt (v)) + getTextValueSuffix();
  40290. }
  40291. double Slider::getValueFromText (const String& text)
  40292. {
  40293. String t (text.trimStart());
  40294. if (t.endsWith (textSuffix))
  40295. t = t.substring (0, t.length() - textSuffix.length());
  40296. while (t.startsWithChar ('+'))
  40297. t = t.substring (1).trimStart();
  40298. return t.initialSectionContainingOnly ("0123456789.,-")
  40299. .getDoubleValue();
  40300. }
  40301. double Slider::proportionOfLengthToValue (double proportion)
  40302. {
  40303. if (skewFactor != 1.0 && proportion > 0.0)
  40304. proportion = exp (log (proportion) / skewFactor);
  40305. return minimum + (maximum - minimum) * proportion;
  40306. }
  40307. double Slider::valueToProportionOfLength (double value)
  40308. {
  40309. const double n = (value - minimum) / (maximum - minimum);
  40310. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40311. }
  40312. double Slider::snapValue (double attemptedValue, const bool)
  40313. {
  40314. return attemptedValue;
  40315. }
  40316. void Slider::startedDragging()
  40317. {
  40318. }
  40319. void Slider::stoppedDragging()
  40320. {
  40321. }
  40322. void Slider::valueChanged()
  40323. {
  40324. }
  40325. void Slider::enablementChanged()
  40326. {
  40327. repaint();
  40328. }
  40329. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40330. {
  40331. menuEnabled = menuEnabled_;
  40332. }
  40333. void Slider::setScrollWheelEnabled (const bool enabled)
  40334. {
  40335. scrollWheelEnabled = enabled;
  40336. }
  40337. void Slider::labelTextChanged (Label* label)
  40338. {
  40339. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40340. if (newValue != (double) currentValue.getValue())
  40341. {
  40342. sendDragStart();
  40343. setValue (newValue, true, true);
  40344. sendDragEnd();
  40345. }
  40346. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40347. }
  40348. void Slider::buttonClicked (Button* button)
  40349. {
  40350. if (style == IncDecButtons)
  40351. {
  40352. sendDragStart();
  40353. if (button == incButton)
  40354. setValue (snapValue (getValue() + interval, false), true, true);
  40355. else if (button == decButton)
  40356. setValue (snapValue (getValue() - interval, false), true, true);
  40357. sendDragEnd();
  40358. }
  40359. }
  40360. double Slider::constrainedValue (double value) const
  40361. {
  40362. if (interval > 0)
  40363. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40364. if (value <= minimum || maximum <= minimum)
  40365. value = minimum;
  40366. else if (value >= maximum)
  40367. value = maximum;
  40368. return value;
  40369. }
  40370. float Slider::getLinearSliderPos (const double value)
  40371. {
  40372. double sliderPosProportional;
  40373. if (maximum > minimum)
  40374. {
  40375. if (value < minimum)
  40376. {
  40377. sliderPosProportional = 0.0;
  40378. }
  40379. else if (value > maximum)
  40380. {
  40381. sliderPosProportional = 1.0;
  40382. }
  40383. else
  40384. {
  40385. sliderPosProportional = valueToProportionOfLength (value);
  40386. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40387. }
  40388. }
  40389. else
  40390. {
  40391. sliderPosProportional = 0.5;
  40392. }
  40393. if (isVertical() || style == IncDecButtons)
  40394. sliderPosProportional = 1.0 - sliderPosProportional;
  40395. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40396. }
  40397. bool Slider::isHorizontal() const
  40398. {
  40399. return style == LinearHorizontal
  40400. || style == LinearBar
  40401. || style == TwoValueHorizontal
  40402. || style == ThreeValueHorizontal;
  40403. }
  40404. bool Slider::isVertical() const
  40405. {
  40406. return style == LinearVertical
  40407. || style == TwoValueVertical
  40408. || style == ThreeValueVertical;
  40409. }
  40410. bool Slider::incDecDragDirectionIsHorizontal() const
  40411. {
  40412. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40413. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40414. }
  40415. float Slider::getPositionOfValue (const double value)
  40416. {
  40417. if (isHorizontal() || isVertical())
  40418. {
  40419. return getLinearSliderPos (value);
  40420. }
  40421. else
  40422. {
  40423. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40424. return 0.0f;
  40425. }
  40426. }
  40427. void Slider::paint (Graphics& g)
  40428. {
  40429. if (style != IncDecButtons)
  40430. {
  40431. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40432. {
  40433. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40434. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40435. getLookAndFeel().drawRotarySlider (g,
  40436. sliderRect.getX(),
  40437. sliderRect.getY(),
  40438. sliderRect.getWidth(),
  40439. sliderRect.getHeight(),
  40440. sliderPos,
  40441. rotaryStart, rotaryEnd,
  40442. *this);
  40443. }
  40444. else
  40445. {
  40446. getLookAndFeel().drawLinearSlider (g,
  40447. sliderRect.getX(),
  40448. sliderRect.getY(),
  40449. sliderRect.getWidth(),
  40450. sliderRect.getHeight(),
  40451. getLinearSliderPos (lastCurrentValue),
  40452. getLinearSliderPos (lastValueMin),
  40453. getLinearSliderPos (lastValueMax),
  40454. style,
  40455. *this);
  40456. }
  40457. if (style == LinearBar && valueBox == 0)
  40458. {
  40459. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40460. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40461. }
  40462. }
  40463. }
  40464. void Slider::resized()
  40465. {
  40466. int minXSpace = 0;
  40467. int minYSpace = 0;
  40468. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40469. minXSpace = 30;
  40470. else
  40471. minYSpace = 15;
  40472. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40473. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40474. if (style == LinearBar)
  40475. {
  40476. if (valueBox != 0)
  40477. valueBox->setBounds (getLocalBounds());
  40478. }
  40479. else
  40480. {
  40481. if (textBoxPos == NoTextBox)
  40482. {
  40483. sliderRect = getLocalBounds();
  40484. }
  40485. else if (textBoxPos == TextBoxLeft)
  40486. {
  40487. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40488. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40489. }
  40490. else if (textBoxPos == TextBoxRight)
  40491. {
  40492. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40493. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40494. }
  40495. else if (textBoxPos == TextBoxAbove)
  40496. {
  40497. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40498. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40499. }
  40500. else if (textBoxPos == TextBoxBelow)
  40501. {
  40502. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40503. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40504. }
  40505. }
  40506. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40507. if (style == LinearBar)
  40508. {
  40509. const int barIndent = 1;
  40510. sliderRegionStart = barIndent;
  40511. sliderRegionSize = getWidth() - barIndent * 2;
  40512. sliderRect.setBounds (sliderRegionStart, barIndent,
  40513. sliderRegionSize, getHeight() - barIndent * 2);
  40514. }
  40515. else if (isHorizontal())
  40516. {
  40517. sliderRegionStart = sliderRect.getX() + indent;
  40518. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40519. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40520. sliderRegionSize, sliderRect.getHeight());
  40521. }
  40522. else if (isVertical())
  40523. {
  40524. sliderRegionStart = sliderRect.getY() + indent;
  40525. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40526. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40527. sliderRect.getWidth(), sliderRegionSize);
  40528. }
  40529. else
  40530. {
  40531. sliderRegionStart = 0;
  40532. sliderRegionSize = 100;
  40533. }
  40534. if (style == IncDecButtons)
  40535. {
  40536. Rectangle<int> buttonRect (sliderRect);
  40537. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40538. buttonRect.expand (-2, 0);
  40539. else
  40540. buttonRect.expand (0, -2);
  40541. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40542. if (incDecButtonsSideBySide)
  40543. {
  40544. decButton->setBounds (buttonRect.getX(),
  40545. buttonRect.getY(),
  40546. buttonRect.getWidth() / 2,
  40547. buttonRect.getHeight());
  40548. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40549. incButton->setBounds (buttonRect.getCentreX(),
  40550. buttonRect.getY(),
  40551. buttonRect.getWidth() / 2,
  40552. buttonRect.getHeight());
  40553. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40554. }
  40555. else
  40556. {
  40557. incButton->setBounds (buttonRect.getX(),
  40558. buttonRect.getY(),
  40559. buttonRect.getWidth(),
  40560. buttonRect.getHeight() / 2);
  40561. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40562. decButton->setBounds (buttonRect.getX(),
  40563. buttonRect.getCentreY(),
  40564. buttonRect.getWidth(),
  40565. buttonRect.getHeight() / 2);
  40566. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40567. }
  40568. }
  40569. }
  40570. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40571. {
  40572. repaint();
  40573. }
  40574. void Slider::mouseDown (const MouseEvent& e)
  40575. {
  40576. mouseWasHidden = false;
  40577. incDecDragged = false;
  40578. mouseXWhenLastDragged = e.x;
  40579. mouseYWhenLastDragged = e.y;
  40580. mouseDragStartX = e.getMouseDownX();
  40581. mouseDragStartY = e.getMouseDownY();
  40582. if (isEnabled())
  40583. {
  40584. if (e.mods.isPopupMenu() && menuEnabled)
  40585. {
  40586. menuShown = true;
  40587. PopupMenu m;
  40588. m.setLookAndFeel (&getLookAndFeel());
  40589. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40590. m.addSeparator();
  40591. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40592. {
  40593. PopupMenu rotaryMenu;
  40594. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40595. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40596. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40597. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40598. }
  40599. const int r = m.show();
  40600. if (r == 1)
  40601. {
  40602. setVelocityBasedMode (! isVelocityBased);
  40603. }
  40604. else if (r == 2)
  40605. {
  40606. setSliderStyle (Rotary);
  40607. }
  40608. else if (r == 3)
  40609. {
  40610. setSliderStyle (RotaryHorizontalDrag);
  40611. }
  40612. else if (r == 4)
  40613. {
  40614. setSliderStyle (RotaryVerticalDrag);
  40615. }
  40616. }
  40617. else if (maximum > minimum)
  40618. {
  40619. menuShown = false;
  40620. if (valueBox != 0)
  40621. valueBox->hideEditor (true);
  40622. sliderBeingDragged = 0;
  40623. if (style == TwoValueHorizontal
  40624. || style == TwoValueVertical
  40625. || style == ThreeValueHorizontal
  40626. || style == ThreeValueVertical)
  40627. {
  40628. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40629. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40630. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40631. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40632. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40633. {
  40634. if (maxPosDistance <= minPosDistance)
  40635. sliderBeingDragged = 2;
  40636. else
  40637. sliderBeingDragged = 1;
  40638. }
  40639. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40640. {
  40641. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40642. sliderBeingDragged = 1;
  40643. else if (normalPosDistance >= maxPosDistance)
  40644. sliderBeingDragged = 2;
  40645. }
  40646. }
  40647. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40648. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40649. * valueToProportionOfLength (currentValue.getValue());
  40650. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40651. : ((sliderBeingDragged == 1) ? valueMin
  40652. : currentValue)).getValue();
  40653. valueOnMouseDown = valueWhenLastDragged;
  40654. if (popupDisplayEnabled)
  40655. {
  40656. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40657. popupDisplay = popup;
  40658. if (parentForPopupDisplay != 0)
  40659. {
  40660. parentForPopupDisplay->addChildComponent (popup);
  40661. }
  40662. else
  40663. {
  40664. popup->addToDesktop (0);
  40665. }
  40666. popup->setVisible (true);
  40667. }
  40668. sendDragStart();
  40669. mouseDrag (e);
  40670. }
  40671. }
  40672. }
  40673. void Slider::mouseUp (const MouseEvent&)
  40674. {
  40675. if (isEnabled()
  40676. && (! menuShown)
  40677. && (maximum > minimum)
  40678. && (style != IncDecButtons || incDecDragged))
  40679. {
  40680. restoreMouseIfHidden();
  40681. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40682. triggerChangeMessage (false);
  40683. sendDragEnd();
  40684. popupDisplay = 0;
  40685. if (style == IncDecButtons)
  40686. {
  40687. incButton->setState (Button::buttonNormal);
  40688. decButton->setState (Button::buttonNormal);
  40689. }
  40690. }
  40691. }
  40692. void Slider::restoreMouseIfHidden()
  40693. {
  40694. if (mouseWasHidden)
  40695. {
  40696. mouseWasHidden = false;
  40697. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40698. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40699. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40700. : ((sliderBeingDragged == 1) ? getMinValue()
  40701. : (double) currentValue.getValue());
  40702. Point<int> mousePos;
  40703. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40704. {
  40705. mousePos = Desktop::getLastMouseDownPosition();
  40706. if (style == RotaryHorizontalDrag)
  40707. {
  40708. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40709. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40710. }
  40711. else
  40712. {
  40713. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40714. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40715. }
  40716. }
  40717. else
  40718. {
  40719. const int pixelPos = (int) getLinearSliderPos (pos);
  40720. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40721. isVertical() ? pixelPos : (getHeight() / 2)));
  40722. }
  40723. Desktop::setMousePosition (mousePos);
  40724. }
  40725. }
  40726. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40727. {
  40728. if (isEnabled()
  40729. && style != IncDecButtons
  40730. && style != Rotary
  40731. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40732. {
  40733. restoreMouseIfHidden();
  40734. }
  40735. }
  40736. namespace SliderHelpers
  40737. {
  40738. double smallestAngleBetween (double a1, double a2) throw()
  40739. {
  40740. return jmin (std::abs (a1 - a2),
  40741. std::abs (a1 + double_Pi * 2.0 - a2),
  40742. std::abs (a2 + double_Pi * 2.0 - a1));
  40743. }
  40744. }
  40745. void Slider::mouseDrag (const MouseEvent& e)
  40746. {
  40747. if (isEnabled()
  40748. && (! menuShown)
  40749. && (maximum > minimum))
  40750. {
  40751. if (style == Rotary)
  40752. {
  40753. int dx = e.x - sliderRect.getCentreX();
  40754. int dy = e.y - sliderRect.getCentreY();
  40755. if (dx * dx + dy * dy > 25)
  40756. {
  40757. double angle = std::atan2 ((double) dx, (double) -dy);
  40758. while (angle < 0.0)
  40759. angle += double_Pi * 2.0;
  40760. if (rotaryStop && ! e.mouseWasClicked())
  40761. {
  40762. if (std::abs (angle - lastAngle) > double_Pi)
  40763. {
  40764. if (angle >= lastAngle)
  40765. angle -= double_Pi * 2.0;
  40766. else
  40767. angle += double_Pi * 2.0;
  40768. }
  40769. if (angle >= lastAngle)
  40770. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40771. else
  40772. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40773. }
  40774. else
  40775. {
  40776. while (angle < rotaryStart)
  40777. angle += double_Pi * 2.0;
  40778. if (angle > rotaryEnd)
  40779. {
  40780. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40781. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40782. angle = rotaryStart;
  40783. else
  40784. angle = rotaryEnd;
  40785. }
  40786. }
  40787. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40788. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40789. lastAngle = angle;
  40790. }
  40791. }
  40792. else
  40793. {
  40794. if (style == LinearBar && e.mouseWasClicked()
  40795. && valueBox != 0 && valueBox->isEditable())
  40796. return;
  40797. if (style == IncDecButtons && ! incDecDragged)
  40798. {
  40799. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40800. return;
  40801. incDecDragged = true;
  40802. mouseDragStartX = e.x;
  40803. mouseDragStartY = e.y;
  40804. }
  40805. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40806. : false))
  40807. || ((maximum - minimum) / sliderRegionSize < interval))
  40808. {
  40809. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40810. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40811. if (style == RotaryHorizontalDrag
  40812. || style == RotaryVerticalDrag
  40813. || style == IncDecButtons
  40814. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40815. && ! snapsToMousePos))
  40816. {
  40817. const int mouseDiff = (style == RotaryHorizontalDrag
  40818. || style == LinearHorizontal
  40819. || style == LinearBar
  40820. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40821. ? e.x - mouseDragStartX
  40822. : mouseDragStartY - e.y;
  40823. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40824. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40825. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40826. if (style == IncDecButtons)
  40827. {
  40828. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40829. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40830. }
  40831. }
  40832. else
  40833. {
  40834. if (isVertical())
  40835. scaledMousePos = 1.0 - scaledMousePos;
  40836. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40837. }
  40838. }
  40839. else
  40840. {
  40841. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40842. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40843. ? e.x - mouseXWhenLastDragged
  40844. : e.y - mouseYWhenLastDragged;
  40845. const double maxSpeed = jmax (200, sliderRegionSize);
  40846. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40847. if (speed != 0)
  40848. {
  40849. speed = 0.2 * velocityModeSensitivity
  40850. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40851. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40852. / maxSpeed))));
  40853. if (mouseDiff < 0)
  40854. speed = -speed;
  40855. if (isVertical() || style == RotaryVerticalDrag
  40856. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40857. speed = -speed;
  40858. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40859. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40860. e.source.enableUnboundedMouseMovement (true, false);
  40861. mouseWasHidden = true;
  40862. }
  40863. }
  40864. }
  40865. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40866. if (sliderBeingDragged == 0)
  40867. {
  40868. setValue (snapValue (valueWhenLastDragged, true),
  40869. ! sendChangeOnlyOnRelease, true);
  40870. }
  40871. else if (sliderBeingDragged == 1)
  40872. {
  40873. setMinValue (snapValue (valueWhenLastDragged, true),
  40874. ! sendChangeOnlyOnRelease, false, true);
  40875. if (e.mods.isShiftDown())
  40876. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40877. else
  40878. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40879. }
  40880. else
  40881. {
  40882. jassert (sliderBeingDragged == 2);
  40883. setMaxValue (snapValue (valueWhenLastDragged, true),
  40884. ! sendChangeOnlyOnRelease, false, true);
  40885. if (e.mods.isShiftDown())
  40886. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40887. else
  40888. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40889. }
  40890. mouseXWhenLastDragged = e.x;
  40891. mouseYWhenLastDragged = e.y;
  40892. }
  40893. }
  40894. void Slider::mouseDoubleClick (const MouseEvent&)
  40895. {
  40896. if (doubleClickToValue
  40897. && isEnabled()
  40898. && style != IncDecButtons
  40899. && minimum <= doubleClickReturnValue
  40900. && maximum >= doubleClickReturnValue)
  40901. {
  40902. sendDragStart();
  40903. setValue (doubleClickReturnValue, true, true);
  40904. sendDragEnd();
  40905. }
  40906. }
  40907. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40908. {
  40909. if (scrollWheelEnabled && isEnabled()
  40910. && style != TwoValueHorizontal
  40911. && style != TwoValueVertical)
  40912. {
  40913. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40914. {
  40915. if (valueBox != 0)
  40916. valueBox->hideEditor (false);
  40917. const double value = (double) currentValue.getValue();
  40918. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40919. const double currentPos = valueToProportionOfLength (value);
  40920. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40921. double delta = (newValue != value)
  40922. ? jmax (std::abs (newValue - value), interval) : 0;
  40923. if (value > newValue)
  40924. delta = -delta;
  40925. sendDragStart();
  40926. setValue (snapValue (value + delta, false), true, true);
  40927. sendDragEnd();
  40928. }
  40929. }
  40930. else
  40931. {
  40932. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40933. }
  40934. }
  40935. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40936. {
  40937. }
  40938. void SliderListener::sliderDragEnded (Slider*)
  40939. {
  40940. }
  40941. END_JUCE_NAMESPACE
  40942. /*** End of inlined file: juce_Slider.cpp ***/
  40943. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40944. BEGIN_JUCE_NAMESPACE
  40945. class DragOverlayComp : public Component
  40946. {
  40947. public:
  40948. DragOverlayComp (const Image& image_)
  40949. : image (image_)
  40950. {
  40951. image.duplicateIfShared();
  40952. image.multiplyAllAlphas (0.8f);
  40953. setAlwaysOnTop (true);
  40954. }
  40955. void paint (Graphics& g)
  40956. {
  40957. g.drawImageAt (image, 0, 0);
  40958. }
  40959. private:
  40960. Image image;
  40961. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  40962. };
  40963. TableHeaderComponent::TableHeaderComponent()
  40964. : columnsChanged (false),
  40965. columnsResized (false),
  40966. sortChanged (false),
  40967. menuActive (true),
  40968. stretchToFit (false),
  40969. columnIdBeingResized (0),
  40970. columnIdBeingDragged (0),
  40971. columnIdUnderMouse (0),
  40972. lastDeliberateWidth (0)
  40973. {
  40974. }
  40975. TableHeaderComponent::~TableHeaderComponent()
  40976. {
  40977. dragOverlayComp = 0;
  40978. }
  40979. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40980. {
  40981. menuActive = hasMenu;
  40982. }
  40983. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40984. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40985. {
  40986. if (onlyCountVisibleColumns)
  40987. {
  40988. int num = 0;
  40989. for (int i = columns.size(); --i >= 0;)
  40990. if (columns.getUnchecked(i)->isVisible())
  40991. ++num;
  40992. return num;
  40993. }
  40994. else
  40995. {
  40996. return columns.size();
  40997. }
  40998. }
  40999. const String TableHeaderComponent::getColumnName (const int columnId) const
  41000. {
  41001. const ColumnInfo* const ci = getInfoForId (columnId);
  41002. return ci != 0 ? ci->name : String::empty;
  41003. }
  41004. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41005. {
  41006. ColumnInfo* const ci = getInfoForId (columnId);
  41007. if (ci != 0 && ci->name != newName)
  41008. {
  41009. ci->name = newName;
  41010. sendColumnsChanged();
  41011. }
  41012. }
  41013. void TableHeaderComponent::addColumn (const String& columnName,
  41014. const int columnId,
  41015. const int width,
  41016. const int minimumWidth,
  41017. const int maximumWidth,
  41018. const int propertyFlags,
  41019. const int insertIndex)
  41020. {
  41021. // can't have a duplicate or null ID!
  41022. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41023. jassert (width > 0);
  41024. ColumnInfo* const ci = new ColumnInfo();
  41025. ci->name = columnName;
  41026. ci->id = columnId;
  41027. ci->width = width;
  41028. ci->lastDeliberateWidth = width;
  41029. ci->minimumWidth = minimumWidth;
  41030. ci->maximumWidth = maximumWidth;
  41031. if (ci->maximumWidth < 0)
  41032. ci->maximumWidth = std::numeric_limits<int>::max();
  41033. jassert (ci->maximumWidth >= ci->minimumWidth);
  41034. ci->propertyFlags = propertyFlags;
  41035. columns.insert (insertIndex, ci);
  41036. sendColumnsChanged();
  41037. }
  41038. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41039. {
  41040. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41041. if (index >= 0)
  41042. {
  41043. columns.remove (index);
  41044. sortChanged = true;
  41045. sendColumnsChanged();
  41046. }
  41047. }
  41048. void TableHeaderComponent::removeAllColumns()
  41049. {
  41050. if (columns.size() > 0)
  41051. {
  41052. columns.clear();
  41053. sendColumnsChanged();
  41054. }
  41055. }
  41056. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41057. {
  41058. const int currentIndex = getIndexOfColumnId (columnId, false);
  41059. newIndex = visibleIndexToTotalIndex (newIndex);
  41060. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41061. {
  41062. columns.move (currentIndex, newIndex);
  41063. sendColumnsChanged();
  41064. }
  41065. }
  41066. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41067. {
  41068. const ColumnInfo* const ci = getInfoForId (columnId);
  41069. return ci != 0 ? ci->width : 0;
  41070. }
  41071. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41072. {
  41073. ColumnInfo* const ci = getInfoForId (columnId);
  41074. if (ci != 0 && ci->width != newWidth)
  41075. {
  41076. const int numColumns = getNumColumns (true);
  41077. ci->lastDeliberateWidth = ci->width
  41078. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41079. if (stretchToFit)
  41080. {
  41081. const int index = getIndexOfColumnId (columnId, true) + 1;
  41082. if (((unsigned int) index) < (unsigned int) numColumns)
  41083. {
  41084. const int x = getColumnPosition (index).getX();
  41085. if (lastDeliberateWidth == 0)
  41086. lastDeliberateWidth = getTotalWidth();
  41087. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41088. }
  41089. }
  41090. repaint();
  41091. columnsResized = true;
  41092. triggerAsyncUpdate();
  41093. }
  41094. }
  41095. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41096. {
  41097. int n = 0;
  41098. for (int i = 0; i < columns.size(); ++i)
  41099. {
  41100. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41101. {
  41102. if (columns.getUnchecked(i)->id == columnId)
  41103. return n;
  41104. ++n;
  41105. }
  41106. }
  41107. return -1;
  41108. }
  41109. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41110. {
  41111. if (onlyCountVisibleColumns)
  41112. index = visibleIndexToTotalIndex (index);
  41113. const ColumnInfo* const ci = columns [index];
  41114. return (ci != 0) ? ci->id : 0;
  41115. }
  41116. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41117. {
  41118. int x = 0, width = 0, n = 0;
  41119. for (int i = 0; i < columns.size(); ++i)
  41120. {
  41121. x += width;
  41122. if (columns.getUnchecked(i)->isVisible())
  41123. {
  41124. width = columns.getUnchecked(i)->width;
  41125. if (n++ == index)
  41126. break;
  41127. }
  41128. else
  41129. {
  41130. width = 0;
  41131. }
  41132. }
  41133. return Rectangle<int> (x, 0, width, getHeight());
  41134. }
  41135. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41136. {
  41137. if (xToFind >= 0)
  41138. {
  41139. int x = 0;
  41140. for (int i = 0; i < columns.size(); ++i)
  41141. {
  41142. const ColumnInfo* const ci = columns.getUnchecked(i);
  41143. if (ci->isVisible())
  41144. {
  41145. x += ci->width;
  41146. if (xToFind < x)
  41147. return ci->id;
  41148. }
  41149. }
  41150. }
  41151. return 0;
  41152. }
  41153. int TableHeaderComponent::getTotalWidth() const
  41154. {
  41155. int w = 0;
  41156. for (int i = columns.size(); --i >= 0;)
  41157. if (columns.getUnchecked(i)->isVisible())
  41158. w += columns.getUnchecked(i)->width;
  41159. return w;
  41160. }
  41161. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41162. {
  41163. stretchToFit = shouldStretchToFit;
  41164. lastDeliberateWidth = getTotalWidth();
  41165. resized();
  41166. }
  41167. bool TableHeaderComponent::isStretchToFitActive() const
  41168. {
  41169. return stretchToFit;
  41170. }
  41171. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41172. {
  41173. if (stretchToFit && getWidth() > 0
  41174. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41175. {
  41176. lastDeliberateWidth = targetTotalWidth;
  41177. resizeColumnsToFit (0, targetTotalWidth);
  41178. }
  41179. }
  41180. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41181. {
  41182. targetTotalWidth = jmax (targetTotalWidth, 0);
  41183. StretchableObjectResizer sor;
  41184. int i;
  41185. for (i = firstColumnIndex; i < columns.size(); ++i)
  41186. {
  41187. ColumnInfo* const ci = columns.getUnchecked(i);
  41188. if (ci->isVisible())
  41189. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41190. }
  41191. sor.resizeToFit (targetTotalWidth);
  41192. int visIndex = 0;
  41193. for (i = firstColumnIndex; i < columns.size(); ++i)
  41194. {
  41195. ColumnInfo* const ci = columns.getUnchecked(i);
  41196. if (ci->isVisible())
  41197. {
  41198. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41199. (int) std::floor (sor.getItemSize (visIndex++)));
  41200. if (newWidth != ci->width)
  41201. {
  41202. ci->width = newWidth;
  41203. repaint();
  41204. columnsResized = true;
  41205. triggerAsyncUpdate();
  41206. }
  41207. }
  41208. }
  41209. }
  41210. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41211. {
  41212. ColumnInfo* const ci = getInfoForId (columnId);
  41213. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41214. {
  41215. if (shouldBeVisible)
  41216. ci->propertyFlags |= visible;
  41217. else
  41218. ci->propertyFlags &= ~visible;
  41219. sendColumnsChanged();
  41220. resized();
  41221. }
  41222. }
  41223. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41224. {
  41225. const ColumnInfo* const ci = getInfoForId (columnId);
  41226. return ci != 0 && ci->isVisible();
  41227. }
  41228. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41229. {
  41230. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41231. {
  41232. for (int i = columns.size(); --i >= 0;)
  41233. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41234. ColumnInfo* const ci = getInfoForId (columnId);
  41235. if (ci != 0)
  41236. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41237. reSortTable();
  41238. }
  41239. }
  41240. int TableHeaderComponent::getSortColumnId() const
  41241. {
  41242. for (int i = columns.size(); --i >= 0;)
  41243. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41244. return columns.getUnchecked(i)->id;
  41245. return 0;
  41246. }
  41247. bool TableHeaderComponent::isSortedForwards() const
  41248. {
  41249. for (int i = columns.size(); --i >= 0;)
  41250. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41251. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41252. return true;
  41253. }
  41254. void TableHeaderComponent::reSortTable()
  41255. {
  41256. sortChanged = true;
  41257. repaint();
  41258. triggerAsyncUpdate();
  41259. }
  41260. const String TableHeaderComponent::toString() const
  41261. {
  41262. String s;
  41263. XmlElement doc ("TABLELAYOUT");
  41264. doc.setAttribute ("sortedCol", getSortColumnId());
  41265. doc.setAttribute ("sortForwards", isSortedForwards());
  41266. for (int i = 0; i < columns.size(); ++i)
  41267. {
  41268. const ColumnInfo* const ci = columns.getUnchecked (i);
  41269. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41270. e->setAttribute ("id", ci->id);
  41271. e->setAttribute ("visible", ci->isVisible());
  41272. e->setAttribute ("width", ci->width);
  41273. }
  41274. return doc.createDocument (String::empty, true, false);
  41275. }
  41276. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41277. {
  41278. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41279. int index = 0;
  41280. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41281. {
  41282. forEachXmlChildElement (*storedXml, col)
  41283. {
  41284. const int tabId = col->getIntAttribute ("id");
  41285. ColumnInfo* const ci = getInfoForId (tabId);
  41286. if (ci != 0)
  41287. {
  41288. columns.move (columns.indexOf (ci), index);
  41289. ci->width = col->getIntAttribute ("width");
  41290. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41291. }
  41292. ++index;
  41293. }
  41294. columnsResized = true;
  41295. sendColumnsChanged();
  41296. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41297. storedXml->getBoolAttribute ("sortForwards", true));
  41298. }
  41299. }
  41300. void TableHeaderComponent::addListener (Listener* const newListener)
  41301. {
  41302. listeners.addIfNotAlreadyThere (newListener);
  41303. }
  41304. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41305. {
  41306. listeners.removeValue (listenerToRemove);
  41307. }
  41308. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41309. {
  41310. const ColumnInfo* const ci = getInfoForId (columnId);
  41311. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41312. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41313. }
  41314. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41315. {
  41316. for (int i = 0; i < columns.size(); ++i)
  41317. {
  41318. const ColumnInfo* const ci = columns.getUnchecked(i);
  41319. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41320. menu.addItem (ci->id, ci->name,
  41321. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41322. isColumnVisible (ci->id));
  41323. }
  41324. }
  41325. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41326. {
  41327. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41328. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41329. }
  41330. void TableHeaderComponent::paint (Graphics& g)
  41331. {
  41332. LookAndFeel& lf = getLookAndFeel();
  41333. lf.drawTableHeaderBackground (g, *this);
  41334. const Rectangle<int> clip (g.getClipBounds());
  41335. int x = 0;
  41336. for (int i = 0; i < columns.size(); ++i)
  41337. {
  41338. const ColumnInfo* const ci = columns.getUnchecked(i);
  41339. if (ci->isVisible())
  41340. {
  41341. if (x + ci->width > clip.getX()
  41342. && (ci->id != columnIdBeingDragged
  41343. || dragOverlayComp == 0
  41344. || ! dragOverlayComp->isVisible()))
  41345. {
  41346. g.saveState();
  41347. g.setOrigin (x, 0);
  41348. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41349. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41350. ci->id == columnIdUnderMouse,
  41351. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41352. ci->propertyFlags);
  41353. g.restoreState();
  41354. }
  41355. x += ci->width;
  41356. if (x >= clip.getRight())
  41357. break;
  41358. }
  41359. }
  41360. }
  41361. void TableHeaderComponent::resized()
  41362. {
  41363. }
  41364. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41365. {
  41366. updateColumnUnderMouse (e.x, e.y);
  41367. }
  41368. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41369. {
  41370. updateColumnUnderMouse (e.x, e.y);
  41371. }
  41372. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41373. {
  41374. updateColumnUnderMouse (e.x, e.y);
  41375. }
  41376. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41377. {
  41378. repaint();
  41379. columnIdBeingResized = 0;
  41380. columnIdBeingDragged = 0;
  41381. if (columnIdUnderMouse != 0)
  41382. {
  41383. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41384. if (e.mods.isPopupMenu())
  41385. columnClicked (columnIdUnderMouse, e.mods);
  41386. }
  41387. if (menuActive && e.mods.isPopupMenu())
  41388. showColumnChooserMenu (columnIdUnderMouse);
  41389. }
  41390. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41391. {
  41392. if (columnIdBeingResized == 0
  41393. && columnIdBeingDragged == 0
  41394. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41395. {
  41396. dragOverlayComp = 0;
  41397. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41398. if (columnIdBeingResized != 0)
  41399. {
  41400. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41401. initialColumnWidth = ci->width;
  41402. }
  41403. else
  41404. {
  41405. beginDrag (e);
  41406. }
  41407. }
  41408. if (columnIdBeingResized != 0)
  41409. {
  41410. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41411. if (ci != 0)
  41412. {
  41413. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41414. initialColumnWidth + e.getDistanceFromDragStartX());
  41415. if (stretchToFit)
  41416. {
  41417. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41418. int minWidthOnRight = 0;
  41419. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41420. if (columns.getUnchecked (i)->isVisible())
  41421. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41422. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41423. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41424. }
  41425. setColumnWidth (columnIdBeingResized, w);
  41426. }
  41427. }
  41428. else if (columnIdBeingDragged != 0)
  41429. {
  41430. if (e.y >= -50 && e.y < getHeight() + 50)
  41431. {
  41432. if (dragOverlayComp != 0)
  41433. {
  41434. dragOverlayComp->setVisible (true);
  41435. dragOverlayComp->setBounds (jlimit (0,
  41436. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41437. e.x - draggingColumnOffset),
  41438. 0,
  41439. dragOverlayComp->getWidth(),
  41440. getHeight());
  41441. for (int i = columns.size(); --i >= 0;)
  41442. {
  41443. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41444. int newIndex = currentIndex;
  41445. if (newIndex > 0)
  41446. {
  41447. // if the previous column isn't draggable, we can't move our column
  41448. // past it, because that'd change the undraggable column's position..
  41449. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41450. if ((previous->propertyFlags & draggable) != 0)
  41451. {
  41452. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41453. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41454. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41455. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41456. {
  41457. --newIndex;
  41458. }
  41459. }
  41460. }
  41461. if (newIndex < columns.size() - 1)
  41462. {
  41463. // if the next column isn't draggable, we can't move our column
  41464. // past it, because that'd change the undraggable column's position..
  41465. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41466. if ((nextCol->propertyFlags & draggable) != 0)
  41467. {
  41468. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41469. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41470. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41471. > abs (dragOverlayComp->getRight() - rightOfNext))
  41472. {
  41473. ++newIndex;
  41474. }
  41475. }
  41476. }
  41477. if (newIndex != currentIndex)
  41478. moveColumn (columnIdBeingDragged, newIndex);
  41479. else
  41480. break;
  41481. }
  41482. }
  41483. }
  41484. else
  41485. {
  41486. endDrag (draggingColumnOriginalIndex);
  41487. }
  41488. }
  41489. }
  41490. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41491. {
  41492. if (columnIdBeingDragged == 0)
  41493. {
  41494. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41495. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41496. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41497. {
  41498. columnIdBeingDragged = 0;
  41499. }
  41500. else
  41501. {
  41502. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41503. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41504. const int temp = columnIdBeingDragged;
  41505. columnIdBeingDragged = 0;
  41506. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41507. columnIdBeingDragged = temp;
  41508. dragOverlayComp->setBounds (columnRect);
  41509. for (int i = listeners.size(); --i >= 0;)
  41510. {
  41511. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41512. i = jmin (i, listeners.size() - 1);
  41513. }
  41514. }
  41515. }
  41516. }
  41517. void TableHeaderComponent::endDrag (const int finalIndex)
  41518. {
  41519. if (columnIdBeingDragged != 0)
  41520. {
  41521. moveColumn (columnIdBeingDragged, finalIndex);
  41522. columnIdBeingDragged = 0;
  41523. repaint();
  41524. for (int i = listeners.size(); --i >= 0;)
  41525. {
  41526. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41527. i = jmin (i, listeners.size() - 1);
  41528. }
  41529. }
  41530. }
  41531. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41532. {
  41533. mouseDrag (e);
  41534. for (int i = columns.size(); --i >= 0;)
  41535. if (columns.getUnchecked (i)->isVisible())
  41536. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41537. columnIdBeingResized = 0;
  41538. repaint();
  41539. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41540. updateColumnUnderMouse (e.x, e.y);
  41541. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41542. columnClicked (columnIdUnderMouse, e.mods);
  41543. dragOverlayComp = 0;
  41544. }
  41545. const MouseCursor TableHeaderComponent::getMouseCursor()
  41546. {
  41547. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41548. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41549. return Component::getMouseCursor();
  41550. }
  41551. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41552. {
  41553. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41554. }
  41555. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41556. {
  41557. for (int i = columns.size(); --i >= 0;)
  41558. if (columns.getUnchecked(i)->id == id)
  41559. return columns.getUnchecked(i);
  41560. return 0;
  41561. }
  41562. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41563. {
  41564. int n = 0;
  41565. for (int i = 0; i < columns.size(); ++i)
  41566. {
  41567. if (columns.getUnchecked(i)->isVisible())
  41568. {
  41569. if (n == visibleIndex)
  41570. return i;
  41571. ++n;
  41572. }
  41573. }
  41574. return -1;
  41575. }
  41576. void TableHeaderComponent::sendColumnsChanged()
  41577. {
  41578. if (stretchToFit && lastDeliberateWidth > 0)
  41579. resizeAllColumnsToFit (lastDeliberateWidth);
  41580. repaint();
  41581. columnsChanged = true;
  41582. triggerAsyncUpdate();
  41583. }
  41584. void TableHeaderComponent::handleAsyncUpdate()
  41585. {
  41586. const bool changed = columnsChanged || sortChanged;
  41587. const bool sized = columnsResized || changed;
  41588. const bool sorted = sortChanged;
  41589. columnsChanged = false;
  41590. columnsResized = false;
  41591. sortChanged = false;
  41592. if (sorted)
  41593. {
  41594. for (int i = listeners.size(); --i >= 0;)
  41595. {
  41596. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41597. i = jmin (i, listeners.size() - 1);
  41598. }
  41599. }
  41600. if (changed)
  41601. {
  41602. for (int i = listeners.size(); --i >= 0;)
  41603. {
  41604. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41605. i = jmin (i, listeners.size() - 1);
  41606. }
  41607. }
  41608. if (sized)
  41609. {
  41610. for (int i = listeners.size(); --i >= 0;)
  41611. {
  41612. listeners.getUnchecked(i)->tableColumnsResized (this);
  41613. i = jmin (i, listeners.size() - 1);
  41614. }
  41615. }
  41616. }
  41617. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41618. {
  41619. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41620. {
  41621. const int draggableDistance = 3;
  41622. int x = 0;
  41623. for (int i = 0; i < columns.size(); ++i)
  41624. {
  41625. const ColumnInfo* const ci = columns.getUnchecked(i);
  41626. if (ci->isVisible())
  41627. {
  41628. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41629. && (ci->propertyFlags & resizable) != 0)
  41630. return ci->id;
  41631. x += ci->width;
  41632. }
  41633. }
  41634. }
  41635. return 0;
  41636. }
  41637. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41638. {
  41639. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41640. ? getColumnIdAtX (x) : 0;
  41641. if (newCol != columnIdUnderMouse)
  41642. {
  41643. columnIdUnderMouse = newCol;
  41644. repaint();
  41645. }
  41646. }
  41647. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41648. {
  41649. PopupMenu m;
  41650. addMenuItems (m, columnIdClicked);
  41651. if (m.getNumItems() > 0)
  41652. {
  41653. m.setLookAndFeel (&getLookAndFeel());
  41654. const int result = m.show();
  41655. if (result != 0)
  41656. reactToMenuItem (result, columnIdClicked);
  41657. }
  41658. }
  41659. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41660. {
  41661. }
  41662. END_JUCE_NAMESPACE
  41663. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41664. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41665. BEGIN_JUCE_NAMESPACE
  41666. class TableListRowComp : public Component,
  41667. public TooltipClient
  41668. {
  41669. public:
  41670. TableListRowComp (TableListBox& owner_)
  41671. : owner (owner_), row (-1), isSelected (false)
  41672. {
  41673. }
  41674. void paint (Graphics& g)
  41675. {
  41676. TableListBoxModel* const model = owner.getModel();
  41677. if (model != 0)
  41678. {
  41679. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41680. const TableHeaderComponent& header = owner.getHeader();
  41681. const int numColumns = header.getNumColumns (true);
  41682. for (int i = 0; i < numColumns; ++i)
  41683. {
  41684. if (columnComponents[i] == 0)
  41685. {
  41686. const int columnId = header.getColumnIdOfIndex (i, true);
  41687. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41688. g.saveState();
  41689. g.reduceClipRegion (columnRect);
  41690. g.setOrigin (columnRect.getX(), 0);
  41691. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41692. g.restoreState();
  41693. }
  41694. }
  41695. }
  41696. }
  41697. void update (const int newRow, const bool isNowSelected)
  41698. {
  41699. jassert (newRow >= 0);
  41700. if (newRow != row || isNowSelected != isSelected)
  41701. {
  41702. row = newRow;
  41703. isSelected = isNowSelected;
  41704. repaint();
  41705. }
  41706. TableListBoxModel* const model = owner.getModel();
  41707. if (model != 0 && row < owner.getNumRows())
  41708. {
  41709. const Identifier columnProperty ("_tableColumnId");
  41710. const int numColumns = owner.getHeader().getNumColumns (true);
  41711. for (int i = 0; i < numColumns; ++i)
  41712. {
  41713. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41714. Component* comp = columnComponents[i];
  41715. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41716. {
  41717. columnComponents.set (i, 0);
  41718. comp = 0;
  41719. }
  41720. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41721. columnComponents.set (i, comp, false);
  41722. if (comp != 0)
  41723. {
  41724. comp->getProperties().set (columnProperty, columnId);
  41725. addAndMakeVisible (comp);
  41726. resizeCustomComp (i);
  41727. }
  41728. }
  41729. columnComponents.removeRange (numColumns, columnComponents.size());
  41730. }
  41731. else
  41732. {
  41733. columnComponents.clear();
  41734. }
  41735. }
  41736. void resized()
  41737. {
  41738. for (int i = columnComponents.size(); --i >= 0;)
  41739. resizeCustomComp (i);
  41740. }
  41741. void resizeCustomComp (const int index)
  41742. {
  41743. Component* const c = columnComponents.getUnchecked (index);
  41744. if (c != 0)
  41745. c->setBounds (owner.getHeader().getColumnPosition (index)
  41746. .withY (0).withHeight (getHeight()));
  41747. }
  41748. void mouseDown (const MouseEvent& e)
  41749. {
  41750. isDragging = false;
  41751. selectRowOnMouseUp = false;
  41752. if (isEnabled())
  41753. {
  41754. if (! isSelected)
  41755. {
  41756. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41757. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41758. if (columnId != 0 && owner.getModel() != 0)
  41759. owner.getModel()->cellClicked (row, columnId, e);
  41760. }
  41761. else
  41762. {
  41763. selectRowOnMouseUp = true;
  41764. }
  41765. }
  41766. }
  41767. void mouseDrag (const MouseEvent& e)
  41768. {
  41769. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41770. {
  41771. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41772. if (selectedRows.size() > 0)
  41773. {
  41774. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41775. if (dragDescription.isNotEmpty())
  41776. {
  41777. isDragging = true;
  41778. owner.startDragAndDrop (e, dragDescription);
  41779. }
  41780. }
  41781. }
  41782. }
  41783. void mouseUp (const MouseEvent& e)
  41784. {
  41785. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41786. {
  41787. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41788. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41789. if (columnId != 0 && owner.getModel() != 0)
  41790. owner.getModel()->cellClicked (row, columnId, e);
  41791. }
  41792. }
  41793. void mouseDoubleClick (const MouseEvent& e)
  41794. {
  41795. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41796. if (columnId != 0 && owner.getModel() != 0)
  41797. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41798. }
  41799. const String getTooltip()
  41800. {
  41801. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41802. if (columnId != 0 && owner.getModel() != 0)
  41803. return owner.getModel()->getCellTooltip (row, columnId);
  41804. return String::empty;
  41805. }
  41806. Component* findChildComponentForColumn (const int columnId) const
  41807. {
  41808. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41809. }
  41810. private:
  41811. TableListBox& owner;
  41812. OwnedArray<Component> columnComponents;
  41813. int row;
  41814. bool isSelected, isDragging, selectRowOnMouseUp;
  41815. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41816. };
  41817. class TableListBoxHeader : public TableHeaderComponent
  41818. {
  41819. public:
  41820. TableListBoxHeader (TableListBox& owner_)
  41821. : owner (owner_)
  41822. {
  41823. }
  41824. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41825. {
  41826. if (owner.isAutoSizeMenuOptionShown())
  41827. {
  41828. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41829. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41830. menu.addSeparator();
  41831. }
  41832. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41833. }
  41834. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41835. {
  41836. switch (menuReturnId)
  41837. {
  41838. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41839. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41840. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41841. }
  41842. }
  41843. private:
  41844. TableListBox& owner;
  41845. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41846. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41847. };
  41848. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41849. : ListBox (name, 0),
  41850. model (model_),
  41851. autoSizeOptionsShown (true)
  41852. {
  41853. ListBox::model = this;
  41854. header = new TableListBoxHeader (*this);
  41855. header->setSize (100, 28);
  41856. header->addListener (this);
  41857. setHeaderComponent (header);
  41858. }
  41859. TableListBox::~TableListBox()
  41860. {
  41861. header = 0;
  41862. }
  41863. void TableListBox::setModel (TableListBoxModel* const newModel)
  41864. {
  41865. if (model != newModel)
  41866. {
  41867. model = newModel;
  41868. updateContent();
  41869. }
  41870. }
  41871. int TableListBox::getHeaderHeight() const
  41872. {
  41873. return header->getHeight();
  41874. }
  41875. void TableListBox::setHeaderHeight (const int newHeight)
  41876. {
  41877. header->setSize (header->getWidth(), newHeight);
  41878. resized();
  41879. }
  41880. void TableListBox::autoSizeColumn (const int columnId)
  41881. {
  41882. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41883. if (width > 0)
  41884. header->setColumnWidth (columnId, width);
  41885. }
  41886. void TableListBox::autoSizeAllColumns()
  41887. {
  41888. for (int i = 0; i < header->getNumColumns (true); ++i)
  41889. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41890. }
  41891. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41892. {
  41893. autoSizeOptionsShown = shouldBeShown;
  41894. }
  41895. bool TableListBox::isAutoSizeMenuOptionShown() const
  41896. {
  41897. return autoSizeOptionsShown;
  41898. }
  41899. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41900. const bool relativeToComponentTopLeft) const
  41901. {
  41902. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41903. if (relativeToComponentTopLeft)
  41904. headerCell.translate (header->getX(), 0);
  41905. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41906. .withX (headerCell.getX())
  41907. .withWidth (headerCell.getWidth());
  41908. }
  41909. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41910. {
  41911. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41912. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41913. }
  41914. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41915. {
  41916. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41917. if (scrollbar != 0)
  41918. {
  41919. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41920. double x = scrollbar->getCurrentRangeStart();
  41921. const double w = scrollbar->getCurrentRangeSize();
  41922. if (pos.getX() < x)
  41923. x = pos.getX();
  41924. else if (pos.getRight() > x + w)
  41925. x += jmax (0.0, pos.getRight() - (x + w));
  41926. scrollbar->setCurrentRangeStart (x);
  41927. }
  41928. }
  41929. int TableListBox::getNumRows()
  41930. {
  41931. return model != 0 ? model->getNumRows() : 0;
  41932. }
  41933. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41934. {
  41935. }
  41936. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41937. {
  41938. if (existingComponentToUpdate == 0)
  41939. existingComponentToUpdate = new TableListRowComp (*this);
  41940. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41941. return existingComponentToUpdate;
  41942. }
  41943. void TableListBox::selectedRowsChanged (int row)
  41944. {
  41945. if (model != 0)
  41946. model->selectedRowsChanged (row);
  41947. }
  41948. void TableListBox::deleteKeyPressed (int row)
  41949. {
  41950. if (model != 0)
  41951. model->deleteKeyPressed (row);
  41952. }
  41953. void TableListBox::returnKeyPressed (int row)
  41954. {
  41955. if (model != 0)
  41956. model->returnKeyPressed (row);
  41957. }
  41958. void TableListBox::backgroundClicked()
  41959. {
  41960. if (model != 0)
  41961. model->backgroundClicked();
  41962. }
  41963. void TableListBox::listWasScrolled()
  41964. {
  41965. if (model != 0)
  41966. model->listWasScrolled();
  41967. }
  41968. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41969. {
  41970. setMinimumContentWidth (header->getTotalWidth());
  41971. repaint();
  41972. updateColumnComponents();
  41973. }
  41974. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41975. {
  41976. setMinimumContentWidth (header->getTotalWidth());
  41977. repaint();
  41978. updateColumnComponents();
  41979. }
  41980. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41981. {
  41982. if (model != 0)
  41983. model->sortOrderChanged (header->getSortColumnId(),
  41984. header->isSortedForwards());
  41985. }
  41986. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41987. {
  41988. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41989. repaint();
  41990. }
  41991. void TableListBox::resized()
  41992. {
  41993. ListBox::resized();
  41994. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41995. setMinimumContentWidth (header->getTotalWidth());
  41996. }
  41997. void TableListBox::updateColumnComponents() const
  41998. {
  41999. const int firstRow = getRowContainingPosition (0, 0);
  42000. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42001. {
  42002. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42003. if (rowComp != 0)
  42004. rowComp->resized();
  42005. }
  42006. }
  42007. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  42008. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  42009. void TableListBoxModel::backgroundClicked() {}
  42010. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  42011. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  42012. void TableListBoxModel::selectedRowsChanged (int) {}
  42013. void TableListBoxModel::deleteKeyPressed (int) {}
  42014. void TableListBoxModel::returnKeyPressed (int) {}
  42015. void TableListBoxModel::listWasScrolled() {}
  42016. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  42017. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  42018. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42019. {
  42020. (void) existingComponentToUpdate;
  42021. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42022. return 0;
  42023. }
  42024. END_JUCE_NAMESPACE
  42025. /*** End of inlined file: juce_TableListBox.cpp ***/
  42026. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42027. BEGIN_JUCE_NAMESPACE
  42028. // a word or space that can't be broken down any further
  42029. struct TextAtom
  42030. {
  42031. String atomText;
  42032. float width;
  42033. int numChars;
  42034. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42035. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42036. const String getText (const juce_wchar passwordCharacter) const
  42037. {
  42038. if (passwordCharacter == 0)
  42039. return atomText;
  42040. else
  42041. return String::repeatedString (String::charToString (passwordCharacter),
  42042. atomText.length());
  42043. }
  42044. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42045. {
  42046. if (passwordCharacter == 0)
  42047. return atomText.substring (0, numChars);
  42048. else if (isNewLine())
  42049. return String::empty;
  42050. else
  42051. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42052. }
  42053. };
  42054. // a run of text with a single font and colour
  42055. class TextEditor::UniformTextSection
  42056. {
  42057. public:
  42058. UniformTextSection (const String& text,
  42059. const Font& font_,
  42060. const Colour& colour_,
  42061. const juce_wchar passwordCharacter)
  42062. : font (font_),
  42063. colour (colour_)
  42064. {
  42065. initialiseAtoms (text, passwordCharacter);
  42066. }
  42067. UniformTextSection (const UniformTextSection& other)
  42068. : font (other.font),
  42069. colour (other.colour)
  42070. {
  42071. atoms.ensureStorageAllocated (other.atoms.size());
  42072. for (int i = 0; i < other.atoms.size(); ++i)
  42073. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42074. }
  42075. ~UniformTextSection()
  42076. {
  42077. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42078. }
  42079. void clear()
  42080. {
  42081. for (int i = atoms.size(); --i >= 0;)
  42082. delete getAtom(i);
  42083. atoms.clear();
  42084. }
  42085. int getNumAtoms() const
  42086. {
  42087. return atoms.size();
  42088. }
  42089. TextAtom* getAtom (const int index) const throw()
  42090. {
  42091. return atoms.getUnchecked (index);
  42092. }
  42093. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42094. {
  42095. if (other.atoms.size() > 0)
  42096. {
  42097. TextAtom* const lastAtom = atoms.getLast();
  42098. int i = 0;
  42099. if (lastAtom != 0)
  42100. {
  42101. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42102. {
  42103. TextAtom* const first = other.getAtom(0);
  42104. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42105. {
  42106. lastAtom->atomText += first->atomText;
  42107. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42108. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42109. delete first;
  42110. ++i;
  42111. }
  42112. }
  42113. }
  42114. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42115. while (i < other.atoms.size())
  42116. {
  42117. atoms.add (other.getAtom(i));
  42118. ++i;
  42119. }
  42120. }
  42121. }
  42122. UniformTextSection* split (const int indexToBreakAt,
  42123. const juce_wchar passwordCharacter)
  42124. {
  42125. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42126. font, colour,
  42127. passwordCharacter);
  42128. int index = 0;
  42129. for (int i = 0; i < atoms.size(); ++i)
  42130. {
  42131. TextAtom* const atom = getAtom(i);
  42132. const int nextIndex = index + atom->numChars;
  42133. if (index == indexToBreakAt)
  42134. {
  42135. int j;
  42136. for (j = i; j < atoms.size(); ++j)
  42137. section2->atoms.add (getAtom (j));
  42138. for (j = atoms.size(); --j >= i;)
  42139. atoms.remove (j);
  42140. break;
  42141. }
  42142. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42143. {
  42144. TextAtom* const secondAtom = new TextAtom();
  42145. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42146. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42147. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42148. section2->atoms.add (secondAtom);
  42149. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42150. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42151. atom->numChars = (uint16) (indexToBreakAt - index);
  42152. int j;
  42153. for (j = i + 1; j < atoms.size(); ++j)
  42154. section2->atoms.add (getAtom (j));
  42155. for (j = atoms.size(); --j > i;)
  42156. atoms.remove (j);
  42157. break;
  42158. }
  42159. index = nextIndex;
  42160. }
  42161. return section2;
  42162. }
  42163. void appendAllText (String::Concatenator& concatenator) const
  42164. {
  42165. for (int i = 0; i < atoms.size(); ++i)
  42166. concatenator.append (getAtom(i)->atomText);
  42167. }
  42168. void appendSubstring (String::Concatenator& concatenator,
  42169. const Range<int>& range) const
  42170. {
  42171. int index = 0;
  42172. for (int i = 0; i < atoms.size(); ++i)
  42173. {
  42174. const TextAtom* const atom = getAtom (i);
  42175. const int nextIndex = index + atom->numChars;
  42176. if (range.getStart() < nextIndex)
  42177. {
  42178. if (range.getEnd() <= index)
  42179. break;
  42180. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42181. if (! r.isEmpty())
  42182. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42183. }
  42184. index = nextIndex;
  42185. }
  42186. }
  42187. int getTotalLength() const
  42188. {
  42189. int total = 0;
  42190. for (int i = atoms.size(); --i >= 0;)
  42191. total += getAtom(i)->numChars;
  42192. return total;
  42193. }
  42194. void setFont (const Font& newFont,
  42195. const juce_wchar passwordCharacter)
  42196. {
  42197. if (font != newFont)
  42198. {
  42199. font = newFont;
  42200. for (int i = atoms.size(); --i >= 0;)
  42201. {
  42202. TextAtom* const atom = atoms.getUnchecked(i);
  42203. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42204. }
  42205. }
  42206. }
  42207. Font font;
  42208. Colour colour;
  42209. private:
  42210. Array <TextAtom*> atoms;
  42211. void initialiseAtoms (const String& textToParse,
  42212. const juce_wchar passwordCharacter)
  42213. {
  42214. int i = 0;
  42215. const int len = textToParse.length();
  42216. const juce_wchar* const text = textToParse;
  42217. while (i < len)
  42218. {
  42219. int start = i;
  42220. // create a whitespace atom unless it starts with non-ws
  42221. if (CharacterFunctions::isWhitespace (text[i])
  42222. && text[i] != '\r'
  42223. && text[i] != '\n')
  42224. {
  42225. while (i < len
  42226. && CharacterFunctions::isWhitespace (text[i])
  42227. && text[i] != '\r'
  42228. && text[i] != '\n')
  42229. {
  42230. ++i;
  42231. }
  42232. }
  42233. else
  42234. {
  42235. if (text[i] == '\r')
  42236. {
  42237. ++i;
  42238. if ((i < len) && (text[i] == '\n'))
  42239. {
  42240. ++start;
  42241. ++i;
  42242. }
  42243. }
  42244. else if (text[i] == '\n')
  42245. {
  42246. ++i;
  42247. }
  42248. else
  42249. {
  42250. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42251. ++i;
  42252. }
  42253. }
  42254. TextAtom* const atom = new TextAtom();
  42255. atom->atomText = String (text + start, i - start);
  42256. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42257. atom->numChars = (uint16) (i - start);
  42258. atoms.add (atom);
  42259. }
  42260. }
  42261. UniformTextSection& operator= (const UniformTextSection& other);
  42262. JUCE_LEAK_DETECTOR (UniformTextSection);
  42263. };
  42264. class TextEditor::Iterator
  42265. {
  42266. public:
  42267. Iterator (const Array <UniformTextSection*>& sections_,
  42268. const float wordWrapWidth_,
  42269. const juce_wchar passwordCharacter_)
  42270. : indexInText (0),
  42271. lineY (0),
  42272. lineHeight (0),
  42273. maxDescent (0),
  42274. atomX (0),
  42275. atomRight (0),
  42276. atom (0),
  42277. currentSection (0),
  42278. sections (sections_),
  42279. sectionIndex (0),
  42280. atomIndex (0),
  42281. wordWrapWidth (wordWrapWidth_),
  42282. passwordCharacter (passwordCharacter_)
  42283. {
  42284. jassert (wordWrapWidth_ > 0);
  42285. if (sections.size() > 0)
  42286. {
  42287. currentSection = sections.getUnchecked (sectionIndex);
  42288. if (currentSection != 0)
  42289. beginNewLine();
  42290. }
  42291. }
  42292. Iterator (const Iterator& other)
  42293. : indexInText (other.indexInText),
  42294. lineY (other.lineY),
  42295. lineHeight (other.lineHeight),
  42296. maxDescent (other.maxDescent),
  42297. atomX (other.atomX),
  42298. atomRight (other.atomRight),
  42299. atom (other.atom),
  42300. currentSection (other.currentSection),
  42301. sections (other.sections),
  42302. sectionIndex (other.sectionIndex),
  42303. atomIndex (other.atomIndex),
  42304. wordWrapWidth (other.wordWrapWidth),
  42305. passwordCharacter (other.passwordCharacter),
  42306. tempAtom (other.tempAtom)
  42307. {
  42308. }
  42309. ~Iterator()
  42310. {
  42311. }
  42312. bool next()
  42313. {
  42314. if (atom == &tempAtom)
  42315. {
  42316. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42317. if (numRemaining > 0)
  42318. {
  42319. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42320. atomX = 0;
  42321. if (tempAtom.numChars > 0)
  42322. lineY += lineHeight;
  42323. indexInText += tempAtom.numChars;
  42324. GlyphArrangement g;
  42325. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42326. int split;
  42327. for (split = 0; split < g.getNumGlyphs(); ++split)
  42328. if (shouldWrap (g.getGlyph (split).getRight()))
  42329. break;
  42330. if (split > 0 && split <= numRemaining)
  42331. {
  42332. tempAtom.numChars = (uint16) split;
  42333. tempAtom.width = g.getGlyph (split - 1).getRight();
  42334. atomRight = atomX + tempAtom.width;
  42335. return true;
  42336. }
  42337. }
  42338. }
  42339. bool forceNewLine = false;
  42340. if (sectionIndex >= sections.size())
  42341. {
  42342. moveToEndOfLastAtom();
  42343. return false;
  42344. }
  42345. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42346. {
  42347. if (atomIndex >= currentSection->getNumAtoms())
  42348. {
  42349. if (++sectionIndex >= sections.size())
  42350. {
  42351. moveToEndOfLastAtom();
  42352. return false;
  42353. }
  42354. atomIndex = 0;
  42355. currentSection = sections.getUnchecked (sectionIndex);
  42356. }
  42357. else
  42358. {
  42359. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42360. if (! lastAtom->isWhitespace())
  42361. {
  42362. // handle the case where the last atom in a section is actually part of the same
  42363. // word as the first atom of the next section...
  42364. float right = atomRight + lastAtom->width;
  42365. float lineHeight2 = lineHeight;
  42366. float maxDescent2 = maxDescent;
  42367. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42368. {
  42369. const UniformTextSection* const s = sections.getUnchecked (section);
  42370. if (s->getNumAtoms() == 0)
  42371. break;
  42372. const TextAtom* const nextAtom = s->getAtom (0);
  42373. if (nextAtom->isWhitespace())
  42374. break;
  42375. right += nextAtom->width;
  42376. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42377. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42378. if (shouldWrap (right))
  42379. {
  42380. lineHeight = lineHeight2;
  42381. maxDescent = maxDescent2;
  42382. forceNewLine = true;
  42383. break;
  42384. }
  42385. if (s->getNumAtoms() > 1)
  42386. break;
  42387. }
  42388. }
  42389. }
  42390. }
  42391. if (atom != 0)
  42392. {
  42393. atomX = atomRight;
  42394. indexInText += atom->numChars;
  42395. if (atom->isNewLine())
  42396. beginNewLine();
  42397. }
  42398. atom = currentSection->getAtom (atomIndex);
  42399. atomRight = atomX + atom->width;
  42400. ++atomIndex;
  42401. if (shouldWrap (atomRight) || forceNewLine)
  42402. {
  42403. if (atom->isWhitespace())
  42404. {
  42405. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42406. atomRight = jmin (atomRight, wordWrapWidth);
  42407. }
  42408. else
  42409. {
  42410. atomRight = atom->width;
  42411. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42412. {
  42413. tempAtom = *atom;
  42414. tempAtom.width = 0;
  42415. tempAtom.numChars = 0;
  42416. atom = &tempAtom;
  42417. if (atomX > 0)
  42418. beginNewLine();
  42419. return next();
  42420. }
  42421. beginNewLine();
  42422. return true;
  42423. }
  42424. }
  42425. return true;
  42426. }
  42427. void beginNewLine()
  42428. {
  42429. atomX = 0;
  42430. lineY += lineHeight;
  42431. int tempSectionIndex = sectionIndex;
  42432. int tempAtomIndex = atomIndex;
  42433. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42434. lineHeight = section->font.getHeight();
  42435. maxDescent = section->font.getDescent();
  42436. float x = (atom != 0) ? atom->width : 0;
  42437. while (! shouldWrap (x))
  42438. {
  42439. if (tempSectionIndex >= sections.size())
  42440. break;
  42441. bool checkSize = false;
  42442. if (tempAtomIndex >= section->getNumAtoms())
  42443. {
  42444. if (++tempSectionIndex >= sections.size())
  42445. break;
  42446. tempAtomIndex = 0;
  42447. section = sections.getUnchecked (tempSectionIndex);
  42448. checkSize = true;
  42449. }
  42450. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42451. if (nextAtom == 0)
  42452. break;
  42453. x += nextAtom->width;
  42454. if (shouldWrap (x) || nextAtom->isNewLine())
  42455. break;
  42456. if (checkSize)
  42457. {
  42458. lineHeight = jmax (lineHeight, section->font.getHeight());
  42459. maxDescent = jmax (maxDescent, section->font.getDescent());
  42460. }
  42461. ++tempAtomIndex;
  42462. }
  42463. }
  42464. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42465. {
  42466. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42467. {
  42468. if (lastSection != currentSection)
  42469. {
  42470. lastSection = currentSection;
  42471. g.setColour (currentSection->colour);
  42472. g.setFont (currentSection->font);
  42473. }
  42474. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42475. GlyphArrangement ga;
  42476. ga.addLineOfText (currentSection->font,
  42477. atom->getTrimmedText (passwordCharacter),
  42478. atomX,
  42479. (float) roundToInt (lineY + lineHeight - maxDescent));
  42480. ga.draw (g);
  42481. }
  42482. }
  42483. void drawSelection (Graphics& g,
  42484. const Range<int>& selection) const
  42485. {
  42486. const int startX = roundToInt (indexToX (selection.getStart()));
  42487. const int endX = roundToInt (indexToX (selection.getEnd()));
  42488. const int y = roundToInt (lineY);
  42489. const int nextY = roundToInt (lineY + lineHeight);
  42490. g.fillRect (startX, y, endX - startX, nextY - y);
  42491. }
  42492. void drawSelectedText (Graphics& g,
  42493. const Range<int>& selection,
  42494. const Colour& selectedTextColour) const
  42495. {
  42496. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42497. {
  42498. GlyphArrangement ga;
  42499. ga.addLineOfText (currentSection->font,
  42500. atom->getTrimmedText (passwordCharacter),
  42501. atomX,
  42502. (float) roundToInt (lineY + lineHeight - maxDescent));
  42503. if (selection.getEnd() < indexInText + atom->numChars)
  42504. {
  42505. GlyphArrangement ga2 (ga);
  42506. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42507. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42508. g.setColour (currentSection->colour);
  42509. ga2.draw (g);
  42510. }
  42511. if (selection.getStart() > indexInText)
  42512. {
  42513. GlyphArrangement ga2 (ga);
  42514. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42515. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42516. g.setColour (currentSection->colour);
  42517. ga2.draw (g);
  42518. }
  42519. g.setColour (selectedTextColour);
  42520. ga.draw (g);
  42521. }
  42522. }
  42523. float indexToX (const int indexToFind) const
  42524. {
  42525. if (indexToFind <= indexInText)
  42526. return atomX;
  42527. if (indexToFind >= indexInText + atom->numChars)
  42528. return atomRight;
  42529. GlyphArrangement g;
  42530. g.addLineOfText (currentSection->font,
  42531. atom->getText (passwordCharacter),
  42532. atomX, 0.0f);
  42533. if (indexToFind - indexInText >= g.getNumGlyphs())
  42534. return atomRight;
  42535. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42536. }
  42537. int xToIndex (const float xToFind) const
  42538. {
  42539. if (xToFind <= atomX || atom->isNewLine())
  42540. return indexInText;
  42541. if (xToFind >= atomRight)
  42542. return indexInText + atom->numChars;
  42543. GlyphArrangement g;
  42544. g.addLineOfText (currentSection->font,
  42545. atom->getText (passwordCharacter),
  42546. atomX, 0.0f);
  42547. int j;
  42548. for (j = 0; j < g.getNumGlyphs(); ++j)
  42549. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42550. break;
  42551. return indexInText + j;
  42552. }
  42553. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42554. {
  42555. while (next())
  42556. {
  42557. if (indexInText + atom->numChars > index)
  42558. {
  42559. cx = indexToX (index);
  42560. cy = lineY;
  42561. lineHeight_ = lineHeight;
  42562. return true;
  42563. }
  42564. }
  42565. cx = atomX;
  42566. cy = lineY;
  42567. lineHeight_ = lineHeight;
  42568. return false;
  42569. }
  42570. int indexInText;
  42571. float lineY, lineHeight, maxDescent;
  42572. float atomX, atomRight;
  42573. const TextAtom* atom;
  42574. const UniformTextSection* currentSection;
  42575. private:
  42576. const Array <UniformTextSection*>& sections;
  42577. int sectionIndex, atomIndex;
  42578. const float wordWrapWidth;
  42579. const juce_wchar passwordCharacter;
  42580. TextAtom tempAtom;
  42581. Iterator& operator= (const Iterator&);
  42582. void moveToEndOfLastAtom()
  42583. {
  42584. if (atom != 0)
  42585. {
  42586. atomX = atomRight;
  42587. if (atom->isNewLine())
  42588. {
  42589. atomX = 0.0f;
  42590. lineY += lineHeight;
  42591. }
  42592. }
  42593. }
  42594. bool shouldWrap (const float x) const
  42595. {
  42596. return (x - 0.0001f) >= wordWrapWidth;
  42597. }
  42598. JUCE_LEAK_DETECTOR (Iterator);
  42599. };
  42600. class TextEditor::InsertAction : public UndoableAction
  42601. {
  42602. public:
  42603. InsertAction (TextEditor& owner_,
  42604. const String& text_,
  42605. const int insertIndex_,
  42606. const Font& font_,
  42607. const Colour& colour_,
  42608. const int oldCaretPos_,
  42609. const int newCaretPos_)
  42610. : owner (owner_),
  42611. text (text_),
  42612. insertIndex (insertIndex_),
  42613. oldCaretPos (oldCaretPos_),
  42614. newCaretPos (newCaretPos_),
  42615. font (font_),
  42616. colour (colour_)
  42617. {
  42618. }
  42619. bool perform()
  42620. {
  42621. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42622. return true;
  42623. }
  42624. bool undo()
  42625. {
  42626. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42627. return true;
  42628. }
  42629. int getSizeInUnits()
  42630. {
  42631. return text.length() + 16;
  42632. }
  42633. private:
  42634. TextEditor& owner;
  42635. const String text;
  42636. const int insertIndex, oldCaretPos, newCaretPos;
  42637. const Font font;
  42638. const Colour colour;
  42639. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42640. };
  42641. class TextEditor::RemoveAction : public UndoableAction
  42642. {
  42643. public:
  42644. RemoveAction (TextEditor& owner_,
  42645. const Range<int> range_,
  42646. const int oldCaretPos_,
  42647. const int newCaretPos_,
  42648. const Array <UniformTextSection*>& removedSections_)
  42649. : owner (owner_),
  42650. range (range_),
  42651. oldCaretPos (oldCaretPos_),
  42652. newCaretPos (newCaretPos_),
  42653. removedSections (removedSections_)
  42654. {
  42655. }
  42656. ~RemoveAction()
  42657. {
  42658. for (int i = removedSections.size(); --i >= 0;)
  42659. {
  42660. UniformTextSection* const section = removedSections.getUnchecked (i);
  42661. section->clear();
  42662. delete section;
  42663. }
  42664. }
  42665. bool perform()
  42666. {
  42667. owner.remove (range, 0, newCaretPos);
  42668. return true;
  42669. }
  42670. bool undo()
  42671. {
  42672. owner.reinsert (range.getStart(), removedSections);
  42673. owner.moveCursorTo (oldCaretPos, false);
  42674. return true;
  42675. }
  42676. int getSizeInUnits()
  42677. {
  42678. int n = 0;
  42679. for (int i = removedSections.size(); --i >= 0;)
  42680. n += removedSections.getUnchecked (i)->getTotalLength();
  42681. return n + 16;
  42682. }
  42683. private:
  42684. TextEditor& owner;
  42685. const Range<int> range;
  42686. const int oldCaretPos, newCaretPos;
  42687. Array <UniformTextSection*> removedSections;
  42688. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42689. };
  42690. class TextEditor::TextHolderComponent : public Component,
  42691. public Timer,
  42692. public ValueListener
  42693. {
  42694. public:
  42695. TextHolderComponent (TextEditor& owner_)
  42696. : owner (owner_)
  42697. {
  42698. setWantsKeyboardFocus (false);
  42699. setInterceptsMouseClicks (false, true);
  42700. owner.getTextValue().addListener (this);
  42701. }
  42702. ~TextHolderComponent()
  42703. {
  42704. owner.getTextValue().removeListener (this);
  42705. }
  42706. void paint (Graphics& g)
  42707. {
  42708. owner.drawContent (g);
  42709. }
  42710. void timerCallback()
  42711. {
  42712. owner.timerCallbackInt();
  42713. }
  42714. const MouseCursor getMouseCursor()
  42715. {
  42716. return owner.getMouseCursor();
  42717. }
  42718. void valueChanged (Value&)
  42719. {
  42720. owner.textWasChangedByValue();
  42721. }
  42722. private:
  42723. TextEditor& owner;
  42724. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42725. };
  42726. class TextEditorViewport : public Viewport
  42727. {
  42728. public:
  42729. TextEditorViewport (TextEditor* const owner_)
  42730. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42731. {
  42732. }
  42733. ~TextEditorViewport()
  42734. {
  42735. }
  42736. void visibleAreaChanged (int, int, int, int)
  42737. {
  42738. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42739. // appear and disappear, causing the wrap width to change.
  42740. {
  42741. const float wordWrapWidth = owner->getWordWrapWidth();
  42742. if (wordWrapWidth != lastWordWrapWidth)
  42743. {
  42744. lastWordWrapWidth = wordWrapWidth;
  42745. rentrant = true;
  42746. owner->updateTextHolderSize();
  42747. rentrant = false;
  42748. }
  42749. }
  42750. }
  42751. private:
  42752. TextEditor* const owner;
  42753. float lastWordWrapWidth;
  42754. bool rentrant;
  42755. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42756. };
  42757. namespace TextEditorDefs
  42758. {
  42759. const int flashSpeedIntervalMs = 380;
  42760. const int textChangeMessageId = 0x10003001;
  42761. const int returnKeyMessageId = 0x10003002;
  42762. const int escapeKeyMessageId = 0x10003003;
  42763. const int focusLossMessageId = 0x10003004;
  42764. const int maxActionsPerTransaction = 100;
  42765. int getCharacterCategory (const juce_wchar character)
  42766. {
  42767. return CharacterFunctions::isLetterOrDigit (character)
  42768. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42769. }
  42770. }
  42771. TextEditor::TextEditor (const String& name,
  42772. const juce_wchar passwordCharacter_)
  42773. : Component (name),
  42774. borderSize (1, 1, 1, 3),
  42775. readOnly (false),
  42776. multiline (false),
  42777. wordWrap (false),
  42778. returnKeyStartsNewLine (false),
  42779. caretVisible (true),
  42780. popupMenuEnabled (true),
  42781. selectAllTextWhenFocused (false),
  42782. scrollbarVisible (true),
  42783. wasFocused (false),
  42784. caretFlashState (true),
  42785. keepCursorOnScreen (true),
  42786. tabKeyUsed (false),
  42787. menuActive (false),
  42788. valueTextNeedsUpdating (false),
  42789. cursorX (0),
  42790. cursorY (0),
  42791. cursorHeight (0),
  42792. maxTextLength (0),
  42793. leftIndent (4),
  42794. topIndent (4),
  42795. lastTransactionTime (0),
  42796. currentFont (14.0f),
  42797. totalNumChars (0),
  42798. caretPosition (0),
  42799. passwordCharacter (passwordCharacter_),
  42800. dragType (notDragging)
  42801. {
  42802. setOpaque (true);
  42803. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42804. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42805. viewport->setWantsKeyboardFocus (false);
  42806. viewport->setScrollBarsShown (false, false);
  42807. setMouseCursor (MouseCursor::IBeamCursor);
  42808. setWantsKeyboardFocus (true);
  42809. }
  42810. TextEditor::~TextEditor()
  42811. {
  42812. textValue.referTo (Value());
  42813. clearInternal (0);
  42814. viewport = 0;
  42815. textHolder = 0;
  42816. }
  42817. void TextEditor::newTransaction()
  42818. {
  42819. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42820. undoManager.beginNewTransaction();
  42821. }
  42822. void TextEditor::doUndoRedo (const bool isRedo)
  42823. {
  42824. if (! isReadOnly())
  42825. {
  42826. if (isRedo ? undoManager.redo()
  42827. : undoManager.undo())
  42828. {
  42829. scrollToMakeSureCursorIsVisible();
  42830. repaint();
  42831. textChanged();
  42832. }
  42833. }
  42834. }
  42835. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42836. const bool shouldWordWrap)
  42837. {
  42838. if (multiline != shouldBeMultiLine
  42839. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42840. {
  42841. multiline = shouldBeMultiLine;
  42842. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42843. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42844. scrollbarVisible && multiline);
  42845. viewport->setViewPosition (0, 0);
  42846. resized();
  42847. scrollToMakeSureCursorIsVisible();
  42848. }
  42849. }
  42850. bool TextEditor::isMultiLine() const
  42851. {
  42852. return multiline;
  42853. }
  42854. void TextEditor::setScrollbarsShown (bool shown)
  42855. {
  42856. if (scrollbarVisible != shown)
  42857. {
  42858. scrollbarVisible = shown;
  42859. shown = shown && isMultiLine();
  42860. viewport->setScrollBarsShown (shown, shown);
  42861. }
  42862. }
  42863. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42864. {
  42865. if (readOnly != shouldBeReadOnly)
  42866. {
  42867. readOnly = shouldBeReadOnly;
  42868. enablementChanged();
  42869. }
  42870. }
  42871. bool TextEditor::isReadOnly() const
  42872. {
  42873. return readOnly || ! isEnabled();
  42874. }
  42875. bool TextEditor::isTextInputActive() const
  42876. {
  42877. return ! isReadOnly();
  42878. }
  42879. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42880. {
  42881. returnKeyStartsNewLine = shouldStartNewLine;
  42882. }
  42883. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42884. {
  42885. tabKeyUsed = shouldTabKeyBeUsed;
  42886. }
  42887. void TextEditor::setPopupMenuEnabled (const bool b)
  42888. {
  42889. popupMenuEnabled = b;
  42890. }
  42891. void TextEditor::setSelectAllWhenFocused (const bool b)
  42892. {
  42893. selectAllTextWhenFocused = b;
  42894. }
  42895. const Font TextEditor::getFont() const
  42896. {
  42897. return currentFont;
  42898. }
  42899. void TextEditor::setFont (const Font& newFont)
  42900. {
  42901. currentFont = newFont;
  42902. scrollToMakeSureCursorIsVisible();
  42903. }
  42904. void TextEditor::applyFontToAllText (const Font& newFont)
  42905. {
  42906. currentFont = newFont;
  42907. const Colour overallColour (findColour (textColourId));
  42908. for (int i = sections.size(); --i >= 0;)
  42909. {
  42910. UniformTextSection* const uts = sections.getUnchecked (i);
  42911. uts->setFont (newFont, passwordCharacter);
  42912. uts->colour = overallColour;
  42913. }
  42914. coalesceSimilarSections();
  42915. updateTextHolderSize();
  42916. scrollToMakeSureCursorIsVisible();
  42917. repaint();
  42918. }
  42919. void TextEditor::colourChanged()
  42920. {
  42921. setOpaque (findColour (backgroundColourId).isOpaque());
  42922. repaint();
  42923. }
  42924. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42925. {
  42926. caretVisible = shouldCaretBeVisible;
  42927. if (shouldCaretBeVisible)
  42928. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42929. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42930. : MouseCursor::NormalCursor);
  42931. }
  42932. void TextEditor::setInputRestrictions (const int maxLen,
  42933. const String& chars)
  42934. {
  42935. maxTextLength = jmax (0, maxLen);
  42936. allowedCharacters = chars;
  42937. }
  42938. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42939. {
  42940. textToShowWhenEmpty = text;
  42941. colourForTextWhenEmpty = colourToUse;
  42942. }
  42943. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42944. {
  42945. if (passwordCharacter != newPasswordCharacter)
  42946. {
  42947. passwordCharacter = newPasswordCharacter;
  42948. resized();
  42949. repaint();
  42950. }
  42951. }
  42952. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42953. {
  42954. viewport->setScrollBarThickness (newThicknessPixels);
  42955. }
  42956. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42957. {
  42958. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42959. }
  42960. void TextEditor::clear()
  42961. {
  42962. clearInternal (0);
  42963. updateTextHolderSize();
  42964. undoManager.clearUndoHistory();
  42965. }
  42966. void TextEditor::setText (const String& newText,
  42967. const bool sendTextChangeMessage)
  42968. {
  42969. const int newLength = newText.length();
  42970. if (newLength != getTotalNumChars() || getText() != newText)
  42971. {
  42972. const int oldCursorPos = caretPosition;
  42973. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42974. clearInternal (0);
  42975. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42976. // if you're adding text with line-feeds to a single-line text editor, it
  42977. // ain't gonna look right!
  42978. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42979. if (cursorWasAtEnd && ! isMultiLine())
  42980. moveCursorTo (getTotalNumChars(), false);
  42981. else
  42982. moveCursorTo (oldCursorPos, false);
  42983. if (sendTextChangeMessage)
  42984. textChanged();
  42985. updateTextHolderSize();
  42986. scrollToMakeSureCursorIsVisible();
  42987. undoManager.clearUndoHistory();
  42988. repaint();
  42989. }
  42990. }
  42991. Value& TextEditor::getTextValue()
  42992. {
  42993. if (valueTextNeedsUpdating)
  42994. {
  42995. valueTextNeedsUpdating = false;
  42996. textValue = getText();
  42997. }
  42998. return textValue;
  42999. }
  43000. void TextEditor::textWasChangedByValue()
  43001. {
  43002. if (textValue.getValueSource().getReferenceCount() > 1)
  43003. setText (textValue.getValue());
  43004. }
  43005. void TextEditor::textChanged()
  43006. {
  43007. updateTextHolderSize();
  43008. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43009. if (textValue.getValueSource().getReferenceCount() > 1)
  43010. {
  43011. valueTextNeedsUpdating = false;
  43012. textValue = getText();
  43013. }
  43014. }
  43015. void TextEditor::returnPressed()
  43016. {
  43017. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43018. }
  43019. void TextEditor::escapePressed()
  43020. {
  43021. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43022. }
  43023. void TextEditor::addListener (TextEditorListener* const newListener)
  43024. {
  43025. listeners.add (newListener);
  43026. }
  43027. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  43028. {
  43029. listeners.remove (listenerToRemove);
  43030. }
  43031. void TextEditor::timerCallbackInt()
  43032. {
  43033. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43034. if (caretFlashState != newState)
  43035. {
  43036. caretFlashState = newState;
  43037. if (caretFlashState)
  43038. wasFocused = true;
  43039. if (caretVisible
  43040. && hasKeyboardFocus (false)
  43041. && ! isReadOnly())
  43042. {
  43043. repaintCaret();
  43044. }
  43045. }
  43046. const unsigned int now = Time::getApproximateMillisecondCounter();
  43047. if (now > lastTransactionTime + 200)
  43048. newTransaction();
  43049. }
  43050. void TextEditor::repaintCaret()
  43051. {
  43052. if (! findColour (caretColourId).isTransparent())
  43053. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43054. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43055. 4,
  43056. roundToInt (cursorHeight) + 2);
  43057. }
  43058. void TextEditor::repaintText (const Range<int>& range)
  43059. {
  43060. if (! range.isEmpty())
  43061. {
  43062. float x = 0, y = 0, lh = currentFont.getHeight();
  43063. const float wordWrapWidth = getWordWrapWidth();
  43064. if (wordWrapWidth > 0)
  43065. {
  43066. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43067. i.getCharPosition (range.getStart(), x, y, lh);
  43068. const int y1 = (int) y;
  43069. int y2;
  43070. if (range.getEnd() >= getTotalNumChars())
  43071. {
  43072. y2 = textHolder->getHeight();
  43073. }
  43074. else
  43075. {
  43076. i.getCharPosition (range.getEnd(), x, y, lh);
  43077. y2 = (int) (y + lh * 2.0f);
  43078. }
  43079. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43080. }
  43081. }
  43082. }
  43083. void TextEditor::moveCaret (int newCaretPos)
  43084. {
  43085. if (newCaretPos < 0)
  43086. newCaretPos = 0;
  43087. else if (newCaretPos > getTotalNumChars())
  43088. newCaretPos = getTotalNumChars();
  43089. if (newCaretPos != getCaretPosition())
  43090. {
  43091. repaintCaret();
  43092. caretFlashState = true;
  43093. caretPosition = newCaretPos;
  43094. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43095. scrollToMakeSureCursorIsVisible();
  43096. repaintCaret();
  43097. }
  43098. }
  43099. void TextEditor::setCaretPosition (const int newIndex)
  43100. {
  43101. moveCursorTo (newIndex, false);
  43102. }
  43103. int TextEditor::getCaretPosition() const
  43104. {
  43105. return caretPosition;
  43106. }
  43107. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43108. const int desiredCaretY)
  43109. {
  43110. updateCaretPosition();
  43111. int vx = roundToInt (cursorX) - desiredCaretX;
  43112. int vy = roundToInt (cursorY) - desiredCaretY;
  43113. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43114. {
  43115. vx += desiredCaretX - proportionOfWidth (0.2f);
  43116. }
  43117. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43118. {
  43119. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43120. }
  43121. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43122. if (! isMultiLine())
  43123. {
  43124. vy = viewport->getViewPositionY();
  43125. }
  43126. else
  43127. {
  43128. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43129. const int curH = roundToInt (cursorHeight);
  43130. if (desiredCaretY < 0)
  43131. {
  43132. vy = jmax (0, desiredCaretY + vy);
  43133. }
  43134. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43135. {
  43136. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43137. }
  43138. }
  43139. viewport->setViewPosition (vx, vy);
  43140. }
  43141. const Rectangle<int> TextEditor::getCaretRectangle()
  43142. {
  43143. updateCaretPosition();
  43144. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43145. roundToInt (cursorY) - viewport->getY(),
  43146. 1, roundToInt (cursorHeight));
  43147. }
  43148. float TextEditor::getWordWrapWidth() const
  43149. {
  43150. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43151. : 1.0e10f;
  43152. }
  43153. void TextEditor::updateTextHolderSize()
  43154. {
  43155. const float wordWrapWidth = getWordWrapWidth();
  43156. if (wordWrapWidth > 0)
  43157. {
  43158. float maxWidth = 0.0f;
  43159. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43160. while (i.next())
  43161. maxWidth = jmax (maxWidth, i.atomRight);
  43162. const int w = leftIndent + roundToInt (maxWidth);
  43163. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43164. currentFont.getHeight()));
  43165. textHolder->setSize (w + 1, h + 1);
  43166. }
  43167. }
  43168. int TextEditor::getTextWidth() const
  43169. {
  43170. return textHolder->getWidth();
  43171. }
  43172. int TextEditor::getTextHeight() const
  43173. {
  43174. return textHolder->getHeight();
  43175. }
  43176. void TextEditor::setIndents (const int newLeftIndent,
  43177. const int newTopIndent)
  43178. {
  43179. leftIndent = newLeftIndent;
  43180. topIndent = newTopIndent;
  43181. }
  43182. void TextEditor::setBorder (const BorderSize& border)
  43183. {
  43184. borderSize = border;
  43185. resized();
  43186. }
  43187. const BorderSize TextEditor::getBorder() const
  43188. {
  43189. return borderSize;
  43190. }
  43191. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43192. {
  43193. keepCursorOnScreen = shouldScrollToShowCursor;
  43194. }
  43195. void TextEditor::updateCaretPosition()
  43196. {
  43197. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43198. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43199. }
  43200. void TextEditor::scrollToMakeSureCursorIsVisible()
  43201. {
  43202. updateCaretPosition();
  43203. if (keepCursorOnScreen)
  43204. {
  43205. int x = viewport->getViewPositionX();
  43206. int y = viewport->getViewPositionY();
  43207. const int relativeCursorX = roundToInt (cursorX) - x;
  43208. const int relativeCursorY = roundToInt (cursorY) - y;
  43209. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43210. {
  43211. x += relativeCursorX - proportionOfWidth (0.2f);
  43212. }
  43213. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43214. {
  43215. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43216. }
  43217. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43218. if (! isMultiLine())
  43219. {
  43220. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43221. }
  43222. else
  43223. {
  43224. const int curH = roundToInt (cursorHeight);
  43225. if (relativeCursorY < 0)
  43226. {
  43227. y = jmax (0, relativeCursorY + y);
  43228. }
  43229. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43230. {
  43231. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43232. }
  43233. }
  43234. viewport->setViewPosition (x, y);
  43235. }
  43236. }
  43237. void TextEditor::moveCursorTo (const int newPosition,
  43238. const bool isSelecting)
  43239. {
  43240. if (isSelecting)
  43241. {
  43242. moveCaret (newPosition);
  43243. const Range<int> oldSelection (selection);
  43244. if (dragType == notDragging)
  43245. {
  43246. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43247. dragType = draggingSelectionStart;
  43248. else
  43249. dragType = draggingSelectionEnd;
  43250. }
  43251. if (dragType == draggingSelectionStart)
  43252. {
  43253. if (getCaretPosition() >= selection.getEnd())
  43254. dragType = draggingSelectionEnd;
  43255. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43256. }
  43257. else
  43258. {
  43259. if (getCaretPosition() < selection.getStart())
  43260. dragType = draggingSelectionStart;
  43261. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43262. }
  43263. repaintText (selection.getUnionWith (oldSelection));
  43264. }
  43265. else
  43266. {
  43267. dragType = notDragging;
  43268. repaintText (selection);
  43269. moveCaret (newPosition);
  43270. selection = Range<int>::emptyRange (getCaretPosition());
  43271. }
  43272. }
  43273. int TextEditor::getTextIndexAt (const int x,
  43274. const int y)
  43275. {
  43276. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43277. (float) (y + viewport->getViewPositionY() - topIndent));
  43278. }
  43279. void TextEditor::insertTextAtCaret (const String& newText_)
  43280. {
  43281. String newText (newText_);
  43282. if (allowedCharacters.isNotEmpty())
  43283. newText = newText.retainCharacters (allowedCharacters);
  43284. if ((! returnKeyStartsNewLine) && newText == "\n")
  43285. {
  43286. returnPressed();
  43287. return;
  43288. }
  43289. if (! isMultiLine())
  43290. newText = newText.replaceCharacters ("\r\n", " ");
  43291. else
  43292. newText = newText.replace ("\r\n", "\n");
  43293. const int newCaretPos = selection.getStart() + newText.length();
  43294. const int insertIndex = selection.getStart();
  43295. remove (selection, getUndoManager(),
  43296. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43297. if (maxTextLength > 0)
  43298. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43299. if (newText.isNotEmpty())
  43300. insert (newText,
  43301. insertIndex,
  43302. currentFont,
  43303. findColour (textColourId),
  43304. getUndoManager(),
  43305. newCaretPos);
  43306. textChanged();
  43307. }
  43308. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43309. {
  43310. moveCursorTo (newSelection.getStart(), false);
  43311. moveCursorTo (newSelection.getEnd(), true);
  43312. }
  43313. void TextEditor::copy()
  43314. {
  43315. if (passwordCharacter == 0)
  43316. {
  43317. const String selectedText (getHighlightedText());
  43318. if (selectedText.isNotEmpty())
  43319. SystemClipboard::copyTextToClipboard (selectedText);
  43320. }
  43321. }
  43322. void TextEditor::paste()
  43323. {
  43324. if (! isReadOnly())
  43325. {
  43326. const String clip (SystemClipboard::getTextFromClipboard());
  43327. if (clip.isNotEmpty())
  43328. insertTextAtCaret (clip);
  43329. }
  43330. }
  43331. void TextEditor::cut()
  43332. {
  43333. if (! isReadOnly())
  43334. {
  43335. moveCaret (selection.getEnd());
  43336. insertTextAtCaret (String::empty);
  43337. }
  43338. }
  43339. void TextEditor::drawContent (Graphics& g)
  43340. {
  43341. const float wordWrapWidth = getWordWrapWidth();
  43342. if (wordWrapWidth > 0)
  43343. {
  43344. g.setOrigin (leftIndent, topIndent);
  43345. const Rectangle<int> clip (g.getClipBounds());
  43346. Colour selectedTextColour;
  43347. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43348. while (i.lineY + 200.0 < clip.getY() && i.next())
  43349. {}
  43350. if (! selection.isEmpty())
  43351. {
  43352. g.setColour (findColour (highlightColourId)
  43353. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43354. selectedTextColour = findColour (highlightedTextColourId);
  43355. Iterator i2 (i);
  43356. while (i2.next() && i2.lineY < clip.getBottom())
  43357. {
  43358. if (i2.lineY + i2.lineHeight >= clip.getY()
  43359. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43360. {
  43361. i2.drawSelection (g, selection);
  43362. }
  43363. }
  43364. }
  43365. const UniformTextSection* lastSection = 0;
  43366. while (i.next() && i.lineY < clip.getBottom())
  43367. {
  43368. if (i.lineY + i.lineHeight >= clip.getY())
  43369. {
  43370. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43371. {
  43372. i.drawSelectedText (g, selection, selectedTextColour);
  43373. lastSection = 0;
  43374. }
  43375. else
  43376. {
  43377. i.draw (g, lastSection);
  43378. }
  43379. }
  43380. }
  43381. }
  43382. }
  43383. void TextEditor::paint (Graphics& g)
  43384. {
  43385. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43386. }
  43387. void TextEditor::paintOverChildren (Graphics& g)
  43388. {
  43389. if (caretFlashState
  43390. && hasKeyboardFocus (false)
  43391. && caretVisible
  43392. && ! isReadOnly())
  43393. {
  43394. g.setColour (findColour (caretColourId));
  43395. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43396. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43397. 2.0f, cursorHeight);
  43398. }
  43399. if (textToShowWhenEmpty.isNotEmpty()
  43400. && (! hasKeyboardFocus (false))
  43401. && getTotalNumChars() == 0)
  43402. {
  43403. g.setColour (colourForTextWhenEmpty);
  43404. g.setFont (getFont());
  43405. if (isMultiLine())
  43406. {
  43407. g.drawText (textToShowWhenEmpty,
  43408. 0, 0, getWidth(), getHeight(),
  43409. Justification::centred, true);
  43410. }
  43411. else
  43412. {
  43413. g.drawText (textToShowWhenEmpty,
  43414. leftIndent, topIndent,
  43415. viewport->getWidth() - leftIndent,
  43416. viewport->getHeight() - topIndent,
  43417. Justification::centredLeft, true);
  43418. }
  43419. }
  43420. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43421. }
  43422. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43423. {
  43424. public:
  43425. TextEditorMenuPerformer (TextEditor* const editor_)
  43426. : editor (editor_)
  43427. {
  43428. }
  43429. void modalStateFinished (int returnValue)
  43430. {
  43431. if (editor != 0 && returnValue != 0)
  43432. editor->performPopupMenuAction (returnValue);
  43433. }
  43434. private:
  43435. Component::SafePointer<TextEditor> editor;
  43436. JUCE_DECLARE_NON_COPYABLE (TextEditorMenuPerformer);
  43437. };
  43438. void TextEditor::mouseDown (const MouseEvent& e)
  43439. {
  43440. beginDragAutoRepeat (100);
  43441. newTransaction();
  43442. if (wasFocused || ! selectAllTextWhenFocused)
  43443. {
  43444. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43445. {
  43446. moveCursorTo (getTextIndexAt (e.x, e.y),
  43447. e.mods.isShiftDown());
  43448. }
  43449. else
  43450. {
  43451. PopupMenu m;
  43452. m.setLookAndFeel (&getLookAndFeel());
  43453. addPopupMenuItems (m, &e);
  43454. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43455. }
  43456. }
  43457. }
  43458. void TextEditor::mouseDrag (const MouseEvent& e)
  43459. {
  43460. if (wasFocused || ! selectAllTextWhenFocused)
  43461. {
  43462. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43463. {
  43464. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43465. }
  43466. }
  43467. }
  43468. void TextEditor::mouseUp (const MouseEvent& e)
  43469. {
  43470. newTransaction();
  43471. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43472. if (wasFocused || ! selectAllTextWhenFocused)
  43473. {
  43474. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43475. {
  43476. moveCaret (getTextIndexAt (e.x, e.y));
  43477. }
  43478. }
  43479. wasFocused = true;
  43480. }
  43481. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43482. {
  43483. int tokenEnd = getTextIndexAt (e.x, e.y);
  43484. int tokenStart = tokenEnd;
  43485. if (e.getNumberOfClicks() > 3)
  43486. {
  43487. tokenStart = 0;
  43488. tokenEnd = getTotalNumChars();
  43489. }
  43490. else
  43491. {
  43492. const String t (getText());
  43493. const int totalLength = getTotalNumChars();
  43494. while (tokenEnd < totalLength)
  43495. {
  43496. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43497. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43498. ++tokenEnd;
  43499. else
  43500. break;
  43501. }
  43502. tokenStart = tokenEnd;
  43503. while (tokenStart > 0)
  43504. {
  43505. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43506. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43507. --tokenStart;
  43508. else
  43509. break;
  43510. }
  43511. if (e.getNumberOfClicks() > 2)
  43512. {
  43513. while (tokenEnd < totalLength)
  43514. {
  43515. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43516. ++tokenEnd;
  43517. else
  43518. break;
  43519. }
  43520. while (tokenStart > 0)
  43521. {
  43522. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43523. --tokenStart;
  43524. else
  43525. break;
  43526. }
  43527. }
  43528. }
  43529. moveCursorTo (tokenEnd, false);
  43530. moveCursorTo (tokenStart, true);
  43531. }
  43532. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43533. {
  43534. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43535. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43536. }
  43537. bool TextEditor::keyPressed (const KeyPress& key)
  43538. {
  43539. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43540. return false;
  43541. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43542. if (key.isKeyCode (KeyPress::leftKey)
  43543. || key.isKeyCode (KeyPress::upKey))
  43544. {
  43545. newTransaction();
  43546. int newPos;
  43547. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43548. newPos = indexAtPosition (cursorX, cursorY - 1);
  43549. else if (moveInWholeWordSteps)
  43550. newPos = findWordBreakBefore (getCaretPosition());
  43551. else
  43552. newPos = getCaretPosition() - 1;
  43553. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43554. }
  43555. else if (key.isKeyCode (KeyPress::rightKey)
  43556. || key.isKeyCode (KeyPress::downKey))
  43557. {
  43558. newTransaction();
  43559. int newPos;
  43560. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43561. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43562. else if (moveInWholeWordSteps)
  43563. newPos = findWordBreakAfter (getCaretPosition());
  43564. else
  43565. newPos = getCaretPosition() + 1;
  43566. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43567. }
  43568. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43569. {
  43570. newTransaction();
  43571. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43572. key.getModifiers().isShiftDown());
  43573. }
  43574. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43575. {
  43576. newTransaction();
  43577. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43578. key.getModifiers().isShiftDown());
  43579. }
  43580. else if (key.isKeyCode (KeyPress::homeKey))
  43581. {
  43582. newTransaction();
  43583. if (isMultiLine() && ! moveInWholeWordSteps)
  43584. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43585. key.getModifiers().isShiftDown());
  43586. else
  43587. moveCursorTo (0, key.getModifiers().isShiftDown());
  43588. }
  43589. else if (key.isKeyCode (KeyPress::endKey))
  43590. {
  43591. newTransaction();
  43592. if (isMultiLine() && ! moveInWholeWordSteps)
  43593. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43594. key.getModifiers().isShiftDown());
  43595. else
  43596. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43597. }
  43598. else if (key.isKeyCode (KeyPress::backspaceKey))
  43599. {
  43600. if (moveInWholeWordSteps)
  43601. {
  43602. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43603. }
  43604. else
  43605. {
  43606. if (selection.isEmpty() && selection.getStart() > 0)
  43607. selection.setStart (selection.getEnd() - 1);
  43608. }
  43609. cut();
  43610. }
  43611. else if (key.isKeyCode (KeyPress::deleteKey))
  43612. {
  43613. if (key.getModifiers().isShiftDown())
  43614. copy();
  43615. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43616. selection.setEnd (selection.getStart() + 1);
  43617. cut();
  43618. }
  43619. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43620. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43621. {
  43622. newTransaction();
  43623. copy();
  43624. }
  43625. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43626. {
  43627. newTransaction();
  43628. copy();
  43629. cut();
  43630. }
  43631. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43632. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43633. {
  43634. newTransaction();
  43635. paste();
  43636. }
  43637. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43638. {
  43639. newTransaction();
  43640. doUndoRedo (false);
  43641. }
  43642. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43643. {
  43644. newTransaction();
  43645. doUndoRedo (true);
  43646. }
  43647. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43648. {
  43649. newTransaction();
  43650. moveCursorTo (getTotalNumChars(), false);
  43651. moveCursorTo (0, true);
  43652. }
  43653. else if (key == KeyPress::returnKey)
  43654. {
  43655. newTransaction();
  43656. insertTextAtCaret ("\n");
  43657. }
  43658. else if (key.isKeyCode (KeyPress::escapeKey))
  43659. {
  43660. newTransaction();
  43661. moveCursorTo (getCaretPosition(), false);
  43662. escapePressed();
  43663. }
  43664. else if (key.getTextCharacter() >= ' '
  43665. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43666. {
  43667. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43668. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43669. }
  43670. else
  43671. {
  43672. return false;
  43673. }
  43674. return true;
  43675. }
  43676. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43677. {
  43678. if (! isKeyDown)
  43679. return false;
  43680. #if JUCE_WINDOWS
  43681. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43682. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43683. #endif
  43684. // (overridden to avoid forwarding key events to the parent)
  43685. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43686. }
  43687. const int baseMenuItemID = 0x7fff0000;
  43688. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43689. {
  43690. const bool writable = ! isReadOnly();
  43691. if (passwordCharacter == 0)
  43692. {
  43693. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43694. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43695. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43696. }
  43697. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43698. m.addSeparator();
  43699. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43700. m.addSeparator();
  43701. if (getUndoManager() != 0)
  43702. {
  43703. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43704. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43705. }
  43706. }
  43707. void TextEditor::performPopupMenuAction (const int menuItemID)
  43708. {
  43709. switch (menuItemID)
  43710. {
  43711. case baseMenuItemID + 1:
  43712. copy();
  43713. cut();
  43714. break;
  43715. case baseMenuItemID + 2:
  43716. copy();
  43717. break;
  43718. case baseMenuItemID + 3:
  43719. paste();
  43720. break;
  43721. case baseMenuItemID + 4:
  43722. cut();
  43723. break;
  43724. case baseMenuItemID + 5:
  43725. moveCursorTo (getTotalNumChars(), false);
  43726. moveCursorTo (0, true);
  43727. break;
  43728. case baseMenuItemID + 6:
  43729. doUndoRedo (false);
  43730. break;
  43731. case baseMenuItemID + 7:
  43732. doUndoRedo (true);
  43733. break;
  43734. default:
  43735. break;
  43736. }
  43737. }
  43738. void TextEditor::focusGained (FocusChangeType)
  43739. {
  43740. newTransaction();
  43741. caretFlashState = true;
  43742. if (selectAllTextWhenFocused)
  43743. {
  43744. moveCursorTo (0, false);
  43745. moveCursorTo (getTotalNumChars(), true);
  43746. }
  43747. repaint();
  43748. if (caretVisible)
  43749. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43750. ComponentPeer* const peer = getPeer();
  43751. if (peer != 0 && ! isReadOnly())
  43752. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43753. }
  43754. void TextEditor::focusLost (FocusChangeType)
  43755. {
  43756. newTransaction();
  43757. wasFocused = false;
  43758. textHolder->stopTimer();
  43759. caretFlashState = false;
  43760. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43761. repaint();
  43762. }
  43763. void TextEditor::resized()
  43764. {
  43765. viewport->setBoundsInset (borderSize);
  43766. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43767. updateTextHolderSize();
  43768. if (! isMultiLine())
  43769. {
  43770. scrollToMakeSureCursorIsVisible();
  43771. }
  43772. else
  43773. {
  43774. updateCaretPosition();
  43775. }
  43776. }
  43777. void TextEditor::handleCommandMessage (const int commandId)
  43778. {
  43779. Component::BailOutChecker checker (this);
  43780. switch (commandId)
  43781. {
  43782. case TextEditorDefs::textChangeMessageId:
  43783. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43784. break;
  43785. case TextEditorDefs::returnKeyMessageId:
  43786. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43787. break;
  43788. case TextEditorDefs::escapeKeyMessageId:
  43789. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43790. break;
  43791. case TextEditorDefs::focusLossMessageId:
  43792. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43793. break;
  43794. default:
  43795. jassertfalse;
  43796. break;
  43797. }
  43798. }
  43799. void TextEditor::enablementChanged()
  43800. {
  43801. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43802. : MouseCursor::IBeamCursor);
  43803. repaint();
  43804. }
  43805. UndoManager* TextEditor::getUndoManager() throw()
  43806. {
  43807. return isReadOnly() ? 0 : &undoManager;
  43808. }
  43809. void TextEditor::clearInternal (UndoManager* const um)
  43810. {
  43811. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43812. }
  43813. void TextEditor::insert (const String& text,
  43814. const int insertIndex,
  43815. const Font& font,
  43816. const Colour& colour,
  43817. UndoManager* const um,
  43818. const int caretPositionToMoveTo)
  43819. {
  43820. if (text.isNotEmpty())
  43821. {
  43822. if (um != 0)
  43823. {
  43824. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43825. newTransaction();
  43826. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43827. caretPosition, caretPositionToMoveTo));
  43828. }
  43829. else
  43830. {
  43831. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43832. // a line gets moved due to word wrap
  43833. int index = 0;
  43834. int nextIndex = 0;
  43835. for (int i = 0; i < sections.size(); ++i)
  43836. {
  43837. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43838. if (insertIndex == index)
  43839. {
  43840. sections.insert (i, new UniformTextSection (text,
  43841. font, colour,
  43842. passwordCharacter));
  43843. break;
  43844. }
  43845. else if (insertIndex > index && insertIndex < nextIndex)
  43846. {
  43847. splitSection (i, insertIndex - index);
  43848. sections.insert (i + 1, new UniformTextSection (text,
  43849. font, colour,
  43850. passwordCharacter));
  43851. break;
  43852. }
  43853. index = nextIndex;
  43854. }
  43855. if (nextIndex == insertIndex)
  43856. sections.add (new UniformTextSection (text,
  43857. font, colour,
  43858. passwordCharacter));
  43859. coalesceSimilarSections();
  43860. totalNumChars = -1;
  43861. valueTextNeedsUpdating = true;
  43862. moveCursorTo (caretPositionToMoveTo, false);
  43863. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43864. }
  43865. }
  43866. }
  43867. void TextEditor::reinsert (const int insertIndex,
  43868. const Array <UniformTextSection*>& sectionsToInsert)
  43869. {
  43870. int index = 0;
  43871. int nextIndex = 0;
  43872. for (int i = 0; i < sections.size(); ++i)
  43873. {
  43874. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43875. if (insertIndex == index)
  43876. {
  43877. for (int j = sectionsToInsert.size(); --j >= 0;)
  43878. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43879. break;
  43880. }
  43881. else if (insertIndex > index && insertIndex < nextIndex)
  43882. {
  43883. splitSection (i, insertIndex - index);
  43884. for (int j = sectionsToInsert.size(); --j >= 0;)
  43885. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43886. break;
  43887. }
  43888. index = nextIndex;
  43889. }
  43890. if (nextIndex == insertIndex)
  43891. {
  43892. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43893. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43894. }
  43895. coalesceSimilarSections();
  43896. totalNumChars = -1;
  43897. valueTextNeedsUpdating = true;
  43898. }
  43899. void TextEditor::remove (const Range<int>& range,
  43900. UndoManager* const um,
  43901. const int caretPositionToMoveTo)
  43902. {
  43903. if (! range.isEmpty())
  43904. {
  43905. int index = 0;
  43906. for (int i = 0; i < sections.size(); ++i)
  43907. {
  43908. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43909. if (range.getStart() > index && range.getStart() < nextIndex)
  43910. {
  43911. splitSection (i, range.getStart() - index);
  43912. --i;
  43913. }
  43914. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43915. {
  43916. splitSection (i, range.getEnd() - index);
  43917. --i;
  43918. }
  43919. else
  43920. {
  43921. index = nextIndex;
  43922. if (index > range.getEnd())
  43923. break;
  43924. }
  43925. }
  43926. index = 0;
  43927. if (um != 0)
  43928. {
  43929. Array <UniformTextSection*> removedSections;
  43930. for (int i = 0; i < sections.size(); ++i)
  43931. {
  43932. if (range.getEnd() <= range.getStart())
  43933. break;
  43934. UniformTextSection* const section = sections.getUnchecked (i);
  43935. const int nextIndex = index + section->getTotalLength();
  43936. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43937. removedSections.add (new UniformTextSection (*section));
  43938. index = nextIndex;
  43939. }
  43940. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43941. newTransaction();
  43942. um->perform (new RemoveAction (*this, range, caretPosition,
  43943. caretPositionToMoveTo, removedSections));
  43944. }
  43945. else
  43946. {
  43947. Range<int> remainingRange (range);
  43948. for (int i = 0; i < sections.size(); ++i)
  43949. {
  43950. UniformTextSection* const section = sections.getUnchecked (i);
  43951. const int nextIndex = index + section->getTotalLength();
  43952. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43953. {
  43954. sections.remove(i);
  43955. section->clear();
  43956. delete section;
  43957. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43958. if (remainingRange.isEmpty())
  43959. break;
  43960. --i;
  43961. }
  43962. else
  43963. {
  43964. index = nextIndex;
  43965. }
  43966. }
  43967. coalesceSimilarSections();
  43968. totalNumChars = -1;
  43969. valueTextNeedsUpdating = true;
  43970. moveCursorTo (caretPositionToMoveTo, false);
  43971. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43972. }
  43973. }
  43974. }
  43975. const String TextEditor::getText() const
  43976. {
  43977. String t;
  43978. t.preallocateStorage (getTotalNumChars());
  43979. String::Concatenator concatenator (t);
  43980. for (int i = 0; i < sections.size(); ++i)
  43981. sections.getUnchecked (i)->appendAllText (concatenator);
  43982. return t;
  43983. }
  43984. const String TextEditor::getTextInRange (const Range<int>& range) const
  43985. {
  43986. String t;
  43987. if (! range.isEmpty())
  43988. {
  43989. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43990. String::Concatenator concatenator (t);
  43991. int index = 0;
  43992. for (int i = 0; i < sections.size(); ++i)
  43993. {
  43994. const UniformTextSection* const s = sections.getUnchecked (i);
  43995. const int nextIndex = index + s->getTotalLength();
  43996. if (range.getStart() < nextIndex)
  43997. {
  43998. if (range.getEnd() <= index)
  43999. break;
  44000. s->appendSubstring (concatenator, range - index);
  44001. }
  44002. index = nextIndex;
  44003. }
  44004. }
  44005. return t;
  44006. }
  44007. const String TextEditor::getHighlightedText() const
  44008. {
  44009. return getTextInRange (selection);
  44010. }
  44011. int TextEditor::getTotalNumChars() const
  44012. {
  44013. if (totalNumChars < 0)
  44014. {
  44015. totalNumChars = 0;
  44016. for (int i = sections.size(); --i >= 0;)
  44017. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44018. }
  44019. return totalNumChars;
  44020. }
  44021. bool TextEditor::isEmpty() const
  44022. {
  44023. return getTotalNumChars() == 0;
  44024. }
  44025. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44026. {
  44027. const float wordWrapWidth = getWordWrapWidth();
  44028. if (wordWrapWidth > 0 && sections.size() > 0)
  44029. {
  44030. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44031. i.getCharPosition (index, cx, cy, lineHeight);
  44032. }
  44033. else
  44034. {
  44035. cx = cy = 0;
  44036. lineHeight = currentFont.getHeight();
  44037. }
  44038. }
  44039. int TextEditor::indexAtPosition (const float x, const float y)
  44040. {
  44041. const float wordWrapWidth = getWordWrapWidth();
  44042. if (wordWrapWidth > 0)
  44043. {
  44044. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44045. while (i.next())
  44046. {
  44047. if (i.lineY + i.lineHeight > y)
  44048. {
  44049. if (i.lineY > y)
  44050. return jmax (0, i.indexInText - 1);
  44051. if (i.atomX >= x)
  44052. return i.indexInText;
  44053. if (x < i.atomRight)
  44054. return i.xToIndex (x);
  44055. }
  44056. }
  44057. }
  44058. return getTotalNumChars();
  44059. }
  44060. int TextEditor::findWordBreakAfter (const int position) const
  44061. {
  44062. const String t (getTextInRange (Range<int> (position, position + 512)));
  44063. const int totalLength = t.length();
  44064. int i = 0;
  44065. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44066. ++i;
  44067. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44068. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44069. ++i;
  44070. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44071. ++i;
  44072. return position + i;
  44073. }
  44074. int TextEditor::findWordBreakBefore (const int position) const
  44075. {
  44076. if (position <= 0)
  44077. return 0;
  44078. const int startOfBuffer = jmax (0, position - 512);
  44079. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44080. int i = position - startOfBuffer;
  44081. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44082. --i;
  44083. if (i > 0)
  44084. {
  44085. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44086. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44087. --i;
  44088. }
  44089. jassert (startOfBuffer + i >= 0);
  44090. return startOfBuffer + i;
  44091. }
  44092. void TextEditor::splitSection (const int sectionIndex,
  44093. const int charToSplitAt)
  44094. {
  44095. jassert (sections[sectionIndex] != 0);
  44096. sections.insert (sectionIndex + 1,
  44097. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44098. }
  44099. void TextEditor::coalesceSimilarSections()
  44100. {
  44101. for (int i = 0; i < sections.size() - 1; ++i)
  44102. {
  44103. UniformTextSection* const s1 = sections.getUnchecked (i);
  44104. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44105. if (s1->font == s2->font
  44106. && s1->colour == s2->colour)
  44107. {
  44108. s1->append (*s2, passwordCharacter);
  44109. sections.remove (i + 1);
  44110. delete s2;
  44111. --i;
  44112. }
  44113. }
  44114. }
  44115. END_JUCE_NAMESPACE
  44116. /*** End of inlined file: juce_TextEditor.cpp ***/
  44117. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44118. BEGIN_JUCE_NAMESPACE
  44119. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44120. class ToolbarSpacerComp : public ToolbarItemComponent
  44121. {
  44122. public:
  44123. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44124. : ToolbarItemComponent (itemId_, String::empty, false),
  44125. fixedSize (fixedSize_),
  44126. drawBar (drawBar_)
  44127. {
  44128. }
  44129. ~ToolbarSpacerComp()
  44130. {
  44131. }
  44132. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44133. int& preferredSize, int& minSize, int& maxSize)
  44134. {
  44135. if (fixedSize <= 0)
  44136. {
  44137. preferredSize = toolbarThickness * 2;
  44138. minSize = 4;
  44139. maxSize = 32768;
  44140. }
  44141. else
  44142. {
  44143. maxSize = roundToInt (toolbarThickness * fixedSize);
  44144. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44145. preferredSize = maxSize;
  44146. if (getEditingMode() == editableOnPalette)
  44147. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44148. }
  44149. return true;
  44150. }
  44151. void paintButtonArea (Graphics&, int, int, bool, bool)
  44152. {
  44153. }
  44154. void contentAreaChanged (const Rectangle<int>&)
  44155. {
  44156. }
  44157. int getResizeOrder() const throw()
  44158. {
  44159. return fixedSize <= 0 ? 0 : 1;
  44160. }
  44161. void paint (Graphics& g)
  44162. {
  44163. const int w = getWidth();
  44164. const int h = getHeight();
  44165. if (drawBar)
  44166. {
  44167. g.setColour (findColour (Toolbar::separatorColourId, true));
  44168. const float thickness = 0.2f;
  44169. if (isToolbarVertical())
  44170. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44171. else
  44172. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44173. }
  44174. if (getEditingMode() != normalMode && ! drawBar)
  44175. {
  44176. g.setColour (findColour (Toolbar::separatorColourId, true));
  44177. const int indentX = jmin (2, (w - 3) / 2);
  44178. const int indentY = jmin (2, (h - 3) / 2);
  44179. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44180. if (fixedSize <= 0)
  44181. {
  44182. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44183. if (isToolbarVertical())
  44184. {
  44185. x1 = w * 0.5f;
  44186. y1 = h * 0.4f;
  44187. x2 = x1;
  44188. y2 = indentX * 2.0f;
  44189. x3 = x1;
  44190. y3 = h * 0.6f;
  44191. x4 = x1;
  44192. y4 = h - y2;
  44193. hw = w * 0.15f;
  44194. hl = w * 0.2f;
  44195. }
  44196. else
  44197. {
  44198. x1 = w * 0.4f;
  44199. y1 = h * 0.5f;
  44200. x2 = indentX * 2.0f;
  44201. y2 = y1;
  44202. x3 = w * 0.6f;
  44203. y3 = y1;
  44204. x4 = w - x2;
  44205. y4 = y1;
  44206. hw = h * 0.15f;
  44207. hl = h * 0.2f;
  44208. }
  44209. Path p;
  44210. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44211. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44212. g.fillPath (p);
  44213. }
  44214. }
  44215. }
  44216. private:
  44217. const float fixedSize;
  44218. const bool drawBar;
  44219. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  44220. };
  44221. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44222. {
  44223. public:
  44224. MissingItemsComponent (Toolbar& owner_, const int height_)
  44225. : PopupMenuCustomComponent (true),
  44226. owner (&owner_),
  44227. height (height_)
  44228. {
  44229. for (int i = owner_.items.size(); --i >= 0;)
  44230. {
  44231. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44232. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44233. {
  44234. oldIndexes.insert (0, i);
  44235. addAndMakeVisible (tc, 0);
  44236. }
  44237. }
  44238. layout (400);
  44239. }
  44240. ~MissingItemsComponent()
  44241. {
  44242. if (owner != 0)
  44243. {
  44244. for (int i = 0; i < getNumChildComponents(); ++i)
  44245. {
  44246. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44247. if (tc != 0)
  44248. {
  44249. tc->setVisible (false);
  44250. const int index = oldIndexes.remove (i);
  44251. owner->addChildComponent (tc, index);
  44252. --i;
  44253. }
  44254. }
  44255. owner->resized();
  44256. }
  44257. }
  44258. void layout (const int preferredWidth)
  44259. {
  44260. const int indent = 8;
  44261. int x = indent;
  44262. int y = indent;
  44263. int maxX = 0;
  44264. for (int i = 0; i < getNumChildComponents(); ++i)
  44265. {
  44266. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44267. if (tc != 0)
  44268. {
  44269. int preferredSize = 1, minSize = 1, maxSize = 1;
  44270. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44271. {
  44272. if (x + preferredSize > preferredWidth && x > indent)
  44273. {
  44274. x = indent;
  44275. y += height;
  44276. }
  44277. tc->setBounds (x, y, preferredSize, height);
  44278. x += preferredSize;
  44279. maxX = jmax (maxX, x);
  44280. }
  44281. }
  44282. }
  44283. setSize (maxX + 8, y + height + 8);
  44284. }
  44285. void getIdealSize (int& idealWidth, int& idealHeight)
  44286. {
  44287. idealWidth = getWidth();
  44288. idealHeight = getHeight();
  44289. }
  44290. private:
  44291. Component::SafePointer<Toolbar> owner;
  44292. const int height;
  44293. Array <int> oldIndexes;
  44294. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  44295. };
  44296. Toolbar::Toolbar()
  44297. : vertical (false),
  44298. isEditingActive (false),
  44299. toolbarStyle (Toolbar::iconsOnly)
  44300. {
  44301. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44302. missingItemsButton->setAlwaysOnTop (true);
  44303. missingItemsButton->addButtonListener (this);
  44304. }
  44305. Toolbar::~Toolbar()
  44306. {
  44307. items.clear();
  44308. }
  44309. void Toolbar::setVertical (const bool shouldBeVertical)
  44310. {
  44311. if (vertical != shouldBeVertical)
  44312. {
  44313. vertical = shouldBeVertical;
  44314. resized();
  44315. }
  44316. }
  44317. void Toolbar::clear()
  44318. {
  44319. items.clear();
  44320. resized();
  44321. }
  44322. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44323. {
  44324. if (itemId == ToolbarItemFactory::separatorBarId)
  44325. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44326. else if (itemId == ToolbarItemFactory::spacerId)
  44327. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44328. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44329. return new ToolbarSpacerComp (itemId, 0, false);
  44330. return factory.createItem (itemId);
  44331. }
  44332. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44333. const int itemId,
  44334. const int insertIndex)
  44335. {
  44336. // An ID can't be zero - this might indicate a mistake somewhere?
  44337. jassert (itemId != 0);
  44338. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44339. if (tc != 0)
  44340. {
  44341. #if JUCE_DEBUG
  44342. Array <int> allowedIds;
  44343. factory.getAllToolbarItemIds (allowedIds);
  44344. // If your factory can create an item for a given ID, it must also return
  44345. // that ID from its getAllToolbarItemIds() method!
  44346. jassert (allowedIds.contains (itemId));
  44347. #endif
  44348. items.insert (insertIndex, tc);
  44349. addAndMakeVisible (tc, insertIndex);
  44350. }
  44351. }
  44352. void Toolbar::addItem (ToolbarItemFactory& factory,
  44353. const int itemId,
  44354. const int insertIndex)
  44355. {
  44356. addItemInternal (factory, itemId, insertIndex);
  44357. resized();
  44358. }
  44359. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44360. {
  44361. Array <int> ids;
  44362. factoryToUse.getDefaultItemSet (ids);
  44363. clear();
  44364. for (int i = 0; i < ids.size(); ++i)
  44365. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44366. resized();
  44367. }
  44368. void Toolbar::removeToolbarItem (const int itemIndex)
  44369. {
  44370. items.remove (itemIndex);
  44371. resized();
  44372. }
  44373. int Toolbar::getNumItems() const throw()
  44374. {
  44375. return items.size();
  44376. }
  44377. int Toolbar::getItemId (const int itemIndex) const throw()
  44378. {
  44379. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44380. return tc != 0 ? tc->getItemId() : 0;
  44381. }
  44382. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44383. {
  44384. return items [itemIndex];
  44385. }
  44386. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44387. {
  44388. for (;;)
  44389. {
  44390. index += delta;
  44391. ToolbarItemComponent* const tc = getItemComponent (index);
  44392. if (tc == 0)
  44393. break;
  44394. if (tc->isActive)
  44395. return tc;
  44396. }
  44397. return 0;
  44398. }
  44399. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44400. {
  44401. if (toolbarStyle != newStyle)
  44402. {
  44403. toolbarStyle = newStyle;
  44404. updateAllItemPositions (false);
  44405. }
  44406. }
  44407. const String Toolbar::toString() const
  44408. {
  44409. String s ("TB:");
  44410. for (int i = 0; i < getNumItems(); ++i)
  44411. s << getItemId(i) << ' ';
  44412. return s.trimEnd();
  44413. }
  44414. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44415. const String& savedVersion)
  44416. {
  44417. if (! savedVersion.startsWith ("TB:"))
  44418. return false;
  44419. StringArray tokens;
  44420. tokens.addTokens (savedVersion.substring (3), false);
  44421. clear();
  44422. for (int i = 0; i < tokens.size(); ++i)
  44423. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44424. resized();
  44425. return true;
  44426. }
  44427. void Toolbar::paint (Graphics& g)
  44428. {
  44429. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44430. }
  44431. int Toolbar::getThickness() const throw()
  44432. {
  44433. return vertical ? getWidth() : getHeight();
  44434. }
  44435. int Toolbar::getLength() const throw()
  44436. {
  44437. return vertical ? getHeight() : getWidth();
  44438. }
  44439. void Toolbar::setEditingActive (const bool active)
  44440. {
  44441. if (isEditingActive != active)
  44442. {
  44443. isEditingActive = active;
  44444. updateAllItemPositions (false);
  44445. }
  44446. }
  44447. void Toolbar::resized()
  44448. {
  44449. updateAllItemPositions (false);
  44450. }
  44451. void Toolbar::updateAllItemPositions (const bool animate)
  44452. {
  44453. if (getWidth() > 0 && getHeight() > 0)
  44454. {
  44455. StretchableObjectResizer resizer;
  44456. int i;
  44457. for (i = 0; i < items.size(); ++i)
  44458. {
  44459. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44460. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44461. : ToolbarItemComponent::normalMode);
  44462. tc->setStyle (toolbarStyle);
  44463. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44464. int preferredSize = 1, minSize = 1, maxSize = 1;
  44465. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44466. preferredSize, minSize, maxSize))
  44467. {
  44468. tc->isActive = true;
  44469. resizer.addItem (preferredSize, minSize, maxSize,
  44470. spacer != 0 ? spacer->getResizeOrder() : 2);
  44471. }
  44472. else
  44473. {
  44474. tc->isActive = false;
  44475. tc->setVisible (false);
  44476. }
  44477. }
  44478. resizer.resizeToFit (getLength());
  44479. int totalLength = 0;
  44480. for (i = 0; i < resizer.getNumItems(); ++i)
  44481. totalLength += (int) resizer.getItemSize (i);
  44482. const bool itemsOffTheEnd = totalLength > getLength();
  44483. const int extrasButtonSize = getThickness() / 2;
  44484. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44485. missingItemsButton->setVisible (itemsOffTheEnd);
  44486. missingItemsButton->setEnabled (! isEditingActive);
  44487. if (vertical)
  44488. missingItemsButton->setCentrePosition (getWidth() / 2,
  44489. getHeight() - 4 - extrasButtonSize / 2);
  44490. else
  44491. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44492. getHeight() / 2);
  44493. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44494. : missingItemsButton->getX()) - 4
  44495. : getLength();
  44496. int pos = 0, activeIndex = 0;
  44497. for (i = 0; i < items.size(); ++i)
  44498. {
  44499. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44500. if (tc->isActive)
  44501. {
  44502. const int size = (int) resizer.getItemSize (activeIndex++);
  44503. Rectangle<int> newBounds;
  44504. if (vertical)
  44505. newBounds.setBounds (0, pos, getWidth(), size);
  44506. else
  44507. newBounds.setBounds (pos, 0, size, getHeight());
  44508. if (animate)
  44509. {
  44510. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44511. }
  44512. else
  44513. {
  44514. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44515. tc->setBounds (newBounds);
  44516. }
  44517. pos += size;
  44518. tc->setVisible (pos <= maxLength
  44519. && ((! tc->isBeingDragged)
  44520. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44521. }
  44522. }
  44523. }
  44524. }
  44525. void Toolbar::buttonClicked (Button*)
  44526. {
  44527. jassert (missingItemsButton->isShowing());
  44528. if (missingItemsButton->isShowing())
  44529. {
  44530. PopupMenu m;
  44531. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44532. m.showAt (missingItemsButton);
  44533. }
  44534. }
  44535. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44536. Component* /*sourceComponent*/)
  44537. {
  44538. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44539. }
  44540. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44541. {
  44542. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44543. if (tc != 0)
  44544. {
  44545. if (! items.contains (tc))
  44546. {
  44547. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44548. {
  44549. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44550. if (palette != 0)
  44551. palette->replaceComponent (tc);
  44552. }
  44553. else
  44554. {
  44555. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44556. }
  44557. items.add (tc);
  44558. addChildComponent (tc);
  44559. updateAllItemPositions (true);
  44560. }
  44561. for (int i = getNumItems(); --i >= 0;)
  44562. {
  44563. const int currentIndex = items.indexOf (tc);
  44564. int newIndex = currentIndex;
  44565. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44566. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44567. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44568. .getComponentDestination (getChildComponent (newIndex)));
  44569. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44570. if (prev != 0)
  44571. {
  44572. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44573. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44574. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44575. {
  44576. newIndex = getIndexOfChildComponent (prev);
  44577. }
  44578. }
  44579. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44580. if (next != 0)
  44581. {
  44582. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44583. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44584. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44585. {
  44586. newIndex = getIndexOfChildComponent (next) + 1;
  44587. }
  44588. }
  44589. if (newIndex == currentIndex)
  44590. break;
  44591. items.removeObject (tc, false);
  44592. removeChildComponent (tc);
  44593. addChildComponent (tc, newIndex);
  44594. items.insert (newIndex, tc);
  44595. updateAllItemPositions (true);
  44596. }
  44597. }
  44598. }
  44599. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44600. {
  44601. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44602. if (tc != 0 && isParentOf (tc))
  44603. {
  44604. items.removeObject (tc, false);
  44605. removeChildComponent (tc);
  44606. updateAllItemPositions (true);
  44607. }
  44608. }
  44609. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44610. {
  44611. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44612. if (tc != 0)
  44613. tc->setState (Button::buttonNormal);
  44614. }
  44615. void Toolbar::mouseDown (const MouseEvent&)
  44616. {
  44617. }
  44618. class ToolbarCustomisationDialog : public DialogWindow
  44619. {
  44620. public:
  44621. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44622. Toolbar* const toolbar_,
  44623. const int optionFlags)
  44624. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44625. toolbar (toolbar_)
  44626. {
  44627. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44628. setResizable (true, true);
  44629. setResizeLimits (400, 300, 1500, 1000);
  44630. positionNearBar();
  44631. }
  44632. ~ToolbarCustomisationDialog()
  44633. {
  44634. setContentComponent (0, true);
  44635. }
  44636. void closeButtonPressed()
  44637. {
  44638. setVisible (false);
  44639. }
  44640. bool canModalEventBeSentToComponent (const Component* comp)
  44641. {
  44642. return toolbar->isParentOf (comp);
  44643. }
  44644. void positionNearBar()
  44645. {
  44646. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44647. const int tbx = toolbar->getScreenX();
  44648. const int tby = toolbar->getScreenY();
  44649. const int gap = 8;
  44650. int x, y;
  44651. if (toolbar->isVertical())
  44652. {
  44653. y = tby;
  44654. if (tbx > screenSize.getCentreX())
  44655. x = tbx - getWidth() - gap;
  44656. else
  44657. x = tbx + toolbar->getWidth() + gap;
  44658. }
  44659. else
  44660. {
  44661. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44662. if (tby > screenSize.getCentreY())
  44663. y = tby - getHeight() - gap;
  44664. else
  44665. y = tby + toolbar->getHeight() + gap;
  44666. }
  44667. setTopLeftPosition (x, y);
  44668. }
  44669. private:
  44670. Toolbar* const toolbar;
  44671. class CustomiserPanel : public Component,
  44672. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44673. private ButtonListener
  44674. {
  44675. public:
  44676. CustomiserPanel (ToolbarItemFactory& factory_,
  44677. Toolbar* const toolbar_,
  44678. const int optionFlags)
  44679. : factory (factory_),
  44680. toolbar (toolbar_),
  44681. palette (factory_, toolbar_),
  44682. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44683. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44684. defaultButton (TRANS ("Restore to default set of items"))
  44685. {
  44686. addAndMakeVisible (&palette);
  44687. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44688. | Toolbar::allowIconsWithTextChoice
  44689. | Toolbar::allowTextOnlyChoice)) != 0)
  44690. {
  44691. addAndMakeVisible (&styleBox);
  44692. styleBox.setEditableText (false);
  44693. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44694. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44695. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44696. int selectedStyle = 0;
  44697. switch (toolbar_->getStyle())
  44698. {
  44699. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44700. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44701. case Toolbar::textOnly: selectedStyle = 3; break;
  44702. }
  44703. styleBox.setSelectedId (selectedStyle);
  44704. styleBox.addListener (this);
  44705. }
  44706. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44707. {
  44708. addAndMakeVisible (&defaultButton);
  44709. defaultButton.addButtonListener (this);
  44710. }
  44711. addAndMakeVisible (&instructions);
  44712. instructions.setFont (Font (13.0f));
  44713. setSize (500, 300);
  44714. }
  44715. void comboBoxChanged (ComboBox*)
  44716. {
  44717. switch (styleBox.getSelectedId())
  44718. {
  44719. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44720. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44721. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44722. }
  44723. palette.resized(); // to make it update the styles
  44724. }
  44725. void buttonClicked (Button*)
  44726. {
  44727. toolbar->addDefaultItems (factory);
  44728. }
  44729. void paint (Graphics& g)
  44730. {
  44731. Colour background;
  44732. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44733. if (dw != 0)
  44734. background = dw->getBackgroundColour();
  44735. g.setColour (background.contrasting().withAlpha (0.3f));
  44736. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44737. }
  44738. void resized()
  44739. {
  44740. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44741. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44742. defaultButton.changeWidthToFitText (22);
  44743. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44744. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44745. }
  44746. private:
  44747. ToolbarItemFactory& factory;
  44748. Toolbar* const toolbar;
  44749. ToolbarItemPalette palette;
  44750. Label instructions;
  44751. ComboBox styleBox;
  44752. TextButton defaultButton;
  44753. };
  44754. };
  44755. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44756. {
  44757. setEditingActive (true);
  44758. #if JUCE_DEBUG
  44759. Component::SafePointer<Component> checker (this);
  44760. #endif
  44761. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44762. dw.runModalLoop();
  44763. #if JUCE_DEBUG
  44764. jassert (checker != 0); // Don't delete the toolbar while it's being customised!
  44765. #endif
  44766. setEditingActive (false);
  44767. }
  44768. END_JUCE_NAMESPACE
  44769. /*** End of inlined file: juce_Toolbar.cpp ***/
  44770. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44771. BEGIN_JUCE_NAMESPACE
  44772. ToolbarItemFactory::ToolbarItemFactory()
  44773. {
  44774. }
  44775. ToolbarItemFactory::~ToolbarItemFactory()
  44776. {
  44777. }
  44778. class ItemDragAndDropOverlayComponent : public Component
  44779. {
  44780. public:
  44781. ItemDragAndDropOverlayComponent()
  44782. : isDragging (false)
  44783. {
  44784. setAlwaysOnTop (true);
  44785. setRepaintsOnMouseActivity (true);
  44786. setMouseCursor (MouseCursor::DraggingHandCursor);
  44787. }
  44788. void paint (Graphics& g)
  44789. {
  44790. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44791. if (isMouseOverOrDragging()
  44792. && tc != 0
  44793. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44794. {
  44795. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44796. g.drawRect (0, 0, getWidth(), getHeight(),
  44797. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44798. }
  44799. }
  44800. void mouseDown (const MouseEvent& e)
  44801. {
  44802. isDragging = false;
  44803. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44804. if (tc != 0)
  44805. {
  44806. tc->dragOffsetX = e.x;
  44807. tc->dragOffsetY = e.y;
  44808. }
  44809. }
  44810. void mouseDrag (const MouseEvent& e)
  44811. {
  44812. if (! (isDragging || e.mouseWasClicked()))
  44813. {
  44814. isDragging = true;
  44815. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44816. if (dnd != 0)
  44817. {
  44818. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44819. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44820. if (tc != 0)
  44821. {
  44822. tc->isBeingDragged = true;
  44823. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44824. tc->setVisible (false);
  44825. }
  44826. }
  44827. }
  44828. }
  44829. void mouseUp (const MouseEvent&)
  44830. {
  44831. isDragging = false;
  44832. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44833. if (tc != 0)
  44834. {
  44835. tc->isBeingDragged = false;
  44836. Toolbar* const tb = tc->getToolbar();
  44837. if (tb != 0)
  44838. tb->updateAllItemPositions (true);
  44839. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44840. delete tc;
  44841. }
  44842. }
  44843. void parentSizeChanged()
  44844. {
  44845. setBounds (0, 0, getParentWidth(), getParentHeight());
  44846. }
  44847. private:
  44848. bool isDragging;
  44849. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44850. };
  44851. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44852. const String& labelText,
  44853. const bool isBeingUsedAsAButton_)
  44854. : Button (labelText),
  44855. itemId (itemId_),
  44856. mode (normalMode),
  44857. toolbarStyle (Toolbar::iconsOnly),
  44858. dragOffsetX (0),
  44859. dragOffsetY (0),
  44860. isActive (true),
  44861. isBeingDragged (false),
  44862. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44863. {
  44864. // Your item ID can't be 0!
  44865. jassert (itemId_ != 0);
  44866. }
  44867. ToolbarItemComponent::~ToolbarItemComponent()
  44868. {
  44869. overlayComp = 0;
  44870. }
  44871. Toolbar* ToolbarItemComponent::getToolbar() const
  44872. {
  44873. return dynamic_cast <Toolbar*> (getParentComponent());
  44874. }
  44875. bool ToolbarItemComponent::isToolbarVertical() const
  44876. {
  44877. const Toolbar* const t = getToolbar();
  44878. return t != 0 && t->isVertical();
  44879. }
  44880. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44881. {
  44882. if (toolbarStyle != newStyle)
  44883. {
  44884. toolbarStyle = newStyle;
  44885. repaint();
  44886. resized();
  44887. }
  44888. }
  44889. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44890. {
  44891. if (isBeingUsedAsAButton)
  44892. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44893. over, down, *this);
  44894. if (toolbarStyle != Toolbar::iconsOnly)
  44895. {
  44896. const int indent = contentArea.getX();
  44897. int y = indent;
  44898. int h = getHeight() - indent * 2;
  44899. if (toolbarStyle == Toolbar::iconsWithText)
  44900. {
  44901. y = contentArea.getBottom() + indent / 2;
  44902. h -= contentArea.getHeight();
  44903. }
  44904. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44905. getButtonText(), *this);
  44906. }
  44907. if (! contentArea.isEmpty())
  44908. {
  44909. g.saveState();
  44910. g.reduceClipRegion (contentArea);
  44911. g.setOrigin (contentArea.getX(), contentArea.getY());
  44912. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44913. g.restoreState();
  44914. }
  44915. }
  44916. void ToolbarItemComponent::resized()
  44917. {
  44918. if (toolbarStyle != Toolbar::textOnly)
  44919. {
  44920. const int indent = jmin (proportionOfWidth (0.08f),
  44921. proportionOfHeight (0.08f));
  44922. contentArea = Rectangle<int> (indent, indent,
  44923. getWidth() - indent * 2,
  44924. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44925. : (getHeight() - indent * 2));
  44926. }
  44927. else
  44928. {
  44929. contentArea = Rectangle<int>();
  44930. }
  44931. contentAreaChanged (contentArea);
  44932. }
  44933. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44934. {
  44935. if (mode != newMode)
  44936. {
  44937. mode = newMode;
  44938. repaint();
  44939. if (mode == normalMode)
  44940. {
  44941. overlayComp = 0;
  44942. }
  44943. else if (overlayComp == 0)
  44944. {
  44945. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44946. overlayComp->parentSizeChanged();
  44947. }
  44948. resized();
  44949. }
  44950. }
  44951. END_JUCE_NAMESPACE
  44952. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44953. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44954. BEGIN_JUCE_NAMESPACE
  44955. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44956. Toolbar* const toolbar_)
  44957. : factory (factory_),
  44958. toolbar (toolbar_)
  44959. {
  44960. Component* const itemHolder = new Component();
  44961. viewport.setViewedComponent (itemHolder);
  44962. Array <int> allIds;
  44963. factory.getAllToolbarItemIds (allIds);
  44964. for (int i = 0; i < allIds.size(); ++i)
  44965. addComponent (allIds.getUnchecked (i), -1);
  44966. addAndMakeVisible (&viewport);
  44967. }
  44968. ToolbarItemPalette::~ToolbarItemPalette()
  44969. {
  44970. }
  44971. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  44972. {
  44973. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  44974. jassert (tc != 0);
  44975. if (tc != 0)
  44976. {
  44977. items.insert (index, tc);
  44978. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  44979. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44980. }
  44981. }
  44982. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44983. {
  44984. const int index = items.indexOf (comp);
  44985. jassert (index >= 0);
  44986. items.removeObject (comp, false);
  44987. addComponent (comp->getItemId(), index);
  44988. resized();
  44989. }
  44990. void ToolbarItemPalette::resized()
  44991. {
  44992. viewport.setBoundsInset (BorderSize (1));
  44993. Component* const itemHolder = viewport.getViewedComponent();
  44994. const int indent = 8;
  44995. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  44996. const int height = toolbar->getThickness();
  44997. int x = indent;
  44998. int y = indent;
  44999. int maxX = 0;
  45000. for (int i = 0; i < items.size(); ++i)
  45001. {
  45002. ToolbarItemComponent* const tc = items.getUnchecked(i);
  45003. tc->setStyle (toolbar->getStyle());
  45004. int preferredSize = 1, minSize = 1, maxSize = 1;
  45005. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45006. {
  45007. if (x + preferredSize > preferredWidth && x > indent)
  45008. {
  45009. x = indent;
  45010. y += height;
  45011. }
  45012. tc->setBounds (x, y, preferredSize, height);
  45013. x += preferredSize + 8;
  45014. maxX = jmax (maxX, x);
  45015. }
  45016. }
  45017. itemHolder->setSize (maxX, y + height + 8);
  45018. }
  45019. END_JUCE_NAMESPACE
  45020. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45021. /*** Start of inlined file: juce_TreeView.cpp ***/
  45022. BEGIN_JUCE_NAMESPACE
  45023. class TreeViewContentComponent : public Component,
  45024. public TooltipClient
  45025. {
  45026. public:
  45027. TreeViewContentComponent (TreeView& owner_)
  45028. : owner (owner_),
  45029. buttonUnderMouse (0),
  45030. isDragging (false)
  45031. {
  45032. }
  45033. ~TreeViewContentComponent()
  45034. {
  45035. }
  45036. void mouseDown (const MouseEvent& e)
  45037. {
  45038. updateButtonUnderMouse (e);
  45039. isDragging = false;
  45040. needSelectionOnMouseUp = false;
  45041. Rectangle<int> pos;
  45042. TreeViewItem* const item = findItemAt (e.y, pos);
  45043. if (item == 0)
  45044. return;
  45045. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45046. // as selection clicks)
  45047. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45048. {
  45049. if (e.x >= pos.getX() - owner.getIndentSize())
  45050. item->setOpen (! item->isOpen());
  45051. // (clicks to the left of an open/close button are ignored)
  45052. }
  45053. else
  45054. {
  45055. // mouse-down inside the body of the item..
  45056. if (! owner.isMultiSelectEnabled())
  45057. item->setSelected (true, true);
  45058. else if (item->isSelected())
  45059. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45060. else
  45061. selectBasedOnModifiers (item, e.mods);
  45062. if (e.x >= pos.getX())
  45063. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45064. }
  45065. }
  45066. void mouseUp (const MouseEvent& e)
  45067. {
  45068. updateButtonUnderMouse (e);
  45069. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45070. {
  45071. Rectangle<int> pos;
  45072. TreeViewItem* const item = findItemAt (e.y, pos);
  45073. if (item != 0)
  45074. selectBasedOnModifiers (item, e.mods);
  45075. }
  45076. }
  45077. void mouseDoubleClick (const MouseEvent& e)
  45078. {
  45079. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45080. {
  45081. Rectangle<int> pos;
  45082. TreeViewItem* const item = findItemAt (e.y, pos);
  45083. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45084. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45085. }
  45086. }
  45087. void mouseDrag (const MouseEvent& e)
  45088. {
  45089. if (isEnabled()
  45090. && ! (isDragging || e.mouseWasClicked()
  45091. || e.getDistanceFromDragStart() < 5
  45092. || e.mods.isPopupMenu()))
  45093. {
  45094. isDragging = true;
  45095. Rectangle<int> pos;
  45096. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45097. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45098. {
  45099. const String dragDescription (item->getDragSourceDescription());
  45100. if (dragDescription.isNotEmpty())
  45101. {
  45102. DragAndDropContainer* const dragContainer
  45103. = DragAndDropContainer::findParentDragContainerFor (this);
  45104. if (dragContainer != 0)
  45105. {
  45106. pos.setSize (pos.getWidth(), item->itemHeight);
  45107. Image dragImage (Component::createComponentSnapshot (pos, true));
  45108. dragImage.multiplyAllAlphas (0.6f);
  45109. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45110. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45111. }
  45112. else
  45113. {
  45114. // to be able to do a drag-and-drop operation, the treeview needs to
  45115. // be inside a component which is also a DragAndDropContainer.
  45116. jassertfalse;
  45117. }
  45118. }
  45119. }
  45120. }
  45121. }
  45122. void mouseMove (const MouseEvent& e)
  45123. {
  45124. updateButtonUnderMouse (e);
  45125. }
  45126. void mouseExit (const MouseEvent& e)
  45127. {
  45128. updateButtonUnderMouse (e);
  45129. }
  45130. void paint (Graphics& g)
  45131. {
  45132. if (owner.rootItem != 0)
  45133. {
  45134. owner.handleAsyncUpdate();
  45135. if (! owner.rootItemVisible)
  45136. g.setOrigin (0, -owner.rootItem->itemHeight);
  45137. owner.rootItem->paintRecursively (g, getWidth());
  45138. }
  45139. }
  45140. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45141. {
  45142. if (owner.rootItem != 0)
  45143. {
  45144. owner.handleAsyncUpdate();
  45145. if (! owner.rootItemVisible)
  45146. y += owner.rootItem->itemHeight;
  45147. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45148. if (ti != 0)
  45149. itemPosition = ti->getItemPosition (false);
  45150. return ti;
  45151. }
  45152. return 0;
  45153. }
  45154. void updateComponents()
  45155. {
  45156. const int visibleTop = -getY();
  45157. const int visibleBottom = visibleTop + getParentHeight();
  45158. {
  45159. for (int i = items.size(); --i >= 0;)
  45160. items.getUnchecked(i)->shouldKeep = false;
  45161. }
  45162. {
  45163. TreeViewItem* item = owner.rootItem;
  45164. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45165. while (item != 0 && y < visibleBottom)
  45166. {
  45167. y += item->itemHeight;
  45168. if (y >= visibleTop)
  45169. {
  45170. RowItem* const ri = findItem (item->uid);
  45171. if (ri != 0)
  45172. {
  45173. ri->shouldKeep = true;
  45174. }
  45175. else
  45176. {
  45177. Component* const comp = item->createItemComponent();
  45178. if (comp != 0)
  45179. {
  45180. items.add (new RowItem (item, comp, item->uid));
  45181. addAndMakeVisible (comp);
  45182. }
  45183. }
  45184. }
  45185. item = item->getNextVisibleItem (true);
  45186. }
  45187. }
  45188. for (int i = items.size(); --i >= 0;)
  45189. {
  45190. RowItem* const ri = items.getUnchecked(i);
  45191. bool keep = false;
  45192. if (isParentOf (ri->component))
  45193. {
  45194. if (ri->shouldKeep)
  45195. {
  45196. Rectangle<int> pos (ri->item->getItemPosition (false));
  45197. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  45198. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45199. {
  45200. keep = true;
  45201. ri->component->setBounds (pos);
  45202. }
  45203. }
  45204. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  45205. {
  45206. keep = true;
  45207. ri->component->setSize (0, 0);
  45208. }
  45209. }
  45210. if (! keep)
  45211. items.remove (i);
  45212. }
  45213. }
  45214. void updateButtonUnderMouse (const MouseEvent& e)
  45215. {
  45216. TreeViewItem* newItem = 0;
  45217. if (owner.openCloseButtonsVisible)
  45218. {
  45219. Rectangle<int> pos;
  45220. TreeViewItem* item = findItemAt (e.y, pos);
  45221. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45222. {
  45223. newItem = item;
  45224. if (! newItem->mightContainSubItems())
  45225. newItem = 0;
  45226. }
  45227. }
  45228. if (buttonUnderMouse != newItem)
  45229. {
  45230. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45231. {
  45232. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45233. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45234. }
  45235. buttonUnderMouse = newItem;
  45236. if (buttonUnderMouse != 0)
  45237. {
  45238. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45239. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45240. }
  45241. }
  45242. }
  45243. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45244. {
  45245. return item == buttonUnderMouse;
  45246. }
  45247. void resized()
  45248. {
  45249. owner.itemsChanged();
  45250. }
  45251. const String getTooltip()
  45252. {
  45253. Rectangle<int> pos;
  45254. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45255. if (item != 0)
  45256. return item->getTooltip();
  45257. return owner.getTooltip();
  45258. }
  45259. private:
  45260. TreeView& owner;
  45261. struct RowItem
  45262. {
  45263. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45264. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45265. {
  45266. }
  45267. ~RowItem()
  45268. {
  45269. component.deleteAndZero();
  45270. }
  45271. Component::SafePointer<Component> component;
  45272. TreeViewItem* item;
  45273. int uid;
  45274. bool shouldKeep;
  45275. };
  45276. OwnedArray <RowItem> items;
  45277. TreeViewItem* buttonUnderMouse;
  45278. bool isDragging, needSelectionOnMouseUp;
  45279. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45280. {
  45281. TreeViewItem* firstSelected = 0;
  45282. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45283. {
  45284. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45285. jassert (lastSelected != 0);
  45286. int rowStart = firstSelected->getRowNumberInTree();
  45287. int rowEnd = lastSelected->getRowNumberInTree();
  45288. if (rowStart > rowEnd)
  45289. swapVariables (rowStart, rowEnd);
  45290. int ourRow = item->getRowNumberInTree();
  45291. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45292. if (ourRow > otherEnd)
  45293. swapVariables (ourRow, otherEnd);
  45294. for (int i = ourRow; i <= otherEnd; ++i)
  45295. owner.getItemOnRow (i)->setSelected (true, false);
  45296. }
  45297. else
  45298. {
  45299. const bool cmd = modifiers.isCommandDown();
  45300. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45301. }
  45302. }
  45303. bool containsItem (TreeViewItem* const item) const throw()
  45304. {
  45305. for (int i = items.size(); --i >= 0;)
  45306. if (items.getUnchecked(i)->item == item)
  45307. return true;
  45308. return false;
  45309. }
  45310. RowItem* findItem (const int uid) const throw()
  45311. {
  45312. for (int i = items.size(); --i >= 0;)
  45313. {
  45314. RowItem* const ri = items.getUnchecked(i);
  45315. if (ri->uid == uid)
  45316. return ri;
  45317. }
  45318. return 0;
  45319. }
  45320. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45321. {
  45322. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45323. {
  45324. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45325. if (source->isDragging())
  45326. {
  45327. Component* const underMouse = source->getComponentUnderMouse();
  45328. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45329. return true;
  45330. }
  45331. }
  45332. return false;
  45333. }
  45334. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45335. };
  45336. class TreeView::TreeViewport : public Viewport
  45337. {
  45338. public:
  45339. TreeViewport() throw() : lastX (-1) {}
  45340. ~TreeViewport() throw() {}
  45341. void updateComponents (const bool triggerResize = false)
  45342. {
  45343. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45344. if (tvc != 0)
  45345. {
  45346. if (triggerResize)
  45347. tvc->resized();
  45348. else
  45349. tvc->updateComponents();
  45350. }
  45351. repaint();
  45352. }
  45353. void visibleAreaChanged (int x, int, int, int)
  45354. {
  45355. const bool hasScrolledSideways = (x != lastX);
  45356. lastX = x;
  45357. updateComponents (hasScrolledSideways);
  45358. }
  45359. private:
  45360. int lastX;
  45361. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45362. };
  45363. TreeView::TreeView (const String& componentName)
  45364. : Component (componentName),
  45365. rootItem (0),
  45366. indentSize (24),
  45367. defaultOpenness (false),
  45368. needsRecalculating (true),
  45369. rootItemVisible (true),
  45370. multiSelectEnabled (false),
  45371. openCloseButtonsVisible (true)
  45372. {
  45373. addAndMakeVisible (viewport = new TreeViewport());
  45374. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45375. viewport->setWantsKeyboardFocus (false);
  45376. setWantsKeyboardFocus (true);
  45377. }
  45378. TreeView::~TreeView()
  45379. {
  45380. if (rootItem != 0)
  45381. rootItem->setOwnerView (0);
  45382. }
  45383. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45384. {
  45385. if (rootItem != newRootItem)
  45386. {
  45387. if (newRootItem != 0)
  45388. {
  45389. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45390. if (newRootItem->ownerView != 0)
  45391. newRootItem->ownerView->setRootItem (0);
  45392. }
  45393. if (rootItem != 0)
  45394. rootItem->setOwnerView (0);
  45395. rootItem = newRootItem;
  45396. if (newRootItem != 0)
  45397. newRootItem->setOwnerView (this);
  45398. needsRecalculating = true;
  45399. handleAsyncUpdate();
  45400. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45401. {
  45402. rootItem->setOpen (false); // force a re-open
  45403. rootItem->setOpen (true);
  45404. }
  45405. }
  45406. }
  45407. void TreeView::deleteRootItem()
  45408. {
  45409. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45410. setRootItem (0);
  45411. }
  45412. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45413. {
  45414. rootItemVisible = shouldBeVisible;
  45415. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45416. {
  45417. rootItem->setOpen (false); // force a re-open
  45418. rootItem->setOpen (true);
  45419. }
  45420. itemsChanged();
  45421. }
  45422. void TreeView::colourChanged()
  45423. {
  45424. setOpaque (findColour (backgroundColourId).isOpaque());
  45425. repaint();
  45426. }
  45427. void TreeView::setIndentSize (const int newIndentSize)
  45428. {
  45429. if (indentSize != newIndentSize)
  45430. {
  45431. indentSize = newIndentSize;
  45432. resized();
  45433. }
  45434. }
  45435. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45436. {
  45437. if (defaultOpenness != isOpenByDefault)
  45438. {
  45439. defaultOpenness = isOpenByDefault;
  45440. itemsChanged();
  45441. }
  45442. }
  45443. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45444. {
  45445. multiSelectEnabled = canMultiSelect;
  45446. }
  45447. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45448. {
  45449. if (openCloseButtonsVisible != shouldBeVisible)
  45450. {
  45451. openCloseButtonsVisible = shouldBeVisible;
  45452. itemsChanged();
  45453. }
  45454. }
  45455. Viewport* TreeView::getViewport() const throw()
  45456. {
  45457. return viewport;
  45458. }
  45459. void TreeView::clearSelectedItems()
  45460. {
  45461. if (rootItem != 0)
  45462. rootItem->deselectAllRecursively();
  45463. }
  45464. int TreeView::getNumSelectedItems() const throw()
  45465. {
  45466. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45467. }
  45468. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45469. {
  45470. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45471. }
  45472. int TreeView::getNumRowsInTree() const
  45473. {
  45474. if (rootItem != 0)
  45475. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45476. return 0;
  45477. }
  45478. TreeViewItem* TreeView::getItemOnRow (int index) const
  45479. {
  45480. if (! rootItemVisible)
  45481. ++index;
  45482. if (rootItem != 0 && index >= 0)
  45483. return rootItem->getItemOnRow (index);
  45484. return 0;
  45485. }
  45486. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45487. {
  45488. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45489. Rectangle<int> pos;
  45490. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45491. }
  45492. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45493. {
  45494. if (rootItem == 0)
  45495. return 0;
  45496. return rootItem->findItemFromIdentifierString (identifierString);
  45497. }
  45498. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45499. {
  45500. XmlElement* e = 0;
  45501. if (rootItem != 0)
  45502. {
  45503. e = rootItem->getOpennessState();
  45504. if (e != 0 && alsoIncludeScrollPosition)
  45505. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45506. }
  45507. return e;
  45508. }
  45509. void TreeView::restoreOpennessState (const XmlElement& newState)
  45510. {
  45511. if (rootItem != 0)
  45512. {
  45513. rootItem->restoreOpennessState (newState);
  45514. if (newState.hasAttribute ("scrollPos"))
  45515. viewport->setViewPosition (viewport->getViewPositionX(),
  45516. newState.getIntAttribute ("scrollPos"));
  45517. }
  45518. }
  45519. void TreeView::paint (Graphics& g)
  45520. {
  45521. g.fillAll (findColour (backgroundColourId));
  45522. }
  45523. void TreeView::resized()
  45524. {
  45525. viewport->setBounds (getLocalBounds());
  45526. itemsChanged();
  45527. handleAsyncUpdate();
  45528. }
  45529. void TreeView::enablementChanged()
  45530. {
  45531. repaint();
  45532. }
  45533. void TreeView::moveSelectedRow (int delta)
  45534. {
  45535. if (delta == 0)
  45536. return;
  45537. int rowSelected = 0;
  45538. TreeViewItem* const firstSelected = getSelectedItem (0);
  45539. if (firstSelected != 0)
  45540. rowSelected = firstSelected->getRowNumberInTree();
  45541. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45542. for (;;)
  45543. {
  45544. TreeViewItem* item = getItemOnRow (rowSelected);
  45545. if (item != 0)
  45546. {
  45547. if (! item->canBeSelected())
  45548. {
  45549. // if the row we want to highlight doesn't allow it, try skipping
  45550. // to the next item..
  45551. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45552. rowSelected + (delta < 0 ? -1 : 1));
  45553. if (rowSelected != nextRowToTry)
  45554. {
  45555. rowSelected = nextRowToTry;
  45556. continue;
  45557. }
  45558. else
  45559. {
  45560. break;
  45561. }
  45562. }
  45563. item->setSelected (true, true);
  45564. scrollToKeepItemVisible (item);
  45565. }
  45566. break;
  45567. }
  45568. }
  45569. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45570. {
  45571. if (item != 0 && item->ownerView == this)
  45572. {
  45573. handleAsyncUpdate();
  45574. item = item->getDeepestOpenParentItem();
  45575. int y = item->y;
  45576. int viewTop = viewport->getViewPositionY();
  45577. if (y < viewTop)
  45578. {
  45579. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45580. }
  45581. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45582. {
  45583. viewport->setViewPosition (viewport->getViewPositionX(),
  45584. (y + item->itemHeight) - viewport->getViewHeight());
  45585. }
  45586. }
  45587. }
  45588. bool TreeView::keyPressed (const KeyPress& key)
  45589. {
  45590. if (key.isKeyCode (KeyPress::upKey))
  45591. {
  45592. moveSelectedRow (-1);
  45593. }
  45594. else if (key.isKeyCode (KeyPress::downKey))
  45595. {
  45596. moveSelectedRow (1);
  45597. }
  45598. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45599. {
  45600. if (rootItem != 0)
  45601. {
  45602. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45603. if (key.isKeyCode (KeyPress::pageUpKey))
  45604. rowsOnScreen = -rowsOnScreen;
  45605. moveSelectedRow (rowsOnScreen);
  45606. }
  45607. }
  45608. else if (key.isKeyCode (KeyPress::homeKey))
  45609. {
  45610. moveSelectedRow (-0x3fffffff);
  45611. }
  45612. else if (key.isKeyCode (KeyPress::endKey))
  45613. {
  45614. moveSelectedRow (0x3fffffff);
  45615. }
  45616. else if (key.isKeyCode (KeyPress::returnKey))
  45617. {
  45618. TreeViewItem* const firstSelected = getSelectedItem (0);
  45619. if (firstSelected != 0)
  45620. firstSelected->setOpen (! firstSelected->isOpen());
  45621. }
  45622. else if (key.isKeyCode (KeyPress::leftKey))
  45623. {
  45624. TreeViewItem* const firstSelected = getSelectedItem (0);
  45625. if (firstSelected != 0)
  45626. {
  45627. if (firstSelected->isOpen())
  45628. {
  45629. firstSelected->setOpen (false);
  45630. }
  45631. else
  45632. {
  45633. TreeViewItem* parent = firstSelected->parentItem;
  45634. if ((! rootItemVisible) && parent == rootItem)
  45635. parent = 0;
  45636. if (parent != 0)
  45637. {
  45638. parent->setSelected (true, true);
  45639. scrollToKeepItemVisible (parent);
  45640. }
  45641. }
  45642. }
  45643. }
  45644. else if (key.isKeyCode (KeyPress::rightKey))
  45645. {
  45646. TreeViewItem* const firstSelected = getSelectedItem (0);
  45647. if (firstSelected != 0)
  45648. {
  45649. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45650. moveSelectedRow (1);
  45651. else
  45652. firstSelected->setOpen (true);
  45653. }
  45654. }
  45655. else
  45656. {
  45657. return false;
  45658. }
  45659. return true;
  45660. }
  45661. void TreeView::itemsChanged() throw()
  45662. {
  45663. needsRecalculating = true;
  45664. repaint();
  45665. triggerAsyncUpdate();
  45666. }
  45667. void TreeView::handleAsyncUpdate()
  45668. {
  45669. if (needsRecalculating)
  45670. {
  45671. needsRecalculating = false;
  45672. const ScopedLock sl (nodeAlterationLock);
  45673. if (rootItem != 0)
  45674. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45675. viewport->updateComponents();
  45676. if (rootItem != 0)
  45677. {
  45678. viewport->getViewedComponent()
  45679. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45680. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45681. }
  45682. else
  45683. {
  45684. viewport->getViewedComponent()->setSize (0, 0);
  45685. }
  45686. }
  45687. }
  45688. class TreeView::InsertPointHighlight : public Component
  45689. {
  45690. public:
  45691. InsertPointHighlight()
  45692. : lastItem (0)
  45693. {
  45694. setSize (100, 12);
  45695. setAlwaysOnTop (true);
  45696. setInterceptsMouseClicks (false, false);
  45697. }
  45698. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45699. {
  45700. lastItem = item;
  45701. lastIndex = insertIndex;
  45702. const int offset = getHeight() / 2;
  45703. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45704. }
  45705. void paint (Graphics& g)
  45706. {
  45707. Path p;
  45708. const float h = (float) getHeight();
  45709. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45710. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45711. p.lineTo ((float) getWidth(), h / 2.0f);
  45712. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45713. g.strokePath (p, PathStrokeType (2.0f));
  45714. }
  45715. TreeViewItem* lastItem;
  45716. int lastIndex;
  45717. private:
  45718. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45719. };
  45720. class TreeView::TargetGroupHighlight : public Component
  45721. {
  45722. public:
  45723. TargetGroupHighlight()
  45724. {
  45725. setAlwaysOnTop (true);
  45726. setInterceptsMouseClicks (false, false);
  45727. }
  45728. void setTargetPosition (TreeViewItem* const item) throw()
  45729. {
  45730. Rectangle<int> r (item->getItemPosition (true));
  45731. r.setHeight (item->getItemHeight());
  45732. setBounds (r);
  45733. }
  45734. void paint (Graphics& g)
  45735. {
  45736. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45737. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45738. }
  45739. private:
  45740. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45741. };
  45742. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45743. {
  45744. beginDragAutoRepeat (100);
  45745. if (dragInsertPointHighlight == 0)
  45746. {
  45747. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45748. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45749. }
  45750. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45751. dragTargetGroupHighlight->setTargetPosition (item);
  45752. }
  45753. void TreeView::hideDragHighlight() throw()
  45754. {
  45755. dragInsertPointHighlight = 0;
  45756. dragTargetGroupHighlight = 0;
  45757. }
  45758. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45759. const StringArray& files, const String& sourceDescription,
  45760. Component* sourceComponent) const throw()
  45761. {
  45762. insertIndex = 0;
  45763. TreeViewItem* item = getItemAt (y);
  45764. if (item == 0)
  45765. return 0;
  45766. Rectangle<int> itemPos (item->getItemPosition (true));
  45767. insertIndex = item->getIndexInParent();
  45768. const int oldY = y;
  45769. y = itemPos.getY();
  45770. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45771. {
  45772. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45773. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45774. {
  45775. // Check if we're trying to drag into an empty group item..
  45776. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45777. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45778. {
  45779. insertIndex = 0;
  45780. x = itemPos.getX() + getIndentSize();
  45781. y = itemPos.getBottom();
  45782. return item;
  45783. }
  45784. }
  45785. }
  45786. if (oldY > itemPos.getCentreY())
  45787. {
  45788. y += item->getItemHeight();
  45789. while (item->isLastOfSiblings() && item->parentItem != 0
  45790. && item->parentItem->parentItem != 0)
  45791. {
  45792. if (x > itemPos.getX())
  45793. break;
  45794. item = item->parentItem;
  45795. itemPos = item->getItemPosition (true);
  45796. insertIndex = item->getIndexInParent();
  45797. }
  45798. ++insertIndex;
  45799. }
  45800. x = itemPos.getX();
  45801. return item->parentItem;
  45802. }
  45803. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45804. {
  45805. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45806. int insertIndex;
  45807. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45808. if (item != 0)
  45809. {
  45810. if (scrolled || dragInsertPointHighlight == 0
  45811. || dragInsertPointHighlight->lastItem != item
  45812. || dragInsertPointHighlight->lastIndex != insertIndex)
  45813. {
  45814. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45815. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45816. showDragHighlight (item, insertIndex, x, y);
  45817. else
  45818. hideDragHighlight();
  45819. }
  45820. }
  45821. else
  45822. {
  45823. hideDragHighlight();
  45824. }
  45825. }
  45826. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45827. {
  45828. hideDragHighlight();
  45829. int insertIndex;
  45830. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45831. if (item != 0)
  45832. {
  45833. if (files.size() > 0)
  45834. {
  45835. if (item->isInterestedInFileDrag (files))
  45836. item->filesDropped (files, insertIndex);
  45837. }
  45838. else
  45839. {
  45840. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45841. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45842. }
  45843. }
  45844. }
  45845. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45846. {
  45847. return true;
  45848. }
  45849. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45850. {
  45851. fileDragMove (files, x, y);
  45852. }
  45853. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45854. {
  45855. handleDrag (files, String::empty, 0, x, y);
  45856. }
  45857. void TreeView::fileDragExit (const StringArray&)
  45858. {
  45859. hideDragHighlight();
  45860. }
  45861. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45862. {
  45863. handleDrop (files, String::empty, 0, x, y);
  45864. }
  45865. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45866. {
  45867. return true;
  45868. }
  45869. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45870. {
  45871. itemDragMove (sourceDescription, sourceComponent, x, y);
  45872. }
  45873. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45874. {
  45875. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45876. }
  45877. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45878. {
  45879. hideDragHighlight();
  45880. }
  45881. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45882. {
  45883. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45884. }
  45885. enum TreeViewOpenness
  45886. {
  45887. opennessDefault = 0,
  45888. opennessClosed = 1,
  45889. opennessOpen = 2
  45890. };
  45891. TreeViewItem::TreeViewItem()
  45892. : ownerView (0),
  45893. parentItem (0),
  45894. y (0),
  45895. itemHeight (0),
  45896. totalHeight (0),
  45897. selected (false),
  45898. redrawNeeded (true),
  45899. drawLinesInside (true),
  45900. drawsInLeftMargin (false),
  45901. openness (opennessDefault)
  45902. {
  45903. static int nextUID = 0;
  45904. uid = nextUID++;
  45905. }
  45906. TreeViewItem::~TreeViewItem()
  45907. {
  45908. }
  45909. const String TreeViewItem::getUniqueName() const
  45910. {
  45911. return String::empty;
  45912. }
  45913. void TreeViewItem::itemOpennessChanged (bool)
  45914. {
  45915. }
  45916. int TreeViewItem::getNumSubItems() const throw()
  45917. {
  45918. return subItems.size();
  45919. }
  45920. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45921. {
  45922. return subItems [index];
  45923. }
  45924. void TreeViewItem::clearSubItems()
  45925. {
  45926. if (subItems.size() > 0)
  45927. {
  45928. if (ownerView != 0)
  45929. {
  45930. const ScopedLock sl (ownerView->nodeAlterationLock);
  45931. subItems.clear();
  45932. treeHasChanged();
  45933. }
  45934. else
  45935. {
  45936. subItems.clear();
  45937. }
  45938. }
  45939. }
  45940. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45941. {
  45942. if (newItem != 0)
  45943. {
  45944. newItem->parentItem = this;
  45945. newItem->setOwnerView (ownerView);
  45946. newItem->y = 0;
  45947. newItem->itemHeight = newItem->getItemHeight();
  45948. newItem->totalHeight = 0;
  45949. newItem->itemWidth = newItem->getItemWidth();
  45950. newItem->totalWidth = 0;
  45951. if (ownerView != 0)
  45952. {
  45953. const ScopedLock sl (ownerView->nodeAlterationLock);
  45954. subItems.insert (insertPosition, newItem);
  45955. treeHasChanged();
  45956. if (newItem->isOpen())
  45957. newItem->itemOpennessChanged (true);
  45958. }
  45959. else
  45960. {
  45961. subItems.insert (insertPosition, newItem);
  45962. if (newItem->isOpen())
  45963. newItem->itemOpennessChanged (true);
  45964. }
  45965. }
  45966. }
  45967. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45968. {
  45969. if (ownerView != 0)
  45970. {
  45971. const ScopedLock sl (ownerView->nodeAlterationLock);
  45972. if (((unsigned int) index) < (unsigned int) subItems.size())
  45973. {
  45974. subItems.remove (index, deleteItem);
  45975. treeHasChanged();
  45976. }
  45977. }
  45978. else
  45979. {
  45980. subItems.remove (index, deleteItem);
  45981. }
  45982. }
  45983. bool TreeViewItem::isOpen() const throw()
  45984. {
  45985. if (openness == opennessDefault)
  45986. return ownerView != 0 && ownerView->defaultOpenness;
  45987. else
  45988. return openness == opennessOpen;
  45989. }
  45990. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45991. {
  45992. if (isOpen() != shouldBeOpen)
  45993. {
  45994. openness = shouldBeOpen ? opennessOpen
  45995. : opennessClosed;
  45996. treeHasChanged();
  45997. itemOpennessChanged (isOpen());
  45998. }
  45999. }
  46000. bool TreeViewItem::isSelected() const throw()
  46001. {
  46002. return selected;
  46003. }
  46004. void TreeViewItem::deselectAllRecursively()
  46005. {
  46006. setSelected (false, false);
  46007. for (int i = 0; i < subItems.size(); ++i)
  46008. subItems.getUnchecked(i)->deselectAllRecursively();
  46009. }
  46010. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46011. const bool deselectOtherItemsFirst)
  46012. {
  46013. if (shouldBeSelected && ! canBeSelected())
  46014. return;
  46015. if (deselectOtherItemsFirst)
  46016. getTopLevelItem()->deselectAllRecursively();
  46017. if (shouldBeSelected != selected)
  46018. {
  46019. selected = shouldBeSelected;
  46020. if (ownerView != 0)
  46021. ownerView->repaint();
  46022. itemSelectionChanged (shouldBeSelected);
  46023. }
  46024. }
  46025. void TreeViewItem::paintItem (Graphics&, int, int)
  46026. {
  46027. }
  46028. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46029. {
  46030. ownerView->getLookAndFeel()
  46031. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46032. }
  46033. void TreeViewItem::itemClicked (const MouseEvent&)
  46034. {
  46035. }
  46036. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46037. {
  46038. if (mightContainSubItems())
  46039. setOpen (! isOpen());
  46040. }
  46041. void TreeViewItem::itemSelectionChanged (bool)
  46042. {
  46043. }
  46044. const String TreeViewItem::getTooltip()
  46045. {
  46046. return String::empty;
  46047. }
  46048. const String TreeViewItem::getDragSourceDescription()
  46049. {
  46050. return String::empty;
  46051. }
  46052. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46053. {
  46054. return false;
  46055. }
  46056. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46057. {
  46058. }
  46059. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46060. {
  46061. return false;
  46062. }
  46063. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46064. {
  46065. }
  46066. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46067. {
  46068. const int indentX = getIndentX();
  46069. int width = itemWidth;
  46070. if (ownerView != 0 && width < 0)
  46071. width = ownerView->viewport->getViewWidth() - indentX;
  46072. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46073. if (relativeToTreeViewTopLeft)
  46074. r -= ownerView->viewport->getViewPosition();
  46075. return r;
  46076. }
  46077. void TreeViewItem::treeHasChanged() const throw()
  46078. {
  46079. if (ownerView != 0)
  46080. ownerView->itemsChanged();
  46081. }
  46082. void TreeViewItem::repaintItem() const
  46083. {
  46084. if (ownerView != 0 && areAllParentsOpen())
  46085. {
  46086. Rectangle<int> r (getItemPosition (true));
  46087. r.setLeft (0);
  46088. ownerView->viewport->repaint (r);
  46089. }
  46090. }
  46091. bool TreeViewItem::areAllParentsOpen() const throw()
  46092. {
  46093. return parentItem == 0
  46094. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46095. }
  46096. void TreeViewItem::updatePositions (int newY)
  46097. {
  46098. y = newY;
  46099. itemHeight = getItemHeight();
  46100. totalHeight = itemHeight;
  46101. itemWidth = getItemWidth();
  46102. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46103. if (isOpen())
  46104. {
  46105. newY += totalHeight;
  46106. for (int i = 0; i < subItems.size(); ++i)
  46107. {
  46108. TreeViewItem* const ti = subItems.getUnchecked(i);
  46109. ti->updatePositions (newY);
  46110. newY += ti->totalHeight;
  46111. totalHeight += ti->totalHeight;
  46112. totalWidth = jmax (totalWidth, ti->totalWidth);
  46113. }
  46114. }
  46115. }
  46116. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46117. {
  46118. TreeViewItem* result = this;
  46119. TreeViewItem* item = this;
  46120. while (item->parentItem != 0)
  46121. {
  46122. item = item->parentItem;
  46123. if (! item->isOpen())
  46124. result = item;
  46125. }
  46126. return result;
  46127. }
  46128. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46129. {
  46130. ownerView = newOwner;
  46131. for (int i = subItems.size(); --i >= 0;)
  46132. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46133. }
  46134. int TreeViewItem::getIndentX() const throw()
  46135. {
  46136. const int indentWidth = ownerView->getIndentSize();
  46137. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46138. if (! ownerView->openCloseButtonsVisible)
  46139. x -= indentWidth;
  46140. TreeViewItem* p = parentItem;
  46141. while (p != 0)
  46142. {
  46143. x += indentWidth;
  46144. p = p->parentItem;
  46145. }
  46146. return x;
  46147. }
  46148. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46149. {
  46150. drawsInLeftMargin = canDrawInLeftMargin;
  46151. }
  46152. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46153. {
  46154. jassert (ownerView != 0);
  46155. if (ownerView == 0)
  46156. return;
  46157. const int indent = getIndentX();
  46158. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46159. {
  46160. g.saveState();
  46161. g.setOrigin (indent, 0);
  46162. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46163. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46164. paintItem (g, itemW, itemHeight);
  46165. g.restoreState();
  46166. }
  46167. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46168. const float halfH = itemHeight * 0.5f;
  46169. int depth = 0;
  46170. TreeViewItem* p = parentItem;
  46171. while (p != 0)
  46172. {
  46173. ++depth;
  46174. p = p->parentItem;
  46175. }
  46176. if (! ownerView->rootItemVisible)
  46177. --depth;
  46178. const int indentWidth = ownerView->getIndentSize();
  46179. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46180. {
  46181. float x = (depth + 0.5f) * indentWidth;
  46182. if (depth >= 0)
  46183. {
  46184. if (parentItem != 0 && parentItem->drawLinesInside)
  46185. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46186. if ((parentItem != 0 && parentItem->drawLinesInside)
  46187. || (parentItem == 0 && drawLinesInside))
  46188. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46189. }
  46190. p = parentItem;
  46191. int d = depth;
  46192. while (p != 0 && --d >= 0)
  46193. {
  46194. x -= (float) indentWidth;
  46195. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46196. && ! p->isLastOfSiblings())
  46197. {
  46198. g.drawLine (x, 0, x, (float) itemHeight);
  46199. }
  46200. p = p->parentItem;
  46201. }
  46202. if (mightContainSubItems())
  46203. {
  46204. g.saveState();
  46205. g.setOrigin (depth * indentWidth, 0);
  46206. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46207. paintOpenCloseButton (g, indentWidth, itemHeight,
  46208. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46209. ->isMouseOverButton (this));
  46210. g.restoreState();
  46211. }
  46212. }
  46213. if (isOpen())
  46214. {
  46215. const Rectangle<int> clip (g.getClipBounds());
  46216. for (int i = 0; i < subItems.size(); ++i)
  46217. {
  46218. TreeViewItem* const ti = subItems.getUnchecked(i);
  46219. const int relY = ti->y - y;
  46220. if (relY >= clip.getBottom())
  46221. break;
  46222. if (relY + ti->totalHeight >= clip.getY())
  46223. {
  46224. g.saveState();
  46225. g.setOrigin (0, relY);
  46226. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46227. ti->paintRecursively (g, width);
  46228. g.restoreState();
  46229. }
  46230. }
  46231. }
  46232. }
  46233. bool TreeViewItem::isLastOfSiblings() const throw()
  46234. {
  46235. return parentItem == 0
  46236. || parentItem->subItems.getLast() == this;
  46237. }
  46238. int TreeViewItem::getIndexInParent() const throw()
  46239. {
  46240. return parentItem == 0 ? 0
  46241. : parentItem->subItems.indexOf (this);
  46242. }
  46243. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46244. {
  46245. return parentItem == 0 ? this
  46246. : parentItem->getTopLevelItem();
  46247. }
  46248. int TreeViewItem::getNumRows() const throw()
  46249. {
  46250. int num = 1;
  46251. if (isOpen())
  46252. {
  46253. for (int i = subItems.size(); --i >= 0;)
  46254. num += subItems.getUnchecked(i)->getNumRows();
  46255. }
  46256. return num;
  46257. }
  46258. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46259. {
  46260. if (index == 0)
  46261. return this;
  46262. if (index > 0 && isOpen())
  46263. {
  46264. --index;
  46265. for (int i = 0; i < subItems.size(); ++i)
  46266. {
  46267. TreeViewItem* const item = subItems.getUnchecked(i);
  46268. if (index == 0)
  46269. return item;
  46270. const int numRows = item->getNumRows();
  46271. if (numRows > index)
  46272. return item->getItemOnRow (index);
  46273. index -= numRows;
  46274. }
  46275. }
  46276. return 0;
  46277. }
  46278. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46279. {
  46280. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46281. {
  46282. const int h = itemHeight;
  46283. if (targetY < h)
  46284. return this;
  46285. if (isOpen())
  46286. {
  46287. targetY -= h;
  46288. for (int i = 0; i < subItems.size(); ++i)
  46289. {
  46290. TreeViewItem* const ti = subItems.getUnchecked(i);
  46291. if (targetY < ti->totalHeight)
  46292. return ti->findItemRecursively (targetY);
  46293. targetY -= ti->totalHeight;
  46294. }
  46295. }
  46296. }
  46297. return 0;
  46298. }
  46299. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46300. {
  46301. int total = isSelected() ? 1 : 0;
  46302. for (int i = subItems.size(); --i >= 0;)
  46303. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46304. return total;
  46305. }
  46306. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46307. {
  46308. if (isSelected())
  46309. {
  46310. if (index == 0)
  46311. return this;
  46312. --index;
  46313. }
  46314. if (index >= 0)
  46315. {
  46316. for (int i = 0; i < subItems.size(); ++i)
  46317. {
  46318. TreeViewItem* const item = subItems.getUnchecked(i);
  46319. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46320. if (found != 0)
  46321. return found;
  46322. index -= item->countSelectedItemsRecursively();
  46323. }
  46324. }
  46325. return 0;
  46326. }
  46327. int TreeViewItem::getRowNumberInTree() const throw()
  46328. {
  46329. if (parentItem != 0 && ownerView != 0)
  46330. {
  46331. int n = 1 + parentItem->getRowNumberInTree();
  46332. int ourIndex = parentItem->subItems.indexOf (this);
  46333. jassert (ourIndex >= 0);
  46334. while (--ourIndex >= 0)
  46335. n += parentItem->subItems [ourIndex]->getNumRows();
  46336. if (parentItem->parentItem == 0
  46337. && ! ownerView->rootItemVisible)
  46338. --n;
  46339. return n;
  46340. }
  46341. else
  46342. {
  46343. return 0;
  46344. }
  46345. }
  46346. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46347. {
  46348. drawLinesInside = drawLines;
  46349. }
  46350. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46351. {
  46352. if (recurse && isOpen() && subItems.size() > 0)
  46353. return subItems [0];
  46354. if (parentItem != 0)
  46355. {
  46356. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46357. if (nextIndex >= parentItem->subItems.size())
  46358. return parentItem->getNextVisibleItem (false);
  46359. return parentItem->subItems [nextIndex];
  46360. }
  46361. return 0;
  46362. }
  46363. const String TreeViewItem::getItemIdentifierString() const
  46364. {
  46365. String s;
  46366. if (parentItem != 0)
  46367. s = parentItem->getItemIdentifierString();
  46368. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46369. }
  46370. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46371. {
  46372. const String thisId (getUniqueName());
  46373. if (thisId == identifierString)
  46374. return this;
  46375. if (identifierString.startsWith (thisId + "/"))
  46376. {
  46377. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46378. bool wasOpen = isOpen();
  46379. setOpen (true);
  46380. for (int i = subItems.size(); --i >= 0;)
  46381. {
  46382. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46383. if (item != 0)
  46384. return item;
  46385. }
  46386. setOpen (wasOpen);
  46387. }
  46388. return 0;
  46389. }
  46390. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46391. {
  46392. if (e.hasTagName ("CLOSED"))
  46393. {
  46394. setOpen (false);
  46395. }
  46396. else if (e.hasTagName ("OPEN"))
  46397. {
  46398. setOpen (true);
  46399. forEachXmlChildElement (e, n)
  46400. {
  46401. const String id (n->getStringAttribute ("id"));
  46402. for (int i = 0; i < subItems.size(); ++i)
  46403. {
  46404. TreeViewItem* const ti = subItems.getUnchecked(i);
  46405. if (ti->getUniqueName() == id)
  46406. {
  46407. ti->restoreOpennessState (*n);
  46408. break;
  46409. }
  46410. }
  46411. }
  46412. }
  46413. }
  46414. XmlElement* TreeViewItem::getOpennessState() const throw()
  46415. {
  46416. const String name (getUniqueName());
  46417. if (name.isNotEmpty())
  46418. {
  46419. XmlElement* e;
  46420. if (isOpen())
  46421. {
  46422. e = new XmlElement ("OPEN");
  46423. for (int i = 0; i < subItems.size(); ++i)
  46424. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46425. }
  46426. else
  46427. {
  46428. e = new XmlElement ("CLOSED");
  46429. }
  46430. e->setAttribute ("id", name);
  46431. return e;
  46432. }
  46433. else
  46434. {
  46435. // trying to save the openness for an element that has no name - this won't
  46436. // work because it needs the names to identify what to open.
  46437. jassertfalse;
  46438. }
  46439. return 0;
  46440. }
  46441. END_JUCE_NAMESPACE
  46442. /*** End of inlined file: juce_TreeView.cpp ***/
  46443. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46444. BEGIN_JUCE_NAMESPACE
  46445. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46446. : fileList (listToShow)
  46447. {
  46448. }
  46449. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46450. {
  46451. }
  46452. FileBrowserListener::~FileBrowserListener()
  46453. {
  46454. }
  46455. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46456. {
  46457. listeners.add (listener);
  46458. }
  46459. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46460. {
  46461. listeners.remove (listener);
  46462. }
  46463. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46464. {
  46465. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46466. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46467. }
  46468. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46469. {
  46470. if (fileList.getDirectory().exists())
  46471. {
  46472. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46473. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46474. }
  46475. }
  46476. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46477. {
  46478. if (fileList.getDirectory().exists())
  46479. {
  46480. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46481. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46482. }
  46483. }
  46484. END_JUCE_NAMESPACE
  46485. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46486. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46487. BEGIN_JUCE_NAMESPACE
  46488. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46489. TimeSliceThread& thread_)
  46490. : fileFilter (fileFilter_),
  46491. thread (thread_),
  46492. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46493. fileFindHandle (0),
  46494. shouldStop (true)
  46495. {
  46496. }
  46497. DirectoryContentsList::~DirectoryContentsList()
  46498. {
  46499. clear();
  46500. }
  46501. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46502. {
  46503. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46504. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46505. }
  46506. bool DirectoryContentsList::ignoresHiddenFiles() const
  46507. {
  46508. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46509. }
  46510. const File& DirectoryContentsList::getDirectory() const
  46511. {
  46512. return root;
  46513. }
  46514. void DirectoryContentsList::setDirectory (const File& directory,
  46515. const bool includeDirectories,
  46516. const bool includeFiles)
  46517. {
  46518. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46519. if (directory != root)
  46520. {
  46521. clear();
  46522. root = directory;
  46523. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46524. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46525. }
  46526. int newFlags = fileTypeFlags;
  46527. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46528. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46529. setTypeFlags (newFlags);
  46530. }
  46531. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46532. {
  46533. if (fileTypeFlags != newFlags)
  46534. {
  46535. fileTypeFlags = newFlags;
  46536. refresh();
  46537. }
  46538. }
  46539. void DirectoryContentsList::clear()
  46540. {
  46541. shouldStop = true;
  46542. thread.removeTimeSliceClient (this);
  46543. fileFindHandle = 0;
  46544. if (files.size() > 0)
  46545. {
  46546. files.clear();
  46547. changed();
  46548. }
  46549. }
  46550. void DirectoryContentsList::refresh()
  46551. {
  46552. clear();
  46553. if (root.isDirectory())
  46554. {
  46555. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46556. shouldStop = false;
  46557. thread.addTimeSliceClient (this);
  46558. }
  46559. }
  46560. int DirectoryContentsList::getNumFiles() const
  46561. {
  46562. return files.size();
  46563. }
  46564. bool DirectoryContentsList::getFileInfo (const int index,
  46565. FileInfo& result) const
  46566. {
  46567. const ScopedLock sl (fileListLock);
  46568. const FileInfo* const info = files [index];
  46569. if (info != 0)
  46570. {
  46571. result = *info;
  46572. return true;
  46573. }
  46574. return false;
  46575. }
  46576. const File DirectoryContentsList::getFile (const int index) const
  46577. {
  46578. const ScopedLock sl (fileListLock);
  46579. const FileInfo* const info = files [index];
  46580. if (info != 0)
  46581. return root.getChildFile (info->filename);
  46582. return File::nonexistent;
  46583. }
  46584. bool DirectoryContentsList::isStillLoading() const
  46585. {
  46586. return fileFindHandle != 0;
  46587. }
  46588. void DirectoryContentsList::changed()
  46589. {
  46590. sendChangeMessage();
  46591. }
  46592. bool DirectoryContentsList::useTimeSlice()
  46593. {
  46594. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46595. bool hasChanged = false;
  46596. for (int i = 100; --i >= 0;)
  46597. {
  46598. if (! checkNextFile (hasChanged))
  46599. {
  46600. if (hasChanged)
  46601. changed();
  46602. return false;
  46603. }
  46604. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46605. break;
  46606. }
  46607. if (hasChanged)
  46608. changed();
  46609. return true;
  46610. }
  46611. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46612. {
  46613. if (fileFindHandle != 0)
  46614. {
  46615. bool fileFoundIsDir, isHidden, isReadOnly;
  46616. int64 fileSize;
  46617. Time modTime, creationTime;
  46618. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46619. &modTime, &creationTime, &isReadOnly))
  46620. {
  46621. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46622. fileSize, modTime, creationTime, isReadOnly))
  46623. {
  46624. hasChanged = true;
  46625. }
  46626. return true;
  46627. }
  46628. else
  46629. {
  46630. fileFindHandle = 0;
  46631. }
  46632. }
  46633. return false;
  46634. }
  46635. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46636. const DirectoryContentsList::FileInfo* const second)
  46637. {
  46638. #if JUCE_WINDOWS
  46639. if (first->isDirectory != second->isDirectory)
  46640. return first->isDirectory ? -1 : 1;
  46641. #endif
  46642. return first->filename.compareIgnoreCase (second->filename);
  46643. }
  46644. bool DirectoryContentsList::addFile (const File& file,
  46645. const bool isDir,
  46646. const int64 fileSize,
  46647. const Time& modTime,
  46648. const Time& creationTime,
  46649. const bool isReadOnly)
  46650. {
  46651. if (fileFilter == 0
  46652. || ((! isDir) && fileFilter->isFileSuitable (file))
  46653. || (isDir && fileFilter->isDirectorySuitable (file)))
  46654. {
  46655. ScopedPointer <FileInfo> info (new FileInfo());
  46656. info->filename = file.getFileName();
  46657. info->fileSize = fileSize;
  46658. info->modificationTime = modTime;
  46659. info->creationTime = creationTime;
  46660. info->isDirectory = isDir;
  46661. info->isReadOnly = isReadOnly;
  46662. const ScopedLock sl (fileListLock);
  46663. for (int i = files.size(); --i >= 0;)
  46664. if (files.getUnchecked(i)->filename == info->filename)
  46665. return false;
  46666. files.addSorted (*this, info.release());
  46667. return true;
  46668. }
  46669. return false;
  46670. }
  46671. END_JUCE_NAMESPACE
  46672. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46673. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46674. BEGIN_JUCE_NAMESPACE
  46675. FileBrowserComponent::FileBrowserComponent (int flags_,
  46676. const File& initialFileOrDirectory,
  46677. const FileFilter* fileFilter_,
  46678. FilePreviewComponent* previewComp_)
  46679. : FileFilter (String::empty),
  46680. fileFilter (fileFilter_),
  46681. flags (flags_),
  46682. previewComp (previewComp_),
  46683. currentPathBox ("path"),
  46684. fileLabel ("f", TRANS ("file:")),
  46685. thread ("Juce FileBrowser")
  46686. {
  46687. // You need to specify one or other of the open/save flags..
  46688. jassert ((flags & (saveMode | openMode)) != 0);
  46689. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46690. // You need to specify at least one of these flags..
  46691. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46692. String filename;
  46693. if (initialFileOrDirectory == File::nonexistent)
  46694. {
  46695. currentRoot = File::getCurrentWorkingDirectory();
  46696. }
  46697. else if (initialFileOrDirectory.isDirectory())
  46698. {
  46699. currentRoot = initialFileOrDirectory;
  46700. }
  46701. else
  46702. {
  46703. chosenFiles.add (initialFileOrDirectory);
  46704. currentRoot = initialFileOrDirectory.getParentDirectory();
  46705. filename = initialFileOrDirectory.getFileName();
  46706. }
  46707. fileList = new DirectoryContentsList (this, thread);
  46708. if ((flags & useTreeView) != 0)
  46709. {
  46710. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46711. fileListComponent = tree;
  46712. if ((flags & canSelectMultipleItems) != 0)
  46713. tree->setMultiSelectEnabled (true);
  46714. addAndMakeVisible (tree);
  46715. }
  46716. else
  46717. {
  46718. FileListComponent* const list = new FileListComponent (*fileList);
  46719. fileListComponent = list;
  46720. list->setOutlineThickness (1);
  46721. if ((flags & canSelectMultipleItems) != 0)
  46722. list->setMultipleSelectionEnabled (true);
  46723. addAndMakeVisible (list);
  46724. }
  46725. fileListComponent->addListener (this);
  46726. addAndMakeVisible (&currentPathBox);
  46727. currentPathBox.setEditableText (true);
  46728. StringArray rootNames, rootPaths;
  46729. const BigInteger separators (getRoots (rootNames, rootPaths));
  46730. for (int i = 0; i < rootNames.size(); ++i)
  46731. {
  46732. if (separators [i])
  46733. currentPathBox.addSeparator();
  46734. currentPathBox.addItem (rootNames[i], i + 1);
  46735. }
  46736. currentPathBox.addSeparator();
  46737. currentPathBox.addListener (this);
  46738. addAndMakeVisible (&filenameBox);
  46739. filenameBox.setMultiLine (false);
  46740. filenameBox.setSelectAllWhenFocused (true);
  46741. filenameBox.setText (filename, false);
  46742. filenameBox.addListener (this);
  46743. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46744. addAndMakeVisible (&fileLabel);
  46745. fileLabel.attachToComponent (&filenameBox, true);
  46746. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46747. goUpButton->addButtonListener (this);
  46748. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46749. if (previewComp != 0)
  46750. addAndMakeVisible (previewComp);
  46751. setRoot (currentRoot);
  46752. thread.startThread (4);
  46753. }
  46754. FileBrowserComponent::~FileBrowserComponent()
  46755. {
  46756. fileListComponent = 0;
  46757. fileList = 0;
  46758. thread.stopThread (10000);
  46759. }
  46760. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46761. {
  46762. listeners.add (newListener);
  46763. }
  46764. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46765. {
  46766. listeners.remove (listener);
  46767. }
  46768. bool FileBrowserComponent::isSaveMode() const throw()
  46769. {
  46770. return (flags & saveMode) != 0;
  46771. }
  46772. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46773. {
  46774. if (chosenFiles.size() == 0 && currentFileIsValid())
  46775. return 1;
  46776. return chosenFiles.size();
  46777. }
  46778. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46779. {
  46780. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46781. return currentRoot;
  46782. if (! filenameBox.isReadOnly())
  46783. return currentRoot.getChildFile (filenameBox.getText());
  46784. return chosenFiles[index];
  46785. }
  46786. bool FileBrowserComponent::currentFileIsValid() const
  46787. {
  46788. if (isSaveMode())
  46789. return ! getSelectedFile (0).isDirectory();
  46790. else
  46791. return getSelectedFile (0).exists();
  46792. }
  46793. const File FileBrowserComponent::getHighlightedFile() const throw()
  46794. {
  46795. return fileListComponent->getSelectedFile (0);
  46796. }
  46797. void FileBrowserComponent::deselectAllFiles()
  46798. {
  46799. fileListComponent->deselectAllFiles();
  46800. }
  46801. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46802. {
  46803. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46804. }
  46805. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46806. {
  46807. return true;
  46808. }
  46809. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46810. {
  46811. if (f.isDirectory())
  46812. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46813. return (flags & canSelectFiles) != 0 && f.exists()
  46814. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46815. }
  46816. const File FileBrowserComponent::getRoot() const
  46817. {
  46818. return currentRoot;
  46819. }
  46820. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46821. {
  46822. if (currentRoot != newRootDirectory)
  46823. {
  46824. fileListComponent->scrollToTop();
  46825. String path (newRootDirectory.getFullPathName());
  46826. if (path.isEmpty())
  46827. path = File::separatorString;
  46828. StringArray rootNames, rootPaths;
  46829. getRoots (rootNames, rootPaths);
  46830. if (! rootPaths.contains (path, true))
  46831. {
  46832. bool alreadyListed = false;
  46833. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46834. {
  46835. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46836. {
  46837. alreadyListed = true;
  46838. break;
  46839. }
  46840. }
  46841. if (! alreadyListed)
  46842. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46843. }
  46844. }
  46845. currentRoot = newRootDirectory;
  46846. fileList->setDirectory (currentRoot, true, true);
  46847. String currentRootName (currentRoot.getFullPathName());
  46848. if (currentRootName.isEmpty())
  46849. currentRootName = File::separatorString;
  46850. currentPathBox.setText (currentRootName, true);
  46851. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46852. && currentRoot.getParentDirectory() != currentRoot);
  46853. }
  46854. void FileBrowserComponent::goUp()
  46855. {
  46856. setRoot (getRoot().getParentDirectory());
  46857. }
  46858. void FileBrowserComponent::refresh()
  46859. {
  46860. fileList->refresh();
  46861. }
  46862. const String FileBrowserComponent::getActionVerb() const
  46863. {
  46864. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46865. }
  46866. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46867. {
  46868. return previewComp;
  46869. }
  46870. void FileBrowserComponent::resized()
  46871. {
  46872. getLookAndFeel()
  46873. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46874. &currentPathBox, &filenameBox, goUpButton);
  46875. }
  46876. void FileBrowserComponent::sendListenerChangeMessage()
  46877. {
  46878. Component::BailOutChecker checker (this);
  46879. if (previewComp != 0)
  46880. previewComp->selectedFileChanged (getSelectedFile (0));
  46881. // You shouldn't delete the browser when the file gets changed!
  46882. jassert (! checker.shouldBailOut());
  46883. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46884. }
  46885. void FileBrowserComponent::selectionChanged()
  46886. {
  46887. StringArray newFilenames;
  46888. bool resetChosenFiles = true;
  46889. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46890. {
  46891. const File f (fileListComponent->getSelectedFile (i));
  46892. if (isFileOrDirSuitable (f))
  46893. {
  46894. if (resetChosenFiles)
  46895. {
  46896. chosenFiles.clear();
  46897. resetChosenFiles = false;
  46898. }
  46899. chosenFiles.add (f);
  46900. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46901. }
  46902. }
  46903. if (newFilenames.size() > 0)
  46904. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46905. sendListenerChangeMessage();
  46906. }
  46907. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46908. {
  46909. Component::BailOutChecker checker (this);
  46910. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46911. }
  46912. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46913. {
  46914. if (f.isDirectory())
  46915. {
  46916. setRoot (f);
  46917. if ((flags & canSelectDirectories) != 0)
  46918. filenameBox.setText (String::empty);
  46919. }
  46920. else
  46921. {
  46922. Component::BailOutChecker checker (this);
  46923. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46924. }
  46925. }
  46926. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46927. {
  46928. (void) key;
  46929. #if JUCE_LINUX || JUCE_WINDOWS
  46930. if (key.getModifiers().isCommandDown()
  46931. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46932. {
  46933. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46934. fileList->refresh();
  46935. return true;
  46936. }
  46937. #endif
  46938. return false;
  46939. }
  46940. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46941. {
  46942. sendListenerChangeMessage();
  46943. }
  46944. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46945. {
  46946. if (filenameBox.getText().containsChar (File::separator))
  46947. {
  46948. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46949. if (f.isDirectory())
  46950. {
  46951. setRoot (f);
  46952. chosenFiles.clear();
  46953. filenameBox.setText (String::empty);
  46954. }
  46955. else
  46956. {
  46957. setRoot (f.getParentDirectory());
  46958. chosenFiles.clear();
  46959. chosenFiles.add (f);
  46960. filenameBox.setText (f.getFileName());
  46961. }
  46962. }
  46963. else
  46964. {
  46965. fileDoubleClicked (getSelectedFile (0));
  46966. }
  46967. }
  46968. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46969. {
  46970. }
  46971. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46972. {
  46973. if (! isSaveMode())
  46974. selectionChanged();
  46975. }
  46976. void FileBrowserComponent::buttonClicked (Button*)
  46977. {
  46978. goUp();
  46979. }
  46980. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46981. {
  46982. const String newText (currentPathBox.getText().trim().unquoted());
  46983. if (newText.isNotEmpty())
  46984. {
  46985. const int index = currentPathBox.getSelectedId() - 1;
  46986. StringArray rootNames, rootPaths;
  46987. getRoots (rootNames, rootPaths);
  46988. if (rootPaths [index].isNotEmpty())
  46989. {
  46990. setRoot (File (rootPaths [index]));
  46991. }
  46992. else
  46993. {
  46994. File f (newText);
  46995. for (;;)
  46996. {
  46997. if (f.isDirectory())
  46998. {
  46999. setRoot (f);
  47000. break;
  47001. }
  47002. if (f.getParentDirectory() == f)
  47003. break;
  47004. f = f.getParentDirectory();
  47005. }
  47006. }
  47007. }
  47008. }
  47009. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47010. {
  47011. BigInteger separators;
  47012. #if JUCE_WINDOWS
  47013. Array<File> roots;
  47014. File::findFileSystemRoots (roots);
  47015. rootPaths.clear();
  47016. for (int i = 0; i < roots.size(); ++i)
  47017. {
  47018. const File& drive = roots.getReference(i);
  47019. String name (drive.getFullPathName());
  47020. rootPaths.add (name);
  47021. if (drive.isOnHardDisk())
  47022. {
  47023. String volume (drive.getVolumeLabel());
  47024. if (volume.isEmpty())
  47025. volume = TRANS("Hard Drive");
  47026. name << " [" << volume << ']';
  47027. }
  47028. else if (drive.isOnCDRomDrive())
  47029. {
  47030. name << TRANS(" [CD/DVD drive]");
  47031. }
  47032. rootNames.add (name);
  47033. }
  47034. separators.setBit (rootPaths.size());
  47035. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47036. rootNames.add ("Documents");
  47037. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47038. rootNames.add ("Desktop");
  47039. #endif
  47040. #if JUCE_MAC
  47041. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47042. rootNames.add ("Home folder");
  47043. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47044. rootNames.add ("Documents");
  47045. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47046. rootNames.add ("Desktop");
  47047. separators.setBit (rootPaths.size());
  47048. Array <File> volumes;
  47049. File vol ("/Volumes");
  47050. vol.findChildFiles (volumes, File::findDirectories, false);
  47051. for (int i = 0; i < volumes.size(); ++i)
  47052. {
  47053. const File& volume = volumes.getReference(i);
  47054. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47055. {
  47056. rootPaths.add (volume.getFullPathName());
  47057. rootNames.add (volume.getFileName());
  47058. }
  47059. }
  47060. #endif
  47061. #if JUCE_LINUX
  47062. rootPaths.add ("/");
  47063. rootNames.add ("/");
  47064. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47065. rootNames.add ("Home folder");
  47066. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47067. rootNames.add ("Desktop");
  47068. #endif
  47069. return separators;
  47070. }
  47071. END_JUCE_NAMESPACE
  47072. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47073. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47074. BEGIN_JUCE_NAMESPACE
  47075. FileChooser::FileChooser (const String& chooserBoxTitle,
  47076. const File& currentFileOrDirectory,
  47077. const String& fileFilters,
  47078. const bool useNativeDialogBox_)
  47079. : title (chooserBoxTitle),
  47080. filters (fileFilters),
  47081. startingFile (currentFileOrDirectory),
  47082. useNativeDialogBox (useNativeDialogBox_)
  47083. {
  47084. #if JUCE_LINUX
  47085. useNativeDialogBox = false;
  47086. #endif
  47087. if (! fileFilters.containsNonWhitespaceChars())
  47088. filters = "*";
  47089. }
  47090. FileChooser::~FileChooser()
  47091. {
  47092. }
  47093. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47094. {
  47095. return showDialog (false, true, false, false, false, previewComponent);
  47096. }
  47097. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47098. {
  47099. return showDialog (false, true, false, false, true, previewComponent);
  47100. }
  47101. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47102. {
  47103. return showDialog (true, true, false, false, true, previewComponent);
  47104. }
  47105. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47106. {
  47107. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47108. }
  47109. bool FileChooser::browseForDirectory()
  47110. {
  47111. return showDialog (true, false, false, false, false, 0);
  47112. }
  47113. const File FileChooser::getResult() const
  47114. {
  47115. // if you've used a multiple-file select, you should use the getResults() method
  47116. // to retrieve all the files that were chosen.
  47117. jassert (results.size() <= 1);
  47118. return results.getFirst();
  47119. }
  47120. const Array<File>& FileChooser::getResults() const
  47121. {
  47122. return results;
  47123. }
  47124. bool FileChooser::showDialog (const bool selectsDirectories,
  47125. const bool selectsFiles,
  47126. const bool isSave,
  47127. const bool warnAboutOverwritingExistingFiles,
  47128. const bool selectMultipleFiles,
  47129. FilePreviewComponent* const previewComponent)
  47130. {
  47131. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47132. results.clear();
  47133. // the preview component needs to be the right size before you pass it in here..
  47134. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47135. && previewComponent->getHeight() > 10));
  47136. #if JUCE_WINDOWS
  47137. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47138. #elif JUCE_MAC
  47139. if (useNativeDialogBox && (previewComponent == 0))
  47140. #else
  47141. if (false)
  47142. #endif
  47143. {
  47144. showPlatformDialog (results, title, startingFile, filters,
  47145. selectsDirectories, selectsFiles, isSave,
  47146. warnAboutOverwritingExistingFiles,
  47147. selectMultipleFiles,
  47148. previewComponent);
  47149. }
  47150. else
  47151. {
  47152. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47153. selectsDirectories ? "*" : String::empty,
  47154. String::empty);
  47155. int flags = isSave ? FileBrowserComponent::saveMode
  47156. : FileBrowserComponent::openMode;
  47157. if (selectsFiles)
  47158. flags |= FileBrowserComponent::canSelectFiles;
  47159. if (selectsDirectories)
  47160. {
  47161. flags |= FileBrowserComponent::canSelectDirectories;
  47162. if (! isSave)
  47163. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47164. }
  47165. if (selectMultipleFiles)
  47166. flags |= FileBrowserComponent::canSelectMultipleItems;
  47167. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47168. FileChooserDialogBox box (title, String::empty,
  47169. browserComponent,
  47170. warnAboutOverwritingExistingFiles,
  47171. browserComponent.findColour (AlertWindow::backgroundColourId));
  47172. if (box.show())
  47173. {
  47174. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47175. results.add (browserComponent.getSelectedFile (i));
  47176. }
  47177. }
  47178. if (previouslyFocused != 0)
  47179. previouslyFocused->grabKeyboardFocus();
  47180. return results.size() > 0;
  47181. }
  47182. FilePreviewComponent::FilePreviewComponent()
  47183. {
  47184. }
  47185. FilePreviewComponent::~FilePreviewComponent()
  47186. {
  47187. }
  47188. END_JUCE_NAMESPACE
  47189. /*** End of inlined file: juce_FileChooser.cpp ***/
  47190. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47191. BEGIN_JUCE_NAMESPACE
  47192. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47193. const String& instructions,
  47194. FileBrowserComponent& chooserComponent,
  47195. const bool warnAboutOverwritingExistingFiles_,
  47196. const Colour& backgroundColour)
  47197. : ResizableWindow (name, backgroundColour, true),
  47198. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47199. {
  47200. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47201. setResizable (true, true);
  47202. setResizeLimits (300, 300, 1200, 1000);
  47203. content->okButton.addButtonListener (this);
  47204. content->cancelButton.addButtonListener (this);
  47205. content->chooserComponent.addListener (this);
  47206. }
  47207. FileChooserDialogBox::~FileChooserDialogBox()
  47208. {
  47209. content->chooserComponent.removeListener (this);
  47210. }
  47211. bool FileChooserDialogBox::show (int w, int h)
  47212. {
  47213. return showAt (-1, -1, w, h);
  47214. }
  47215. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47216. {
  47217. if (w <= 0)
  47218. {
  47219. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47220. if (previewComp != 0)
  47221. w = 400 + previewComp->getWidth();
  47222. else
  47223. w = 600;
  47224. }
  47225. if (h <= 0)
  47226. h = 500;
  47227. if (x < 0 || y < 0)
  47228. centreWithSize (w, h);
  47229. else
  47230. setBounds (x, y, w, h);
  47231. const bool ok = (runModalLoop() != 0);
  47232. setVisible (false);
  47233. return ok;
  47234. }
  47235. void FileChooserDialogBox::buttonClicked (Button* button)
  47236. {
  47237. if (button == &(content->okButton))
  47238. {
  47239. if (warnAboutOverwritingExistingFiles
  47240. && content->chooserComponent.isSaveMode()
  47241. && content->chooserComponent.getSelectedFile(0).exists())
  47242. {
  47243. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47244. TRANS("File already exists"),
  47245. TRANS("There's already a file called:")
  47246. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47247. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47248. TRANS("overwrite"),
  47249. TRANS("cancel")))
  47250. {
  47251. return;
  47252. }
  47253. }
  47254. exitModalState (1);
  47255. }
  47256. else if (button == &(content->cancelButton))
  47257. {
  47258. closeButtonPressed();
  47259. }
  47260. }
  47261. void FileChooserDialogBox::closeButtonPressed()
  47262. {
  47263. setVisible (false);
  47264. }
  47265. void FileChooserDialogBox::selectionChanged()
  47266. {
  47267. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47268. }
  47269. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47270. {
  47271. }
  47272. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47273. {
  47274. selectionChanged();
  47275. content->okButton.triggerClick();
  47276. }
  47277. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47278. : Component (name), instructions (instructions_),
  47279. chooserComponent (chooserComponent_),
  47280. okButton (chooserComponent_.getActionVerb()),
  47281. cancelButton (TRANS ("Cancel"))
  47282. {
  47283. addAndMakeVisible (&chooserComponent);
  47284. addAndMakeVisible (&okButton);
  47285. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47286. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47287. addAndMakeVisible (&cancelButton);
  47288. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47289. setInterceptsMouseClicks (false, true);
  47290. }
  47291. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47292. {
  47293. }
  47294. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47295. {
  47296. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47297. text.draw (g);
  47298. }
  47299. void FileChooserDialogBox::ContentComponent::resized()
  47300. {
  47301. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47302. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47303. const int y = roundToInt (bb.getBottom()) + 10;
  47304. const int buttonHeight = 26;
  47305. const int buttonY = getHeight() - buttonHeight - 8;
  47306. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47307. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47308. proportionOfWidth (0.2f), buttonHeight);
  47309. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47310. proportionOfWidth (0.2f), buttonHeight);
  47311. }
  47312. END_JUCE_NAMESPACE
  47313. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47314. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47315. BEGIN_JUCE_NAMESPACE
  47316. FileFilter::FileFilter (const String& filterDescription)
  47317. : description (filterDescription)
  47318. {
  47319. }
  47320. FileFilter::~FileFilter()
  47321. {
  47322. }
  47323. const String& FileFilter::getDescription() const throw()
  47324. {
  47325. return description;
  47326. }
  47327. END_JUCE_NAMESPACE
  47328. /*** End of inlined file: juce_FileFilter.cpp ***/
  47329. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47330. BEGIN_JUCE_NAMESPACE
  47331. const Image juce_createIconForFile (const File& file);
  47332. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47333. : ListBox (String::empty, 0),
  47334. DirectoryContentsDisplayComponent (listToShow)
  47335. {
  47336. setModel (this);
  47337. fileList.addChangeListener (this);
  47338. }
  47339. FileListComponent::~FileListComponent()
  47340. {
  47341. fileList.removeChangeListener (this);
  47342. }
  47343. int FileListComponent::getNumSelectedFiles() const
  47344. {
  47345. return getNumSelectedRows();
  47346. }
  47347. const File FileListComponent::getSelectedFile (int index) const
  47348. {
  47349. return fileList.getFile (getSelectedRow (index));
  47350. }
  47351. void FileListComponent::deselectAllFiles()
  47352. {
  47353. deselectAllRows();
  47354. }
  47355. void FileListComponent::scrollToTop()
  47356. {
  47357. getVerticalScrollBar()->setCurrentRangeStart (0);
  47358. }
  47359. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47360. {
  47361. updateContent();
  47362. if (lastDirectory != fileList.getDirectory())
  47363. {
  47364. lastDirectory = fileList.getDirectory();
  47365. deselectAllRows();
  47366. }
  47367. }
  47368. class FileListItemComponent : public Component,
  47369. public TimeSliceClient,
  47370. public AsyncUpdater
  47371. {
  47372. public:
  47373. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47374. : owner (owner_), thread (thread_),
  47375. highlighted (false), index (0), icon (0)
  47376. {
  47377. }
  47378. ~FileListItemComponent()
  47379. {
  47380. thread.removeTimeSliceClient (this);
  47381. clearIcon();
  47382. }
  47383. void paint (Graphics& g)
  47384. {
  47385. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47386. file.getFileName(),
  47387. &icon,
  47388. fileSize, modTime,
  47389. isDirectory, highlighted,
  47390. index, owner);
  47391. }
  47392. void mouseDown (const MouseEvent& e)
  47393. {
  47394. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47395. owner.sendMouseClickMessage (file, e);
  47396. }
  47397. void mouseDoubleClick (const MouseEvent&)
  47398. {
  47399. owner.sendDoubleClickMessage (file);
  47400. }
  47401. void update (const File& root,
  47402. const DirectoryContentsList::FileInfo* const fileInfo,
  47403. const int index_,
  47404. const bool highlighted_)
  47405. {
  47406. thread.removeTimeSliceClient (this);
  47407. if (highlighted_ != highlighted
  47408. || index_ != index)
  47409. {
  47410. index = index_;
  47411. highlighted = highlighted_;
  47412. repaint();
  47413. }
  47414. File newFile;
  47415. String newFileSize;
  47416. String newModTime;
  47417. if (fileInfo != 0)
  47418. {
  47419. newFile = root.getChildFile (fileInfo->filename);
  47420. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47421. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47422. }
  47423. if (newFile != file
  47424. || fileSize != newFileSize
  47425. || modTime != newModTime)
  47426. {
  47427. file = newFile;
  47428. fileSize = newFileSize;
  47429. modTime = newModTime;
  47430. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47431. repaint();
  47432. clearIcon();
  47433. }
  47434. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47435. {
  47436. updateIcon (true);
  47437. if (! icon.isValid())
  47438. thread.addTimeSliceClient (this);
  47439. }
  47440. }
  47441. bool useTimeSlice()
  47442. {
  47443. updateIcon (false);
  47444. return false;
  47445. }
  47446. void handleAsyncUpdate()
  47447. {
  47448. repaint();
  47449. }
  47450. private:
  47451. FileListComponent& owner;
  47452. TimeSliceThread& thread;
  47453. bool highlighted;
  47454. int index;
  47455. File file;
  47456. String fileSize;
  47457. String modTime;
  47458. Image icon;
  47459. bool isDirectory;
  47460. void clearIcon()
  47461. {
  47462. icon = Image::null;
  47463. }
  47464. void updateIcon (const bool onlyUpdateIfCached)
  47465. {
  47466. if (icon.isNull())
  47467. {
  47468. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47469. Image im (ImageCache::getFromHashCode (hashCode));
  47470. if (im.isNull() && ! onlyUpdateIfCached)
  47471. {
  47472. im = juce_createIconForFile (file);
  47473. if (im.isValid())
  47474. ImageCache::addImageToCache (im, hashCode);
  47475. }
  47476. if (im.isValid())
  47477. {
  47478. icon = im;
  47479. triggerAsyncUpdate();
  47480. }
  47481. }
  47482. }
  47483. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47484. };
  47485. int FileListComponent::getNumRows()
  47486. {
  47487. return fileList.getNumFiles();
  47488. }
  47489. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47490. {
  47491. }
  47492. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47493. {
  47494. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47495. if (comp == 0)
  47496. {
  47497. delete existingComponentToUpdate;
  47498. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47499. }
  47500. DirectoryContentsList::FileInfo fileInfo;
  47501. if (fileList.getFileInfo (row, fileInfo))
  47502. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47503. else
  47504. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47505. return comp;
  47506. }
  47507. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47508. {
  47509. sendSelectionChangeMessage();
  47510. }
  47511. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47512. {
  47513. }
  47514. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47515. {
  47516. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47517. }
  47518. END_JUCE_NAMESPACE
  47519. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47520. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47521. BEGIN_JUCE_NAMESPACE
  47522. FilenameComponent::FilenameComponent (const String& name,
  47523. const File& currentFile,
  47524. const bool canEditFilename,
  47525. const bool isDirectory,
  47526. const bool isForSaving,
  47527. const String& fileBrowserWildcard,
  47528. const String& enforcedSuffix_,
  47529. const String& textWhenNothingSelected)
  47530. : Component (name),
  47531. maxRecentFiles (30),
  47532. isDir (isDirectory),
  47533. isSaving (isForSaving),
  47534. isFileDragOver (false),
  47535. wildcard (fileBrowserWildcard),
  47536. enforcedSuffix (enforcedSuffix_)
  47537. {
  47538. addAndMakeVisible (&filenameBox);
  47539. filenameBox.setEditableText (canEditFilename);
  47540. filenameBox.addListener (this);
  47541. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47542. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47543. setBrowseButtonText ("...");
  47544. setCurrentFile (currentFile, true);
  47545. }
  47546. FilenameComponent::~FilenameComponent()
  47547. {
  47548. }
  47549. void FilenameComponent::paintOverChildren (Graphics& g)
  47550. {
  47551. if (isFileDragOver)
  47552. {
  47553. g.setColour (Colours::red.withAlpha (0.2f));
  47554. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47555. }
  47556. }
  47557. void FilenameComponent::resized()
  47558. {
  47559. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47560. }
  47561. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47562. {
  47563. browseButtonText = newBrowseButtonText;
  47564. lookAndFeelChanged();
  47565. }
  47566. void FilenameComponent::lookAndFeelChanged()
  47567. {
  47568. browseButton = 0;
  47569. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47570. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47571. resized();
  47572. browseButton->addButtonListener (this);
  47573. }
  47574. void FilenameComponent::setTooltip (const String& newTooltip)
  47575. {
  47576. SettableTooltipClient::setTooltip (newTooltip);
  47577. filenameBox.setTooltip (newTooltip);
  47578. }
  47579. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47580. {
  47581. defaultBrowseFile = newDefaultDirectory;
  47582. }
  47583. void FilenameComponent::buttonClicked (Button*)
  47584. {
  47585. FileChooser fc (TRANS("Choose a new file"),
  47586. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47587. : getCurrentFile(),
  47588. wildcard);
  47589. if (isDir ? fc.browseForDirectory()
  47590. : (isSaving ? fc.browseForFileToSave (false)
  47591. : fc.browseForFileToOpen()))
  47592. {
  47593. setCurrentFile (fc.getResult(), true);
  47594. }
  47595. }
  47596. void FilenameComponent::comboBoxChanged (ComboBox*)
  47597. {
  47598. setCurrentFile (getCurrentFile(), true);
  47599. }
  47600. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47601. {
  47602. return true;
  47603. }
  47604. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47605. {
  47606. isFileDragOver = false;
  47607. repaint();
  47608. const File f (filenames[0]);
  47609. if (f.exists() && (f.isDirectory() == isDir))
  47610. setCurrentFile (f, true);
  47611. }
  47612. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47613. {
  47614. isFileDragOver = true;
  47615. repaint();
  47616. }
  47617. void FilenameComponent::fileDragExit (const StringArray&)
  47618. {
  47619. isFileDragOver = false;
  47620. repaint();
  47621. }
  47622. const File FilenameComponent::getCurrentFile() const
  47623. {
  47624. File f (filenameBox.getText());
  47625. if (enforcedSuffix.isNotEmpty())
  47626. f = f.withFileExtension (enforcedSuffix);
  47627. return f;
  47628. }
  47629. void FilenameComponent::setCurrentFile (File newFile,
  47630. const bool addToRecentlyUsedList,
  47631. const bool sendChangeNotification)
  47632. {
  47633. if (enforcedSuffix.isNotEmpty())
  47634. newFile = newFile.withFileExtension (enforcedSuffix);
  47635. if (newFile.getFullPathName() != lastFilename)
  47636. {
  47637. lastFilename = newFile.getFullPathName();
  47638. if (addToRecentlyUsedList)
  47639. addRecentlyUsedFile (newFile);
  47640. filenameBox.setText (lastFilename, true);
  47641. if (sendChangeNotification)
  47642. triggerAsyncUpdate();
  47643. }
  47644. }
  47645. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47646. {
  47647. filenameBox.setEditableText (shouldBeEditable);
  47648. }
  47649. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47650. {
  47651. StringArray names;
  47652. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47653. names.add (filenameBox.getItemText (i));
  47654. return names;
  47655. }
  47656. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47657. {
  47658. if (filenames != getRecentlyUsedFilenames())
  47659. {
  47660. filenameBox.clear();
  47661. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47662. filenameBox.addItem (filenames[i], i + 1);
  47663. }
  47664. }
  47665. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47666. {
  47667. maxRecentFiles = jmax (1, newMaximum);
  47668. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47669. }
  47670. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47671. {
  47672. StringArray files (getRecentlyUsedFilenames());
  47673. if (file.getFullPathName().isNotEmpty())
  47674. {
  47675. files.removeString (file.getFullPathName(), true);
  47676. files.insert (0, file.getFullPathName());
  47677. setRecentlyUsedFilenames (files);
  47678. }
  47679. }
  47680. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47681. {
  47682. listeners.add (listener);
  47683. }
  47684. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47685. {
  47686. listeners.remove (listener);
  47687. }
  47688. void FilenameComponent::handleAsyncUpdate()
  47689. {
  47690. Component::BailOutChecker checker (this);
  47691. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47692. }
  47693. END_JUCE_NAMESPACE
  47694. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47695. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47696. BEGIN_JUCE_NAMESPACE
  47697. FileSearchPathListComponent::FileSearchPathListComponent()
  47698. : addButton ("+"),
  47699. removeButton ("-"),
  47700. changeButton (TRANS ("change...")),
  47701. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47702. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47703. {
  47704. listBox.setModel (this);
  47705. addAndMakeVisible (&listBox);
  47706. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47707. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47708. listBox.setOutlineThickness (1);
  47709. addAndMakeVisible (&addButton);
  47710. addButton.addButtonListener (this);
  47711. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47712. addAndMakeVisible (&removeButton);
  47713. removeButton.addButtonListener (this);
  47714. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47715. addAndMakeVisible (&changeButton);
  47716. changeButton.addButtonListener (this);
  47717. addAndMakeVisible (&upButton);
  47718. upButton.addButtonListener (this);
  47719. {
  47720. Path arrowPath;
  47721. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47722. DrawablePath arrowImage;
  47723. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47724. arrowImage.setPath (arrowPath);
  47725. upButton.setImages (&arrowImage);
  47726. }
  47727. addAndMakeVisible (&downButton);
  47728. downButton.addButtonListener (this);
  47729. {
  47730. Path arrowPath;
  47731. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47732. DrawablePath arrowImage;
  47733. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47734. arrowImage.setPath (arrowPath);
  47735. downButton.setImages (&arrowImage);
  47736. }
  47737. updateButtons();
  47738. }
  47739. FileSearchPathListComponent::~FileSearchPathListComponent()
  47740. {
  47741. }
  47742. void FileSearchPathListComponent::updateButtons()
  47743. {
  47744. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47745. removeButton.setEnabled (anythingSelected);
  47746. changeButton.setEnabled (anythingSelected);
  47747. upButton.setEnabled (anythingSelected);
  47748. downButton.setEnabled (anythingSelected);
  47749. }
  47750. void FileSearchPathListComponent::changed()
  47751. {
  47752. listBox.updateContent();
  47753. listBox.repaint();
  47754. updateButtons();
  47755. }
  47756. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47757. {
  47758. if (newPath.toString() != path.toString())
  47759. {
  47760. path = newPath;
  47761. changed();
  47762. }
  47763. }
  47764. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47765. {
  47766. defaultBrowseTarget = newDefaultDirectory;
  47767. }
  47768. int FileSearchPathListComponent::getNumRows()
  47769. {
  47770. return path.getNumPaths();
  47771. }
  47772. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47773. {
  47774. if (rowIsSelected)
  47775. g.fillAll (findColour (TextEditor::highlightColourId));
  47776. g.setColour (findColour (ListBox::textColourId));
  47777. Font f (height * 0.7f);
  47778. f.setHorizontalScale (0.9f);
  47779. g.setFont (f);
  47780. g.drawText (path [rowNumber].getFullPathName(),
  47781. 4, 0, width - 6, height,
  47782. Justification::centredLeft, true);
  47783. }
  47784. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47785. {
  47786. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47787. {
  47788. path.remove (row);
  47789. changed();
  47790. }
  47791. }
  47792. void FileSearchPathListComponent::returnKeyPressed (int row)
  47793. {
  47794. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47795. if (chooser.browseForDirectory())
  47796. {
  47797. path.remove (row);
  47798. path.add (chooser.getResult(), row);
  47799. changed();
  47800. }
  47801. }
  47802. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47803. {
  47804. returnKeyPressed (row);
  47805. }
  47806. void FileSearchPathListComponent::selectedRowsChanged (int)
  47807. {
  47808. updateButtons();
  47809. }
  47810. void FileSearchPathListComponent::paint (Graphics& g)
  47811. {
  47812. g.fillAll (findColour (backgroundColourId));
  47813. }
  47814. void FileSearchPathListComponent::resized()
  47815. {
  47816. const int buttonH = 22;
  47817. const int buttonY = getHeight() - buttonH - 4;
  47818. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47819. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47820. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47821. changeButton.changeWidthToFitText (buttonH);
  47822. downButton.setSize (buttonH * 2, buttonH);
  47823. upButton.setSize (buttonH * 2, buttonH);
  47824. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47825. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47826. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47827. }
  47828. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47829. {
  47830. return true;
  47831. }
  47832. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47833. {
  47834. for (int i = filenames.size(); --i >= 0;)
  47835. {
  47836. const File f (filenames[i]);
  47837. if (f.isDirectory())
  47838. {
  47839. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47840. path.add (f, row);
  47841. changed();
  47842. }
  47843. }
  47844. }
  47845. void FileSearchPathListComponent::buttonClicked (Button* button)
  47846. {
  47847. const int currentRow = listBox.getSelectedRow();
  47848. if (button == &removeButton)
  47849. {
  47850. deleteKeyPressed (currentRow);
  47851. }
  47852. else if (button == &addButton)
  47853. {
  47854. File start (defaultBrowseTarget);
  47855. if (start == File::nonexistent)
  47856. start = path [0];
  47857. if (start == File::nonexistent)
  47858. start = File::getCurrentWorkingDirectory();
  47859. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47860. if (chooser.browseForDirectory())
  47861. {
  47862. path.add (chooser.getResult(), currentRow);
  47863. }
  47864. }
  47865. else if (button == &changeButton)
  47866. {
  47867. returnKeyPressed (currentRow);
  47868. }
  47869. else if (button == &upButton)
  47870. {
  47871. if (currentRow > 0 && currentRow < path.getNumPaths())
  47872. {
  47873. const File f (path[currentRow]);
  47874. path.remove (currentRow);
  47875. path.add (f, currentRow - 1);
  47876. listBox.selectRow (currentRow - 1);
  47877. }
  47878. }
  47879. else if (button == &downButton)
  47880. {
  47881. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47882. {
  47883. const File f (path[currentRow]);
  47884. path.remove (currentRow);
  47885. path.add (f, currentRow + 1);
  47886. listBox.selectRow (currentRow + 1);
  47887. }
  47888. }
  47889. changed();
  47890. }
  47891. END_JUCE_NAMESPACE
  47892. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47893. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47894. BEGIN_JUCE_NAMESPACE
  47895. const Image juce_createIconForFile (const File& file);
  47896. class FileListTreeItem : public TreeViewItem,
  47897. public TimeSliceClient,
  47898. public AsyncUpdater,
  47899. public ChangeListener
  47900. {
  47901. public:
  47902. FileListTreeItem (FileTreeComponent& owner_,
  47903. DirectoryContentsList* const parentContentsList_,
  47904. const int indexInContentsList_,
  47905. const File& file_,
  47906. TimeSliceThread& thread_)
  47907. : file (file_),
  47908. owner (owner_),
  47909. parentContentsList (parentContentsList_),
  47910. indexInContentsList (indexInContentsList_),
  47911. subContentsList (0),
  47912. canDeleteSubContentsList (false),
  47913. thread (thread_),
  47914. icon (0)
  47915. {
  47916. DirectoryContentsList::FileInfo fileInfo;
  47917. if (parentContentsList_ != 0
  47918. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47919. {
  47920. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47921. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47922. isDirectory = fileInfo.isDirectory;
  47923. }
  47924. else
  47925. {
  47926. isDirectory = true;
  47927. }
  47928. }
  47929. ~FileListTreeItem()
  47930. {
  47931. thread.removeTimeSliceClient (this);
  47932. clearSubItems();
  47933. if (canDeleteSubContentsList)
  47934. delete subContentsList;
  47935. }
  47936. bool mightContainSubItems() { return isDirectory; }
  47937. const String getUniqueName() const { return file.getFullPathName(); }
  47938. int getItemHeight() const { return 22; }
  47939. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47940. void itemOpennessChanged (bool isNowOpen)
  47941. {
  47942. if (isNowOpen)
  47943. {
  47944. clearSubItems();
  47945. isDirectory = file.isDirectory();
  47946. if (isDirectory)
  47947. {
  47948. if (subContentsList == 0)
  47949. {
  47950. jassert (parentContentsList != 0);
  47951. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47952. l->setDirectory (file, true, true);
  47953. setSubContentsList (l);
  47954. canDeleteSubContentsList = true;
  47955. }
  47956. changeListenerCallback (0);
  47957. }
  47958. }
  47959. }
  47960. void setSubContentsList (DirectoryContentsList* newList)
  47961. {
  47962. jassert (subContentsList == 0);
  47963. subContentsList = newList;
  47964. newList->addChangeListener (this);
  47965. }
  47966. void changeListenerCallback (ChangeBroadcaster*)
  47967. {
  47968. clearSubItems();
  47969. if (isOpen() && subContentsList != 0)
  47970. {
  47971. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47972. {
  47973. FileListTreeItem* const item
  47974. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47975. addSubItem (item);
  47976. }
  47977. }
  47978. }
  47979. void paintItem (Graphics& g, int width, int height)
  47980. {
  47981. if (file != File::nonexistent)
  47982. {
  47983. updateIcon (true);
  47984. if (icon.isNull())
  47985. thread.addTimeSliceClient (this);
  47986. }
  47987. owner.getLookAndFeel()
  47988. .drawFileBrowserRow (g, width, height,
  47989. file.getFileName(),
  47990. &icon, fileSize, modTime,
  47991. isDirectory, isSelected(),
  47992. indexInContentsList, owner);
  47993. }
  47994. void itemClicked (const MouseEvent& e)
  47995. {
  47996. owner.sendMouseClickMessage (file, e);
  47997. }
  47998. void itemDoubleClicked (const MouseEvent& e)
  47999. {
  48000. TreeViewItem::itemDoubleClicked (e);
  48001. owner.sendDoubleClickMessage (file);
  48002. }
  48003. void itemSelectionChanged (bool)
  48004. {
  48005. owner.sendSelectionChangeMessage();
  48006. }
  48007. bool useTimeSlice()
  48008. {
  48009. updateIcon (false);
  48010. thread.removeTimeSliceClient (this);
  48011. return false;
  48012. }
  48013. void handleAsyncUpdate()
  48014. {
  48015. owner.repaint();
  48016. }
  48017. const File file;
  48018. private:
  48019. FileTreeComponent& owner;
  48020. DirectoryContentsList* parentContentsList;
  48021. int indexInContentsList;
  48022. DirectoryContentsList* subContentsList;
  48023. bool isDirectory, canDeleteSubContentsList;
  48024. TimeSliceThread& thread;
  48025. Image icon;
  48026. String fileSize;
  48027. String modTime;
  48028. void updateIcon (const bool onlyUpdateIfCached)
  48029. {
  48030. if (icon.isNull())
  48031. {
  48032. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48033. Image im (ImageCache::getFromHashCode (hashCode));
  48034. if (im.isNull() && ! onlyUpdateIfCached)
  48035. {
  48036. im = juce_createIconForFile (file);
  48037. if (im.isValid())
  48038. ImageCache::addImageToCache (im, hashCode);
  48039. }
  48040. if (im.isValid())
  48041. {
  48042. icon = im;
  48043. triggerAsyncUpdate();
  48044. }
  48045. }
  48046. }
  48047. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  48048. };
  48049. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48050. : DirectoryContentsDisplayComponent (listToShow)
  48051. {
  48052. FileListTreeItem* const root
  48053. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48054. listToShow.getTimeSliceThread());
  48055. root->setSubContentsList (&listToShow);
  48056. setRootItemVisible (false);
  48057. setRootItem (root);
  48058. }
  48059. FileTreeComponent::~FileTreeComponent()
  48060. {
  48061. deleteRootItem();
  48062. }
  48063. const File FileTreeComponent::getSelectedFile (const int index) const
  48064. {
  48065. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48066. return item != 0 ? item->file
  48067. : File::nonexistent;
  48068. }
  48069. void FileTreeComponent::deselectAllFiles()
  48070. {
  48071. clearSelectedItems();
  48072. }
  48073. void FileTreeComponent::scrollToTop()
  48074. {
  48075. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48076. }
  48077. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48078. {
  48079. dragAndDropDescription = description;
  48080. }
  48081. END_JUCE_NAMESPACE
  48082. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48083. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48084. BEGIN_JUCE_NAMESPACE
  48085. ImagePreviewComponent::ImagePreviewComponent()
  48086. {
  48087. }
  48088. ImagePreviewComponent::~ImagePreviewComponent()
  48089. {
  48090. }
  48091. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48092. {
  48093. const int availableW = proportionOfWidth (0.97f);
  48094. const int availableH = getHeight() - 13 * 4;
  48095. const double scale = jmin (1.0,
  48096. availableW / (double) w,
  48097. availableH / (double) h);
  48098. w = roundToInt (scale * w);
  48099. h = roundToInt (scale * h);
  48100. }
  48101. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48102. {
  48103. if (fileToLoad != file)
  48104. {
  48105. fileToLoad = file;
  48106. startTimer (100);
  48107. }
  48108. }
  48109. void ImagePreviewComponent::timerCallback()
  48110. {
  48111. stopTimer();
  48112. currentThumbnail = Image::null;
  48113. currentDetails = String::empty;
  48114. repaint();
  48115. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48116. if (in != 0)
  48117. {
  48118. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48119. if (format != 0)
  48120. {
  48121. currentThumbnail = format->decodeImage (*in);
  48122. if (currentThumbnail.isValid())
  48123. {
  48124. int w = currentThumbnail.getWidth();
  48125. int h = currentThumbnail.getHeight();
  48126. currentDetails
  48127. << fileToLoad.getFileName() << "\n"
  48128. << format->getFormatName() << "\n"
  48129. << w << " x " << h << " pixels\n"
  48130. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48131. getThumbSize (w, h);
  48132. currentThumbnail = currentThumbnail.rescaled (w, h);
  48133. }
  48134. }
  48135. }
  48136. }
  48137. void ImagePreviewComponent::paint (Graphics& g)
  48138. {
  48139. if (currentThumbnail.isValid())
  48140. {
  48141. g.setFont (13.0f);
  48142. int w = currentThumbnail.getWidth();
  48143. int h = currentThumbnail.getHeight();
  48144. getThumbSize (w, h);
  48145. const int numLines = 4;
  48146. const int totalH = 13 * numLines + h + 4;
  48147. const int y = (getHeight() - totalH) / 2;
  48148. g.drawImageWithin (currentThumbnail,
  48149. (getWidth() - w) / 2, y, w, h,
  48150. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48151. false);
  48152. g.drawFittedText (currentDetails,
  48153. 0, y + h + 4, getWidth(), 100,
  48154. Justification::centredTop, numLines);
  48155. }
  48156. }
  48157. END_JUCE_NAMESPACE
  48158. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48159. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48160. BEGIN_JUCE_NAMESPACE
  48161. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48162. const String& directoryWildcardPatterns,
  48163. const String& description_)
  48164. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48165. : (description_ + " (" + fileWildcardPatterns + ")"))
  48166. {
  48167. parse (fileWildcardPatterns, fileWildcards);
  48168. parse (directoryWildcardPatterns, directoryWildcards);
  48169. }
  48170. WildcardFileFilter::~WildcardFileFilter()
  48171. {
  48172. }
  48173. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48174. {
  48175. return match (file, fileWildcards);
  48176. }
  48177. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48178. {
  48179. return match (file, directoryWildcards);
  48180. }
  48181. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48182. {
  48183. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48184. result.trim();
  48185. result.removeEmptyStrings();
  48186. // special case for *.*, because people use it to mean "any file", but it
  48187. // would actually ignore files with no extension.
  48188. for (int i = result.size(); --i >= 0;)
  48189. if (result[i] == "*.*")
  48190. result.set (i, "*");
  48191. }
  48192. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48193. {
  48194. const String filename (file.getFileName());
  48195. for (int i = wildcards.size(); --i >= 0;)
  48196. if (filename.matchesWildcard (wildcards[i], true))
  48197. return true;
  48198. return false;
  48199. }
  48200. END_JUCE_NAMESPACE
  48201. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48202. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48203. BEGIN_JUCE_NAMESPACE
  48204. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48205. {
  48206. }
  48207. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48208. {
  48209. }
  48210. namespace KeyboardFocusHelpers
  48211. {
  48212. // This will sort a set of components, so that they are ordered in terms of
  48213. // left-to-right and then top-to-bottom.
  48214. class ScreenPositionComparator
  48215. {
  48216. public:
  48217. ScreenPositionComparator() {}
  48218. static int compareElements (const Component* const first, const Component* const second)
  48219. {
  48220. int explicitOrder1 = first->getExplicitFocusOrder();
  48221. if (explicitOrder1 <= 0)
  48222. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48223. int explicitOrder2 = second->getExplicitFocusOrder();
  48224. if (explicitOrder2 <= 0)
  48225. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48226. if (explicitOrder1 != explicitOrder2)
  48227. return explicitOrder1 - explicitOrder2;
  48228. const int diff = first->getY() - second->getY();
  48229. return (diff == 0) ? first->getX() - second->getX()
  48230. : diff;
  48231. }
  48232. };
  48233. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48234. {
  48235. if (parent->getNumChildComponents() > 0)
  48236. {
  48237. Array <Component*> localComps;
  48238. ScreenPositionComparator comparator;
  48239. int i;
  48240. for (i = parent->getNumChildComponents(); --i >= 0;)
  48241. {
  48242. Component* const c = parent->getChildComponent (i);
  48243. if (c->isVisible() && c->isEnabled())
  48244. localComps.addSorted (comparator, c);
  48245. }
  48246. for (i = 0; i < localComps.size(); ++i)
  48247. {
  48248. Component* const c = localComps.getUnchecked (i);
  48249. if (c->getWantsKeyboardFocus())
  48250. comps.add (c);
  48251. if (! c->isFocusContainer())
  48252. findAllFocusableComponents (c, comps);
  48253. }
  48254. }
  48255. }
  48256. }
  48257. namespace KeyboardFocusHelpers
  48258. {
  48259. Component* getIncrementedComponent (Component* const current, const int delta)
  48260. {
  48261. Component* focusContainer = current->getParentComponent();
  48262. if (focusContainer != 0)
  48263. {
  48264. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48265. focusContainer = focusContainer->getParentComponent();
  48266. if (focusContainer != 0)
  48267. {
  48268. Array <Component*> comps;
  48269. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48270. if (comps.size() > 0)
  48271. {
  48272. const int index = comps.indexOf (current);
  48273. return comps [(index + comps.size() + delta) % comps.size()];
  48274. }
  48275. }
  48276. }
  48277. return 0;
  48278. }
  48279. }
  48280. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48281. {
  48282. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48283. }
  48284. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48285. {
  48286. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48287. }
  48288. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48289. {
  48290. Array <Component*> comps;
  48291. if (parentComponent != 0)
  48292. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48293. return comps.getFirst();
  48294. }
  48295. END_JUCE_NAMESPACE
  48296. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48297. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48298. BEGIN_JUCE_NAMESPACE
  48299. bool KeyListener::keyStateChanged (const bool, Component*)
  48300. {
  48301. return false;
  48302. }
  48303. END_JUCE_NAMESPACE
  48304. /*** End of inlined file: juce_KeyListener.cpp ***/
  48305. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48306. BEGIN_JUCE_NAMESPACE
  48307. // N.B. these two includes are put here deliberately to avoid problems with
  48308. // old GCCs failing on long include paths
  48309. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48310. {
  48311. public:
  48312. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48313. const CommandID commandID_,
  48314. const String& keyName,
  48315. const int keyNum_)
  48316. : Button (keyName),
  48317. owner (owner_),
  48318. commandID (commandID_),
  48319. keyNum (keyNum_)
  48320. {
  48321. setWantsKeyboardFocus (false);
  48322. setTriggeredOnMouseDown (keyNum >= 0);
  48323. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48324. : TRANS("click to change this key-mapping"));
  48325. }
  48326. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48327. {
  48328. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48329. keyNum >= 0 ? getName() : String::empty);
  48330. }
  48331. void clicked()
  48332. {
  48333. if (keyNum >= 0)
  48334. {
  48335. // existing key clicked..
  48336. PopupMenu m;
  48337. m.addItem (1, TRANS("change this key-mapping"));
  48338. m.addSeparator();
  48339. m.addItem (2, TRANS("remove this key-mapping"));
  48340. switch (m.show())
  48341. {
  48342. case 1: assignNewKey(); break;
  48343. case 2: owner.getMappings().removeKeyPress (commandID, keyNum); break;
  48344. default: break;
  48345. }
  48346. }
  48347. else
  48348. {
  48349. assignNewKey(); // + button pressed..
  48350. }
  48351. }
  48352. void fitToContent (const int h) throw()
  48353. {
  48354. if (keyNum < 0)
  48355. {
  48356. setSize (h, h);
  48357. }
  48358. else
  48359. {
  48360. Font f (h * 0.6f);
  48361. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48362. }
  48363. }
  48364. class KeyEntryWindow : public AlertWindow
  48365. {
  48366. public:
  48367. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48368. : AlertWindow (TRANS("New key-mapping"),
  48369. TRANS("Please press a key combination now..."),
  48370. AlertWindow::NoIcon),
  48371. owner (owner_)
  48372. {
  48373. addButton (TRANS("Ok"), 1);
  48374. addButton (TRANS("Cancel"), 0);
  48375. // (avoid return + escape keys getting processed by the buttons..)
  48376. for (int i = getNumChildComponents(); --i >= 0;)
  48377. getChildComponent (i)->setWantsKeyboardFocus (false);
  48378. setWantsKeyboardFocus (true);
  48379. grabKeyboardFocus();
  48380. }
  48381. bool keyPressed (const KeyPress& key)
  48382. {
  48383. lastPress = key;
  48384. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48385. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48386. if (previousCommand != 0)
  48387. message << "\n\n" << TRANS("(Currently assigned to \"")
  48388. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48389. setMessage (message);
  48390. return true;
  48391. }
  48392. bool keyStateChanged (bool)
  48393. {
  48394. return true;
  48395. }
  48396. KeyPress lastPress;
  48397. private:
  48398. KeyMappingEditorComponent& owner;
  48399. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48400. };
  48401. void assignNewKey()
  48402. {
  48403. KeyEntryWindow entryWindow (owner);
  48404. if (entryWindow.runModalLoop() != 0)
  48405. {
  48406. entryWindow.setVisible (false);
  48407. if (entryWindow.lastPress.isValid())
  48408. {
  48409. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (entryWindow.lastPress);
  48410. if (previousCommand == 0
  48411. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48412. TRANS("Change key-mapping"),
  48413. TRANS("This key is already assigned to the command \"")
  48414. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48415. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48416. TRANS("Re-assign"),
  48417. TRANS("Cancel")))
  48418. {
  48419. owner.getMappings().removeKeyPress (entryWindow.lastPress);
  48420. if (keyNum >= 0)
  48421. owner.getMappings().removeKeyPress (commandID, keyNum);
  48422. owner.getMappings().addKeyPress (commandID, entryWindow.lastPress, keyNum);
  48423. }
  48424. }
  48425. }
  48426. }
  48427. private:
  48428. KeyMappingEditorComponent& owner;
  48429. const CommandID commandID;
  48430. const int keyNum;
  48431. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48432. };
  48433. class KeyMappingEditorComponent::ItemComponent : public Component
  48434. {
  48435. public:
  48436. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48437. : owner (owner_), commandID (commandID_)
  48438. {
  48439. setInterceptsMouseClicks (false, true);
  48440. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48441. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48442. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48443. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48444. addKeyPressButton (String::empty, -1, isReadOnly);
  48445. }
  48446. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48447. {
  48448. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48449. keyChangeButtons.add (b);
  48450. b->setEnabled (! isReadOnly);
  48451. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48452. addChildComponent (b);
  48453. }
  48454. void paint (Graphics& g)
  48455. {
  48456. g.setFont (getHeight() * 0.7f);
  48457. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48458. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48459. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48460. Justification::centredLeft, true);
  48461. }
  48462. void resized()
  48463. {
  48464. int x = getWidth() - 4;
  48465. for (int i = keyChangeButtons.size(); --i >= 0;)
  48466. {
  48467. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48468. b->fitToContent (getHeight() - 2);
  48469. b->setTopRightPosition (x, 1);
  48470. x = b->getX() - 5;
  48471. }
  48472. }
  48473. private:
  48474. KeyMappingEditorComponent& owner;
  48475. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48476. const CommandID commandID;
  48477. enum { maxNumAssignments = 3 };
  48478. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48479. };
  48480. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48481. {
  48482. public:
  48483. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48484. : owner (owner_), commandID (commandID_)
  48485. {
  48486. }
  48487. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48488. bool mightContainSubItems() { return false; }
  48489. int getItemHeight() const { return 20; }
  48490. Component* createItemComponent()
  48491. {
  48492. return new ItemComponent (owner, commandID);
  48493. }
  48494. private:
  48495. KeyMappingEditorComponent& owner;
  48496. const CommandID commandID;
  48497. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48498. };
  48499. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48500. {
  48501. public:
  48502. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48503. : owner (owner_), categoryName (name)
  48504. {
  48505. }
  48506. const String getUniqueName() const { return categoryName + "_cat"; }
  48507. bool mightContainSubItems() { return true; }
  48508. int getItemHeight() const { return 28; }
  48509. void paintItem (Graphics& g, int width, int height)
  48510. {
  48511. g.setFont (height * 0.6f, Font::bold);
  48512. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48513. g.drawText (categoryName,
  48514. 2, 0, width - 2, height,
  48515. Justification::centredLeft, true);
  48516. }
  48517. void itemOpennessChanged (bool isNowOpen)
  48518. {
  48519. if (isNowOpen)
  48520. {
  48521. if (getNumSubItems() == 0)
  48522. {
  48523. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48524. for (int i = 0; i < commands.size(); ++i)
  48525. {
  48526. if (owner.shouldCommandBeIncluded (commands[i]))
  48527. addSubItem (new MappingItem (owner, commands[i]));
  48528. }
  48529. }
  48530. }
  48531. else
  48532. {
  48533. clearSubItems();
  48534. }
  48535. }
  48536. private:
  48537. KeyMappingEditorComponent& owner;
  48538. String categoryName;
  48539. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48540. };
  48541. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48542. public ChangeListener,
  48543. public ButtonListener
  48544. {
  48545. public:
  48546. TopLevelItem (KeyMappingEditorComponent& owner_)
  48547. : owner (owner_)
  48548. {
  48549. setLinesDrawnForSubItems (false);
  48550. owner.getMappings().addChangeListener (this);
  48551. }
  48552. ~TopLevelItem()
  48553. {
  48554. owner.getMappings().removeChangeListener (this);
  48555. }
  48556. bool mightContainSubItems() { return true; }
  48557. const String getUniqueName() const { return "keys"; }
  48558. void changeListenerCallback (ChangeBroadcaster*)
  48559. {
  48560. const ScopedPointer <XmlElement> oldOpenness (owner.tree.getOpennessState (true));
  48561. clearSubItems();
  48562. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48563. for (int i = 0; i < categories.size(); ++i)
  48564. {
  48565. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48566. int count = 0;
  48567. for (int j = 0; j < commands.size(); ++j)
  48568. if (owner.shouldCommandBeIncluded (commands[j]))
  48569. ++count;
  48570. if (count > 0)
  48571. addSubItem (new CategoryItem (owner, categories[i]));
  48572. }
  48573. if (oldOpenness != 0)
  48574. owner.tree.restoreOpennessState (*oldOpenness);
  48575. }
  48576. void buttonClicked (Button*)
  48577. {
  48578. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48579. TRANS("Reset to defaults"),
  48580. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48581. TRANS("Reset")))
  48582. {
  48583. owner.getMappings().resetToDefaultMappings();
  48584. }
  48585. }
  48586. private:
  48587. KeyMappingEditorComponent& owner;
  48588. };
  48589. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48590. const bool showResetToDefaultButton)
  48591. : mappings (mappingManager),
  48592. resetButton (TRANS ("reset to defaults"))
  48593. {
  48594. treeItem = new TopLevelItem (*this);
  48595. if (showResetToDefaultButton)
  48596. {
  48597. addAndMakeVisible (&resetButton);
  48598. resetButton.addButtonListener (treeItem);
  48599. }
  48600. addAndMakeVisible (&tree);
  48601. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48602. tree.setRootItemVisible (false);
  48603. tree.setDefaultOpenness (true);
  48604. tree.setRootItem (treeItem);
  48605. }
  48606. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48607. {
  48608. tree.setRootItem (0);
  48609. }
  48610. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48611. const Colour& textColour)
  48612. {
  48613. setColour (backgroundColourId, mainBackground);
  48614. setColour (textColourId, textColour);
  48615. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48616. }
  48617. void KeyMappingEditorComponent::parentHierarchyChanged()
  48618. {
  48619. treeItem->changeListenerCallback (0);
  48620. }
  48621. void KeyMappingEditorComponent::resized()
  48622. {
  48623. int h = getHeight();
  48624. if (resetButton.isVisible())
  48625. {
  48626. const int buttonHeight = 20;
  48627. h -= buttonHeight + 8;
  48628. int x = getWidth() - 8;
  48629. resetButton.changeWidthToFitText (buttonHeight);
  48630. resetButton.setTopRightPosition (x, h + 6);
  48631. }
  48632. tree.setBounds (0, 0, getWidth(), h);
  48633. }
  48634. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48635. {
  48636. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48637. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48638. }
  48639. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48640. {
  48641. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48642. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48643. }
  48644. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48645. {
  48646. return key.getTextDescription();
  48647. }
  48648. END_JUCE_NAMESPACE
  48649. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48650. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48651. BEGIN_JUCE_NAMESPACE
  48652. KeyPress::KeyPress() throw()
  48653. : keyCode (0),
  48654. mods (0),
  48655. textCharacter (0)
  48656. {
  48657. }
  48658. KeyPress::KeyPress (const int keyCode_,
  48659. const ModifierKeys& mods_,
  48660. const juce_wchar textCharacter_) throw()
  48661. : keyCode (keyCode_),
  48662. mods (mods_),
  48663. textCharacter (textCharacter_)
  48664. {
  48665. }
  48666. KeyPress::KeyPress (const int keyCode_) throw()
  48667. : keyCode (keyCode_),
  48668. textCharacter (0)
  48669. {
  48670. }
  48671. KeyPress::KeyPress (const KeyPress& other) throw()
  48672. : keyCode (other.keyCode),
  48673. mods (other.mods),
  48674. textCharacter (other.textCharacter)
  48675. {
  48676. }
  48677. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48678. {
  48679. keyCode = other.keyCode;
  48680. mods = other.mods;
  48681. textCharacter = other.textCharacter;
  48682. return *this;
  48683. }
  48684. bool KeyPress::operator== (const KeyPress& other) const throw()
  48685. {
  48686. return mods.getRawFlags() == other.mods.getRawFlags()
  48687. && (textCharacter == other.textCharacter
  48688. || textCharacter == 0
  48689. || other.textCharacter == 0)
  48690. && (keyCode == other.keyCode
  48691. || (keyCode < 256
  48692. && other.keyCode < 256
  48693. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48694. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48695. }
  48696. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48697. {
  48698. return ! operator== (other);
  48699. }
  48700. bool KeyPress::isCurrentlyDown() const
  48701. {
  48702. return isKeyCurrentlyDown (keyCode)
  48703. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48704. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48705. }
  48706. namespace KeyPressHelpers
  48707. {
  48708. struct KeyNameAndCode
  48709. {
  48710. const char* name;
  48711. int code;
  48712. };
  48713. const KeyNameAndCode translations[] =
  48714. {
  48715. { "spacebar", KeyPress::spaceKey },
  48716. { "return", KeyPress::returnKey },
  48717. { "escape", KeyPress::escapeKey },
  48718. { "backspace", KeyPress::backspaceKey },
  48719. { "cursor left", KeyPress::leftKey },
  48720. { "cursor right", KeyPress::rightKey },
  48721. { "cursor up", KeyPress::upKey },
  48722. { "cursor down", KeyPress::downKey },
  48723. { "page up", KeyPress::pageUpKey },
  48724. { "page down", KeyPress::pageDownKey },
  48725. { "home", KeyPress::homeKey },
  48726. { "end", KeyPress::endKey },
  48727. { "delete", KeyPress::deleteKey },
  48728. { "insert", KeyPress::insertKey },
  48729. { "tab", KeyPress::tabKey },
  48730. { "play", KeyPress::playKey },
  48731. { "stop", KeyPress::stopKey },
  48732. { "fast forward", KeyPress::fastForwardKey },
  48733. { "rewind", KeyPress::rewindKey }
  48734. };
  48735. const String numberPadPrefix() { return "numpad "; }
  48736. }
  48737. const KeyPress KeyPress::createFromDescription (const String& desc)
  48738. {
  48739. int modifiers = 0;
  48740. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48741. || desc.containsWholeWordIgnoreCase ("control")
  48742. || desc.containsWholeWordIgnoreCase ("ctl"))
  48743. modifiers |= ModifierKeys::ctrlModifier;
  48744. if (desc.containsWholeWordIgnoreCase ("shift")
  48745. || desc.containsWholeWordIgnoreCase ("shft"))
  48746. modifiers |= ModifierKeys::shiftModifier;
  48747. if (desc.containsWholeWordIgnoreCase ("alt")
  48748. || desc.containsWholeWordIgnoreCase ("option"))
  48749. modifiers |= ModifierKeys::altModifier;
  48750. if (desc.containsWholeWordIgnoreCase ("command")
  48751. || desc.containsWholeWordIgnoreCase ("cmd"))
  48752. modifiers |= ModifierKeys::commandModifier;
  48753. int key = 0;
  48754. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48755. {
  48756. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48757. {
  48758. key = KeyPressHelpers::translations[i].code;
  48759. break;
  48760. }
  48761. }
  48762. if (key == 0)
  48763. {
  48764. // see if it's a numpad key..
  48765. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48766. {
  48767. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48768. if (lastChar >= '0' && lastChar <= '9')
  48769. key = numberPad0 + lastChar - '0';
  48770. else if (lastChar == '+')
  48771. key = numberPadAdd;
  48772. else if (lastChar == '-')
  48773. key = numberPadSubtract;
  48774. else if (lastChar == '*')
  48775. key = numberPadMultiply;
  48776. else if (lastChar == '/')
  48777. key = numberPadDivide;
  48778. else if (lastChar == '.')
  48779. key = numberPadDecimalPoint;
  48780. else if (lastChar == '=')
  48781. key = numberPadEquals;
  48782. else if (desc.endsWith ("separator"))
  48783. key = numberPadSeparator;
  48784. else if (desc.endsWith ("delete"))
  48785. key = numberPadDelete;
  48786. }
  48787. if (key == 0)
  48788. {
  48789. // see if it's a function key..
  48790. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48791. for (int i = 1; i <= 12; ++i)
  48792. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48793. key = F1Key + i - 1;
  48794. if (key == 0)
  48795. {
  48796. // give up and use the hex code..
  48797. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48798. .toLowerCase()
  48799. .retainCharacters ("0123456789abcdef")
  48800. .getHexValue32();
  48801. if (hexCode > 0)
  48802. key = hexCode;
  48803. else
  48804. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48805. }
  48806. }
  48807. }
  48808. return KeyPress (key, ModifierKeys (modifiers), 0);
  48809. }
  48810. const String KeyPress::getTextDescription() const
  48811. {
  48812. String desc;
  48813. if (keyCode > 0)
  48814. {
  48815. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48816. // want to store it as being a slash, not shift+whatever.
  48817. if (textCharacter == '/')
  48818. return "/";
  48819. if (mods.isCtrlDown())
  48820. desc << "ctrl + ";
  48821. if (mods.isShiftDown())
  48822. desc << "shift + ";
  48823. #if JUCE_MAC
  48824. // only do this on the mac, because on Windows ctrl and command are the same,
  48825. // and this would get confusing
  48826. if (mods.isCommandDown())
  48827. desc << "command + ";
  48828. if (mods.isAltDown())
  48829. desc << "option + ";
  48830. #else
  48831. if (mods.isAltDown())
  48832. desc << "alt + ";
  48833. #endif
  48834. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48835. if (keyCode == KeyPressHelpers::translations[i].code)
  48836. return desc + KeyPressHelpers::translations[i].name;
  48837. if (keyCode >= F1Key && keyCode <= F16Key)
  48838. desc << 'F' << (1 + keyCode - F1Key);
  48839. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48840. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48841. else if (keyCode >= 33 && keyCode < 176)
  48842. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48843. else if (keyCode == numberPadAdd)
  48844. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48845. else if (keyCode == numberPadSubtract)
  48846. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48847. else if (keyCode == numberPadMultiply)
  48848. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48849. else if (keyCode == numberPadDivide)
  48850. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48851. else if (keyCode == numberPadSeparator)
  48852. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48853. else if (keyCode == numberPadDecimalPoint)
  48854. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48855. else if (keyCode == numberPadDelete)
  48856. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48857. else
  48858. desc << '#' << String::toHexString (keyCode);
  48859. }
  48860. return desc;
  48861. }
  48862. END_JUCE_NAMESPACE
  48863. /*** End of inlined file: juce_KeyPress.cpp ***/
  48864. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48865. BEGIN_JUCE_NAMESPACE
  48866. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48867. : commandManager (commandManager_)
  48868. {
  48869. // A manager is needed to get the descriptions of commands, and will be called when
  48870. // a command is invoked. So you can't leave this null..
  48871. jassert (commandManager_ != 0);
  48872. Desktop::getInstance().addFocusChangeListener (this);
  48873. }
  48874. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48875. : commandManager (other.commandManager)
  48876. {
  48877. Desktop::getInstance().addFocusChangeListener (this);
  48878. }
  48879. KeyPressMappingSet::~KeyPressMappingSet()
  48880. {
  48881. Desktop::getInstance().removeFocusChangeListener (this);
  48882. }
  48883. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48884. {
  48885. for (int i = 0; i < mappings.size(); ++i)
  48886. if (mappings.getUnchecked(i)->commandID == commandID)
  48887. return mappings.getUnchecked (i)->keypresses;
  48888. return Array <KeyPress> ();
  48889. }
  48890. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48891. const KeyPress& newKeyPress,
  48892. int insertIndex)
  48893. {
  48894. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48895. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48896. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48897. && ! newKeyPress.getModifiers().isShiftDown()));
  48898. if (findCommandForKeyPress (newKeyPress) != commandID)
  48899. {
  48900. removeKeyPress (newKeyPress);
  48901. if (newKeyPress.isValid())
  48902. {
  48903. for (int i = mappings.size(); --i >= 0;)
  48904. {
  48905. if (mappings.getUnchecked(i)->commandID == commandID)
  48906. {
  48907. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48908. sendChangeMessage();
  48909. return;
  48910. }
  48911. }
  48912. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48913. if (ci != 0)
  48914. {
  48915. CommandMapping* const cm = new CommandMapping();
  48916. cm->commandID = commandID;
  48917. cm->keypresses.add (newKeyPress);
  48918. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48919. mappings.add (cm);
  48920. sendChangeMessage();
  48921. }
  48922. }
  48923. }
  48924. }
  48925. void KeyPressMappingSet::resetToDefaultMappings()
  48926. {
  48927. mappings.clear();
  48928. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48929. {
  48930. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48931. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48932. {
  48933. addKeyPress (ci->commandID,
  48934. ci->defaultKeypresses.getReference (j));
  48935. }
  48936. }
  48937. sendChangeMessage();
  48938. }
  48939. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48940. {
  48941. clearAllKeyPresses (commandID);
  48942. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48943. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48944. {
  48945. addKeyPress (ci->commandID,
  48946. ci->defaultKeypresses.getReference (j));
  48947. }
  48948. }
  48949. void KeyPressMappingSet::clearAllKeyPresses()
  48950. {
  48951. if (mappings.size() > 0)
  48952. {
  48953. sendChangeMessage();
  48954. mappings.clear();
  48955. }
  48956. }
  48957. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48958. {
  48959. for (int i = mappings.size(); --i >= 0;)
  48960. {
  48961. if (mappings.getUnchecked(i)->commandID == commandID)
  48962. {
  48963. mappings.remove (i);
  48964. sendChangeMessage();
  48965. }
  48966. }
  48967. }
  48968. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48969. {
  48970. if (keypress.isValid())
  48971. {
  48972. for (int i = mappings.size(); --i >= 0;)
  48973. {
  48974. CommandMapping* const cm = mappings.getUnchecked(i);
  48975. for (int j = cm->keypresses.size(); --j >= 0;)
  48976. {
  48977. if (keypress == cm->keypresses [j])
  48978. {
  48979. cm->keypresses.remove (j);
  48980. sendChangeMessage();
  48981. }
  48982. }
  48983. }
  48984. }
  48985. }
  48986. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48987. {
  48988. for (int i = mappings.size(); --i >= 0;)
  48989. {
  48990. if (mappings.getUnchecked(i)->commandID == commandID)
  48991. {
  48992. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48993. sendChangeMessage();
  48994. break;
  48995. }
  48996. }
  48997. }
  48998. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48999. {
  49000. for (int i = 0; i < mappings.size(); ++i)
  49001. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49002. return mappings.getUnchecked(i)->commandID;
  49003. return 0;
  49004. }
  49005. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49006. {
  49007. for (int i = mappings.size(); --i >= 0;)
  49008. if (mappings.getUnchecked(i)->commandID == commandID)
  49009. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49010. return false;
  49011. }
  49012. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49013. const KeyPress& key,
  49014. const bool isKeyDown,
  49015. const int millisecsSinceKeyPressed,
  49016. Component* const originatingComponent) const
  49017. {
  49018. ApplicationCommandTarget::InvocationInfo info (commandID);
  49019. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49020. info.isKeyDown = isKeyDown;
  49021. info.keyPress = key;
  49022. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49023. info.originatingComponent = originatingComponent;
  49024. commandManager->invoke (info, false);
  49025. }
  49026. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49027. {
  49028. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49029. {
  49030. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49031. {
  49032. // if the XML was created as a set of differences from the default mappings,
  49033. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49034. resetToDefaultMappings();
  49035. }
  49036. else
  49037. {
  49038. // if the XML was created calling createXml (false), then we need to clear all
  49039. // the keys and treat the xml as describing the entire set of mappings.
  49040. clearAllKeyPresses();
  49041. }
  49042. forEachXmlChildElement (xmlVersion, map)
  49043. {
  49044. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49045. if (commandId != 0)
  49046. {
  49047. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49048. if (map->hasTagName ("MAPPING"))
  49049. {
  49050. addKeyPress (commandId, key);
  49051. }
  49052. else if (map->hasTagName ("UNMAPPING"))
  49053. {
  49054. if (containsMapping (commandId, key))
  49055. removeKeyPress (key);
  49056. }
  49057. }
  49058. }
  49059. return true;
  49060. }
  49061. return false;
  49062. }
  49063. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49064. {
  49065. ScopedPointer <KeyPressMappingSet> defaultSet;
  49066. if (saveDifferencesFromDefaultSet)
  49067. {
  49068. defaultSet = new KeyPressMappingSet (commandManager);
  49069. defaultSet->resetToDefaultMappings();
  49070. }
  49071. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49072. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49073. int i;
  49074. for (i = 0; i < mappings.size(); ++i)
  49075. {
  49076. const CommandMapping* const cm = mappings.getUnchecked(i);
  49077. for (int j = 0; j < cm->keypresses.size(); ++j)
  49078. {
  49079. if (defaultSet == 0
  49080. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49081. {
  49082. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49083. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49084. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49085. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49086. }
  49087. }
  49088. }
  49089. if (defaultSet != 0)
  49090. {
  49091. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49092. {
  49093. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49094. for (int j = 0; j < cm->keypresses.size(); ++j)
  49095. {
  49096. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49097. {
  49098. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49099. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49100. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49101. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49102. }
  49103. }
  49104. }
  49105. }
  49106. return doc;
  49107. }
  49108. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49109. Component* originatingComponent)
  49110. {
  49111. bool used = false;
  49112. const CommandID commandID = findCommandForKeyPress (key);
  49113. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49114. if (ci != 0
  49115. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49116. {
  49117. ApplicationCommandInfo info (0);
  49118. if (commandManager->getTargetForCommand (commandID, info) != 0
  49119. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49120. {
  49121. invokeCommand (commandID, key, true, 0, originatingComponent);
  49122. used = true;
  49123. }
  49124. else
  49125. {
  49126. if (originatingComponent != 0)
  49127. originatingComponent->getLookAndFeel().playAlertSound();
  49128. }
  49129. }
  49130. return used;
  49131. }
  49132. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49133. {
  49134. bool used = false;
  49135. const uint32 now = Time::getMillisecondCounter();
  49136. for (int i = mappings.size(); --i >= 0;)
  49137. {
  49138. CommandMapping* const cm = mappings.getUnchecked(i);
  49139. if (cm->wantsKeyUpDownCallbacks)
  49140. {
  49141. for (int j = cm->keypresses.size(); --j >= 0;)
  49142. {
  49143. const KeyPress key (cm->keypresses.getReference (j));
  49144. const bool isDown = key.isCurrentlyDown();
  49145. int keyPressEntryIndex = 0;
  49146. bool wasDown = false;
  49147. for (int k = keysDown.size(); --k >= 0;)
  49148. {
  49149. if (key == keysDown.getUnchecked(k)->key)
  49150. {
  49151. keyPressEntryIndex = k;
  49152. wasDown = true;
  49153. used = true;
  49154. break;
  49155. }
  49156. }
  49157. if (isDown != wasDown)
  49158. {
  49159. int millisecs = 0;
  49160. if (isDown)
  49161. {
  49162. KeyPressTime* const k = new KeyPressTime();
  49163. k->key = key;
  49164. k->timeWhenPressed = now;
  49165. keysDown.add (k);
  49166. }
  49167. else
  49168. {
  49169. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49170. if (now > pressTime)
  49171. millisecs = now - pressTime;
  49172. keysDown.remove (keyPressEntryIndex);
  49173. }
  49174. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49175. used = true;
  49176. }
  49177. }
  49178. }
  49179. }
  49180. return used;
  49181. }
  49182. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49183. {
  49184. if (focusedComponent != 0)
  49185. focusedComponent->keyStateChanged (false);
  49186. }
  49187. END_JUCE_NAMESPACE
  49188. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49189. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49190. BEGIN_JUCE_NAMESPACE
  49191. ModifierKeys::ModifierKeys (const int flags_) throw()
  49192. : flags (flags_)
  49193. {
  49194. }
  49195. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49196. : flags (other.flags)
  49197. {
  49198. }
  49199. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49200. {
  49201. flags = other.flags;
  49202. return *this;
  49203. }
  49204. ModifierKeys ModifierKeys::currentModifiers;
  49205. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49206. {
  49207. return currentModifiers;
  49208. }
  49209. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49210. {
  49211. int num = 0;
  49212. if (isLeftButtonDown()) ++num;
  49213. if (isRightButtonDown()) ++num;
  49214. if (isMiddleButtonDown()) ++num;
  49215. return num;
  49216. }
  49217. END_JUCE_NAMESPACE
  49218. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49219. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49220. BEGIN_JUCE_NAMESPACE
  49221. class ComponentAnimator::AnimationTask
  49222. {
  49223. public:
  49224. AnimationTask (Component* const comp)
  49225. : component (comp)
  49226. {
  49227. }
  49228. void reset (const Rectangle<int>& finalBounds,
  49229. float finalAlpha,
  49230. int millisecondsToSpendMoving,
  49231. bool useProxyComponent,
  49232. double startSpeed_, double endSpeed_)
  49233. {
  49234. msElapsed = 0;
  49235. msTotal = jmax (1, millisecondsToSpendMoving);
  49236. lastProgress = 0;
  49237. destination = finalBounds;
  49238. destAlpha = finalAlpha;
  49239. isMoving = (finalBounds != component->getBounds());
  49240. isChangingAlpha = (finalAlpha != component->getAlpha());
  49241. left = component->getX();
  49242. top = component->getY();
  49243. right = component->getRight();
  49244. bottom = component->getBottom();
  49245. alpha = component->getAlpha();
  49246. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49247. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49248. midSpeed = invTotalDistance;
  49249. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49250. if (useProxyComponent)
  49251. proxy = new ProxyComponent (*component);
  49252. else
  49253. proxy = 0;
  49254. component->setVisible (! useProxyComponent);
  49255. }
  49256. bool useTimeslice (const int elapsed)
  49257. {
  49258. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49259. : static_cast <Component*> (component);
  49260. if (c != 0)
  49261. {
  49262. msElapsed += elapsed;
  49263. double newProgress = msElapsed / (double) msTotal;
  49264. if (newProgress >= 0 && newProgress < 1.0)
  49265. {
  49266. newProgress = timeToDistance (newProgress);
  49267. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49268. jassert (newProgress >= lastProgress);
  49269. lastProgress = newProgress;
  49270. if (delta < 1.0)
  49271. {
  49272. bool stillBusy = false;
  49273. if (isMoving)
  49274. {
  49275. left += (destination.getX() - left) * delta;
  49276. top += (destination.getY() - top) * delta;
  49277. right += (destination.getRight() - right) * delta;
  49278. bottom += (destination.getBottom() - bottom) * delta;
  49279. const Rectangle<int> newBounds (roundToInt (left),
  49280. roundToInt (top),
  49281. roundToInt (right - left),
  49282. roundToInt (bottom - top));
  49283. if (newBounds != destination)
  49284. {
  49285. c->setBounds (newBounds);
  49286. stillBusy = true;
  49287. }
  49288. }
  49289. if (isChangingAlpha)
  49290. {
  49291. alpha += (destAlpha - alpha) * delta;
  49292. c->setAlpha ((float) alpha);
  49293. stillBusy = true;
  49294. }
  49295. if (stillBusy)
  49296. return true;
  49297. }
  49298. }
  49299. }
  49300. moveToFinalDestination();
  49301. return false;
  49302. }
  49303. void moveToFinalDestination()
  49304. {
  49305. if (component != 0)
  49306. {
  49307. component->setAlpha ((float) destAlpha);
  49308. component->setBounds (destination);
  49309. }
  49310. }
  49311. class ProxyComponent : public Component
  49312. {
  49313. public:
  49314. ProxyComponent (Component& component)
  49315. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49316. {
  49317. setBounds (component.getBounds());
  49318. setAlpha (component.getAlpha());
  49319. setInterceptsMouseClicks (false, false);
  49320. Component* const parent = component.getParentComponent();
  49321. if (parent != 0)
  49322. parent->addAndMakeVisible (this);
  49323. else if (component.isOnDesktop() && component.getPeer() != 0)
  49324. addToDesktop (component.getPeer()->getStyleFlags());
  49325. else
  49326. jassertfalse; // seem to be trying to animate a component that's not visible..
  49327. setVisible (true);
  49328. toBehind (&component);
  49329. }
  49330. void paint (Graphics& g)
  49331. {
  49332. g.setOpacity (1.0f);
  49333. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49334. 0, 0, image.getWidth(), image.getHeight());
  49335. }
  49336. private:
  49337. Image image;
  49338. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49339. };
  49340. Component::SafePointer<Component> component;
  49341. ScopedPointer<Component> proxy;
  49342. Rectangle<int> destination;
  49343. double destAlpha;
  49344. int msElapsed, msTotal;
  49345. double startSpeed, midSpeed, endSpeed, lastProgress;
  49346. double left, top, right, bottom, alpha;
  49347. bool isMoving, isChangingAlpha;
  49348. private:
  49349. double timeToDistance (const double time) const throw()
  49350. {
  49351. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49352. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49353. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49354. }
  49355. };
  49356. ComponentAnimator::ComponentAnimator()
  49357. : lastTime (0)
  49358. {
  49359. }
  49360. ComponentAnimator::~ComponentAnimator()
  49361. {
  49362. }
  49363. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49364. {
  49365. for (int i = tasks.size(); --i >= 0;)
  49366. if (component == tasks.getUnchecked(i)->component.getComponent())
  49367. return tasks.getUnchecked(i);
  49368. return 0;
  49369. }
  49370. void ComponentAnimator::animateComponent (Component* const component,
  49371. const Rectangle<int>& finalBounds,
  49372. const float finalAlpha,
  49373. const int millisecondsToSpendMoving,
  49374. const bool useProxyComponent,
  49375. const double startSpeed,
  49376. const double endSpeed)
  49377. {
  49378. // the speeds must be 0 or greater!
  49379. jassert (startSpeed >= 0 && endSpeed >= 0)
  49380. if (component != 0)
  49381. {
  49382. AnimationTask* at = findTaskFor (component);
  49383. if (at == 0)
  49384. {
  49385. at = new AnimationTask (component);
  49386. tasks.add (at);
  49387. sendChangeMessage();
  49388. }
  49389. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49390. useProxyComponent, startSpeed, endSpeed);
  49391. if (! isTimerRunning())
  49392. {
  49393. lastTime = Time::getMillisecondCounter();
  49394. startTimer (1000 / 50);
  49395. }
  49396. }
  49397. }
  49398. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49399. {
  49400. if (component != 0)
  49401. {
  49402. if (component->isShowing() && millisecondsToTake > 0)
  49403. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49404. component->setVisible (false);
  49405. }
  49406. }
  49407. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49408. {
  49409. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49410. {
  49411. component->setAlpha (0.0f);
  49412. component->setVisible (true);
  49413. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49414. }
  49415. }
  49416. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49417. {
  49418. if (tasks.size() > 0)
  49419. {
  49420. if (moveComponentsToTheirFinalPositions)
  49421. for (int i = tasks.size(); --i >= 0;)
  49422. tasks.getUnchecked(i)->moveToFinalDestination();
  49423. tasks.clear();
  49424. sendChangeMessage();
  49425. }
  49426. }
  49427. void ComponentAnimator::cancelAnimation (Component* const component,
  49428. const bool moveComponentToItsFinalPosition)
  49429. {
  49430. AnimationTask* const at = findTaskFor (component);
  49431. if (at != 0)
  49432. {
  49433. if (moveComponentToItsFinalPosition)
  49434. at->moveToFinalDestination();
  49435. tasks.removeObject (at);
  49436. sendChangeMessage();
  49437. }
  49438. }
  49439. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49440. {
  49441. jassert (component != 0);
  49442. AnimationTask* const at = findTaskFor (component);
  49443. if (at != 0)
  49444. return at->destination;
  49445. return component->getBounds();
  49446. }
  49447. bool ComponentAnimator::isAnimating (Component* component) const
  49448. {
  49449. return findTaskFor (component) != 0;
  49450. }
  49451. void ComponentAnimator::timerCallback()
  49452. {
  49453. const uint32 timeNow = Time::getMillisecondCounter();
  49454. if (lastTime == 0 || lastTime == timeNow)
  49455. lastTime = timeNow;
  49456. const int elapsed = timeNow - lastTime;
  49457. for (int i = tasks.size(); --i >= 0;)
  49458. {
  49459. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49460. {
  49461. tasks.remove (i);
  49462. sendChangeMessage();
  49463. }
  49464. }
  49465. lastTime = timeNow;
  49466. if (tasks.size() == 0)
  49467. stopTimer();
  49468. }
  49469. END_JUCE_NAMESPACE
  49470. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49471. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49472. BEGIN_JUCE_NAMESPACE
  49473. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49474. : minW (0),
  49475. maxW (0x3fffffff),
  49476. minH (0),
  49477. maxH (0x3fffffff),
  49478. minOffTop (0),
  49479. minOffLeft (0),
  49480. minOffBottom (0),
  49481. minOffRight (0),
  49482. aspectRatio (0.0)
  49483. {
  49484. }
  49485. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49486. {
  49487. }
  49488. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49489. {
  49490. minW = minimumWidth;
  49491. }
  49492. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49493. {
  49494. maxW = maximumWidth;
  49495. }
  49496. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49497. {
  49498. minH = minimumHeight;
  49499. }
  49500. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49501. {
  49502. maxH = maximumHeight;
  49503. }
  49504. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49505. {
  49506. jassert (maxW >= minimumWidth);
  49507. jassert (maxH >= minimumHeight);
  49508. jassert (minimumWidth > 0 && minimumHeight > 0);
  49509. minW = minimumWidth;
  49510. minH = minimumHeight;
  49511. if (minW > maxW)
  49512. maxW = minW;
  49513. if (minH > maxH)
  49514. maxH = minH;
  49515. }
  49516. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49517. {
  49518. jassert (maximumWidth >= minW);
  49519. jassert (maximumHeight >= minH);
  49520. jassert (maximumWidth > 0 && maximumHeight > 0);
  49521. maxW = jmax (minW, maximumWidth);
  49522. maxH = jmax (minH, maximumHeight);
  49523. }
  49524. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49525. const int minimumHeight,
  49526. const int maximumWidth,
  49527. const int maximumHeight) throw()
  49528. {
  49529. jassert (maximumWidth >= minimumWidth);
  49530. jassert (maximumHeight >= minimumHeight);
  49531. jassert (maximumWidth > 0 && maximumHeight > 0);
  49532. jassert (minimumWidth > 0 && minimumHeight > 0);
  49533. minW = jmax (0, minimumWidth);
  49534. minH = jmax (0, minimumHeight);
  49535. maxW = jmax (minW, maximumWidth);
  49536. maxH = jmax (minH, maximumHeight);
  49537. }
  49538. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49539. const int minimumWhenOffTheLeft,
  49540. const int minimumWhenOffTheBottom,
  49541. const int minimumWhenOffTheRight) throw()
  49542. {
  49543. minOffTop = minimumWhenOffTheTop;
  49544. minOffLeft = minimumWhenOffTheLeft;
  49545. minOffBottom = minimumWhenOffTheBottom;
  49546. minOffRight = minimumWhenOffTheRight;
  49547. }
  49548. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49549. {
  49550. aspectRatio = jmax (0.0, widthOverHeight);
  49551. }
  49552. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49553. {
  49554. return aspectRatio;
  49555. }
  49556. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49557. const Rectangle<int>& targetBounds,
  49558. const bool isStretchingTop,
  49559. const bool isStretchingLeft,
  49560. const bool isStretchingBottom,
  49561. const bool isStretchingRight)
  49562. {
  49563. jassert (component != 0);
  49564. Rectangle<int> limits, bounds (targetBounds);
  49565. BorderSize border;
  49566. Component* const parent = component->getParentComponent();
  49567. if (parent == 0)
  49568. {
  49569. ComponentPeer* peer = component->getPeer();
  49570. if (peer != 0)
  49571. border = peer->getFrameSize();
  49572. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49573. }
  49574. else
  49575. {
  49576. limits.setSize (parent->getWidth(), parent->getHeight());
  49577. }
  49578. border.addTo (bounds);
  49579. checkBounds (bounds,
  49580. border.addedTo (component->getBounds()), limits,
  49581. isStretchingTop, isStretchingLeft,
  49582. isStretchingBottom, isStretchingRight);
  49583. border.subtractFrom (bounds);
  49584. applyBoundsToComponent (component, bounds);
  49585. }
  49586. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49587. {
  49588. setBoundsForComponent (component, component->getBounds(),
  49589. false, false, false, false);
  49590. }
  49591. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49592. const Rectangle<int>& bounds)
  49593. {
  49594. component->setBounds (bounds);
  49595. }
  49596. void ComponentBoundsConstrainer::resizeStart()
  49597. {
  49598. }
  49599. void ComponentBoundsConstrainer::resizeEnd()
  49600. {
  49601. }
  49602. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49603. const Rectangle<int>& old,
  49604. const Rectangle<int>& limits,
  49605. const bool isStretchingTop,
  49606. const bool isStretchingLeft,
  49607. const bool isStretchingBottom,
  49608. const bool isStretchingRight)
  49609. {
  49610. // constrain the size if it's being stretched..
  49611. if (isStretchingLeft)
  49612. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49613. if (isStretchingRight)
  49614. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49615. if (isStretchingTop)
  49616. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49617. if (isStretchingBottom)
  49618. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49619. if (bounds.isEmpty())
  49620. return;
  49621. if (minOffTop > 0)
  49622. {
  49623. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49624. if (bounds.getY() < limit)
  49625. {
  49626. if (isStretchingTop)
  49627. bounds.setTop (limits.getY());
  49628. else
  49629. bounds.setY (limit);
  49630. }
  49631. }
  49632. if (minOffLeft > 0)
  49633. {
  49634. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49635. if (bounds.getX() < limit)
  49636. {
  49637. if (isStretchingLeft)
  49638. bounds.setLeft (limits.getX());
  49639. else
  49640. bounds.setX (limit);
  49641. }
  49642. }
  49643. if (minOffBottom > 0)
  49644. {
  49645. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49646. if (bounds.getY() > limit)
  49647. {
  49648. if (isStretchingBottom)
  49649. bounds.setBottom (limits.getBottom());
  49650. else
  49651. bounds.setY (limit);
  49652. }
  49653. }
  49654. if (minOffRight > 0)
  49655. {
  49656. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49657. if (bounds.getX() > limit)
  49658. {
  49659. if (isStretchingRight)
  49660. bounds.setRight (limits.getRight());
  49661. else
  49662. bounds.setX (limit);
  49663. }
  49664. }
  49665. // constrain the aspect ratio if one has been specified..
  49666. if (aspectRatio > 0.0)
  49667. {
  49668. bool adjustWidth;
  49669. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49670. {
  49671. adjustWidth = true;
  49672. }
  49673. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49674. {
  49675. adjustWidth = false;
  49676. }
  49677. else
  49678. {
  49679. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49680. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49681. adjustWidth = (oldRatio > newRatio);
  49682. }
  49683. if (adjustWidth)
  49684. {
  49685. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49686. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49687. {
  49688. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49689. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49690. }
  49691. }
  49692. else
  49693. {
  49694. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49695. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49696. {
  49697. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49698. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49699. }
  49700. }
  49701. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49702. {
  49703. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49704. }
  49705. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49706. {
  49707. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49708. }
  49709. else
  49710. {
  49711. if (isStretchingLeft)
  49712. bounds.setX (old.getRight() - bounds.getWidth());
  49713. if (isStretchingTop)
  49714. bounds.setY (old.getBottom() - bounds.getHeight());
  49715. }
  49716. }
  49717. jassert (! bounds.isEmpty());
  49718. }
  49719. END_JUCE_NAMESPACE
  49720. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49721. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49722. BEGIN_JUCE_NAMESPACE
  49723. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49724. : component (component_),
  49725. lastPeer (0),
  49726. reentrant (false)
  49727. {
  49728. jassert (component != 0); // can't use this with a null pointer..
  49729. component->addComponentListener (this);
  49730. registerWithParentComps();
  49731. }
  49732. ComponentMovementWatcher::~ComponentMovementWatcher()
  49733. {
  49734. component->removeComponentListener (this);
  49735. unregister();
  49736. }
  49737. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49738. {
  49739. // agh! don't delete the target component without deleting this object first!
  49740. jassert (component != 0);
  49741. if (! reentrant)
  49742. {
  49743. reentrant = true;
  49744. ComponentPeer* const peer = component->getPeer();
  49745. if (peer != lastPeer)
  49746. {
  49747. componentPeerChanged();
  49748. if (component == 0)
  49749. return;
  49750. lastPeer = peer;
  49751. }
  49752. unregister();
  49753. registerWithParentComps();
  49754. reentrant = false;
  49755. componentMovedOrResized (*component, true, true);
  49756. }
  49757. }
  49758. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49759. {
  49760. // agh! don't delete the target component without deleting this object first!
  49761. jassert (component != 0);
  49762. if (wasMoved)
  49763. {
  49764. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49765. wasMoved = lastBounds.getPosition() != pos;
  49766. lastBounds.setPosition (pos);
  49767. }
  49768. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49769. lastBounds.setSize (component->getWidth(), component->getHeight());
  49770. if (wasMoved || wasResized)
  49771. componentMovedOrResized (wasMoved, wasResized);
  49772. }
  49773. void ComponentMovementWatcher::registerWithParentComps()
  49774. {
  49775. Component* p = component->getParentComponent();
  49776. while (p != 0)
  49777. {
  49778. p->addComponentListener (this);
  49779. registeredParentComps.add (p);
  49780. p = p->getParentComponent();
  49781. }
  49782. }
  49783. void ComponentMovementWatcher::unregister()
  49784. {
  49785. for (int i = registeredParentComps.size(); --i >= 0;)
  49786. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49787. registeredParentComps.clear();
  49788. }
  49789. END_JUCE_NAMESPACE
  49790. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49791. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49792. BEGIN_JUCE_NAMESPACE
  49793. GroupComponent::GroupComponent (const String& componentName,
  49794. const String& labelText)
  49795. : Component (componentName),
  49796. text (labelText),
  49797. justification (Justification::left)
  49798. {
  49799. setInterceptsMouseClicks (false, true);
  49800. }
  49801. GroupComponent::~GroupComponent()
  49802. {
  49803. }
  49804. void GroupComponent::setText (const String& newText)
  49805. {
  49806. if (text != newText)
  49807. {
  49808. text = newText;
  49809. repaint();
  49810. }
  49811. }
  49812. const String GroupComponent::getText() const
  49813. {
  49814. return text;
  49815. }
  49816. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49817. {
  49818. if (justification != newJustification)
  49819. {
  49820. justification = newJustification;
  49821. repaint();
  49822. }
  49823. }
  49824. void GroupComponent::paint (Graphics& g)
  49825. {
  49826. getLookAndFeel()
  49827. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49828. text, justification,
  49829. *this);
  49830. }
  49831. void GroupComponent::enablementChanged()
  49832. {
  49833. repaint();
  49834. }
  49835. void GroupComponent::colourChanged()
  49836. {
  49837. repaint();
  49838. }
  49839. END_JUCE_NAMESPACE
  49840. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49841. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49842. BEGIN_JUCE_NAMESPACE
  49843. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49844. : DocumentWindow (String::empty, backgroundColour,
  49845. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49846. {
  49847. }
  49848. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49849. {
  49850. }
  49851. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49852. {
  49853. MultiDocumentPanel* const owner = getOwner();
  49854. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49855. if (owner != 0)
  49856. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49857. }
  49858. void MultiDocumentPanelWindow::closeButtonPressed()
  49859. {
  49860. MultiDocumentPanel* const owner = getOwner();
  49861. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49862. if (owner != 0)
  49863. owner->closeDocument (getContentComponent(), true);
  49864. }
  49865. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49866. {
  49867. DocumentWindow::activeWindowStatusChanged();
  49868. updateOrder();
  49869. }
  49870. void MultiDocumentPanelWindow::broughtToFront()
  49871. {
  49872. DocumentWindow::broughtToFront();
  49873. updateOrder();
  49874. }
  49875. void MultiDocumentPanelWindow::updateOrder()
  49876. {
  49877. MultiDocumentPanel* const owner = getOwner();
  49878. if (owner != 0)
  49879. owner->updateOrder();
  49880. }
  49881. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49882. {
  49883. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49884. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49885. }
  49886. class MDITabbedComponentInternal : public TabbedComponent
  49887. {
  49888. public:
  49889. MDITabbedComponentInternal()
  49890. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49891. {
  49892. }
  49893. ~MDITabbedComponentInternal()
  49894. {
  49895. }
  49896. void currentTabChanged (int, const String&)
  49897. {
  49898. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49899. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49900. if (owner != 0)
  49901. owner->updateOrder();
  49902. }
  49903. };
  49904. MultiDocumentPanel::MultiDocumentPanel()
  49905. : mode (MaximisedWindowsWithTabs),
  49906. backgroundColour (Colours::lightblue),
  49907. maximumNumDocuments (0),
  49908. numDocsBeforeTabsUsed (0)
  49909. {
  49910. setOpaque (true);
  49911. }
  49912. MultiDocumentPanel::~MultiDocumentPanel()
  49913. {
  49914. closeAllDocuments (false);
  49915. }
  49916. namespace MultiDocHelpers
  49917. {
  49918. bool shouldDeleteComp (Component* const c)
  49919. {
  49920. return c->getProperties() ["mdiDocumentDelete_"];
  49921. }
  49922. }
  49923. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49924. {
  49925. while (components.size() > 0)
  49926. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49927. return false;
  49928. return true;
  49929. }
  49930. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49931. {
  49932. return new MultiDocumentPanelWindow (backgroundColour);
  49933. }
  49934. void MultiDocumentPanel::addWindow (Component* component)
  49935. {
  49936. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49937. dw->setResizable (true, false);
  49938. dw->setContentComponent (component, false, true);
  49939. dw->setName (component->getName());
  49940. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49941. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49942. int x = 4;
  49943. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49944. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49945. x += 16;
  49946. dw->setTopLeftPosition (x, x);
  49947. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49948. if (pos.toString().isNotEmpty())
  49949. dw->restoreWindowStateFromString (pos.toString());
  49950. addAndMakeVisible (dw);
  49951. dw->toFront (true);
  49952. }
  49953. bool MultiDocumentPanel::addDocument (Component* const component,
  49954. const Colour& docColour,
  49955. const bool deleteWhenRemoved)
  49956. {
  49957. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49958. // with a frame-within-a-frame! Just pass in the bare content component.
  49959. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49960. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49961. return false;
  49962. components.add (component);
  49963. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49964. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49965. component->addComponentListener (this);
  49966. if (mode == FloatingWindows)
  49967. {
  49968. if (isFullscreenWhenOneDocument())
  49969. {
  49970. if (components.size() == 1)
  49971. {
  49972. addAndMakeVisible (component);
  49973. }
  49974. else
  49975. {
  49976. if (components.size() == 2)
  49977. addWindow (components.getFirst());
  49978. addWindow (component);
  49979. }
  49980. }
  49981. else
  49982. {
  49983. addWindow (component);
  49984. }
  49985. }
  49986. else
  49987. {
  49988. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49989. {
  49990. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49991. Array <Component*> temp (components);
  49992. for (int i = 0; i < temp.size(); ++i)
  49993. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49994. resized();
  49995. }
  49996. else
  49997. {
  49998. if (tabComponent != 0)
  49999. tabComponent->addTab (component->getName(), docColour, component, false);
  50000. else
  50001. addAndMakeVisible (component);
  50002. }
  50003. setActiveDocument (component);
  50004. }
  50005. resized();
  50006. activeDocumentChanged();
  50007. return true;
  50008. }
  50009. bool MultiDocumentPanel::closeDocument (Component* component,
  50010. const bool checkItsOkToCloseFirst)
  50011. {
  50012. if (components.contains (component))
  50013. {
  50014. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50015. return false;
  50016. component->removeComponentListener (this);
  50017. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50018. component->getProperties().remove ("mdiDocumentDelete_");
  50019. component->getProperties().remove ("mdiDocumentBkg_");
  50020. if (mode == FloatingWindows)
  50021. {
  50022. for (int i = getNumChildComponents(); --i >= 0;)
  50023. {
  50024. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50025. if (dw != 0 && dw->getContentComponent() == component)
  50026. {
  50027. dw->setContentComponent (0, false);
  50028. delete dw;
  50029. break;
  50030. }
  50031. }
  50032. if (shouldDelete)
  50033. delete component;
  50034. components.removeValue (component);
  50035. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50036. {
  50037. for (int i = getNumChildComponents(); --i >= 0;)
  50038. {
  50039. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50040. if (dw != 0)
  50041. {
  50042. dw->setContentComponent (0, false);
  50043. delete dw;
  50044. }
  50045. }
  50046. addAndMakeVisible (components.getFirst());
  50047. }
  50048. }
  50049. else
  50050. {
  50051. jassert (components.indexOf (component) >= 0);
  50052. if (tabComponent != 0)
  50053. {
  50054. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50055. if (tabComponent->getTabContentComponent (i) == component)
  50056. tabComponent->removeTab (i);
  50057. }
  50058. else
  50059. {
  50060. removeChildComponent (component);
  50061. }
  50062. if (shouldDelete)
  50063. delete component;
  50064. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50065. tabComponent = 0;
  50066. components.removeValue (component);
  50067. if (components.size() > 0 && tabComponent == 0)
  50068. addAndMakeVisible (components.getFirst());
  50069. }
  50070. resized();
  50071. activeDocumentChanged();
  50072. }
  50073. else
  50074. {
  50075. jassertfalse;
  50076. }
  50077. return true;
  50078. }
  50079. int MultiDocumentPanel::getNumDocuments() const throw()
  50080. {
  50081. return components.size();
  50082. }
  50083. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50084. {
  50085. return components [index];
  50086. }
  50087. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50088. {
  50089. if (mode == FloatingWindows)
  50090. {
  50091. for (int i = getNumChildComponents(); --i >= 0;)
  50092. {
  50093. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50094. if (dw != 0 && dw->isActiveWindow())
  50095. return dw->getContentComponent();
  50096. }
  50097. }
  50098. return components.getLast();
  50099. }
  50100. void MultiDocumentPanel::setActiveDocument (Component* component)
  50101. {
  50102. if (mode == FloatingWindows)
  50103. {
  50104. component = getContainerComp (component);
  50105. if (component != 0)
  50106. component->toFront (true);
  50107. }
  50108. else if (tabComponent != 0)
  50109. {
  50110. jassert (components.indexOf (component) >= 0);
  50111. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50112. {
  50113. if (tabComponent->getTabContentComponent (i) == component)
  50114. {
  50115. tabComponent->setCurrentTabIndex (i);
  50116. break;
  50117. }
  50118. }
  50119. }
  50120. else
  50121. {
  50122. component->grabKeyboardFocus();
  50123. }
  50124. }
  50125. void MultiDocumentPanel::activeDocumentChanged()
  50126. {
  50127. }
  50128. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50129. {
  50130. maximumNumDocuments = newNumber;
  50131. }
  50132. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50133. {
  50134. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50135. }
  50136. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50137. {
  50138. return numDocsBeforeTabsUsed != 0;
  50139. }
  50140. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50141. {
  50142. if (mode != newLayoutMode)
  50143. {
  50144. mode = newLayoutMode;
  50145. if (mode == FloatingWindows)
  50146. {
  50147. tabComponent = 0;
  50148. }
  50149. else
  50150. {
  50151. for (int i = getNumChildComponents(); --i >= 0;)
  50152. {
  50153. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50154. if (dw != 0)
  50155. {
  50156. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50157. dw->setContentComponent (0, false);
  50158. delete dw;
  50159. }
  50160. }
  50161. }
  50162. resized();
  50163. const Array <Component*> tempComps (components);
  50164. components.clear();
  50165. for (int i = 0; i < tempComps.size(); ++i)
  50166. {
  50167. Component* const c = tempComps.getUnchecked(i);
  50168. addDocument (c,
  50169. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50170. MultiDocHelpers::shouldDeleteComp (c));
  50171. }
  50172. }
  50173. }
  50174. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50175. {
  50176. if (backgroundColour != newBackgroundColour)
  50177. {
  50178. backgroundColour = newBackgroundColour;
  50179. setOpaque (newBackgroundColour.isOpaque());
  50180. repaint();
  50181. }
  50182. }
  50183. void MultiDocumentPanel::paint (Graphics& g)
  50184. {
  50185. g.fillAll (backgroundColour);
  50186. }
  50187. void MultiDocumentPanel::resized()
  50188. {
  50189. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50190. {
  50191. for (int i = getNumChildComponents(); --i >= 0;)
  50192. getChildComponent (i)->setBounds (getLocalBounds());
  50193. }
  50194. setWantsKeyboardFocus (components.size() == 0);
  50195. }
  50196. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50197. {
  50198. if (mode == FloatingWindows)
  50199. {
  50200. for (int i = 0; i < getNumChildComponents(); ++i)
  50201. {
  50202. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50203. if (dw != 0 && dw->getContentComponent() == c)
  50204. {
  50205. c = dw;
  50206. break;
  50207. }
  50208. }
  50209. }
  50210. return c;
  50211. }
  50212. void MultiDocumentPanel::componentNameChanged (Component&)
  50213. {
  50214. if (mode == FloatingWindows)
  50215. {
  50216. for (int i = 0; i < getNumChildComponents(); ++i)
  50217. {
  50218. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50219. if (dw != 0)
  50220. dw->setName (dw->getContentComponent()->getName());
  50221. }
  50222. }
  50223. else if (tabComponent != 0)
  50224. {
  50225. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50226. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50227. }
  50228. }
  50229. void MultiDocumentPanel::updateOrder()
  50230. {
  50231. const Array <Component*> oldList (components);
  50232. if (mode == FloatingWindows)
  50233. {
  50234. components.clear();
  50235. for (int i = 0; i < getNumChildComponents(); ++i)
  50236. {
  50237. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50238. if (dw != 0)
  50239. components.add (dw->getContentComponent());
  50240. }
  50241. }
  50242. else
  50243. {
  50244. if (tabComponent != 0)
  50245. {
  50246. Component* const current = tabComponent->getCurrentContentComponent();
  50247. if (current != 0)
  50248. {
  50249. components.removeValue (current);
  50250. components.add (current);
  50251. }
  50252. }
  50253. }
  50254. if (components != oldList)
  50255. activeDocumentChanged();
  50256. }
  50257. END_JUCE_NAMESPACE
  50258. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50259. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50260. BEGIN_JUCE_NAMESPACE
  50261. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50262. : zone (zoneFlags)
  50263. {}
  50264. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50265. : zone (other.zone)
  50266. {}
  50267. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50268. {
  50269. zone = other.zone;
  50270. return *this;
  50271. }
  50272. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50273. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50274. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50275. const BorderSize& border,
  50276. const Point<int>& position)
  50277. {
  50278. int z = 0;
  50279. if (totalSize.contains (position)
  50280. && ! border.subtractedFrom (totalSize).contains (position))
  50281. {
  50282. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50283. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50284. z |= left;
  50285. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50286. z |= right;
  50287. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50288. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50289. z |= top;
  50290. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50291. z |= bottom;
  50292. }
  50293. return Zone (z);
  50294. }
  50295. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50296. {
  50297. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50298. switch (zone)
  50299. {
  50300. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50301. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50302. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50303. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50304. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50305. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50306. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50307. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50308. default: break;
  50309. }
  50310. return mc;
  50311. }
  50312. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50313. ComponentBoundsConstrainer* const constrainer_)
  50314. : component (componentToResize),
  50315. constrainer (constrainer_),
  50316. borderSize (5),
  50317. mouseZone (0)
  50318. {
  50319. }
  50320. ResizableBorderComponent::~ResizableBorderComponent()
  50321. {
  50322. }
  50323. void ResizableBorderComponent::paint (Graphics& g)
  50324. {
  50325. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50326. }
  50327. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50328. {
  50329. updateMouseZone (e);
  50330. }
  50331. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50332. {
  50333. updateMouseZone (e);
  50334. }
  50335. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50336. {
  50337. if (component == 0)
  50338. {
  50339. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50340. return;
  50341. }
  50342. updateMouseZone (e);
  50343. originalBounds = component->getBounds();
  50344. if (constrainer != 0)
  50345. constrainer->resizeStart();
  50346. }
  50347. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50348. {
  50349. if (component == 0)
  50350. {
  50351. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50352. return;
  50353. }
  50354. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50355. if (constrainer != 0)
  50356. constrainer->setBoundsForComponent (component, bounds,
  50357. mouseZone.isDraggingTopEdge(),
  50358. mouseZone.isDraggingLeftEdge(),
  50359. mouseZone.isDraggingBottomEdge(),
  50360. mouseZone.isDraggingRightEdge());
  50361. else
  50362. component->setBounds (bounds);
  50363. }
  50364. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50365. {
  50366. if (constrainer != 0)
  50367. constrainer->resizeEnd();
  50368. }
  50369. bool ResizableBorderComponent::hitTest (int x, int y)
  50370. {
  50371. return x < borderSize.getLeft()
  50372. || x >= getWidth() - borderSize.getRight()
  50373. || y < borderSize.getTop()
  50374. || y >= getHeight() - borderSize.getBottom();
  50375. }
  50376. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50377. {
  50378. if (borderSize != newBorderSize)
  50379. {
  50380. borderSize = newBorderSize;
  50381. repaint();
  50382. }
  50383. }
  50384. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50385. {
  50386. return borderSize;
  50387. }
  50388. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50389. {
  50390. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50391. if (mouseZone != newZone)
  50392. {
  50393. mouseZone = newZone;
  50394. setMouseCursor (newZone.getMouseCursor());
  50395. }
  50396. }
  50397. END_JUCE_NAMESPACE
  50398. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50399. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50400. BEGIN_JUCE_NAMESPACE
  50401. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50402. ComponentBoundsConstrainer* const constrainer_)
  50403. : component (componentToResize),
  50404. constrainer (constrainer_)
  50405. {
  50406. setRepaintsOnMouseActivity (true);
  50407. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50408. }
  50409. ResizableCornerComponent::~ResizableCornerComponent()
  50410. {
  50411. }
  50412. void ResizableCornerComponent::paint (Graphics& g)
  50413. {
  50414. getLookAndFeel()
  50415. .drawCornerResizer (g, getWidth(), getHeight(),
  50416. isMouseOverOrDragging(),
  50417. isMouseButtonDown());
  50418. }
  50419. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50420. {
  50421. if (component == 0)
  50422. {
  50423. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50424. return;
  50425. }
  50426. originalBounds = component->getBounds();
  50427. if (constrainer != 0)
  50428. constrainer->resizeStart();
  50429. }
  50430. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50431. {
  50432. if (component == 0)
  50433. {
  50434. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50435. return;
  50436. }
  50437. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50438. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50439. if (constrainer != 0)
  50440. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50441. else
  50442. component->setBounds (r);
  50443. }
  50444. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50445. {
  50446. if (constrainer != 0)
  50447. constrainer->resizeStart();
  50448. }
  50449. bool ResizableCornerComponent::hitTest (int x, int y)
  50450. {
  50451. if (getWidth() <= 0)
  50452. return false;
  50453. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50454. return y >= yAtX - getHeight() / 4;
  50455. }
  50456. END_JUCE_NAMESPACE
  50457. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50458. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50459. BEGIN_JUCE_NAMESPACE
  50460. class ScrollBar::ScrollbarButton : public Button
  50461. {
  50462. public:
  50463. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50464. : Button (String::empty),
  50465. direction (direction_),
  50466. owner (owner_)
  50467. {
  50468. setWantsKeyboardFocus (false);
  50469. }
  50470. void paintButton (Graphics& g, bool over, bool down)
  50471. {
  50472. getLookAndFeel()
  50473. .drawScrollbarButton (g, owner,
  50474. getWidth(), getHeight(),
  50475. direction,
  50476. owner.isVertical(),
  50477. over, down);
  50478. }
  50479. void clicked()
  50480. {
  50481. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50482. }
  50483. int direction;
  50484. private:
  50485. ScrollBar& owner;
  50486. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50487. };
  50488. ScrollBar::ScrollBar (const bool vertical_,
  50489. const bool buttonsAreVisible)
  50490. : totalRange (0.0, 1.0),
  50491. visibleRange (0.0, 0.1),
  50492. singleStepSize (0.1),
  50493. thumbAreaStart (0),
  50494. thumbAreaSize (0),
  50495. thumbStart (0),
  50496. thumbSize (0),
  50497. initialDelayInMillisecs (100),
  50498. repeatDelayInMillisecs (50),
  50499. minimumDelayInMillisecs (10),
  50500. vertical (vertical_),
  50501. isDraggingThumb (false),
  50502. autohides (true)
  50503. {
  50504. setButtonVisibility (buttonsAreVisible);
  50505. setRepaintsOnMouseActivity (true);
  50506. setFocusContainer (true);
  50507. }
  50508. ScrollBar::~ScrollBar()
  50509. {
  50510. upButton = 0;
  50511. downButton = 0;
  50512. }
  50513. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50514. {
  50515. if (totalRange != newRangeLimit)
  50516. {
  50517. totalRange = newRangeLimit;
  50518. setCurrentRange (visibleRange);
  50519. updateThumbPosition();
  50520. }
  50521. }
  50522. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50523. {
  50524. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50525. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50526. }
  50527. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50528. {
  50529. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50530. if (visibleRange != constrainedRange)
  50531. {
  50532. visibleRange = constrainedRange;
  50533. updateThumbPosition();
  50534. triggerAsyncUpdate();
  50535. }
  50536. }
  50537. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50538. {
  50539. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50540. }
  50541. void ScrollBar::setCurrentRangeStart (const double newStart)
  50542. {
  50543. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50544. }
  50545. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50546. {
  50547. singleStepSize = newSingleStepSize;
  50548. }
  50549. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50550. {
  50551. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50552. }
  50553. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50554. {
  50555. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50556. }
  50557. void ScrollBar::scrollToTop()
  50558. {
  50559. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50560. }
  50561. void ScrollBar::scrollToBottom()
  50562. {
  50563. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50564. }
  50565. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50566. const int repeatDelayInMillisecs_,
  50567. const int minimumDelayInMillisecs_)
  50568. {
  50569. initialDelayInMillisecs = initialDelayInMillisecs_;
  50570. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50571. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50572. if (upButton != 0)
  50573. {
  50574. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50575. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50576. }
  50577. }
  50578. void ScrollBar::addListener (Listener* const listener)
  50579. {
  50580. listeners.add (listener);
  50581. }
  50582. void ScrollBar::removeListener (Listener* const listener)
  50583. {
  50584. listeners.remove (listener);
  50585. }
  50586. void ScrollBar::handleAsyncUpdate()
  50587. {
  50588. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50589. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50590. }
  50591. void ScrollBar::updateThumbPosition()
  50592. {
  50593. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50594. : thumbAreaSize);
  50595. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50596. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50597. if (newThumbSize > thumbAreaSize)
  50598. newThumbSize = thumbAreaSize;
  50599. int newThumbStart = thumbAreaStart;
  50600. if (totalRange.getLength() > visibleRange.getLength())
  50601. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50602. / (totalRange.getLength() - visibleRange.getLength()));
  50603. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50604. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50605. {
  50606. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50607. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50608. if (vertical)
  50609. repaint (0, repaintStart, getWidth(), repaintSize);
  50610. else
  50611. repaint (repaintStart, 0, repaintSize, getHeight());
  50612. thumbStart = newThumbStart;
  50613. thumbSize = newThumbSize;
  50614. }
  50615. }
  50616. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50617. {
  50618. if (vertical != shouldBeVertical)
  50619. {
  50620. vertical = shouldBeVertical;
  50621. if (upButton != 0)
  50622. {
  50623. upButton->direction = vertical ? 0 : 3;
  50624. downButton->direction = vertical ? 2 : 1;
  50625. }
  50626. updateThumbPosition();
  50627. }
  50628. }
  50629. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50630. {
  50631. upButton = 0;
  50632. downButton = 0;
  50633. if (buttonsAreVisible)
  50634. {
  50635. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50636. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50637. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50638. }
  50639. updateThumbPosition();
  50640. }
  50641. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50642. {
  50643. autohides = shouldHideWhenFullRange;
  50644. updateThumbPosition();
  50645. }
  50646. bool ScrollBar::autoHides() const throw()
  50647. {
  50648. return autohides;
  50649. }
  50650. void ScrollBar::paint (Graphics& g)
  50651. {
  50652. if (thumbAreaSize > 0)
  50653. {
  50654. LookAndFeel& lf = getLookAndFeel();
  50655. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50656. ? thumbSize : 0;
  50657. if (vertical)
  50658. {
  50659. lf.drawScrollbar (g, *this,
  50660. 0, thumbAreaStart,
  50661. getWidth(), thumbAreaSize,
  50662. vertical,
  50663. thumbStart, thumb,
  50664. isMouseOver(), isMouseButtonDown());
  50665. }
  50666. else
  50667. {
  50668. lf.drawScrollbar (g, *this,
  50669. thumbAreaStart, 0,
  50670. thumbAreaSize, getHeight(),
  50671. vertical,
  50672. thumbStart, thumb,
  50673. isMouseOver(), isMouseButtonDown());
  50674. }
  50675. }
  50676. }
  50677. void ScrollBar::lookAndFeelChanged()
  50678. {
  50679. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50680. }
  50681. void ScrollBar::resized()
  50682. {
  50683. const int length = ((vertical) ? getHeight() : getWidth());
  50684. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50685. : 0;
  50686. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50687. {
  50688. thumbAreaStart = length >> 1;
  50689. thumbAreaSize = 0;
  50690. }
  50691. else
  50692. {
  50693. thumbAreaStart = buttonSize;
  50694. thumbAreaSize = length - (buttonSize << 1);
  50695. }
  50696. if (upButton != 0)
  50697. {
  50698. if (vertical)
  50699. {
  50700. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50701. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50702. }
  50703. else
  50704. {
  50705. upButton->setBounds (0, 0, buttonSize, getHeight());
  50706. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50707. }
  50708. }
  50709. updateThumbPosition();
  50710. }
  50711. void ScrollBar::mouseDown (const MouseEvent& e)
  50712. {
  50713. isDraggingThumb = false;
  50714. lastMousePos = vertical ? e.y : e.x;
  50715. dragStartMousePos = lastMousePos;
  50716. dragStartRange = visibleRange.getStart();
  50717. if (dragStartMousePos < thumbStart)
  50718. {
  50719. moveScrollbarInPages (-1);
  50720. startTimer (400);
  50721. }
  50722. else if (dragStartMousePos >= thumbStart + thumbSize)
  50723. {
  50724. moveScrollbarInPages (1);
  50725. startTimer (400);
  50726. }
  50727. else
  50728. {
  50729. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50730. && (thumbAreaSize > thumbSize);
  50731. }
  50732. }
  50733. void ScrollBar::mouseDrag (const MouseEvent& e)
  50734. {
  50735. if (isDraggingThumb)
  50736. {
  50737. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50738. setCurrentRangeStart (dragStartRange
  50739. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50740. / (thumbAreaSize - thumbSize));
  50741. }
  50742. else
  50743. {
  50744. lastMousePos = (vertical) ? e.y : e.x;
  50745. }
  50746. }
  50747. void ScrollBar::mouseUp (const MouseEvent&)
  50748. {
  50749. isDraggingThumb = false;
  50750. stopTimer();
  50751. repaint();
  50752. }
  50753. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50754. float wheelIncrementX,
  50755. float wheelIncrementY)
  50756. {
  50757. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50758. if (increment < 0)
  50759. increment = jmin (increment * 10.0f, -1.0f);
  50760. else if (increment > 0)
  50761. increment = jmax (increment * 10.0f, 1.0f);
  50762. setCurrentRange (visibleRange - singleStepSize * increment);
  50763. }
  50764. void ScrollBar::timerCallback()
  50765. {
  50766. if (isMouseButtonDown())
  50767. {
  50768. startTimer (40);
  50769. if (lastMousePos < thumbStart)
  50770. setCurrentRange (visibleRange - visibleRange.getLength());
  50771. else if (lastMousePos > thumbStart + thumbSize)
  50772. setCurrentRangeStart (visibleRange.getEnd());
  50773. }
  50774. else
  50775. {
  50776. stopTimer();
  50777. }
  50778. }
  50779. bool ScrollBar::keyPressed (const KeyPress& key)
  50780. {
  50781. if (! isVisible())
  50782. return false;
  50783. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50784. moveScrollbarInSteps (-1);
  50785. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50786. moveScrollbarInSteps (1);
  50787. else if (key.isKeyCode (KeyPress::pageUpKey))
  50788. moveScrollbarInPages (-1);
  50789. else if (key.isKeyCode (KeyPress::pageDownKey))
  50790. moveScrollbarInPages (1);
  50791. else if (key.isKeyCode (KeyPress::homeKey))
  50792. scrollToTop();
  50793. else if (key.isKeyCode (KeyPress::endKey))
  50794. scrollToBottom();
  50795. else
  50796. return false;
  50797. return true;
  50798. }
  50799. END_JUCE_NAMESPACE
  50800. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50801. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50802. BEGIN_JUCE_NAMESPACE
  50803. StretchableLayoutManager::StretchableLayoutManager()
  50804. : totalSize (0)
  50805. {
  50806. }
  50807. StretchableLayoutManager::~StretchableLayoutManager()
  50808. {
  50809. }
  50810. void StretchableLayoutManager::clearAllItems()
  50811. {
  50812. items.clear();
  50813. totalSize = 0;
  50814. }
  50815. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50816. const double minimumSize,
  50817. const double maximumSize,
  50818. const double preferredSize)
  50819. {
  50820. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50821. if (layout == 0)
  50822. {
  50823. layout = new ItemLayoutProperties();
  50824. layout->itemIndex = itemIndex;
  50825. int i;
  50826. for (i = 0; i < items.size(); ++i)
  50827. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50828. break;
  50829. items.insert (i, layout);
  50830. }
  50831. layout->minSize = minimumSize;
  50832. layout->maxSize = maximumSize;
  50833. layout->preferredSize = preferredSize;
  50834. layout->currentSize = 0;
  50835. }
  50836. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50837. double& minimumSize,
  50838. double& maximumSize,
  50839. double& preferredSize) const
  50840. {
  50841. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50842. if (layout != 0)
  50843. {
  50844. minimumSize = layout->minSize;
  50845. maximumSize = layout->maxSize;
  50846. preferredSize = layout->preferredSize;
  50847. return true;
  50848. }
  50849. return false;
  50850. }
  50851. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50852. {
  50853. totalSize = newTotalSize;
  50854. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50855. }
  50856. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50857. {
  50858. int pos = 0;
  50859. for (int i = 0; i < itemIndex; ++i)
  50860. {
  50861. const ItemLayoutProperties* const layout = getInfoFor (i);
  50862. if (layout != 0)
  50863. pos += layout->currentSize;
  50864. }
  50865. return pos;
  50866. }
  50867. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50868. {
  50869. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50870. if (layout != 0)
  50871. return layout->currentSize;
  50872. return 0;
  50873. }
  50874. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50875. {
  50876. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50877. if (layout != 0)
  50878. return -layout->currentSize / (double) totalSize;
  50879. return 0;
  50880. }
  50881. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50882. int newPosition)
  50883. {
  50884. for (int i = items.size(); --i >= 0;)
  50885. {
  50886. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50887. if (layout->itemIndex == itemIndex)
  50888. {
  50889. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50890. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50891. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50892. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50893. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50894. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50895. endPos += layout->currentSize;
  50896. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50897. updatePrefSizesToMatchCurrentPositions();
  50898. break;
  50899. }
  50900. }
  50901. }
  50902. void StretchableLayoutManager::layOutComponents (Component** const components,
  50903. int numComponents,
  50904. int x, int y, int w, int h,
  50905. const bool vertically,
  50906. const bool resizeOtherDimension)
  50907. {
  50908. setTotalSize (vertically ? h : w);
  50909. int pos = vertically ? y : x;
  50910. for (int i = 0; i < numComponents; ++i)
  50911. {
  50912. const ItemLayoutProperties* const layout = getInfoFor (i);
  50913. if (layout != 0)
  50914. {
  50915. Component* const c = components[i];
  50916. if (c != 0)
  50917. {
  50918. if (i == numComponents - 1)
  50919. {
  50920. // if it's the last item, crop it to exactly fit the available space..
  50921. if (resizeOtherDimension)
  50922. {
  50923. if (vertically)
  50924. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50925. else
  50926. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50927. }
  50928. else
  50929. {
  50930. if (vertically)
  50931. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50932. else
  50933. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50934. }
  50935. }
  50936. else
  50937. {
  50938. if (resizeOtherDimension)
  50939. {
  50940. if (vertically)
  50941. c->setBounds (x, pos, w, layout->currentSize);
  50942. else
  50943. c->setBounds (pos, y, layout->currentSize, h);
  50944. }
  50945. else
  50946. {
  50947. if (vertically)
  50948. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50949. else
  50950. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50951. }
  50952. }
  50953. }
  50954. pos += layout->currentSize;
  50955. }
  50956. }
  50957. }
  50958. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50959. {
  50960. for (int i = items.size(); --i >= 0;)
  50961. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50962. return items.getUnchecked(i);
  50963. return 0;
  50964. }
  50965. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50966. const int endIndex,
  50967. const int availableSpace,
  50968. int startPos)
  50969. {
  50970. // calculate the total sizes
  50971. int i;
  50972. double totalIdealSize = 0.0;
  50973. int totalMinimums = 0;
  50974. for (i = startIndex; i < endIndex; ++i)
  50975. {
  50976. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50977. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50978. totalMinimums += layout->currentSize;
  50979. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  50980. }
  50981. if (totalIdealSize <= 0)
  50982. totalIdealSize = 1.0;
  50983. // now calc the best sizes..
  50984. int extraSpace = availableSpace - totalMinimums;
  50985. while (extraSpace > 0)
  50986. {
  50987. int numWantingMoreSpace = 0;
  50988. int numHavingTakenExtraSpace = 0;
  50989. // first figure out how many comps want a slice of the extra space..
  50990. for (i = startIndex; i < endIndex; ++i)
  50991. {
  50992. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50993. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  50994. const int bestSize = jlimit (layout->currentSize,
  50995. jmax (layout->currentSize,
  50996. sizeToRealSize (layout->maxSize, totalSize)),
  50997. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50998. if (bestSize > layout->currentSize)
  50999. ++numWantingMoreSpace;
  51000. }
  51001. // ..share out the extra space..
  51002. for (i = startIndex; i < endIndex; ++i)
  51003. {
  51004. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51005. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51006. int bestSize = jlimit (layout->currentSize,
  51007. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51008. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51009. const int extraWanted = bestSize - layout->currentSize;
  51010. if (extraWanted > 0)
  51011. {
  51012. const int extraAllowed = jmin (extraWanted,
  51013. extraSpace / jmax (1, numWantingMoreSpace));
  51014. if (extraAllowed > 0)
  51015. {
  51016. ++numHavingTakenExtraSpace;
  51017. --numWantingMoreSpace;
  51018. layout->currentSize += extraAllowed;
  51019. extraSpace -= extraAllowed;
  51020. }
  51021. }
  51022. }
  51023. if (numHavingTakenExtraSpace <= 0)
  51024. break;
  51025. }
  51026. // ..and calculate the end position
  51027. for (i = startIndex; i < endIndex; ++i)
  51028. {
  51029. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51030. startPos += layout->currentSize;
  51031. }
  51032. return startPos;
  51033. }
  51034. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51035. const int endIndex) const
  51036. {
  51037. int totalMinimums = 0;
  51038. for (int i = startIndex; i < endIndex; ++i)
  51039. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51040. return totalMinimums;
  51041. }
  51042. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51043. {
  51044. int totalMaximums = 0;
  51045. for (int i = startIndex; i < endIndex; ++i)
  51046. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51047. return totalMaximums;
  51048. }
  51049. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51050. {
  51051. for (int i = 0; i < items.size(); ++i)
  51052. {
  51053. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51054. layout->preferredSize
  51055. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51056. : getItemCurrentAbsoluteSize (i);
  51057. }
  51058. }
  51059. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51060. {
  51061. if (size < 0)
  51062. size *= -totalSpace;
  51063. return roundToInt (size);
  51064. }
  51065. END_JUCE_NAMESPACE
  51066. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51067. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51068. BEGIN_JUCE_NAMESPACE
  51069. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51070. const int itemIndex_,
  51071. const bool isVertical_)
  51072. : layout (layout_),
  51073. itemIndex (itemIndex_),
  51074. isVertical (isVertical_)
  51075. {
  51076. setRepaintsOnMouseActivity (true);
  51077. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51078. : MouseCursor::UpDownResizeCursor));
  51079. }
  51080. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51081. {
  51082. }
  51083. void StretchableLayoutResizerBar::paint (Graphics& g)
  51084. {
  51085. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51086. getWidth(), getHeight(),
  51087. isVertical,
  51088. isMouseOver(),
  51089. isMouseButtonDown());
  51090. }
  51091. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51092. {
  51093. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51094. }
  51095. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51096. {
  51097. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51098. : e.getDistanceFromDragStartY());
  51099. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51100. {
  51101. layout->setItemPosition (itemIndex, desiredPos);
  51102. hasBeenMoved();
  51103. }
  51104. }
  51105. void StretchableLayoutResizerBar::hasBeenMoved()
  51106. {
  51107. if (getParentComponent() != 0)
  51108. getParentComponent()->resized();
  51109. }
  51110. END_JUCE_NAMESPACE
  51111. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51112. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51113. BEGIN_JUCE_NAMESPACE
  51114. StretchableObjectResizer::StretchableObjectResizer()
  51115. {
  51116. }
  51117. StretchableObjectResizer::~StretchableObjectResizer()
  51118. {
  51119. }
  51120. void StretchableObjectResizer::addItem (const double size,
  51121. const double minSize, const double maxSize,
  51122. const int order)
  51123. {
  51124. // the order must be >= 0 but less than the maximum integer value.
  51125. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51126. Item* const item = new Item();
  51127. item->size = size;
  51128. item->minSize = minSize;
  51129. item->maxSize = maxSize;
  51130. item->order = order;
  51131. items.add (item);
  51132. }
  51133. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51134. {
  51135. const Item* const it = items [index];
  51136. return it != 0 ? it->size : 0;
  51137. }
  51138. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51139. {
  51140. int order = 0;
  51141. for (;;)
  51142. {
  51143. double currentSize = 0;
  51144. double minSize = 0;
  51145. double maxSize = 0;
  51146. int nextHighestOrder = std::numeric_limits<int>::max();
  51147. for (int i = 0; i < items.size(); ++i)
  51148. {
  51149. const Item* const it = items.getUnchecked(i);
  51150. currentSize += it->size;
  51151. if (it->order <= order)
  51152. {
  51153. minSize += it->minSize;
  51154. maxSize += it->maxSize;
  51155. }
  51156. else
  51157. {
  51158. minSize += it->size;
  51159. maxSize += it->size;
  51160. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51161. }
  51162. }
  51163. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51164. if (thisIterationTarget >= currentSize)
  51165. {
  51166. const double availableExtraSpace = maxSize - currentSize;
  51167. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51168. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51169. for (int i = 0; i < items.size(); ++i)
  51170. {
  51171. Item* const it = items.getUnchecked(i);
  51172. if (it->order <= order)
  51173. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51174. }
  51175. }
  51176. else
  51177. {
  51178. const double amountOfSlack = currentSize - minSize;
  51179. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51180. const double scale = targetAmountOfSlack / amountOfSlack;
  51181. for (int i = 0; i < items.size(); ++i)
  51182. {
  51183. Item* const it = items.getUnchecked(i);
  51184. if (it->order <= order)
  51185. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51186. }
  51187. }
  51188. if (nextHighestOrder < std::numeric_limits<int>::max())
  51189. order = nextHighestOrder;
  51190. else
  51191. break;
  51192. }
  51193. }
  51194. END_JUCE_NAMESPACE
  51195. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51196. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51197. BEGIN_JUCE_NAMESPACE
  51198. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51199. : Button (name),
  51200. owner (owner_),
  51201. overlapPixels (0)
  51202. {
  51203. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51204. setComponentEffect (&shadow);
  51205. setWantsKeyboardFocus (false);
  51206. }
  51207. TabBarButton::~TabBarButton()
  51208. {
  51209. }
  51210. int TabBarButton::getIndex() const
  51211. {
  51212. return owner.indexOfTabButton (this);
  51213. }
  51214. void TabBarButton::paintButton (Graphics& g,
  51215. bool isMouseOverButton,
  51216. bool isButtonDown)
  51217. {
  51218. const Rectangle<int> area (getActiveArea());
  51219. g.setOrigin (area.getX(), area.getY());
  51220. getLookAndFeel()
  51221. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51222. owner.getTabBackgroundColour (getIndex()),
  51223. getIndex(), getButtonText(), *this,
  51224. owner.getOrientation(),
  51225. isMouseOverButton, isButtonDown,
  51226. getToggleState());
  51227. }
  51228. void TabBarButton::clicked (const ModifierKeys& mods)
  51229. {
  51230. if (mods.isPopupMenu())
  51231. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51232. else
  51233. owner.setCurrentTabIndex (getIndex());
  51234. }
  51235. bool TabBarButton::hitTest (int mx, int my)
  51236. {
  51237. const Rectangle<int> area (getActiveArea());
  51238. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51239. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51240. {
  51241. if (((unsigned int) mx) < (unsigned int) getWidth()
  51242. && my >= area.getY() + overlapPixels
  51243. && my < area.getBottom() - overlapPixels)
  51244. return true;
  51245. }
  51246. else
  51247. {
  51248. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51249. && ((unsigned int) my) < (unsigned int) getHeight())
  51250. return true;
  51251. }
  51252. Path p;
  51253. getLookAndFeel()
  51254. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51255. owner.getOrientation(), false, false, getToggleState());
  51256. return p.contains ((float) (mx - area.getX()),
  51257. (float) (my - area.getY()));
  51258. }
  51259. int TabBarButton::getBestTabLength (const int depth)
  51260. {
  51261. return jlimit (depth * 2,
  51262. depth * 7,
  51263. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51264. }
  51265. const Rectangle<int> TabBarButton::getActiveArea()
  51266. {
  51267. Rectangle<int> r (getLocalBounds());
  51268. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51269. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51270. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51271. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51272. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51273. return r;
  51274. }
  51275. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51276. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51277. {
  51278. public:
  51279. BehindFrontTabComp (TabbedButtonBar& owner_)
  51280. : owner (owner_)
  51281. {
  51282. setInterceptsMouseClicks (false, false);
  51283. }
  51284. void paint (Graphics& g)
  51285. {
  51286. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51287. owner, owner.getOrientation());
  51288. }
  51289. void enablementChanged()
  51290. {
  51291. repaint();
  51292. }
  51293. void buttonClicked (Button*)
  51294. {
  51295. owner.showExtraItemsMenu();
  51296. }
  51297. private:
  51298. TabbedButtonBar& owner;
  51299. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51300. };
  51301. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51302. : orientation (orientation_),
  51303. minimumScale (0.7),
  51304. currentTabIndex (-1)
  51305. {
  51306. setInterceptsMouseClicks (false, true);
  51307. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51308. setFocusContainer (true);
  51309. }
  51310. TabbedButtonBar::~TabbedButtonBar()
  51311. {
  51312. tabs.clear();
  51313. extraTabsButton = 0;
  51314. }
  51315. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51316. {
  51317. orientation = newOrientation;
  51318. for (int i = getNumChildComponents(); --i >= 0;)
  51319. getChildComponent (i)->resized();
  51320. resized();
  51321. }
  51322. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51323. {
  51324. return new TabBarButton (name, *this);
  51325. }
  51326. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51327. {
  51328. minimumScale = newMinimumScale;
  51329. resized();
  51330. }
  51331. void TabbedButtonBar::clearTabs()
  51332. {
  51333. tabs.clear();
  51334. extraTabsButton = 0;
  51335. setCurrentTabIndex (-1);
  51336. }
  51337. void TabbedButtonBar::addTab (const String& tabName,
  51338. const Colour& tabBackgroundColour,
  51339. int insertIndex)
  51340. {
  51341. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51342. if (tabName.isNotEmpty())
  51343. {
  51344. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51345. insertIndex = tabs.size();
  51346. TabInfo* newTab = new TabInfo();
  51347. newTab->name = tabName;
  51348. newTab->colour = tabBackgroundColour;
  51349. newTab->component = createTabButton (tabName, insertIndex);
  51350. jassert (newTab->component != 0);
  51351. tabs.insert (insertIndex, newTab);
  51352. addAndMakeVisible (newTab->component, insertIndex);
  51353. resized();
  51354. if (currentTabIndex < 0)
  51355. setCurrentTabIndex (0);
  51356. }
  51357. }
  51358. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51359. {
  51360. TabInfo* const tab = tabs [tabIndex];
  51361. if (tab != 0 && tab->name != newName)
  51362. {
  51363. tab->name = newName;
  51364. tab->component->setButtonText (newName);
  51365. resized();
  51366. }
  51367. }
  51368. void TabbedButtonBar::removeTab (const int tabIndex)
  51369. {
  51370. if (tabs [tabIndex] != 0)
  51371. {
  51372. const int oldTabIndex = currentTabIndex;
  51373. if (currentTabIndex == tabIndex)
  51374. currentTabIndex = -1;
  51375. tabs.remove (tabIndex);
  51376. resized();
  51377. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51378. }
  51379. }
  51380. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51381. {
  51382. tabs.move (currentIndex, newIndex);
  51383. resized();
  51384. }
  51385. int TabbedButtonBar::getNumTabs() const
  51386. {
  51387. return tabs.size();
  51388. }
  51389. const String TabbedButtonBar::getCurrentTabName() const
  51390. {
  51391. TabInfo* tab = tabs [currentTabIndex];
  51392. return tab == 0 ? String::empty : tab->name;
  51393. }
  51394. const StringArray TabbedButtonBar::getTabNames() const
  51395. {
  51396. StringArray names;
  51397. for (int i = 0; i < tabs.size(); ++i)
  51398. names.add (tabs.getUnchecked(i)->name);
  51399. return names;
  51400. }
  51401. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51402. {
  51403. if (currentTabIndex != newIndex)
  51404. {
  51405. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51406. newIndex = -1;
  51407. currentTabIndex = newIndex;
  51408. for (int i = 0; i < tabs.size(); ++i)
  51409. {
  51410. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51411. tb->setToggleState (i == newIndex, false);
  51412. }
  51413. resized();
  51414. if (sendChangeMessage_)
  51415. sendChangeMessage();
  51416. currentTabChanged (newIndex, getCurrentTabName());
  51417. }
  51418. }
  51419. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51420. {
  51421. TabInfo* const tab = tabs[index];
  51422. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51423. }
  51424. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51425. {
  51426. for (int i = tabs.size(); --i >= 0;)
  51427. if (tabs.getUnchecked(i)->component == button)
  51428. return i;
  51429. return -1;
  51430. }
  51431. void TabbedButtonBar::lookAndFeelChanged()
  51432. {
  51433. extraTabsButton = 0;
  51434. resized();
  51435. }
  51436. void TabbedButtonBar::resized()
  51437. {
  51438. int depth = getWidth();
  51439. int length = getHeight();
  51440. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51441. swapVariables (depth, length);
  51442. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51443. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51444. int i, totalLength = overlap;
  51445. int numVisibleButtons = tabs.size();
  51446. for (i = 0; i < tabs.size(); ++i)
  51447. {
  51448. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51449. totalLength += tb->getBestTabLength (depth) - overlap;
  51450. tb->overlapPixels = overlap / 2;
  51451. }
  51452. double scale = 1.0;
  51453. if (totalLength > length)
  51454. scale = jmax (minimumScale, length / (double) totalLength);
  51455. const bool isTooBig = totalLength * scale > length;
  51456. int tabsButtonPos = 0;
  51457. if (isTooBig)
  51458. {
  51459. if (extraTabsButton == 0)
  51460. {
  51461. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51462. extraTabsButton->addButtonListener (behindFrontTab);
  51463. extraTabsButton->setAlwaysOnTop (true);
  51464. extraTabsButton->setTriggeredOnMouseDown (true);
  51465. }
  51466. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51467. extraTabsButton->setSize (buttonSize, buttonSize);
  51468. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51469. {
  51470. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51471. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51472. }
  51473. else
  51474. {
  51475. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51476. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51477. }
  51478. totalLength = 0;
  51479. for (i = 0; i < tabs.size(); ++i)
  51480. {
  51481. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51482. const int newLength = totalLength + tb->getBestTabLength (depth);
  51483. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51484. {
  51485. totalLength += overlap;
  51486. break;
  51487. }
  51488. numVisibleButtons = i + 1;
  51489. totalLength = newLength - overlap;
  51490. }
  51491. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51492. }
  51493. else
  51494. {
  51495. extraTabsButton = 0;
  51496. }
  51497. int pos = 0;
  51498. TabBarButton* frontTab = 0;
  51499. for (i = 0; i < tabs.size(); ++i)
  51500. {
  51501. TabBarButton* const tb = getTabButton (i);
  51502. if (tb != 0)
  51503. {
  51504. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51505. if (i < numVisibleButtons)
  51506. {
  51507. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51508. tb->setBounds (pos, 0, bestLength, getHeight());
  51509. else
  51510. tb->setBounds (0, pos, getWidth(), bestLength);
  51511. tb->toBack();
  51512. if (i == currentTabIndex)
  51513. frontTab = tb;
  51514. tb->setVisible (true);
  51515. }
  51516. else
  51517. {
  51518. tb->setVisible (false);
  51519. }
  51520. pos += bestLength - overlap;
  51521. }
  51522. }
  51523. behindFrontTab->setBounds (getLocalBounds());
  51524. if (frontTab != 0)
  51525. {
  51526. frontTab->toFront (false);
  51527. behindFrontTab->toBehind (frontTab);
  51528. }
  51529. }
  51530. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51531. {
  51532. TabInfo* const tab = tabs [tabIndex];
  51533. return tab == 0 ? Colours::white : tab->colour;
  51534. }
  51535. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51536. {
  51537. TabInfo* const tab = tabs [tabIndex];
  51538. if (tab != 0 && tab->colour != newColour)
  51539. {
  51540. tab->colour = newColour;
  51541. repaint();
  51542. }
  51543. }
  51544. void TabbedButtonBar::showExtraItemsMenu()
  51545. {
  51546. PopupMenu m;
  51547. for (int i = 0; i < tabs.size(); ++i)
  51548. {
  51549. const TabInfo* const tab = tabs.getUnchecked(i);
  51550. if (! tab->component->isVisible())
  51551. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51552. }
  51553. const int res = m.showAt (extraTabsButton);
  51554. if (res != 0)
  51555. setCurrentTabIndex (res - 1);
  51556. }
  51557. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51558. {
  51559. }
  51560. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51561. {
  51562. }
  51563. END_JUCE_NAMESPACE
  51564. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51565. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51566. BEGIN_JUCE_NAMESPACE
  51567. class TabCompButtonBar : public TabbedButtonBar
  51568. {
  51569. public:
  51570. TabCompButtonBar (TabbedComponent& owner_,
  51571. const TabbedButtonBar::Orientation orientation_)
  51572. : TabbedButtonBar (orientation_),
  51573. owner (owner_)
  51574. {
  51575. }
  51576. ~TabCompButtonBar()
  51577. {
  51578. }
  51579. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51580. {
  51581. owner.changeCallback (newCurrentTabIndex, newTabName);
  51582. }
  51583. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51584. {
  51585. owner.popupMenuClickOnTab (tabIndex, tabName);
  51586. }
  51587. const Colour getTabBackgroundColour (const int tabIndex)
  51588. {
  51589. return owner.tabs->getTabBackgroundColour (tabIndex);
  51590. }
  51591. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51592. {
  51593. return owner.createTabButton (tabName, tabIndex);
  51594. }
  51595. private:
  51596. TabbedComponent& owner;
  51597. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabCompButtonBar);
  51598. };
  51599. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51600. : tabDepth (30),
  51601. outlineThickness (1),
  51602. edgeIndent (0)
  51603. {
  51604. addAndMakeVisible (tabs = new TabCompButtonBar (*this, orientation));
  51605. }
  51606. TabbedComponent::~TabbedComponent()
  51607. {
  51608. clearTabs();
  51609. tabs = 0;
  51610. }
  51611. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51612. {
  51613. tabs->setOrientation (orientation);
  51614. resized();
  51615. }
  51616. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51617. {
  51618. return tabs->getOrientation();
  51619. }
  51620. void TabbedComponent::setTabBarDepth (const int newDepth)
  51621. {
  51622. if (tabDepth != newDepth)
  51623. {
  51624. tabDepth = newDepth;
  51625. resized();
  51626. }
  51627. }
  51628. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51629. {
  51630. return new TabBarButton (tabName, *tabs);
  51631. }
  51632. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51633. void TabbedComponent::clearTabs()
  51634. {
  51635. if (panelComponent != 0)
  51636. {
  51637. panelComponent->setVisible (false);
  51638. removeChildComponent (panelComponent);
  51639. panelComponent = 0;
  51640. }
  51641. tabs->clearTabs();
  51642. for (int i = contentComponents.size(); --i >= 0;)
  51643. {
  51644. Component::SafePointer<Component>& c = *contentComponents.getUnchecked (i);
  51645. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51646. c.deleteAndZero();
  51647. }
  51648. contentComponents.clear();
  51649. }
  51650. void TabbedComponent::addTab (const String& tabName,
  51651. const Colour& tabBackgroundColour,
  51652. Component* const contentComponent,
  51653. const bool deleteComponentWhenNotNeeded,
  51654. const int insertIndex)
  51655. {
  51656. contentComponents.insert (insertIndex, new Component::SafePointer<Component> (contentComponent));
  51657. if (contentComponent != 0)
  51658. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51659. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51660. }
  51661. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51662. {
  51663. tabs->setTabName (tabIndex, newName);
  51664. }
  51665. void TabbedComponent::removeTab (const int tabIndex)
  51666. {
  51667. Component::SafePointer<Component>* c = contentComponents [tabIndex];
  51668. if (c != 0)
  51669. {
  51670. if ((bool) ((*c)->getProperties() [deleteComponentId]))
  51671. c->deleteAndZero();
  51672. contentComponents.remove (tabIndex);
  51673. tabs->removeTab (tabIndex);
  51674. }
  51675. }
  51676. int TabbedComponent::getNumTabs() const
  51677. {
  51678. return tabs->getNumTabs();
  51679. }
  51680. const StringArray TabbedComponent::getTabNames() const
  51681. {
  51682. return tabs->getTabNames();
  51683. }
  51684. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51685. {
  51686. Component::SafePointer<Component>* const c = contentComponents [tabIndex];
  51687. return c != 0 ? *c : 0;
  51688. }
  51689. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51690. {
  51691. return tabs->getTabBackgroundColour (tabIndex);
  51692. }
  51693. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51694. {
  51695. tabs->setTabBackgroundColour (tabIndex, newColour);
  51696. if (getCurrentTabIndex() == tabIndex)
  51697. repaint();
  51698. }
  51699. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51700. {
  51701. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51702. }
  51703. int TabbedComponent::getCurrentTabIndex() const
  51704. {
  51705. return tabs->getCurrentTabIndex();
  51706. }
  51707. const String TabbedComponent::getCurrentTabName() const
  51708. {
  51709. return tabs->getCurrentTabName();
  51710. }
  51711. void TabbedComponent::setOutline (int thickness)
  51712. {
  51713. outlineThickness = thickness;
  51714. repaint();
  51715. }
  51716. void TabbedComponent::setIndent (const int indentThickness)
  51717. {
  51718. edgeIndent = indentThickness;
  51719. }
  51720. void TabbedComponent::paint (Graphics& g)
  51721. {
  51722. g.fillAll (findColour (backgroundColourId));
  51723. const TabbedButtonBar::Orientation o = getOrientation();
  51724. int x = 0;
  51725. int y = 0;
  51726. int r = getWidth();
  51727. int b = getHeight();
  51728. if (o == TabbedButtonBar::TabsAtTop)
  51729. y += tabDepth;
  51730. else if (o == TabbedButtonBar::TabsAtBottom)
  51731. b -= tabDepth;
  51732. else if (o == TabbedButtonBar::TabsAtLeft)
  51733. x += tabDepth;
  51734. else if (o == TabbedButtonBar::TabsAtRight)
  51735. r -= tabDepth;
  51736. g.reduceClipRegion (x, y, r - x, b - y);
  51737. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51738. if (outlineThickness > 0)
  51739. {
  51740. if (o == TabbedButtonBar::TabsAtTop)
  51741. --y;
  51742. else if (o == TabbedButtonBar::TabsAtBottom)
  51743. ++b;
  51744. else if (o == TabbedButtonBar::TabsAtLeft)
  51745. --x;
  51746. else if (o == TabbedButtonBar::TabsAtRight)
  51747. ++r;
  51748. g.setColour (findColour (outlineColourId));
  51749. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51750. }
  51751. }
  51752. void TabbedComponent::resized()
  51753. {
  51754. const TabbedButtonBar::Orientation o = getOrientation();
  51755. const int indent = edgeIndent + outlineThickness;
  51756. BorderSize indents (indent);
  51757. if (o == TabbedButtonBar::TabsAtTop)
  51758. {
  51759. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51760. indents.setTop (tabDepth + edgeIndent);
  51761. }
  51762. else if (o == TabbedButtonBar::TabsAtBottom)
  51763. {
  51764. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51765. indents.setBottom (tabDepth + edgeIndent);
  51766. }
  51767. else if (o == TabbedButtonBar::TabsAtLeft)
  51768. {
  51769. tabs->setBounds (0, 0, tabDepth, getHeight());
  51770. indents.setLeft (tabDepth + edgeIndent);
  51771. }
  51772. else if (o == TabbedButtonBar::TabsAtRight)
  51773. {
  51774. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51775. indents.setRight (tabDepth + edgeIndent);
  51776. }
  51777. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51778. for (int i = contentComponents.size(); --i >= 0;)
  51779. if (*contentComponents.getUnchecked (i) != 0)
  51780. (*contentComponents.getUnchecked (i))->setBounds (bounds);
  51781. }
  51782. void TabbedComponent::lookAndFeelChanged()
  51783. {
  51784. for (int i = contentComponents.size(); --i >= 0;)
  51785. if (*contentComponents.getUnchecked (i) != 0)
  51786. (*contentComponents.getUnchecked (i))->lookAndFeelChanged();
  51787. }
  51788. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51789. const String& newTabName)
  51790. {
  51791. if (panelComponent != 0)
  51792. {
  51793. panelComponent->setVisible (false);
  51794. removeChildComponent (panelComponent);
  51795. panelComponent = 0;
  51796. }
  51797. if (getCurrentTabIndex() >= 0)
  51798. {
  51799. panelComponent = getTabContentComponent (getCurrentTabIndex());
  51800. if (panelComponent != 0)
  51801. {
  51802. // do these ops as two stages instead of addAndMakeVisible() so that the
  51803. // component has always got a parent when it gets the visibilityChanged() callback
  51804. addChildComponent (panelComponent);
  51805. panelComponent->setVisible (true);
  51806. panelComponent->toFront (true);
  51807. }
  51808. repaint();
  51809. }
  51810. resized();
  51811. currentTabChanged (newCurrentTabIndex, newTabName);
  51812. }
  51813. void TabbedComponent::currentTabChanged (const int, const String&)
  51814. {
  51815. }
  51816. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51817. {
  51818. }
  51819. END_JUCE_NAMESPACE
  51820. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51821. /*** Start of inlined file: juce_Viewport.cpp ***/
  51822. BEGIN_JUCE_NAMESPACE
  51823. Viewport::Viewport (const String& componentName)
  51824. : Component (componentName),
  51825. scrollBarThickness (0),
  51826. singleStepX (16),
  51827. singleStepY (16),
  51828. showHScrollbar (true),
  51829. showVScrollbar (true),
  51830. verticalScrollBar (true),
  51831. horizontalScrollBar (false)
  51832. {
  51833. // content holder is used to clip the contents so they don't overlap the scrollbars
  51834. addAndMakeVisible (&contentHolder);
  51835. contentHolder.setInterceptsMouseClicks (false, true);
  51836. addChildComponent (&verticalScrollBar);
  51837. addChildComponent (&horizontalScrollBar);
  51838. verticalScrollBar.addListener (this);
  51839. horizontalScrollBar.addListener (this);
  51840. setInterceptsMouseClicks (false, true);
  51841. setWantsKeyboardFocus (true);
  51842. }
  51843. Viewport::~Viewport()
  51844. {
  51845. deleteContentComp();
  51846. }
  51847. void Viewport::visibleAreaChanged (int, int, int, int)
  51848. {
  51849. }
  51850. void Viewport::deleteContentComp()
  51851. {
  51852. // This sets the content comp to a null pointer before deleting the old one, in case
  51853. // anything tries to use the old one while it's in mid-deletion..
  51854. ScopedPointer<Component> oldCompDeleter (contentComp);
  51855. contentComp = 0;
  51856. }
  51857. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51858. {
  51859. if (contentComp.getComponent() != newViewedComponent)
  51860. {
  51861. deleteContentComp();
  51862. contentComp = newViewedComponent;
  51863. if (contentComp != 0)
  51864. {
  51865. contentComp->setTopLeftPosition (0, 0);
  51866. contentHolder.addAndMakeVisible (contentComp);
  51867. contentComp->addComponentListener (this);
  51868. }
  51869. updateVisibleArea();
  51870. }
  51871. }
  51872. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  51873. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  51874. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51875. {
  51876. if (contentComp != 0)
  51877. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51878. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51879. }
  51880. void Viewport::setViewPosition (const Point<int>& newPosition)
  51881. {
  51882. setViewPosition (newPosition.getX(), newPosition.getY());
  51883. }
  51884. void Viewport::setViewPositionProportionately (const double x, const double y)
  51885. {
  51886. if (contentComp != 0)
  51887. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51888. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51889. }
  51890. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51891. {
  51892. if (contentComp != 0)
  51893. {
  51894. int dx = 0, dy = 0;
  51895. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51896. {
  51897. if (mouseX < activeBorderThickness)
  51898. dx = activeBorderThickness - mouseX;
  51899. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51900. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51901. if (dx < 0)
  51902. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51903. else
  51904. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51905. }
  51906. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51907. {
  51908. if (mouseY < activeBorderThickness)
  51909. dy = activeBorderThickness - mouseY;
  51910. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51911. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51912. if (dy < 0)
  51913. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51914. else
  51915. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51916. }
  51917. if (dx != 0 || dy != 0)
  51918. {
  51919. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51920. contentComp->getY() + dy);
  51921. return true;
  51922. }
  51923. }
  51924. return false;
  51925. }
  51926. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51927. {
  51928. updateVisibleArea();
  51929. }
  51930. void Viewport::resized()
  51931. {
  51932. updateVisibleArea();
  51933. }
  51934. void Viewport::updateVisibleArea()
  51935. {
  51936. const int scrollbarWidth = getScrollBarThickness();
  51937. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51938. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51939. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51940. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51941. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51942. Rectangle<int> contentArea (getLocalBounds());
  51943. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51944. {
  51945. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51946. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51947. if (vBarVisible)
  51948. contentArea.setWidth (getWidth() - scrollbarWidth);
  51949. if (hBarVisible)
  51950. contentArea.setHeight (getHeight() - scrollbarWidth);
  51951. if (! contentArea.contains (contentComp->getBounds()))
  51952. {
  51953. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51954. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51955. }
  51956. }
  51957. if (vBarVisible)
  51958. contentArea.setWidth (getWidth() - scrollbarWidth);
  51959. if (hBarVisible)
  51960. contentArea.setHeight (getHeight() - scrollbarWidth);
  51961. contentHolder.setBounds (contentArea);
  51962. Rectangle<int> contentBounds;
  51963. if (contentComp != 0)
  51964. contentBounds = contentComp->getBounds();
  51965. const Point<int> visibleOrigin (-contentBounds.getPosition());
  51966. if (hBarVisible)
  51967. {
  51968. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51969. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51970. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51971. horizontalScrollBar.setSingleStepSize (singleStepX);
  51972. horizontalScrollBar.cancelPendingUpdate();
  51973. }
  51974. if (vBarVisible)
  51975. {
  51976. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51977. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51978. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51979. verticalScrollBar.setSingleStepSize (singleStepY);
  51980. verticalScrollBar.cancelPendingUpdate();
  51981. }
  51982. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51983. horizontalScrollBar.setVisible (hBarVisible);
  51984. verticalScrollBar.setVisible (vBarVisible);
  51985. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51986. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51987. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51988. if (lastVisibleArea != visibleArea)
  51989. {
  51990. lastVisibleArea = visibleArea;
  51991. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  51992. }
  51993. horizontalScrollBar.handleUpdateNowIfNeeded();
  51994. verticalScrollBar.handleUpdateNowIfNeeded();
  51995. }
  51996. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51997. {
  51998. if (singleStepX != stepX || singleStepY != stepY)
  51999. {
  52000. singleStepX = stepX;
  52001. singleStepY = stepY;
  52002. updateVisibleArea();
  52003. }
  52004. }
  52005. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52006. const bool showHorizontalScrollbarIfNeeded)
  52007. {
  52008. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52009. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52010. {
  52011. showVScrollbar = showVerticalScrollbarIfNeeded;
  52012. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52013. updateVisibleArea();
  52014. }
  52015. }
  52016. void Viewport::setScrollBarThickness (const int thickness)
  52017. {
  52018. if (scrollBarThickness != thickness)
  52019. {
  52020. scrollBarThickness = thickness;
  52021. updateVisibleArea();
  52022. }
  52023. }
  52024. int Viewport::getScrollBarThickness() const
  52025. {
  52026. return scrollBarThickness > 0 ? scrollBarThickness
  52027. : getLookAndFeel().getDefaultScrollbarWidth();
  52028. }
  52029. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52030. {
  52031. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52032. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52033. }
  52034. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52035. {
  52036. const int newRangeStartInt = roundToInt (newRangeStart);
  52037. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52038. {
  52039. setViewPosition (newRangeStartInt, getViewPositionY());
  52040. }
  52041. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52042. {
  52043. setViewPosition (getViewPositionX(), newRangeStartInt);
  52044. }
  52045. }
  52046. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52047. {
  52048. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52049. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52050. }
  52051. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52052. {
  52053. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52054. {
  52055. const bool hasVertBar = verticalScrollBar.isVisible();
  52056. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52057. if (hasHorzBar || hasVertBar)
  52058. {
  52059. if (wheelIncrementX != 0)
  52060. {
  52061. wheelIncrementX *= 14.0f * singleStepX;
  52062. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52063. : jmax (wheelIncrementX, 1.0f);
  52064. }
  52065. if (wheelIncrementY != 0)
  52066. {
  52067. wheelIncrementY *= 14.0f * singleStepY;
  52068. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52069. : jmax (wheelIncrementY, 1.0f);
  52070. }
  52071. Point<int> pos (getViewPosition());
  52072. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52073. {
  52074. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52075. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52076. }
  52077. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52078. {
  52079. if (wheelIncrementX == 0 && ! hasVertBar)
  52080. wheelIncrementX = wheelIncrementY;
  52081. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52082. }
  52083. else if (hasVertBar && wheelIncrementY != 0)
  52084. {
  52085. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52086. }
  52087. if (pos != getViewPosition())
  52088. {
  52089. setViewPosition (pos);
  52090. return true;
  52091. }
  52092. }
  52093. }
  52094. return false;
  52095. }
  52096. bool Viewport::keyPressed (const KeyPress& key)
  52097. {
  52098. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52099. || key.isKeyCode (KeyPress::downKey)
  52100. || key.isKeyCode (KeyPress::pageUpKey)
  52101. || key.isKeyCode (KeyPress::pageDownKey)
  52102. || key.isKeyCode (KeyPress::homeKey)
  52103. || key.isKeyCode (KeyPress::endKey);
  52104. if (verticalScrollBar.isVisible() && isUpDownKey)
  52105. return verticalScrollBar.keyPressed (key);
  52106. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52107. || key.isKeyCode (KeyPress::rightKey);
  52108. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52109. return horizontalScrollBar.keyPressed (key);
  52110. return false;
  52111. }
  52112. END_JUCE_NAMESPACE
  52113. /*** End of inlined file: juce_Viewport.cpp ***/
  52114. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52115. BEGIN_JUCE_NAMESPACE
  52116. namespace LookAndFeelHelpers
  52117. {
  52118. void createRoundedPath (Path& p,
  52119. const float x, const float y,
  52120. const float w, const float h,
  52121. const float cs,
  52122. const bool curveTopLeft, const bool curveTopRight,
  52123. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52124. {
  52125. const float cs2 = 2.0f * cs;
  52126. if (curveTopLeft)
  52127. {
  52128. p.startNewSubPath (x, y + cs);
  52129. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52130. }
  52131. else
  52132. {
  52133. p.startNewSubPath (x, y);
  52134. }
  52135. if (curveTopRight)
  52136. {
  52137. p.lineTo (x + w - cs, y);
  52138. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52139. }
  52140. else
  52141. {
  52142. p.lineTo (x + w, y);
  52143. }
  52144. if (curveBottomRight)
  52145. {
  52146. p.lineTo (x + w, y + h - cs);
  52147. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52148. }
  52149. else
  52150. {
  52151. p.lineTo (x + w, y + h);
  52152. }
  52153. if (curveBottomLeft)
  52154. {
  52155. p.lineTo (x + cs, y + h);
  52156. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52157. }
  52158. else
  52159. {
  52160. p.lineTo (x, y + h);
  52161. }
  52162. p.closeSubPath();
  52163. }
  52164. const Colour createBaseColour (const Colour& buttonColour,
  52165. const bool hasKeyboardFocus,
  52166. const bool isMouseOverButton,
  52167. const bool isButtonDown) throw()
  52168. {
  52169. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52170. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52171. if (isButtonDown)
  52172. return baseColour.contrasting (0.2f);
  52173. else if (isMouseOverButton)
  52174. return baseColour.contrasting (0.1f);
  52175. return baseColour;
  52176. }
  52177. const TextLayout layoutTooltipText (const String& text) throw()
  52178. {
  52179. const float tooltipFontSize = 12.0f;
  52180. const int maxToolTipWidth = 400;
  52181. const Font f (tooltipFontSize, Font::bold);
  52182. TextLayout tl (text, f);
  52183. tl.layout (maxToolTipWidth, Justification::left, true);
  52184. return tl;
  52185. }
  52186. LookAndFeel* defaultLF = 0;
  52187. LookAndFeel* currentDefaultLF = 0;
  52188. }
  52189. LookAndFeel::LookAndFeel()
  52190. {
  52191. /* if this fails it means you're trying to create a LookAndFeel object before
  52192. the static Colours have been initialised. That ain't gonna work. It probably
  52193. means that you're using a static LookAndFeel object and that your compiler has
  52194. decided to intialise it before the Colours class.
  52195. */
  52196. jassert (Colours::white == Colour (0xffffffff));
  52197. // set up the standard set of colours..
  52198. const int textButtonColour = 0xffbbbbff;
  52199. const int textHighlightColour = 0x401111ee;
  52200. const int standardOutlineColour = 0xb2808080;
  52201. static const int standardColours[] =
  52202. {
  52203. TextButton::buttonColourId, textButtonColour,
  52204. TextButton::buttonOnColourId, 0xff4444ff,
  52205. TextButton::textColourOnId, 0xff000000,
  52206. TextButton::textColourOffId, 0xff000000,
  52207. ComboBox::buttonColourId, 0xffbbbbff,
  52208. ComboBox::outlineColourId, standardOutlineColour,
  52209. ToggleButton::textColourId, 0xff000000,
  52210. TextEditor::backgroundColourId, 0xffffffff,
  52211. TextEditor::textColourId, 0xff000000,
  52212. TextEditor::highlightColourId, textHighlightColour,
  52213. TextEditor::highlightedTextColourId, 0xff000000,
  52214. TextEditor::caretColourId, 0xff000000,
  52215. TextEditor::outlineColourId, 0x00000000,
  52216. TextEditor::focusedOutlineColourId, textButtonColour,
  52217. TextEditor::shadowColourId, 0x38000000,
  52218. Label::backgroundColourId, 0x00000000,
  52219. Label::textColourId, 0xff000000,
  52220. Label::outlineColourId, 0x00000000,
  52221. ScrollBar::backgroundColourId, 0x00000000,
  52222. ScrollBar::thumbColourId, 0xffffffff,
  52223. ScrollBar::trackColourId, 0xffffffff,
  52224. TreeView::linesColourId, 0x4c000000,
  52225. TreeView::backgroundColourId, 0x00000000,
  52226. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52227. PopupMenu::backgroundColourId, 0xffffffff,
  52228. PopupMenu::textColourId, 0xff000000,
  52229. PopupMenu::headerTextColourId, 0xff000000,
  52230. PopupMenu::highlightedTextColourId, 0xffffffff,
  52231. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52232. ComboBox::textColourId, 0xff000000,
  52233. ComboBox::backgroundColourId, 0xffffffff,
  52234. ComboBox::arrowColourId, 0x99000000,
  52235. ListBox::backgroundColourId, 0xffffffff,
  52236. ListBox::outlineColourId, standardOutlineColour,
  52237. ListBox::textColourId, 0xff000000,
  52238. Slider::backgroundColourId, 0x00000000,
  52239. Slider::thumbColourId, textButtonColour,
  52240. Slider::trackColourId, 0x7fffffff,
  52241. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52242. Slider::rotarySliderOutlineColourId, 0x66000000,
  52243. Slider::textBoxTextColourId, 0xff000000,
  52244. Slider::textBoxBackgroundColourId, 0xffffffff,
  52245. Slider::textBoxHighlightColourId, textHighlightColour,
  52246. Slider::textBoxOutlineColourId, standardOutlineColour,
  52247. ResizableWindow::backgroundColourId, 0xff777777,
  52248. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52249. AlertWindow::backgroundColourId, 0xffededed,
  52250. AlertWindow::textColourId, 0xff000000,
  52251. AlertWindow::outlineColourId, 0xff666666,
  52252. ProgressBar::backgroundColourId, 0xffeeeeee,
  52253. ProgressBar::foregroundColourId, 0xffaaaaee,
  52254. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52255. TooltipWindow::textColourId, 0xff000000,
  52256. TooltipWindow::outlineColourId, 0x4c000000,
  52257. TabbedComponent::backgroundColourId, 0x00000000,
  52258. TabbedComponent::outlineColourId, 0xff777777,
  52259. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52260. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52261. Toolbar::backgroundColourId, 0xfff6f8f9,
  52262. Toolbar::separatorColourId, 0x4c000000,
  52263. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52264. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52265. Toolbar::labelTextColourId, 0xff000000,
  52266. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52267. HyperlinkButton::textColourId, 0xcc1111ee,
  52268. GroupComponent::outlineColourId, 0x66000000,
  52269. GroupComponent::textColourId, 0xff000000,
  52270. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52271. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52272. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52273. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52274. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52275. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52276. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52277. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52278. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52279. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52280. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52281. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52282. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52283. CodeEditorComponent::caretColourId, 0xff000000,
  52284. CodeEditorComponent::highlightColourId, textHighlightColour,
  52285. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52286. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52287. ColourSelector::labelTextColourId, 0xff000000,
  52288. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52289. KeyMappingEditorComponent::textColourId, 0xff000000,
  52290. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52291. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52292. DrawableButton::textColourId, 0xff000000,
  52293. };
  52294. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52295. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52296. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52297. if (defaultSansName.isEmpty())
  52298. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52299. defaultSans = defaultSansName;
  52300. defaultSerif = defaultSerifName;
  52301. defaultFixed = defaultFixedName;
  52302. Font::setFallbackFontName (defaultFallback);
  52303. }
  52304. LookAndFeel::~LookAndFeel()
  52305. {
  52306. if (this == LookAndFeelHelpers::currentDefaultLF)
  52307. setDefaultLookAndFeel (0);
  52308. }
  52309. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52310. {
  52311. const int index = colourIds.indexOf (colourId);
  52312. if (index >= 0)
  52313. return colours [index];
  52314. jassertfalse;
  52315. return Colours::black;
  52316. }
  52317. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52318. {
  52319. const int index = colourIds.indexOf (colourId);
  52320. if (index >= 0)
  52321. {
  52322. colours.set (index, colour);
  52323. }
  52324. else
  52325. {
  52326. colourIds.add (colourId);
  52327. colours.add (colour);
  52328. }
  52329. }
  52330. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52331. {
  52332. return colourIds.contains (colourId);
  52333. }
  52334. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52335. {
  52336. // if this happens, your app hasn't initialised itself properly.. if you're
  52337. // trying to hack your own main() function, have a look at
  52338. // JUCEApplication::initialiseForGUI()
  52339. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52340. return *LookAndFeelHelpers::currentDefaultLF;
  52341. }
  52342. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52343. {
  52344. using namespace LookAndFeelHelpers;
  52345. if (newDefaultLookAndFeel == 0)
  52346. {
  52347. if (defaultLF == 0)
  52348. defaultLF = new LookAndFeel();
  52349. newDefaultLookAndFeel = defaultLF;
  52350. }
  52351. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52352. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52353. {
  52354. Component* const c = Desktop::getInstance().getComponent (i);
  52355. if (c != 0)
  52356. c->sendLookAndFeelChange();
  52357. }
  52358. }
  52359. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52360. {
  52361. using namespace LookAndFeelHelpers;
  52362. if (currentDefaultLF == defaultLF)
  52363. currentDefaultLF = 0;
  52364. deleteAndZero (defaultLF);
  52365. }
  52366. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52367. {
  52368. String faceName (font.getTypefaceName());
  52369. if (faceName == Font::getDefaultSansSerifFontName())
  52370. faceName = defaultSans;
  52371. else if (faceName == Font::getDefaultSerifFontName())
  52372. faceName = defaultSerif;
  52373. else if (faceName == Font::getDefaultMonospacedFontName())
  52374. faceName = defaultFixed;
  52375. Font f (font);
  52376. f.setTypefaceName (faceName);
  52377. return Typeface::createSystemTypefaceFor (f);
  52378. }
  52379. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52380. {
  52381. defaultSans = newName;
  52382. }
  52383. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52384. {
  52385. return component.getMouseCursor();
  52386. }
  52387. void LookAndFeel::drawButtonBackground (Graphics& g,
  52388. Button& button,
  52389. const Colour& backgroundColour,
  52390. bool isMouseOverButton,
  52391. bool isButtonDown)
  52392. {
  52393. const int width = button.getWidth();
  52394. const int height = button.getHeight();
  52395. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52396. const float halfThickness = outlineThickness * 0.5f;
  52397. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52398. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52399. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52400. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52401. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52402. button.hasKeyboardFocus (true),
  52403. isMouseOverButton, isButtonDown)
  52404. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52405. drawGlassLozenge (g,
  52406. indentL,
  52407. indentT,
  52408. width - indentL - indentR,
  52409. height - indentT - indentB,
  52410. baseColour, outlineThickness, -1.0f,
  52411. button.isConnectedOnLeft(),
  52412. button.isConnectedOnRight(),
  52413. button.isConnectedOnTop(),
  52414. button.isConnectedOnBottom());
  52415. }
  52416. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52417. {
  52418. return button.getFont();
  52419. }
  52420. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52421. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52422. {
  52423. Font font (getFontForTextButton (button));
  52424. g.setFont (font);
  52425. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52426. : TextButton::textColourOffId)
  52427. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52428. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52429. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52430. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52431. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52432. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52433. g.drawFittedText (button.getButtonText(),
  52434. leftIndent,
  52435. yIndent,
  52436. button.getWidth() - leftIndent - rightIndent,
  52437. button.getHeight() - yIndent * 2,
  52438. Justification::centred, 2);
  52439. }
  52440. void LookAndFeel::drawTickBox (Graphics& g,
  52441. Component& component,
  52442. float x, float y, float w, float h,
  52443. const bool ticked,
  52444. const bool isEnabled,
  52445. const bool isMouseOverButton,
  52446. const bool isButtonDown)
  52447. {
  52448. const float boxSize = w * 0.7f;
  52449. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52450. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52451. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52452. true, isMouseOverButton, isButtonDown),
  52453. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52454. if (ticked)
  52455. {
  52456. Path tick;
  52457. tick.startNewSubPath (1.5f, 3.0f);
  52458. tick.lineTo (3.0f, 6.0f);
  52459. tick.lineTo (6.0f, 0.0f);
  52460. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52461. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52462. .translated (x, y));
  52463. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52464. }
  52465. }
  52466. void LookAndFeel::drawToggleButton (Graphics& g,
  52467. ToggleButton& button,
  52468. bool isMouseOverButton,
  52469. bool isButtonDown)
  52470. {
  52471. if (button.hasKeyboardFocus (true))
  52472. {
  52473. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52474. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52475. }
  52476. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52477. const float tickWidth = fontSize * 1.1f;
  52478. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52479. tickWidth, tickWidth,
  52480. button.getToggleState(),
  52481. button.isEnabled(),
  52482. isMouseOverButton,
  52483. isButtonDown);
  52484. g.setColour (button.findColour (ToggleButton::textColourId));
  52485. g.setFont (fontSize);
  52486. if (! button.isEnabled())
  52487. g.setOpacity (0.5f);
  52488. const int textX = (int) tickWidth + 5;
  52489. g.drawFittedText (button.getButtonText(),
  52490. textX, 0,
  52491. button.getWidth() - textX - 2, button.getHeight(),
  52492. Justification::centredLeft, 10);
  52493. }
  52494. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52495. {
  52496. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52497. const int tickWidth = jmin (24, button.getHeight());
  52498. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52499. button.getHeight());
  52500. }
  52501. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52502. const String& message,
  52503. const String& button1,
  52504. const String& button2,
  52505. const String& button3,
  52506. AlertWindow::AlertIconType iconType,
  52507. int numButtons,
  52508. Component* associatedComponent)
  52509. {
  52510. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52511. if (numButtons == 1)
  52512. {
  52513. aw->addButton (button1, 0,
  52514. KeyPress (KeyPress::escapeKey, 0, 0),
  52515. KeyPress (KeyPress::returnKey, 0, 0));
  52516. }
  52517. else
  52518. {
  52519. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52520. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52521. if (button1ShortCut == button2ShortCut)
  52522. button2ShortCut = KeyPress();
  52523. if (numButtons == 2)
  52524. {
  52525. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52526. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52527. }
  52528. else if (numButtons == 3)
  52529. {
  52530. aw->addButton (button1, 1, button1ShortCut);
  52531. aw->addButton (button2, 2, button2ShortCut);
  52532. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52533. }
  52534. }
  52535. return aw;
  52536. }
  52537. void LookAndFeel::drawAlertBox (Graphics& g,
  52538. AlertWindow& alert,
  52539. const Rectangle<int>& textArea,
  52540. TextLayout& textLayout)
  52541. {
  52542. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52543. int iconSpaceUsed = 0;
  52544. Justification alignment (Justification::horizontallyCentred);
  52545. const int iconWidth = 80;
  52546. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52547. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52548. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52549. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52550. iconSize, iconSize);
  52551. if (alert.getAlertType() != AlertWindow::NoIcon)
  52552. {
  52553. Path icon;
  52554. uint32 colour;
  52555. char character;
  52556. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52557. {
  52558. colour = 0x55ff5555;
  52559. character = '!';
  52560. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52561. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52562. (float) iconRect.getX(), (float) iconRect.getBottom());
  52563. icon = icon.createPathWithRoundedCorners (5.0f);
  52564. }
  52565. else
  52566. {
  52567. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52568. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52569. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52570. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52571. }
  52572. GlyphArrangement ga;
  52573. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52574. String::charToString (character),
  52575. (float) iconRect.getX(), (float) iconRect.getY(),
  52576. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52577. Justification::centred, false);
  52578. ga.createPath (icon);
  52579. icon.setUsingNonZeroWinding (false);
  52580. g.setColour (Colour (colour));
  52581. g.fillPath (icon);
  52582. iconSpaceUsed = iconWidth;
  52583. alignment = Justification::left;
  52584. }
  52585. g.setColour (alert.findColour (AlertWindow::textColourId));
  52586. textLayout.drawWithin (g,
  52587. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52588. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52589. alignment.getFlags() | Justification::top);
  52590. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52591. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52592. }
  52593. int LookAndFeel::getAlertBoxWindowFlags()
  52594. {
  52595. return ComponentPeer::windowAppearsOnTaskbar
  52596. | ComponentPeer::windowHasDropShadow;
  52597. }
  52598. int LookAndFeel::getAlertWindowButtonHeight()
  52599. {
  52600. return 28;
  52601. }
  52602. const Font LookAndFeel::getAlertWindowFont()
  52603. {
  52604. return Font (12.0f);
  52605. }
  52606. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52607. int width, int height,
  52608. double progress, const String& textToShow)
  52609. {
  52610. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52611. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52612. g.fillAll (background);
  52613. if (progress >= 0.0f && progress < 1.0f)
  52614. {
  52615. drawGlassLozenge (g, 1.0f, 1.0f,
  52616. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52617. (float) (height - 2),
  52618. foreground,
  52619. 0.5f, 0.0f,
  52620. true, true, true, true);
  52621. }
  52622. else
  52623. {
  52624. // spinning bar..
  52625. g.setColour (foreground);
  52626. const int stripeWidth = height * 2;
  52627. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52628. Path p;
  52629. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52630. p.addQuadrilateral (x, 0.0f,
  52631. x + stripeWidth * 0.5f, 0.0f,
  52632. x, (float) height,
  52633. x - stripeWidth * 0.5f, (float) height);
  52634. Image im (Image::ARGB, width, height, true);
  52635. {
  52636. Graphics g2 (im);
  52637. drawGlassLozenge (g2, 1.0f, 1.0f,
  52638. (float) (width - 2),
  52639. (float) (height - 2),
  52640. foreground,
  52641. 0.5f, 0.0f,
  52642. true, true, true, true);
  52643. }
  52644. g.setTiledImageFill (im, 0, 0, 0.85f);
  52645. g.fillPath (p);
  52646. }
  52647. if (textToShow.isNotEmpty())
  52648. {
  52649. g.setColour (Colour::contrasting (background, foreground));
  52650. g.setFont (height * 0.6f);
  52651. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52652. }
  52653. }
  52654. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52655. {
  52656. const float radius = jmin (w, h) * 0.4f;
  52657. const float thickness = radius * 0.15f;
  52658. Path p;
  52659. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52660. radius * 0.6f, thickness,
  52661. thickness * 0.5f);
  52662. const float cx = x + w * 0.5f;
  52663. const float cy = y + h * 0.5f;
  52664. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52665. for (int i = 0; i < 12; ++i)
  52666. {
  52667. const int n = (i + 12 - animationIndex) % 12;
  52668. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52669. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52670. .translated (cx, cy));
  52671. }
  52672. }
  52673. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52674. ScrollBar& scrollbar,
  52675. int width, int height,
  52676. int buttonDirection,
  52677. bool /*isScrollbarVertical*/,
  52678. bool /*isMouseOverButton*/,
  52679. bool isButtonDown)
  52680. {
  52681. Path p;
  52682. if (buttonDirection == 0)
  52683. p.addTriangle (width * 0.5f, height * 0.2f,
  52684. width * 0.1f, height * 0.7f,
  52685. width * 0.9f, height * 0.7f);
  52686. else if (buttonDirection == 1)
  52687. p.addTriangle (width * 0.8f, height * 0.5f,
  52688. width * 0.3f, height * 0.1f,
  52689. width * 0.3f, height * 0.9f);
  52690. else if (buttonDirection == 2)
  52691. p.addTriangle (width * 0.5f, height * 0.8f,
  52692. width * 0.1f, height * 0.3f,
  52693. width * 0.9f, height * 0.3f);
  52694. else if (buttonDirection == 3)
  52695. p.addTriangle (width * 0.2f, height * 0.5f,
  52696. width * 0.7f, height * 0.1f,
  52697. width * 0.7f, height * 0.9f);
  52698. if (isButtonDown)
  52699. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52700. else
  52701. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52702. g.fillPath (p);
  52703. g.setColour (Colour (0x80000000));
  52704. g.strokePath (p, PathStrokeType (0.5f));
  52705. }
  52706. void LookAndFeel::drawScrollbar (Graphics& g,
  52707. ScrollBar& scrollbar,
  52708. int x, int y,
  52709. int width, int height,
  52710. bool isScrollbarVertical,
  52711. int thumbStartPosition,
  52712. int thumbSize,
  52713. bool /*isMouseOver*/,
  52714. bool /*isMouseDown*/)
  52715. {
  52716. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52717. Path slotPath, thumbPath;
  52718. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52719. const float slotIndentx2 = slotIndent * 2.0f;
  52720. const float thumbIndent = slotIndent + 1.0f;
  52721. const float thumbIndentx2 = thumbIndent * 2.0f;
  52722. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52723. if (isScrollbarVertical)
  52724. {
  52725. slotPath.addRoundedRectangle (x + slotIndent,
  52726. y + slotIndent,
  52727. width - slotIndentx2,
  52728. height - slotIndentx2,
  52729. (width - slotIndentx2) * 0.5f);
  52730. if (thumbSize > 0)
  52731. thumbPath.addRoundedRectangle (x + thumbIndent,
  52732. thumbStartPosition + thumbIndent,
  52733. width - thumbIndentx2,
  52734. thumbSize - thumbIndentx2,
  52735. (width - thumbIndentx2) * 0.5f);
  52736. gx1 = (float) x;
  52737. gx2 = x + width * 0.7f;
  52738. }
  52739. else
  52740. {
  52741. slotPath.addRoundedRectangle (x + slotIndent,
  52742. y + slotIndent,
  52743. width - slotIndentx2,
  52744. height - slotIndentx2,
  52745. (height - slotIndentx2) * 0.5f);
  52746. if (thumbSize > 0)
  52747. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52748. y + thumbIndent,
  52749. thumbSize - thumbIndentx2,
  52750. height - thumbIndentx2,
  52751. (height - thumbIndentx2) * 0.5f);
  52752. gy1 = (float) y;
  52753. gy2 = y + height * 0.7f;
  52754. }
  52755. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52756. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52757. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52758. g.fillPath (slotPath);
  52759. if (isScrollbarVertical)
  52760. {
  52761. gx1 = x + width * 0.6f;
  52762. gx2 = (float) x + width;
  52763. }
  52764. else
  52765. {
  52766. gy1 = y + height * 0.6f;
  52767. gy2 = (float) y + height;
  52768. }
  52769. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52770. Colour (0x19000000), gx2, gy2, false));
  52771. g.fillPath (slotPath);
  52772. g.setColour (thumbColour);
  52773. g.fillPath (thumbPath);
  52774. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52775. Colours::transparentBlack, gx2, gy2, false));
  52776. g.saveState();
  52777. if (isScrollbarVertical)
  52778. g.reduceClipRegion (x + width / 2, y, width, height);
  52779. else
  52780. g.reduceClipRegion (x, y + height / 2, width, height);
  52781. g.fillPath (thumbPath);
  52782. g.restoreState();
  52783. g.setColour (Colour (0x4c000000));
  52784. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52785. }
  52786. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52787. {
  52788. return 0;
  52789. }
  52790. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52791. {
  52792. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52793. }
  52794. int LookAndFeel::getDefaultScrollbarWidth()
  52795. {
  52796. return 18;
  52797. }
  52798. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52799. {
  52800. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52801. : scrollbar.getHeight());
  52802. }
  52803. const Path LookAndFeel::getTickShape (const float height)
  52804. {
  52805. static const unsigned char tickShapeData[] =
  52806. {
  52807. 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,
  52808. 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,
  52809. 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,
  52810. 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,
  52811. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52812. };
  52813. Path p;
  52814. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52815. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52816. return p;
  52817. }
  52818. const Path LookAndFeel::getCrossShape (const float height)
  52819. {
  52820. static const unsigned char crossShapeData[] =
  52821. {
  52822. 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,
  52823. 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,
  52824. 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,
  52825. 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,
  52826. 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,
  52827. 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,
  52828. 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
  52829. };
  52830. Path p;
  52831. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52832. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52833. return p;
  52834. }
  52835. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52836. {
  52837. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52838. x += (w - boxSize) >> 1;
  52839. y += (h - boxSize) >> 1;
  52840. w = boxSize;
  52841. h = boxSize;
  52842. g.setColour (Colour (0xe5ffffff));
  52843. g.fillRect (x, y, w, h);
  52844. g.setColour (Colour (0x80000000));
  52845. g.drawRect (x, y, w, h);
  52846. const float size = boxSize / 2 + 1.0f;
  52847. const float centre = (float) (boxSize / 2);
  52848. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52849. if (isPlus)
  52850. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52851. }
  52852. void LookAndFeel::drawBubble (Graphics& g,
  52853. float tipX, float tipY,
  52854. float boxX, float boxY,
  52855. float boxW, float boxH)
  52856. {
  52857. int side = 0;
  52858. if (tipX < boxX)
  52859. side = 1;
  52860. else if (tipX > boxX + boxW)
  52861. side = 3;
  52862. else if (tipY > boxY + boxH)
  52863. side = 2;
  52864. const float indent = 2.0f;
  52865. Path p;
  52866. p.addBubble (boxX + indent,
  52867. boxY + indent,
  52868. boxW - indent * 2.0f,
  52869. boxH - indent * 2.0f,
  52870. 5.0f,
  52871. tipX, tipY,
  52872. side,
  52873. 0.5f,
  52874. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52875. //xxx need to take comp as param for colour
  52876. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52877. g.fillPath (p);
  52878. //xxx as above
  52879. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52880. g.strokePath (p, PathStrokeType (1.33f));
  52881. }
  52882. const Font LookAndFeel::getPopupMenuFont()
  52883. {
  52884. return Font (17.0f);
  52885. }
  52886. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52887. const bool isSeparator,
  52888. int standardMenuItemHeight,
  52889. int& idealWidth,
  52890. int& idealHeight)
  52891. {
  52892. if (isSeparator)
  52893. {
  52894. idealWidth = 50;
  52895. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52896. }
  52897. else
  52898. {
  52899. Font font (getPopupMenuFont());
  52900. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52901. font.setHeight (standardMenuItemHeight / 1.3f);
  52902. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52903. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52904. }
  52905. }
  52906. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52907. {
  52908. const Colour background (findColour (PopupMenu::backgroundColourId));
  52909. g.fillAll (background);
  52910. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52911. for (int i = 0; i < height; i += 3)
  52912. g.fillRect (0, i, width, 1);
  52913. #if ! JUCE_MAC
  52914. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52915. g.drawRect (0, 0, width, height);
  52916. #endif
  52917. }
  52918. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52919. int width, int height,
  52920. bool isScrollUpArrow)
  52921. {
  52922. const Colour background (findColour (PopupMenu::backgroundColourId));
  52923. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52924. background.withAlpha (0.0f),
  52925. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52926. false));
  52927. g.fillRect (1, 1, width - 2, height - 2);
  52928. const float hw = width * 0.5f;
  52929. const float arrowW = height * 0.3f;
  52930. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52931. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52932. Path p;
  52933. p.addTriangle (hw - arrowW, y1,
  52934. hw + arrowW, y1,
  52935. hw, y2);
  52936. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52937. g.fillPath (p);
  52938. }
  52939. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52940. int width, int height,
  52941. const bool isSeparator,
  52942. const bool isActive,
  52943. const bool isHighlighted,
  52944. const bool isTicked,
  52945. const bool hasSubMenu,
  52946. const String& text,
  52947. const String& shortcutKeyText,
  52948. Image* image,
  52949. const Colour* const textColourToUse)
  52950. {
  52951. const float halfH = height * 0.5f;
  52952. if (isSeparator)
  52953. {
  52954. const float separatorIndent = 5.5f;
  52955. g.setColour (Colour (0x33000000));
  52956. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52957. g.setColour (Colour (0x66ffffff));
  52958. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52959. }
  52960. else
  52961. {
  52962. Colour textColour (findColour (PopupMenu::textColourId));
  52963. if (textColourToUse != 0)
  52964. textColour = *textColourToUse;
  52965. if (isHighlighted)
  52966. {
  52967. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52968. g.fillRect (1, 1, width - 2, height - 2);
  52969. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52970. }
  52971. else
  52972. {
  52973. g.setColour (textColour);
  52974. }
  52975. if (! isActive)
  52976. g.setOpacity (0.3f);
  52977. Font font (getPopupMenuFont());
  52978. if (font.getHeight() > height / 1.3f)
  52979. font.setHeight (height / 1.3f);
  52980. g.setFont (font);
  52981. const int leftBorder = (height * 5) / 4;
  52982. const int rightBorder = 4;
  52983. if (image != 0)
  52984. {
  52985. g.drawImageWithin (*image,
  52986. 2, 1, leftBorder - 4, height - 2,
  52987. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52988. }
  52989. else if (isTicked)
  52990. {
  52991. const Path tick (getTickShape (1.0f));
  52992. const float th = font.getAscent();
  52993. const float ty = halfH - th * 0.5f;
  52994. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52995. th, true));
  52996. }
  52997. g.drawFittedText (text,
  52998. leftBorder, 0,
  52999. width - (leftBorder + rightBorder), height,
  53000. Justification::centredLeft, 1);
  53001. if (shortcutKeyText.isNotEmpty())
  53002. {
  53003. Font f2 (font);
  53004. f2.setHeight (f2.getHeight() * 0.75f);
  53005. f2.setHorizontalScale (0.95f);
  53006. g.setFont (f2);
  53007. g.drawText (shortcutKeyText,
  53008. leftBorder,
  53009. 0,
  53010. width - (leftBorder + rightBorder + 4),
  53011. height,
  53012. Justification::centredRight,
  53013. true);
  53014. }
  53015. if (hasSubMenu)
  53016. {
  53017. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53018. const float x = width - height * 0.6f;
  53019. Path p;
  53020. p.addTriangle (x, halfH - arrowH * 0.5f,
  53021. x, halfH + arrowH * 0.5f,
  53022. x + arrowH * 0.6f, halfH);
  53023. g.fillPath (p);
  53024. }
  53025. }
  53026. }
  53027. int LookAndFeel::getMenuWindowFlags()
  53028. {
  53029. return ComponentPeer::windowHasDropShadow;
  53030. }
  53031. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53032. bool, MenuBarComponent& menuBar)
  53033. {
  53034. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53035. if (menuBar.isEnabled())
  53036. {
  53037. drawShinyButtonShape (g,
  53038. -4.0f, 0.0f,
  53039. width + 8.0f, (float) height,
  53040. 0.0f,
  53041. baseColour,
  53042. 0.4f,
  53043. true, true, true, true);
  53044. }
  53045. else
  53046. {
  53047. g.fillAll (baseColour);
  53048. }
  53049. }
  53050. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53051. {
  53052. return Font (menuBar.getHeight() * 0.7f);
  53053. }
  53054. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53055. {
  53056. return getMenuBarFont (menuBar, itemIndex, itemText)
  53057. .getStringWidth (itemText) + menuBar.getHeight();
  53058. }
  53059. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53060. int width, int height,
  53061. int itemIndex,
  53062. const String& itemText,
  53063. bool isMouseOverItem,
  53064. bool isMenuOpen,
  53065. bool /*isMouseOverBar*/,
  53066. MenuBarComponent& menuBar)
  53067. {
  53068. if (! menuBar.isEnabled())
  53069. {
  53070. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53071. .withMultipliedAlpha (0.5f));
  53072. }
  53073. else if (isMenuOpen || isMouseOverItem)
  53074. {
  53075. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53076. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53077. }
  53078. else
  53079. {
  53080. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53081. }
  53082. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53083. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53084. }
  53085. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53086. TextEditor& textEditor)
  53087. {
  53088. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53089. }
  53090. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53091. {
  53092. if (textEditor.isEnabled())
  53093. {
  53094. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53095. {
  53096. const int border = 2;
  53097. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53098. g.drawRect (0, 0, width, height, border);
  53099. g.setOpacity (1.0f);
  53100. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53101. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53102. }
  53103. else
  53104. {
  53105. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53106. g.drawRect (0, 0, width, height);
  53107. g.setOpacity (1.0f);
  53108. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53109. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53110. }
  53111. }
  53112. }
  53113. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53114. const bool isButtonDown,
  53115. int buttonX, int buttonY,
  53116. int buttonW, int buttonH,
  53117. ComboBox& box)
  53118. {
  53119. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53120. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53121. {
  53122. g.setColour (box.findColour (TextButton::buttonColourId));
  53123. g.drawRect (0, 0, width, height, 2);
  53124. }
  53125. else
  53126. {
  53127. g.setColour (box.findColour (ComboBox::outlineColourId));
  53128. g.drawRect (0, 0, width, height);
  53129. }
  53130. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53131. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53132. box.hasKeyboardFocus (true),
  53133. false, isButtonDown)
  53134. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53135. drawGlassLozenge (g,
  53136. buttonX + outlineThickness, buttonY + outlineThickness,
  53137. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53138. baseColour, outlineThickness, -1.0f,
  53139. true, true, true, true);
  53140. if (box.isEnabled())
  53141. {
  53142. const float arrowX = 0.3f;
  53143. const float arrowH = 0.2f;
  53144. Path p;
  53145. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53146. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53147. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53148. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53149. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53150. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53151. g.setColour (box.findColour (ComboBox::arrowColourId));
  53152. g.fillPath (p);
  53153. }
  53154. }
  53155. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53156. {
  53157. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53158. }
  53159. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53160. {
  53161. return new Label (String::empty, String::empty);
  53162. }
  53163. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53164. {
  53165. label.setBounds (1, 1,
  53166. box.getWidth() + 3 - box.getHeight(),
  53167. box.getHeight() - 2);
  53168. label.setFont (getComboBoxFont (box));
  53169. }
  53170. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53171. {
  53172. g.fillAll (label.findColour (Label::backgroundColourId));
  53173. if (! label.isBeingEdited())
  53174. {
  53175. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53176. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53177. g.setFont (label.getFont());
  53178. g.drawFittedText (label.getText(),
  53179. label.getHorizontalBorderSize(),
  53180. label.getVerticalBorderSize(),
  53181. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53182. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53183. label.getJustificationType(),
  53184. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53185. label.getMinimumHorizontalScale());
  53186. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53187. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53188. }
  53189. else if (label.isEnabled())
  53190. {
  53191. g.setColour (label.findColour (Label::outlineColourId));
  53192. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53193. }
  53194. }
  53195. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53196. int x, int y,
  53197. int width, int height,
  53198. float /*sliderPos*/,
  53199. float /*minSliderPos*/,
  53200. float /*maxSliderPos*/,
  53201. const Slider::SliderStyle /*style*/,
  53202. Slider& slider)
  53203. {
  53204. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53205. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53206. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53207. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53208. Path indent;
  53209. if (slider.isHorizontal())
  53210. {
  53211. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53212. const float ih = sliderRadius;
  53213. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53214. gradCol2, 0.0f, iy + ih, false));
  53215. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53216. width + sliderRadius, ih,
  53217. 5.0f);
  53218. g.fillPath (indent);
  53219. }
  53220. else
  53221. {
  53222. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53223. const float iw = sliderRadius;
  53224. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53225. gradCol2, ix + iw, 0.0f, false));
  53226. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53227. iw, height + sliderRadius,
  53228. 5.0f);
  53229. g.fillPath (indent);
  53230. }
  53231. g.setColour (Colour (0x4c000000));
  53232. g.strokePath (indent, PathStrokeType (0.5f));
  53233. }
  53234. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53235. int x, int y,
  53236. int width, int height,
  53237. float sliderPos,
  53238. float minSliderPos,
  53239. float maxSliderPos,
  53240. const Slider::SliderStyle style,
  53241. Slider& slider)
  53242. {
  53243. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53244. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53245. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53246. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53247. slider.isMouseButtonDown() && slider.isEnabled()));
  53248. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53249. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53250. {
  53251. float kx, ky;
  53252. if (style == Slider::LinearVertical)
  53253. {
  53254. kx = x + width * 0.5f;
  53255. ky = sliderPos;
  53256. }
  53257. else
  53258. {
  53259. kx = sliderPos;
  53260. ky = y + height * 0.5f;
  53261. }
  53262. drawGlassSphere (g,
  53263. kx - sliderRadius,
  53264. ky - sliderRadius,
  53265. sliderRadius * 2.0f,
  53266. knobColour, outlineThickness);
  53267. }
  53268. else
  53269. {
  53270. if (style == Slider::ThreeValueVertical)
  53271. {
  53272. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53273. sliderPos - sliderRadius,
  53274. sliderRadius * 2.0f,
  53275. knobColour, outlineThickness);
  53276. }
  53277. else if (style == Slider::ThreeValueHorizontal)
  53278. {
  53279. drawGlassSphere (g,sliderPos - sliderRadius,
  53280. y + height * 0.5f - sliderRadius,
  53281. sliderRadius * 2.0f,
  53282. knobColour, outlineThickness);
  53283. }
  53284. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53285. {
  53286. const float sr = jmin (sliderRadius, width * 0.4f);
  53287. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53288. minSliderPos - sliderRadius,
  53289. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53290. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53291. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53292. }
  53293. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53294. {
  53295. const float sr = jmin (sliderRadius, height * 0.4f);
  53296. drawGlassPointer (g, minSliderPos - sr,
  53297. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53298. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53299. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53300. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53301. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53302. }
  53303. }
  53304. }
  53305. void LookAndFeel::drawLinearSlider (Graphics& g,
  53306. int x, int y,
  53307. int width, int height,
  53308. float sliderPos,
  53309. float minSliderPos,
  53310. float maxSliderPos,
  53311. const Slider::SliderStyle style,
  53312. Slider& slider)
  53313. {
  53314. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53315. if (style == Slider::LinearBar)
  53316. {
  53317. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53318. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53319. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53320. false, isMouseOver,
  53321. isMouseOver || slider.isMouseButtonDown()));
  53322. drawShinyButtonShape (g,
  53323. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53324. baseColour,
  53325. slider.isEnabled() ? 0.9f : 0.3f,
  53326. true, true, true, true);
  53327. }
  53328. else
  53329. {
  53330. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53331. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53332. }
  53333. }
  53334. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53335. {
  53336. return jmin (7,
  53337. slider.getHeight() / 2,
  53338. slider.getWidth() / 2) + 2;
  53339. }
  53340. void LookAndFeel::drawRotarySlider (Graphics& g,
  53341. int x, int y,
  53342. int width, int height,
  53343. float sliderPos,
  53344. const float rotaryStartAngle,
  53345. const float rotaryEndAngle,
  53346. Slider& slider)
  53347. {
  53348. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53349. const float centreX = x + width * 0.5f;
  53350. const float centreY = y + height * 0.5f;
  53351. const float rx = centreX - radius;
  53352. const float ry = centreY - radius;
  53353. const float rw = radius * 2.0f;
  53354. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53355. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53356. if (radius > 12.0f)
  53357. {
  53358. if (slider.isEnabled())
  53359. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53360. else
  53361. g.setColour (Colour (0x80808080));
  53362. const float thickness = 0.7f;
  53363. {
  53364. Path filledArc;
  53365. filledArc.addPieSegment (rx, ry, rw, rw,
  53366. rotaryStartAngle,
  53367. angle,
  53368. thickness);
  53369. g.fillPath (filledArc);
  53370. }
  53371. if (thickness > 0)
  53372. {
  53373. const float innerRadius = radius * 0.2f;
  53374. Path p;
  53375. p.addTriangle (-innerRadius, 0.0f,
  53376. 0.0f, -radius * thickness * 1.1f,
  53377. innerRadius, 0.0f);
  53378. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53379. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53380. }
  53381. if (slider.isEnabled())
  53382. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53383. else
  53384. g.setColour (Colour (0x80808080));
  53385. Path outlineArc;
  53386. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53387. outlineArc.closeSubPath();
  53388. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53389. }
  53390. else
  53391. {
  53392. if (slider.isEnabled())
  53393. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53394. else
  53395. g.setColour (Colour (0x80808080));
  53396. Path p;
  53397. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53398. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53399. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53400. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53401. }
  53402. }
  53403. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53404. {
  53405. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53406. }
  53407. class SliderLabelComp : public Label
  53408. {
  53409. public:
  53410. SliderLabelComp() : Label (String::empty, String::empty) {}
  53411. ~SliderLabelComp() {}
  53412. void mouseWheelMove (const MouseEvent&, float, float) {}
  53413. };
  53414. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53415. {
  53416. Label* const l = new SliderLabelComp();
  53417. l->setJustificationType (Justification::centred);
  53418. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53419. l->setColour (Label::backgroundColourId,
  53420. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53421. : slider.findColour (Slider::textBoxBackgroundColourId));
  53422. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53423. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53424. l->setColour (TextEditor::backgroundColourId,
  53425. slider.findColour (Slider::textBoxBackgroundColourId)
  53426. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53427. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53428. return l;
  53429. }
  53430. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53431. {
  53432. return 0;
  53433. }
  53434. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53435. {
  53436. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53437. width = tl.getWidth() + 14;
  53438. height = tl.getHeight() + 6;
  53439. }
  53440. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53441. {
  53442. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53443. const Colour textCol (findColour (TooltipWindow::textColourId));
  53444. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53445. g.setColour (findColour (TooltipWindow::outlineColourId));
  53446. g.drawRect (0, 0, width, height, 1);
  53447. #endif
  53448. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53449. g.setColour (findColour (TooltipWindow::textColourId));
  53450. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53451. }
  53452. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53453. {
  53454. return new TextButton (text, TRANS("click to browse for a different file"));
  53455. }
  53456. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53457. ComboBox* filenameBox,
  53458. Button* browseButton)
  53459. {
  53460. browseButton->setSize (80, filenameComp.getHeight());
  53461. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53462. if (tb != 0)
  53463. tb->changeWidthToFitText();
  53464. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53465. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53466. }
  53467. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53468. int imageX, int imageY, int imageW, int imageH,
  53469. const Colour& overlayColour,
  53470. float imageOpacity,
  53471. ImageButton& button)
  53472. {
  53473. if (! button.isEnabled())
  53474. imageOpacity *= 0.3f;
  53475. if (! overlayColour.isOpaque())
  53476. {
  53477. g.setOpacity (imageOpacity);
  53478. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53479. 0, 0, image->getWidth(), image->getHeight(), false);
  53480. }
  53481. if (! overlayColour.isTransparent())
  53482. {
  53483. g.setColour (overlayColour);
  53484. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53485. 0, 0, image->getWidth(), image->getHeight(), true);
  53486. }
  53487. }
  53488. void LookAndFeel::drawCornerResizer (Graphics& g,
  53489. int w, int h,
  53490. bool /*isMouseOver*/,
  53491. bool /*isMouseDragging*/)
  53492. {
  53493. const float lineThickness = jmin (w, h) * 0.075f;
  53494. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53495. {
  53496. g.setColour (Colours::lightgrey);
  53497. g.drawLine (w * i,
  53498. h + 1.0f,
  53499. w + 1.0f,
  53500. h * i,
  53501. lineThickness);
  53502. g.setColour (Colours::darkgrey);
  53503. g.drawLine (w * i + lineThickness,
  53504. h + 1.0f,
  53505. w + 1.0f,
  53506. h * i + lineThickness,
  53507. lineThickness);
  53508. }
  53509. }
  53510. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53511. {
  53512. if (! border.isEmpty())
  53513. {
  53514. const Rectangle<int> fullSize (0, 0, w, h);
  53515. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53516. g.saveState();
  53517. g.excludeClipRegion (centreArea);
  53518. g.setColour (Colour (0x50000000));
  53519. g.drawRect (fullSize);
  53520. g.setColour (Colour (0x19000000));
  53521. g.drawRect (centreArea.expanded (1, 1));
  53522. g.restoreState();
  53523. }
  53524. }
  53525. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53526. const BorderSize& /*border*/, ResizableWindow& window)
  53527. {
  53528. g.fillAll (window.getBackgroundColour());
  53529. }
  53530. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53531. const BorderSize& /*border*/, ResizableWindow&)
  53532. {
  53533. }
  53534. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53535. Graphics& g, int w, int h,
  53536. int titleSpaceX, int titleSpaceW,
  53537. const Image* icon,
  53538. bool drawTitleTextOnLeft)
  53539. {
  53540. const bool isActive = window.isActiveWindow();
  53541. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53542. 0.0f, 0.0f,
  53543. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53544. 0.0f, (float) h, false));
  53545. g.fillAll();
  53546. Font font (h * 0.65f, Font::bold);
  53547. g.setFont (font);
  53548. int textW = font.getStringWidth (window.getName());
  53549. int iconW = 0;
  53550. int iconH = 0;
  53551. if (icon != 0)
  53552. {
  53553. iconH = (int) font.getHeight();
  53554. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53555. }
  53556. textW = jmin (titleSpaceW, textW + iconW);
  53557. int textX = drawTitleTextOnLeft ? titleSpaceX
  53558. : jmax (titleSpaceX, (w - textW) / 2);
  53559. if (textX + textW > titleSpaceX + titleSpaceW)
  53560. textX = titleSpaceX + titleSpaceW - textW;
  53561. if (icon != 0)
  53562. {
  53563. g.setOpacity (isActive ? 1.0f : 0.6f);
  53564. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53565. RectanglePlacement::centred, false);
  53566. textX += iconW;
  53567. textW -= iconW;
  53568. }
  53569. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53570. g.setColour (findColour (DocumentWindow::textColourId));
  53571. else
  53572. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53573. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53574. }
  53575. class GlassWindowButton : public Button
  53576. {
  53577. public:
  53578. GlassWindowButton (const String& name, const Colour& col,
  53579. const Path& normalShape_,
  53580. const Path& toggledShape_) throw()
  53581. : Button (name),
  53582. colour (col),
  53583. normalShape (normalShape_),
  53584. toggledShape (toggledShape_)
  53585. {
  53586. }
  53587. ~GlassWindowButton()
  53588. {
  53589. }
  53590. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53591. {
  53592. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53593. if (! isEnabled())
  53594. alpha *= 0.5f;
  53595. float x = 0, y = 0, diam;
  53596. if (getWidth() < getHeight())
  53597. {
  53598. diam = (float) getWidth();
  53599. y = (getHeight() - getWidth()) * 0.5f;
  53600. }
  53601. else
  53602. {
  53603. diam = (float) getHeight();
  53604. y = (getWidth() - getHeight()) * 0.5f;
  53605. }
  53606. x += diam * 0.05f;
  53607. y += diam * 0.05f;
  53608. diam *= 0.9f;
  53609. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53610. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53611. g.fillEllipse (x, y, diam, diam);
  53612. x += 2.0f;
  53613. y += 2.0f;
  53614. diam -= 4.0f;
  53615. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53616. Path& p = getToggleState() ? toggledShape : normalShape;
  53617. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53618. diam * 0.4f, diam * 0.4f, true));
  53619. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53620. g.fillPath (p, t);
  53621. }
  53622. private:
  53623. Colour colour;
  53624. Path normalShape, toggledShape;
  53625. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53626. };
  53627. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53628. {
  53629. Path shape;
  53630. const float crossThickness = 0.25f;
  53631. if (buttonType == DocumentWindow::closeButton)
  53632. {
  53633. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53634. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53635. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53636. }
  53637. else if (buttonType == DocumentWindow::minimiseButton)
  53638. {
  53639. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53640. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53641. }
  53642. else if (buttonType == DocumentWindow::maximiseButton)
  53643. {
  53644. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53645. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53646. Path fullscreenShape;
  53647. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53648. fullscreenShape.lineTo (0.0f, 100.0f);
  53649. fullscreenShape.lineTo (0.0f, 0.0f);
  53650. fullscreenShape.lineTo (100.0f, 0.0f);
  53651. fullscreenShape.lineTo (100.0f, 45.0f);
  53652. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53653. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53654. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53655. }
  53656. jassertfalse;
  53657. return 0;
  53658. }
  53659. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53660. int titleBarX,
  53661. int titleBarY,
  53662. int titleBarW,
  53663. int titleBarH,
  53664. Button* minimiseButton,
  53665. Button* maximiseButton,
  53666. Button* closeButton,
  53667. bool positionTitleBarButtonsOnLeft)
  53668. {
  53669. const int buttonW = titleBarH - titleBarH / 8;
  53670. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53671. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53672. if (closeButton != 0)
  53673. {
  53674. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53675. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53676. }
  53677. if (positionTitleBarButtonsOnLeft)
  53678. swapVariables (minimiseButton, maximiseButton);
  53679. if (maximiseButton != 0)
  53680. {
  53681. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53682. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53683. }
  53684. if (minimiseButton != 0)
  53685. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53686. }
  53687. int LookAndFeel::getDefaultMenuBarHeight()
  53688. {
  53689. return 24;
  53690. }
  53691. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53692. {
  53693. return new DropShadower (0.4f, 1, 5, 10);
  53694. }
  53695. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53696. int w, int h,
  53697. bool /*isVerticalBar*/,
  53698. bool isMouseOver,
  53699. bool isMouseDragging)
  53700. {
  53701. float alpha = 0.5f;
  53702. if (isMouseOver || isMouseDragging)
  53703. {
  53704. g.fillAll (Colour (0x190000ff));
  53705. alpha = 1.0f;
  53706. }
  53707. const float cx = w * 0.5f;
  53708. const float cy = h * 0.5f;
  53709. const float cr = jmin (w, h) * 0.4f;
  53710. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53711. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53712. true));
  53713. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53714. }
  53715. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53716. const String& text,
  53717. const Justification& position,
  53718. GroupComponent& group)
  53719. {
  53720. const float textH = 15.0f;
  53721. const float indent = 3.0f;
  53722. const float textEdgeGap = 4.0f;
  53723. float cs = 5.0f;
  53724. Font f (textH);
  53725. Path p;
  53726. float x = indent;
  53727. float y = f.getAscent() - 3.0f;
  53728. float w = jmax (0.0f, width - x * 2.0f);
  53729. float h = jmax (0.0f, height - y - indent);
  53730. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53731. const float cs2 = 2.0f * cs;
  53732. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53733. float textX = cs + textEdgeGap;
  53734. if (position.testFlags (Justification::horizontallyCentred))
  53735. textX = cs + (w - cs2 - textW) * 0.5f;
  53736. else if (position.testFlags (Justification::right))
  53737. textX = w - cs - textW - textEdgeGap;
  53738. p.startNewSubPath (x + textX + textW, y);
  53739. p.lineTo (x + w - cs, y);
  53740. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53741. p.lineTo (x + w, y + h - cs);
  53742. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53743. p.lineTo (x + cs, y + h);
  53744. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53745. p.lineTo (x, y + cs);
  53746. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53747. p.lineTo (x + textX, y);
  53748. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53749. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53750. .withMultipliedAlpha (alpha));
  53751. g.strokePath (p, PathStrokeType (2.0f));
  53752. g.setColour (group.findColour (GroupComponent::textColourId)
  53753. .withMultipliedAlpha (alpha));
  53754. g.setFont (f);
  53755. g.drawText (text,
  53756. roundToInt (x + textX), 0,
  53757. roundToInt (textW),
  53758. roundToInt (textH),
  53759. Justification::centred, true);
  53760. }
  53761. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53762. {
  53763. return 1 + tabDepth / 3;
  53764. }
  53765. int LookAndFeel::getTabButtonSpaceAroundImage()
  53766. {
  53767. return 4;
  53768. }
  53769. void LookAndFeel::createTabButtonShape (Path& p,
  53770. int width, int height,
  53771. int /*tabIndex*/,
  53772. const String& /*text*/,
  53773. Button& /*button*/,
  53774. TabbedButtonBar::Orientation orientation,
  53775. const bool /*isMouseOver*/,
  53776. const bool /*isMouseDown*/,
  53777. const bool /*isFrontTab*/)
  53778. {
  53779. const float w = (float) width;
  53780. const float h = (float) height;
  53781. float length = w;
  53782. float depth = h;
  53783. if (orientation == TabbedButtonBar::TabsAtLeft
  53784. || orientation == TabbedButtonBar::TabsAtRight)
  53785. {
  53786. swapVariables (length, depth);
  53787. }
  53788. const float indent = (float) getTabButtonOverlap ((int) depth);
  53789. const float overhang = 4.0f;
  53790. if (orientation == TabbedButtonBar::TabsAtLeft)
  53791. {
  53792. p.startNewSubPath (w, 0.0f);
  53793. p.lineTo (0.0f, indent);
  53794. p.lineTo (0.0f, h - indent);
  53795. p.lineTo (w, h);
  53796. p.lineTo (w + overhang, h + overhang);
  53797. p.lineTo (w + overhang, -overhang);
  53798. }
  53799. else if (orientation == TabbedButtonBar::TabsAtRight)
  53800. {
  53801. p.startNewSubPath (0.0f, 0.0f);
  53802. p.lineTo (w, indent);
  53803. p.lineTo (w, h - indent);
  53804. p.lineTo (0.0f, h);
  53805. p.lineTo (-overhang, h + overhang);
  53806. p.lineTo (-overhang, -overhang);
  53807. }
  53808. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53809. {
  53810. p.startNewSubPath (0.0f, 0.0f);
  53811. p.lineTo (indent, h);
  53812. p.lineTo (w - indent, h);
  53813. p.lineTo (w, 0.0f);
  53814. p.lineTo (w + overhang, -overhang);
  53815. p.lineTo (-overhang, -overhang);
  53816. }
  53817. else
  53818. {
  53819. p.startNewSubPath (0.0f, h);
  53820. p.lineTo (indent, 0.0f);
  53821. p.lineTo (w - indent, 0.0f);
  53822. p.lineTo (w, h);
  53823. p.lineTo (w + overhang, h + overhang);
  53824. p.lineTo (-overhang, h + overhang);
  53825. }
  53826. p.closeSubPath();
  53827. p = p.createPathWithRoundedCorners (3.0f);
  53828. }
  53829. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53830. const Path& path,
  53831. const Colour& preferredColour,
  53832. int /*tabIndex*/,
  53833. const String& /*text*/,
  53834. Button& button,
  53835. TabbedButtonBar::Orientation /*orientation*/,
  53836. const bool /*isMouseOver*/,
  53837. const bool /*isMouseDown*/,
  53838. const bool isFrontTab)
  53839. {
  53840. g.setColour (isFrontTab ? preferredColour
  53841. : preferredColour.withMultipliedAlpha (0.9f));
  53842. g.fillPath (path);
  53843. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53844. : TabbedButtonBar::tabOutlineColourId, false)
  53845. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53846. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53847. }
  53848. void LookAndFeel::drawTabButtonText (Graphics& g,
  53849. int x, int y, int w, int h,
  53850. const Colour& preferredBackgroundColour,
  53851. int /*tabIndex*/,
  53852. const String& text,
  53853. Button& button,
  53854. TabbedButtonBar::Orientation orientation,
  53855. const bool isMouseOver,
  53856. const bool isMouseDown,
  53857. const bool isFrontTab)
  53858. {
  53859. int length = w;
  53860. int depth = h;
  53861. if (orientation == TabbedButtonBar::TabsAtLeft
  53862. || orientation == TabbedButtonBar::TabsAtRight)
  53863. {
  53864. swapVariables (length, depth);
  53865. }
  53866. Font font (depth * 0.6f);
  53867. font.setUnderline (button.hasKeyboardFocus (false));
  53868. GlyphArrangement textLayout;
  53869. textLayout.addFittedText (font, text.trim(),
  53870. 0.0f, 0.0f, (float) length, (float) depth,
  53871. Justification::centred,
  53872. jmax (1, depth / 12));
  53873. AffineTransform transform;
  53874. if (orientation == TabbedButtonBar::TabsAtLeft)
  53875. {
  53876. transform = transform.rotated (float_Pi * -0.5f)
  53877. .translated ((float) x, (float) (y + h));
  53878. }
  53879. else if (orientation == TabbedButtonBar::TabsAtRight)
  53880. {
  53881. transform = transform.rotated (float_Pi * 0.5f)
  53882. .translated ((float) (x + w), (float) y);
  53883. }
  53884. else
  53885. {
  53886. transform = transform.translated ((float) x, (float) y);
  53887. }
  53888. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53889. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53890. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53891. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53892. else
  53893. g.setColour (preferredBackgroundColour.contrasting());
  53894. if (! (isMouseOver || isMouseDown))
  53895. g.setOpacity (0.8f);
  53896. if (! button.isEnabled())
  53897. g.setOpacity (0.3f);
  53898. textLayout.draw (g, transform);
  53899. }
  53900. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53901. const String& text,
  53902. int tabDepth,
  53903. Button&)
  53904. {
  53905. Font f (tabDepth * 0.6f);
  53906. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53907. }
  53908. void LookAndFeel::drawTabButton (Graphics& g,
  53909. int w, int h,
  53910. const Colour& preferredColour,
  53911. int tabIndex,
  53912. const String& text,
  53913. Button& button,
  53914. TabbedButtonBar::Orientation orientation,
  53915. const bool isMouseOver,
  53916. const bool isMouseDown,
  53917. const bool isFrontTab)
  53918. {
  53919. int length = w;
  53920. int depth = h;
  53921. if (orientation == TabbedButtonBar::TabsAtLeft
  53922. || orientation == TabbedButtonBar::TabsAtRight)
  53923. {
  53924. swapVariables (length, depth);
  53925. }
  53926. Path tabShape;
  53927. createTabButtonShape (tabShape, w, h,
  53928. tabIndex, text, button, orientation,
  53929. isMouseOver, isMouseDown, isFrontTab);
  53930. fillTabButtonShape (g, tabShape, preferredColour,
  53931. tabIndex, text, button, orientation,
  53932. isMouseOver, isMouseDown, isFrontTab);
  53933. const int indent = getTabButtonOverlap (depth);
  53934. int x = 0, y = 0;
  53935. if (orientation == TabbedButtonBar::TabsAtLeft
  53936. || orientation == TabbedButtonBar::TabsAtRight)
  53937. {
  53938. y += indent;
  53939. h -= indent * 2;
  53940. }
  53941. else
  53942. {
  53943. x += indent;
  53944. w -= indent * 2;
  53945. }
  53946. drawTabButtonText (g, x, y, w, h, preferredColour,
  53947. tabIndex, text, button, orientation,
  53948. isMouseOver, isMouseDown, isFrontTab);
  53949. }
  53950. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53951. int w, int h,
  53952. TabbedButtonBar& tabBar,
  53953. TabbedButtonBar::Orientation orientation)
  53954. {
  53955. const float shadowSize = 0.2f;
  53956. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53957. Rectangle<int> shadowRect;
  53958. if (orientation == TabbedButtonBar::TabsAtLeft)
  53959. {
  53960. x1 = (float) w;
  53961. x2 = w * (1.0f - shadowSize);
  53962. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53963. }
  53964. else if (orientation == TabbedButtonBar::TabsAtRight)
  53965. {
  53966. x2 = w * shadowSize;
  53967. shadowRect.setBounds (0, 0, (int) x2, h);
  53968. }
  53969. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53970. {
  53971. y2 = h * shadowSize;
  53972. shadowRect.setBounds (0, 0, w, (int) y2);
  53973. }
  53974. else
  53975. {
  53976. y1 = (float) h;
  53977. y2 = h * (1.0f - shadowSize);
  53978. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53979. }
  53980. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53981. Colours::transparentBlack, x2, y2, false));
  53982. shadowRect.expand (2, 2);
  53983. g.fillRect (shadowRect);
  53984. g.setColour (Colour (0x80000000));
  53985. if (orientation == TabbedButtonBar::TabsAtLeft)
  53986. {
  53987. g.fillRect (w - 1, 0, 1, h);
  53988. }
  53989. else if (orientation == TabbedButtonBar::TabsAtRight)
  53990. {
  53991. g.fillRect (0, 0, 1, h);
  53992. }
  53993. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53994. {
  53995. g.fillRect (0, 0, w, 1);
  53996. }
  53997. else
  53998. {
  53999. g.fillRect (0, h - 1, w, 1);
  54000. }
  54001. }
  54002. Button* LookAndFeel::createTabBarExtrasButton()
  54003. {
  54004. const float thickness = 7.0f;
  54005. const float indent = 22.0f;
  54006. Path p;
  54007. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54008. DrawablePath ellipse;
  54009. ellipse.setPath (p);
  54010. ellipse.setFill (Colour (0x99ffffff));
  54011. p.clear();
  54012. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54013. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54014. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54015. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54016. p.setUsingNonZeroWinding (false);
  54017. DrawablePath dp;
  54018. dp.setPath (p);
  54019. dp.setFill (Colour (0x59000000));
  54020. DrawableComposite normalImage;
  54021. normalImage.insertDrawable (ellipse);
  54022. normalImage.insertDrawable (dp);
  54023. dp.setFill (Colour (0xcc000000));
  54024. DrawableComposite overImage;
  54025. overImage.insertDrawable (ellipse);
  54026. overImage.insertDrawable (dp);
  54027. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54028. db->setImages (&normalImage, &overImage, 0);
  54029. return db;
  54030. }
  54031. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54032. {
  54033. g.fillAll (Colours::white);
  54034. const int w = header.getWidth();
  54035. const int h = header.getHeight();
  54036. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54037. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54038. false));
  54039. g.fillRect (0, h / 2, w, h);
  54040. g.setColour (Colour (0x33000000));
  54041. g.fillRect (0, h - 1, w, 1);
  54042. for (int i = header.getNumColumns (true); --i >= 0;)
  54043. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54044. }
  54045. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54046. int width, int height,
  54047. bool isMouseOver, bool isMouseDown,
  54048. int columnFlags)
  54049. {
  54050. if (isMouseDown)
  54051. g.fillAll (Colour (0x8899aadd));
  54052. else if (isMouseOver)
  54053. g.fillAll (Colour (0x5599aadd));
  54054. int rightOfText = width - 4;
  54055. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54056. {
  54057. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54058. const float bottom = height - top;
  54059. const float w = height * 0.5f;
  54060. const float x = rightOfText - (w * 1.25f);
  54061. rightOfText = (int) x;
  54062. Path sortArrow;
  54063. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54064. g.setColour (Colour (0x99000000));
  54065. g.fillPath (sortArrow);
  54066. }
  54067. g.setColour (Colours::black);
  54068. g.setFont (height * 0.5f, Font::bold);
  54069. const int textX = 4;
  54070. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54071. }
  54072. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54073. {
  54074. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54075. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54076. background.darker (0.1f),
  54077. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54078. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54079. false));
  54080. g.fillAll();
  54081. }
  54082. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54083. {
  54084. return createTabBarExtrasButton();
  54085. }
  54086. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54087. bool isMouseOver, bool isMouseDown,
  54088. ToolbarItemComponent& component)
  54089. {
  54090. if (isMouseDown)
  54091. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54092. else if (isMouseOver)
  54093. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54094. }
  54095. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54096. const String& text, ToolbarItemComponent& component)
  54097. {
  54098. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54099. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54100. const float fontHeight = jmin (14.0f, height * 0.85f);
  54101. g.setFont (fontHeight);
  54102. g.drawFittedText (text,
  54103. x, y, width, height,
  54104. Justification::centred,
  54105. jmax (1, height / (int) fontHeight));
  54106. }
  54107. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54108. bool isOpen, int width, int height)
  54109. {
  54110. const int buttonSize = (height * 3) / 4;
  54111. const int buttonIndent = (height - buttonSize) / 2;
  54112. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54113. const int textX = buttonIndent * 2 + buttonSize + 2;
  54114. g.setColour (Colours::black);
  54115. g.setFont (height * 0.7f, Font::bold);
  54116. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54117. }
  54118. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54119. PropertyComponent&)
  54120. {
  54121. g.setColour (Colour (0x66ffffff));
  54122. g.fillRect (0, 0, width, height - 1);
  54123. }
  54124. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54125. PropertyComponent& component)
  54126. {
  54127. g.setColour (Colours::black);
  54128. if (! component.isEnabled())
  54129. g.setOpacity (0.6f);
  54130. g.setFont (jmin (height, 24) * 0.65f);
  54131. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54132. g.drawFittedText (component.getName(),
  54133. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54134. Justification::centredLeft, 2);
  54135. }
  54136. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54137. {
  54138. return Rectangle<int> (component.getWidth() / 3, 1,
  54139. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54140. }
  54141. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54142. {
  54143. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54144. {
  54145. Graphics g2 (content);
  54146. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54147. g2.fillPath (path);
  54148. g2.setColour (Colours::white.withAlpha (0.8f));
  54149. g2.strokePath (path, PathStrokeType (2.0f));
  54150. }
  54151. DropShadowEffect shadow;
  54152. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54153. shadow.applyEffect (content, g, 1.0f);
  54154. }
  54155. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54156. const String& instructions,
  54157. GlyphArrangement& text,
  54158. int width)
  54159. {
  54160. text.clear();
  54161. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54162. 8.0f, 22.0f, width - 16.0f,
  54163. Justification::centred);
  54164. text.addJustifiedText (Font (14.0f), instructions,
  54165. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54166. Justification::centred);
  54167. }
  54168. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54169. const String& filename, Image* icon,
  54170. const String& fileSizeDescription,
  54171. const String& fileTimeDescription,
  54172. const bool isDirectory,
  54173. const bool isItemSelected,
  54174. const int /*itemIndex*/,
  54175. DirectoryContentsDisplayComponent&)
  54176. {
  54177. if (isItemSelected)
  54178. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54179. const int x = 32;
  54180. g.setColour (Colours::black);
  54181. if (icon != 0 && icon->isValid())
  54182. {
  54183. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54184. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54185. false);
  54186. }
  54187. else
  54188. {
  54189. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54190. : getDefaultDocumentFileImage();
  54191. if (d != 0)
  54192. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54193. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54194. }
  54195. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54196. g.setFont (height * 0.7f);
  54197. if (width > 450 && ! isDirectory)
  54198. {
  54199. const int sizeX = roundToInt (width * 0.7f);
  54200. const int dateX = roundToInt (width * 0.8f);
  54201. g.drawFittedText (filename,
  54202. x, 0, sizeX - x, height,
  54203. Justification::centredLeft, 1);
  54204. g.setFont (height * 0.5f);
  54205. g.setColour (Colours::darkgrey);
  54206. if (! isDirectory)
  54207. {
  54208. g.drawFittedText (fileSizeDescription,
  54209. sizeX, 0, dateX - sizeX - 8, height,
  54210. Justification::centredRight, 1);
  54211. g.drawFittedText (fileTimeDescription,
  54212. dateX, 0, width - 8 - dateX, height,
  54213. Justification::centredRight, 1);
  54214. }
  54215. }
  54216. else
  54217. {
  54218. g.drawFittedText (filename,
  54219. x, 0, width - x, height,
  54220. Justification::centredLeft, 1);
  54221. }
  54222. }
  54223. Button* LookAndFeel::createFileBrowserGoUpButton()
  54224. {
  54225. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54226. Path arrowPath;
  54227. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54228. DrawablePath arrowImage;
  54229. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54230. arrowImage.setPath (arrowPath);
  54231. goUpButton->setImages (&arrowImage);
  54232. return goUpButton;
  54233. }
  54234. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54235. DirectoryContentsDisplayComponent* fileListComponent,
  54236. FilePreviewComponent* previewComp,
  54237. ComboBox* currentPathBox,
  54238. TextEditor* filenameBox,
  54239. Button* goUpButton)
  54240. {
  54241. const int x = 8;
  54242. int w = browserComp.getWidth() - x - x;
  54243. if (previewComp != 0)
  54244. {
  54245. const int previewWidth = w / 3;
  54246. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54247. w -= previewWidth + 4;
  54248. }
  54249. int y = 4;
  54250. const int controlsHeight = 22;
  54251. const int bottomSectionHeight = controlsHeight + 8;
  54252. const int upButtonWidth = 50;
  54253. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54254. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54255. y += controlsHeight + 4;
  54256. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54257. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54258. y = listAsComp->getBottom() + 4;
  54259. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54260. }
  54261. // Pulls a drawable out of compressed valuetree data..
  54262. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54263. {
  54264. MemoryInputStream m (data, numBytes, false);
  54265. GZIPDecompressorInputStream gz (m);
  54266. ValueTree drawable (ValueTree::readFromStream (gz));
  54267. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54268. }
  54269. const Drawable* LookAndFeel::getDefaultFolderImage()
  54270. {
  54271. if (folderImage == 0)
  54272. {
  54273. static const unsigned char drawableData[] =
  54274. { 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,
  54275. 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,
  54276. 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,
  54277. 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,
  54278. 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,
  54279. 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,
  54280. 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,
  54281. 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,
  54282. 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,
  54283. 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,
  54284. 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,
  54285. 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,
  54286. 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,
  54287. 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,
  54288. 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 };
  54289. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54290. }
  54291. return folderImage;
  54292. }
  54293. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54294. {
  54295. if (documentImage == 0)
  54296. {
  54297. static const unsigned char drawableData[] =
  54298. { 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,
  54299. 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,
  54300. 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,
  54301. 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,
  54302. 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,
  54303. 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,
  54304. 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,
  54305. 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,
  54306. 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,
  54307. 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,
  54308. 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,
  54309. 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,
  54310. 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,
  54311. 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,
  54312. 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,
  54313. 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,
  54314. 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,
  54315. 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,
  54316. 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,
  54317. 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,
  54318. 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,
  54319. 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,
  54320. 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 };
  54321. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54322. }
  54323. return documentImage;
  54324. }
  54325. void LookAndFeel::playAlertSound()
  54326. {
  54327. PlatformUtilities::beep();
  54328. }
  54329. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54330. {
  54331. g.setColour (Colours::white.withAlpha (0.7f));
  54332. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54333. g.setColour (Colours::black.withAlpha (0.2f));
  54334. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54335. const int totalBlocks = 7;
  54336. const int numBlocks = roundToInt (totalBlocks * level);
  54337. const float w = (width - 6.0f) / (float) totalBlocks;
  54338. for (int i = 0; i < totalBlocks; ++i)
  54339. {
  54340. if (i >= numBlocks)
  54341. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54342. else
  54343. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54344. : Colours::red);
  54345. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54346. }
  54347. }
  54348. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54349. {
  54350. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54351. if (keyDescription.isNotEmpty())
  54352. {
  54353. if (button.isEnabled())
  54354. {
  54355. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54356. g.fillAll (textColour.withAlpha (alpha));
  54357. g.setOpacity (0.3f);
  54358. g.drawBevel (0, 0, width, height, 2);
  54359. }
  54360. g.setColour (textColour);
  54361. g.setFont (height * 0.6f);
  54362. g.drawFittedText (keyDescription,
  54363. 3, 0, width - 6, height,
  54364. Justification::centred, 1);
  54365. }
  54366. else
  54367. {
  54368. const float thickness = 7.0f;
  54369. const float indent = 22.0f;
  54370. Path p;
  54371. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54372. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54373. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54374. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54375. p.setUsingNonZeroWinding (false);
  54376. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54377. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54378. }
  54379. if (button.hasKeyboardFocus (false))
  54380. {
  54381. g.setColour (textColour.withAlpha (0.4f));
  54382. g.drawRect (0, 0, width, height);
  54383. }
  54384. }
  54385. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54386. float x, float y, float w, float h,
  54387. float maxCornerSize,
  54388. const Colour& baseColour,
  54389. const float strokeWidth,
  54390. const bool flatOnLeft,
  54391. const bool flatOnRight,
  54392. const bool flatOnTop,
  54393. const bool flatOnBottom) throw()
  54394. {
  54395. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54396. return;
  54397. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54398. Path outline;
  54399. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54400. ! (flatOnLeft || flatOnTop),
  54401. ! (flatOnRight || flatOnTop),
  54402. ! (flatOnLeft || flatOnBottom),
  54403. ! (flatOnRight || flatOnBottom));
  54404. ColourGradient cg (baseColour, 0.0f, y,
  54405. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54406. false);
  54407. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54408. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54409. g.setGradientFill (cg);
  54410. g.fillPath (outline);
  54411. g.setColour (Colour (0x80000000));
  54412. g.strokePath (outline, PathStrokeType (strokeWidth));
  54413. }
  54414. void LookAndFeel::drawGlassSphere (Graphics& g,
  54415. const float x, const float y,
  54416. const float diameter,
  54417. const Colour& colour,
  54418. const float outlineThickness) throw()
  54419. {
  54420. if (diameter <= outlineThickness)
  54421. return;
  54422. Path p;
  54423. p.addEllipse (x, y, diameter, diameter);
  54424. {
  54425. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54426. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54427. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54428. g.setGradientFill (cg);
  54429. g.fillPath (p);
  54430. }
  54431. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54432. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54433. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54434. ColourGradient cg (Colours::transparentBlack,
  54435. x + diameter * 0.5f, y + diameter * 0.5f,
  54436. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54437. x, y + diameter * 0.5f, true);
  54438. cg.addColour (0.7, Colours::transparentBlack);
  54439. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54440. g.setGradientFill (cg);
  54441. g.fillPath (p);
  54442. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54443. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54444. }
  54445. void LookAndFeel::drawGlassPointer (Graphics& g,
  54446. const float x, const float y,
  54447. const float diameter,
  54448. const Colour& colour, const float outlineThickness,
  54449. const int direction) throw()
  54450. {
  54451. if (diameter <= outlineThickness)
  54452. return;
  54453. Path p;
  54454. p.startNewSubPath (x + diameter * 0.5f, y);
  54455. p.lineTo (x + diameter, y + diameter * 0.6f);
  54456. p.lineTo (x + diameter, y + diameter);
  54457. p.lineTo (x, y + diameter);
  54458. p.lineTo (x, y + diameter * 0.6f);
  54459. p.closeSubPath();
  54460. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54461. {
  54462. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54463. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54464. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54465. g.setGradientFill (cg);
  54466. g.fillPath (p);
  54467. }
  54468. ColourGradient cg (Colours::transparentBlack,
  54469. x + diameter * 0.5f, y + diameter * 0.5f,
  54470. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54471. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54472. cg.addColour (0.5, Colours::transparentBlack);
  54473. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54474. g.setGradientFill (cg);
  54475. g.fillPath (p);
  54476. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54477. g.strokePath (p, PathStrokeType (outlineThickness));
  54478. }
  54479. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54480. const float x, const float y,
  54481. const float width, const float height,
  54482. const Colour& colour,
  54483. const float outlineThickness,
  54484. const float cornerSize,
  54485. const bool flatOnLeft,
  54486. const bool flatOnRight,
  54487. const bool flatOnTop,
  54488. const bool flatOnBottom) throw()
  54489. {
  54490. if (width <= outlineThickness || height <= outlineThickness)
  54491. return;
  54492. const int intX = (int) x;
  54493. const int intY = (int) y;
  54494. const int intW = (int) width;
  54495. const int intH = (int) height;
  54496. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54497. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54498. const int intEdge = (int) edgeBlurRadius;
  54499. Path outline;
  54500. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54501. ! (flatOnLeft || flatOnTop),
  54502. ! (flatOnRight || flatOnTop),
  54503. ! (flatOnLeft || flatOnBottom),
  54504. ! (flatOnRight || flatOnBottom));
  54505. {
  54506. ColourGradient cg (colour.darker (0.2f), 0, y,
  54507. colour.darker (0.2f), 0, y + height, false);
  54508. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54509. cg.addColour (0.4, colour);
  54510. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54511. g.setGradientFill (cg);
  54512. g.fillPath (outline);
  54513. }
  54514. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54515. colour.darker (0.2f), x, y + height * 0.5f, true);
  54516. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54517. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54518. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54519. {
  54520. g.saveState();
  54521. g.setGradientFill (cg);
  54522. g.reduceClipRegion (intX, intY, intEdge, intH);
  54523. g.fillPath (outline);
  54524. g.restoreState();
  54525. }
  54526. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54527. {
  54528. cg.point1.setX (x + width - edgeBlurRadius);
  54529. cg.point2.setX (x + width);
  54530. g.saveState();
  54531. g.setGradientFill (cg);
  54532. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54533. g.fillPath (outline);
  54534. g.restoreState();
  54535. }
  54536. {
  54537. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54538. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54539. Path highlight;
  54540. LookAndFeelHelpers::createRoundedPath (highlight,
  54541. x + leftIndent,
  54542. y + cs * 0.1f,
  54543. width - (leftIndent + rightIndent),
  54544. height * 0.4f, cs * 0.4f,
  54545. ! (flatOnLeft || flatOnTop),
  54546. ! (flatOnRight || flatOnTop),
  54547. ! (flatOnLeft || flatOnBottom),
  54548. ! (flatOnRight || flatOnBottom));
  54549. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54550. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54551. g.fillPath (highlight);
  54552. }
  54553. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54554. g.strokePath (outline, PathStrokeType (outlineThickness));
  54555. }
  54556. END_JUCE_NAMESPACE
  54557. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54558. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54559. BEGIN_JUCE_NAMESPACE
  54560. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54561. {
  54562. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54563. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54564. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54565. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54566. setColour (Slider::thumbColourId, Colours::white);
  54567. setColour (Slider::trackColourId, Colour (0x7f000000));
  54568. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54569. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54570. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54571. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54572. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54573. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54574. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54575. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54576. }
  54577. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54578. {
  54579. }
  54580. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54581. Button& button,
  54582. const Colour& backgroundColour,
  54583. bool isMouseOverButton,
  54584. bool isButtonDown)
  54585. {
  54586. const int width = button.getWidth();
  54587. const int height = button.getHeight();
  54588. const float indent = 2.0f;
  54589. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54590. roundToInt (height * 0.4f));
  54591. Path p;
  54592. p.addRoundedRectangle (indent, indent,
  54593. width - indent * 2.0f,
  54594. height - indent * 2.0f,
  54595. (float) cornerSize);
  54596. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54597. if (isMouseOverButton)
  54598. {
  54599. if (isButtonDown)
  54600. bc = bc.brighter();
  54601. else if (bc.getBrightness() > 0.5f)
  54602. bc = bc.darker (0.1f);
  54603. else
  54604. bc = bc.brighter (0.1f);
  54605. }
  54606. g.setColour (bc);
  54607. g.fillPath (p);
  54608. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54609. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54610. }
  54611. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54612. Component& /*component*/,
  54613. float x, float y, float w, float h,
  54614. const bool ticked,
  54615. const bool isEnabled,
  54616. const bool /*isMouseOverButton*/,
  54617. const bool isButtonDown)
  54618. {
  54619. Path box;
  54620. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54621. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54622. : Colours::lightgrey.withAlpha (0.1f));
  54623. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54624. g.fillPath (box, trans);
  54625. g.setColour (Colours::black.withAlpha (0.6f));
  54626. g.strokePath (box, PathStrokeType (0.9f), trans);
  54627. if (ticked)
  54628. {
  54629. Path tick;
  54630. tick.startNewSubPath (1.5f, 3.0f);
  54631. tick.lineTo (3.0f, 6.0f);
  54632. tick.lineTo (6.0f, 0.0f);
  54633. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54634. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54635. }
  54636. }
  54637. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54638. ToggleButton& button,
  54639. bool isMouseOverButton,
  54640. bool isButtonDown)
  54641. {
  54642. if (button.hasKeyboardFocus (true))
  54643. {
  54644. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54645. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54646. }
  54647. const int tickWidth = jmin (20, button.getHeight() - 4);
  54648. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54649. (float) tickWidth, (float) tickWidth,
  54650. button.getToggleState(),
  54651. button.isEnabled(),
  54652. isMouseOverButton,
  54653. isButtonDown);
  54654. g.setColour (button.findColour (ToggleButton::textColourId));
  54655. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54656. if (! button.isEnabled())
  54657. g.setOpacity (0.5f);
  54658. const int textX = tickWidth + 5;
  54659. g.drawFittedText (button.getButtonText(),
  54660. textX, 4,
  54661. button.getWidth() - textX - 2, button.getHeight() - 8,
  54662. Justification::centredLeft, 10);
  54663. }
  54664. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54665. int width, int height,
  54666. double progress, const String& textToShow)
  54667. {
  54668. if (progress < 0 || progress >= 1.0)
  54669. {
  54670. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54671. }
  54672. else
  54673. {
  54674. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54675. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54676. g.fillAll (background);
  54677. g.setColour (foreground);
  54678. g.fillRect (1, 1,
  54679. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54680. height - 2);
  54681. if (textToShow.isNotEmpty())
  54682. {
  54683. g.setColour (Colour::contrasting (background, foreground));
  54684. g.setFont (height * 0.6f);
  54685. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54686. }
  54687. }
  54688. }
  54689. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54690. ScrollBar& bar,
  54691. int width, int height,
  54692. int buttonDirection,
  54693. bool isScrollbarVertical,
  54694. bool isMouseOverButton,
  54695. bool isButtonDown)
  54696. {
  54697. if (isScrollbarVertical)
  54698. width -= 2;
  54699. else
  54700. height -= 2;
  54701. Path p;
  54702. if (buttonDirection == 0)
  54703. p.addTriangle (width * 0.5f, height * 0.2f,
  54704. width * 0.1f, height * 0.7f,
  54705. width * 0.9f, height * 0.7f);
  54706. else if (buttonDirection == 1)
  54707. p.addTriangle (width * 0.8f, height * 0.5f,
  54708. width * 0.3f, height * 0.1f,
  54709. width * 0.3f, height * 0.9f);
  54710. else if (buttonDirection == 2)
  54711. p.addTriangle (width * 0.5f, height * 0.8f,
  54712. width * 0.1f, height * 0.3f,
  54713. width * 0.9f, height * 0.3f);
  54714. else if (buttonDirection == 3)
  54715. p.addTriangle (width * 0.2f, height * 0.5f,
  54716. width * 0.7f, height * 0.1f,
  54717. width * 0.7f, height * 0.9f);
  54718. if (isButtonDown)
  54719. g.setColour (Colours::white);
  54720. else if (isMouseOverButton)
  54721. g.setColour (Colours::white.withAlpha (0.7f));
  54722. else
  54723. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54724. g.fillPath (p);
  54725. g.setColour (Colours::black.withAlpha (0.5f));
  54726. g.strokePath (p, PathStrokeType (0.5f));
  54727. }
  54728. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54729. ScrollBar& bar,
  54730. int x, int y,
  54731. int width, int height,
  54732. bool isScrollbarVertical,
  54733. int thumbStartPosition,
  54734. int thumbSize,
  54735. bool isMouseOver,
  54736. bool isMouseDown)
  54737. {
  54738. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54739. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54740. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54741. if (thumbSize > 0.0f)
  54742. {
  54743. Rectangle<int> thumb;
  54744. if (isScrollbarVertical)
  54745. {
  54746. width -= 2;
  54747. g.fillRect (x + roundToInt (width * 0.35f), y,
  54748. roundToInt (width * 0.3f), height);
  54749. thumb.setBounds (x + 1, thumbStartPosition,
  54750. width - 2, thumbSize);
  54751. }
  54752. else
  54753. {
  54754. height -= 2;
  54755. g.fillRect (x, y + roundToInt (height * 0.35f),
  54756. width, roundToInt (height * 0.3f));
  54757. thumb.setBounds (thumbStartPosition, y + 1,
  54758. thumbSize, height - 2);
  54759. }
  54760. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54761. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54762. g.fillRect (thumb);
  54763. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54764. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54765. if (thumbSize > 16)
  54766. {
  54767. for (int i = 3; --i >= 0;)
  54768. {
  54769. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54770. g.setColour (Colours::black.withAlpha (0.15f));
  54771. if (isScrollbarVertical)
  54772. {
  54773. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54774. g.setColour (Colours::white.withAlpha (0.15f));
  54775. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54776. }
  54777. else
  54778. {
  54779. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54780. g.setColour (Colours::white.withAlpha (0.15f));
  54781. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54782. }
  54783. }
  54784. }
  54785. }
  54786. }
  54787. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54788. {
  54789. return &scrollbarShadow;
  54790. }
  54791. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54792. {
  54793. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54794. g.setColour (Colours::black.withAlpha (0.6f));
  54795. g.drawRect (0, 0, width, height);
  54796. }
  54797. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54798. bool, MenuBarComponent& menuBar)
  54799. {
  54800. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54801. }
  54802. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54803. {
  54804. if (textEditor.isEnabled())
  54805. {
  54806. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54807. g.drawRect (0, 0, width, height);
  54808. }
  54809. }
  54810. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54811. const bool isButtonDown,
  54812. int buttonX, int buttonY,
  54813. int buttonW, int buttonH,
  54814. ComboBox& box)
  54815. {
  54816. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54817. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54818. : ComboBox::backgroundColourId));
  54819. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54820. g.setColour (box.findColour (ComboBox::outlineColourId));
  54821. g.drawRect (0, 0, width, height);
  54822. const float arrowX = 0.2f;
  54823. const float arrowH = 0.3f;
  54824. if (box.isEnabled())
  54825. {
  54826. Path p;
  54827. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54828. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54829. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54830. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54831. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54832. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54833. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54834. : ComboBox::buttonColourId));
  54835. g.fillPath (p);
  54836. }
  54837. }
  54838. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54839. {
  54840. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54841. f.setHorizontalScale (0.9f);
  54842. return f;
  54843. }
  54844. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54845. {
  54846. Path p;
  54847. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54848. g.setColour (fill);
  54849. g.fillPath (p);
  54850. g.setColour (outline);
  54851. g.strokePath (p, PathStrokeType (0.3f));
  54852. }
  54853. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54854. int x, int y,
  54855. int w, int h,
  54856. float sliderPos,
  54857. float minSliderPos,
  54858. float maxSliderPos,
  54859. const Slider::SliderStyle style,
  54860. Slider& slider)
  54861. {
  54862. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54863. if (style == Slider::LinearBar)
  54864. {
  54865. g.setColour (slider.findColour (Slider::thumbColourId));
  54866. g.fillRect (x, y, (int) sliderPos - x, h);
  54867. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54868. g.drawRect (x, y, (int) sliderPos - x, h);
  54869. }
  54870. else
  54871. {
  54872. g.setColour (slider.findColour (Slider::trackColourId)
  54873. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54874. if (slider.isHorizontal())
  54875. {
  54876. g.fillRect (x, y + roundToInt (h * 0.6f),
  54877. w, roundToInt (h * 0.2f));
  54878. }
  54879. else
  54880. {
  54881. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54882. jmin (4, roundToInt (w * 0.2f)), h);
  54883. }
  54884. float alpha = 0.35f;
  54885. if (slider.isEnabled())
  54886. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54887. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54888. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54889. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54890. {
  54891. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54892. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54893. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54894. fill, outline);
  54895. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54896. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54897. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54898. fill, outline);
  54899. }
  54900. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54901. {
  54902. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54903. minSliderPos - 7.0f, y + h * 0.9f ,
  54904. minSliderPos, y + h * 0.9f,
  54905. fill, outline);
  54906. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54907. maxSliderPos, y + h * 0.9f,
  54908. maxSliderPos + 7.0f, y + h * 0.9f,
  54909. fill, outline);
  54910. }
  54911. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54912. {
  54913. drawTriangle (g, sliderPos, y + h * 0.9f,
  54914. sliderPos - 7.0f, y + h * 0.2f,
  54915. sliderPos + 7.0f, y + h * 0.2f,
  54916. fill, outline);
  54917. }
  54918. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54919. {
  54920. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54921. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54922. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54923. fill, outline);
  54924. }
  54925. }
  54926. }
  54927. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54928. {
  54929. if (isIncrement)
  54930. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54931. else
  54932. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54933. }
  54934. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54935. {
  54936. return &scrollbarShadow;
  54937. }
  54938. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54939. {
  54940. return 8;
  54941. }
  54942. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54943. int w, int h,
  54944. bool isMouseOver,
  54945. bool isMouseDragging)
  54946. {
  54947. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54948. : Colours::darkgrey);
  54949. const float lineThickness = jmin (w, h) * 0.1f;
  54950. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54951. {
  54952. g.drawLine (w * i,
  54953. h + 1.0f,
  54954. w + 1.0f,
  54955. h * i,
  54956. lineThickness);
  54957. }
  54958. }
  54959. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54960. {
  54961. Path shape;
  54962. if (buttonType == DocumentWindow::closeButton)
  54963. {
  54964. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54965. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54966. ShapeButton* const b = new ShapeButton ("close",
  54967. Colour (0x7fff3333),
  54968. Colour (0xd7ff3333),
  54969. Colour (0xf7ff3333));
  54970. b->setShape (shape, true, true, true);
  54971. return b;
  54972. }
  54973. else if (buttonType == DocumentWindow::minimiseButton)
  54974. {
  54975. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54976. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54977. DrawablePath dp;
  54978. dp.setPath (shape);
  54979. dp.setFill (Colours::black.withAlpha (0.3f));
  54980. b->setImages (&dp);
  54981. return b;
  54982. }
  54983. else if (buttonType == DocumentWindow::maximiseButton)
  54984. {
  54985. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54986. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54987. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54988. DrawablePath dp;
  54989. dp.setPath (shape);
  54990. dp.setFill (Colours::black.withAlpha (0.3f));
  54991. b->setImages (&dp);
  54992. return b;
  54993. }
  54994. jassertfalse;
  54995. return 0;
  54996. }
  54997. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54998. int titleBarX,
  54999. int titleBarY,
  55000. int titleBarW,
  55001. int titleBarH,
  55002. Button* minimiseButton,
  55003. Button* maximiseButton,
  55004. Button* closeButton,
  55005. bool positionTitleBarButtonsOnLeft)
  55006. {
  55007. titleBarY += titleBarH / 8;
  55008. titleBarH -= titleBarH / 4;
  55009. const int buttonW = titleBarH;
  55010. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55011. : titleBarX + titleBarW - buttonW - 4;
  55012. if (closeButton != 0)
  55013. {
  55014. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55015. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55016. : -(buttonW + buttonW / 5);
  55017. }
  55018. if (positionTitleBarButtonsOnLeft)
  55019. swapVariables (minimiseButton, maximiseButton);
  55020. if (maximiseButton != 0)
  55021. {
  55022. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55023. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55024. }
  55025. if (minimiseButton != 0)
  55026. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55027. }
  55028. END_JUCE_NAMESPACE
  55029. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55030. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55031. BEGIN_JUCE_NAMESPACE
  55032. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55033. : model (0),
  55034. itemUnderMouse (-1),
  55035. currentPopupIndex (-1),
  55036. topLevelIndexClicked (0),
  55037. lastMouseX (0),
  55038. lastMouseY (0)
  55039. {
  55040. setRepaintsOnMouseActivity (true);
  55041. setWantsKeyboardFocus (false);
  55042. setMouseClickGrabsKeyboardFocus (false);
  55043. setModel (model_);
  55044. }
  55045. MenuBarComponent::~MenuBarComponent()
  55046. {
  55047. setModel (0);
  55048. Desktop::getInstance().removeGlobalMouseListener (this);
  55049. }
  55050. MenuBarModel* MenuBarComponent::getModel() const throw()
  55051. {
  55052. return model;
  55053. }
  55054. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55055. {
  55056. if (model != newModel)
  55057. {
  55058. if (model != 0)
  55059. model->removeListener (this);
  55060. model = newModel;
  55061. if (model != 0)
  55062. model->addListener (this);
  55063. repaint();
  55064. menuBarItemsChanged (0);
  55065. }
  55066. }
  55067. void MenuBarComponent::paint (Graphics& g)
  55068. {
  55069. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55070. getLookAndFeel().drawMenuBarBackground (g,
  55071. getWidth(),
  55072. getHeight(),
  55073. isMouseOverBar,
  55074. *this);
  55075. if (model != 0)
  55076. {
  55077. for (int i = 0; i < menuNames.size(); ++i)
  55078. {
  55079. g.saveState();
  55080. g.setOrigin (xPositions [i], 0);
  55081. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55082. getLookAndFeel().drawMenuBarItem (g,
  55083. xPositions[i + 1] - xPositions[i],
  55084. getHeight(),
  55085. i,
  55086. menuNames[i],
  55087. i == itemUnderMouse,
  55088. i == currentPopupIndex,
  55089. isMouseOverBar,
  55090. *this);
  55091. g.restoreState();
  55092. }
  55093. }
  55094. }
  55095. void MenuBarComponent::resized()
  55096. {
  55097. xPositions.clear();
  55098. int x = 0;
  55099. xPositions.add (x);
  55100. for (int i = 0; i < menuNames.size(); ++i)
  55101. {
  55102. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55103. xPositions.add (x);
  55104. }
  55105. }
  55106. int MenuBarComponent::getItemAt (const int x, const int y)
  55107. {
  55108. for (int i = 0; i < xPositions.size(); ++i)
  55109. if (x >= xPositions[i] && x < xPositions[i + 1])
  55110. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55111. return -1;
  55112. }
  55113. void MenuBarComponent::repaintMenuItem (int index)
  55114. {
  55115. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55116. {
  55117. const int x1 = xPositions [index];
  55118. const int x2 = xPositions [index + 1];
  55119. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55120. }
  55121. }
  55122. void MenuBarComponent::setItemUnderMouse (const int index)
  55123. {
  55124. if (itemUnderMouse != index)
  55125. {
  55126. repaintMenuItem (itemUnderMouse);
  55127. itemUnderMouse = index;
  55128. repaintMenuItem (itemUnderMouse);
  55129. }
  55130. }
  55131. void MenuBarComponent::setOpenItem (int index)
  55132. {
  55133. if (currentPopupIndex != index)
  55134. {
  55135. repaintMenuItem (currentPopupIndex);
  55136. currentPopupIndex = index;
  55137. repaintMenuItem (currentPopupIndex);
  55138. if (index >= 0)
  55139. Desktop::getInstance().addGlobalMouseListener (this);
  55140. else
  55141. Desktop::getInstance().removeGlobalMouseListener (this);
  55142. }
  55143. }
  55144. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55145. {
  55146. setItemUnderMouse (getItemAt (x, y));
  55147. }
  55148. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55149. {
  55150. public:
  55151. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55152. : bar (bar_), topLevelIndex (topLevelIndex_)
  55153. {
  55154. }
  55155. void modalStateFinished (int returnValue)
  55156. {
  55157. if (bar != 0)
  55158. bar->menuDismissed (topLevelIndex, returnValue);
  55159. }
  55160. private:
  55161. Component::SafePointer<MenuBarComponent> bar;
  55162. const int topLevelIndex;
  55163. JUCE_DECLARE_NON_COPYABLE (AsyncCallback);
  55164. };
  55165. void MenuBarComponent::showMenu (int index)
  55166. {
  55167. if (index != currentPopupIndex)
  55168. {
  55169. PopupMenu::dismissAllActiveMenus();
  55170. menuBarItemsChanged (0);
  55171. setOpenItem (index);
  55172. setItemUnderMouse (index);
  55173. if (index >= 0)
  55174. {
  55175. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55176. menuNames [itemUnderMouse]));
  55177. if (m.lookAndFeel == 0)
  55178. m.setLookAndFeel (&getLookAndFeel());
  55179. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55180. m.showMenu (localAreaToGlobal (itemPos),
  55181. 0, itemPos.getWidth(), 0, 0, this,
  55182. new AsyncCallback (this, index));
  55183. }
  55184. }
  55185. }
  55186. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55187. {
  55188. topLevelIndexClicked = topLevelIndex;
  55189. postCommandMessage (itemId);
  55190. }
  55191. void MenuBarComponent::handleCommandMessage (int commandId)
  55192. {
  55193. const Point<int> mousePos (getMouseXYRelative());
  55194. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55195. if (currentPopupIndex == topLevelIndexClicked)
  55196. setOpenItem (-1);
  55197. if (commandId != 0 && model != 0)
  55198. model->menuItemSelected (commandId, topLevelIndexClicked);
  55199. }
  55200. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55201. {
  55202. if (e.eventComponent == this)
  55203. updateItemUnderMouse (e.x, e.y);
  55204. }
  55205. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55206. {
  55207. if (e.eventComponent == this)
  55208. updateItemUnderMouse (e.x, e.y);
  55209. }
  55210. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55211. {
  55212. if (currentPopupIndex < 0)
  55213. {
  55214. const MouseEvent e2 (e.getEventRelativeTo (this));
  55215. updateItemUnderMouse (e2.x, e2.y);
  55216. currentPopupIndex = -2;
  55217. showMenu (itemUnderMouse);
  55218. }
  55219. }
  55220. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55221. {
  55222. const MouseEvent e2 (e.getEventRelativeTo (this));
  55223. const int item = getItemAt (e2.x, e2.y);
  55224. if (item >= 0)
  55225. showMenu (item);
  55226. }
  55227. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55228. {
  55229. const MouseEvent e2 (e.getEventRelativeTo (this));
  55230. updateItemUnderMouse (e2.x, e2.y);
  55231. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55232. {
  55233. setOpenItem (-1);
  55234. PopupMenu::dismissAllActiveMenus();
  55235. }
  55236. }
  55237. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55238. {
  55239. const MouseEvent e2 (e.getEventRelativeTo (this));
  55240. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55241. {
  55242. if (currentPopupIndex >= 0)
  55243. {
  55244. const int item = getItemAt (e2.x, e2.y);
  55245. if (item >= 0)
  55246. showMenu (item);
  55247. }
  55248. else
  55249. {
  55250. updateItemUnderMouse (e2.x, e2.y);
  55251. }
  55252. lastMouseX = e2.x;
  55253. lastMouseY = e2.y;
  55254. }
  55255. }
  55256. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55257. {
  55258. bool used = false;
  55259. const int numMenus = menuNames.size();
  55260. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55261. if (key.isKeyCode (KeyPress::leftKey))
  55262. {
  55263. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55264. used = true;
  55265. }
  55266. else if (key.isKeyCode (KeyPress::rightKey))
  55267. {
  55268. showMenu ((currentIndex + 1) % numMenus);
  55269. used = true;
  55270. }
  55271. return used;
  55272. }
  55273. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55274. {
  55275. StringArray newNames;
  55276. if (model != 0)
  55277. newNames = model->getMenuBarNames();
  55278. if (newNames != menuNames)
  55279. {
  55280. menuNames = newNames;
  55281. repaint();
  55282. resized();
  55283. }
  55284. }
  55285. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55286. const ApplicationCommandTarget::InvocationInfo& info)
  55287. {
  55288. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55289. return;
  55290. for (int i = 0; i < menuNames.size(); ++i)
  55291. {
  55292. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55293. if (menu.containsCommandItem (info.commandID))
  55294. {
  55295. setItemUnderMouse (i);
  55296. startTimer (200);
  55297. break;
  55298. }
  55299. }
  55300. }
  55301. void MenuBarComponent::timerCallback()
  55302. {
  55303. stopTimer();
  55304. const Point<int> mousePos (getMouseXYRelative());
  55305. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55306. }
  55307. END_JUCE_NAMESPACE
  55308. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55309. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55310. BEGIN_JUCE_NAMESPACE
  55311. MenuBarModel::MenuBarModel() throw()
  55312. : manager (0)
  55313. {
  55314. }
  55315. MenuBarModel::~MenuBarModel()
  55316. {
  55317. setApplicationCommandManagerToWatch (0);
  55318. }
  55319. void MenuBarModel::menuItemsChanged()
  55320. {
  55321. triggerAsyncUpdate();
  55322. }
  55323. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55324. {
  55325. if (manager != newManager)
  55326. {
  55327. if (manager != 0)
  55328. manager->removeListener (this);
  55329. manager = newManager;
  55330. if (manager != 0)
  55331. manager->addListener (this);
  55332. }
  55333. }
  55334. void MenuBarModel::addListener (Listener* const newListener) throw()
  55335. {
  55336. listeners.add (newListener);
  55337. }
  55338. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55339. {
  55340. // Trying to remove a listener that isn't on the list!
  55341. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55342. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55343. jassert (listeners.contains (listenerToRemove));
  55344. listeners.remove (listenerToRemove);
  55345. }
  55346. void MenuBarModel::handleAsyncUpdate()
  55347. {
  55348. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55349. }
  55350. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55351. {
  55352. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55353. }
  55354. void MenuBarModel::applicationCommandListChanged()
  55355. {
  55356. menuItemsChanged();
  55357. }
  55358. END_JUCE_NAMESPACE
  55359. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55360. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55361. BEGIN_JUCE_NAMESPACE
  55362. class PopupMenu::Item
  55363. {
  55364. public:
  55365. Item()
  55366. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55367. usesColour (false), customComp (0), commandManager (0)
  55368. {
  55369. }
  55370. Item (const int itemId_,
  55371. const String& text_,
  55372. const bool active_,
  55373. const bool isTicked_,
  55374. const Image& im,
  55375. const Colour& textColour_,
  55376. const bool usesColour_,
  55377. PopupMenuCustomComponent* const customComp_,
  55378. const PopupMenu* const subMenu_,
  55379. ApplicationCommandManager* const commandManager_)
  55380. : itemId (itemId_), text (text_), textColour (textColour_),
  55381. active (active_), isSeparator (false), isTicked (isTicked_),
  55382. usesColour (usesColour_), image (im), customComp (customComp_),
  55383. commandManager (commandManager_)
  55384. {
  55385. if (subMenu_ != 0)
  55386. subMenu = new PopupMenu (*subMenu_);
  55387. if (commandManager_ != 0 && itemId_ != 0)
  55388. {
  55389. String shortcutKey;
  55390. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55391. ->getKeyPressesAssignedToCommand (itemId_));
  55392. for (int i = 0; i < keyPresses.size(); ++i)
  55393. {
  55394. const String key (keyPresses.getReference(i).getTextDescription());
  55395. if (shortcutKey.isNotEmpty())
  55396. shortcutKey << ", ";
  55397. if (key.length() == 1)
  55398. shortcutKey << "shortcut: '" << key << '\'';
  55399. else
  55400. shortcutKey << key;
  55401. }
  55402. shortcutKey = shortcutKey.trim();
  55403. if (shortcutKey.isNotEmpty())
  55404. text << "<end>" << shortcutKey;
  55405. }
  55406. }
  55407. Item (const Item& other)
  55408. : itemId (other.itemId),
  55409. text (other.text),
  55410. textColour (other.textColour),
  55411. active (other.active),
  55412. isSeparator (other.isSeparator),
  55413. isTicked (other.isTicked),
  55414. usesColour (other.usesColour),
  55415. image (other.image),
  55416. customComp (other.customComp),
  55417. commandManager (other.commandManager)
  55418. {
  55419. if (other.subMenu != 0)
  55420. subMenu = new PopupMenu (*(other.subMenu));
  55421. }
  55422. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55423. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55424. const int itemId;
  55425. String text;
  55426. const Colour textColour;
  55427. const bool active, isSeparator, isTicked, usesColour;
  55428. Image image;
  55429. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55430. ScopedPointer <PopupMenu> subMenu;
  55431. ApplicationCommandManager* const commandManager;
  55432. private:
  55433. Item& operator= (const Item&);
  55434. JUCE_LEAK_DETECTOR (Item);
  55435. };
  55436. class PopupMenu::ItemComponent : public Component
  55437. {
  55438. public:
  55439. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight)
  55440. : itemInfo (itemInfo_),
  55441. isHighlighted (false)
  55442. {
  55443. if (itemInfo.customComp != 0)
  55444. addAndMakeVisible (itemInfo.customComp);
  55445. int itemW = 80;
  55446. int itemH = 16;
  55447. getIdealSize (itemW, itemH, standardItemHeight);
  55448. setSize (itemW, jlimit (2, 600, itemH));
  55449. }
  55450. ~ItemComponent()
  55451. {
  55452. if (itemInfo.customComp != 0)
  55453. removeChildComponent (itemInfo.customComp);
  55454. }
  55455. void getIdealSize (int& idealWidth,
  55456. int& idealHeight,
  55457. const int standardItemHeight)
  55458. {
  55459. if (itemInfo.customComp != 0)
  55460. {
  55461. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55462. }
  55463. else
  55464. {
  55465. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55466. itemInfo.isSeparator,
  55467. standardItemHeight,
  55468. idealWidth,
  55469. idealHeight);
  55470. }
  55471. }
  55472. void paint (Graphics& g)
  55473. {
  55474. if (itemInfo.customComp == 0)
  55475. {
  55476. String mainText (itemInfo.text);
  55477. String endText;
  55478. const int endIndex = mainText.indexOf ("<end>");
  55479. if (endIndex >= 0)
  55480. {
  55481. endText = mainText.substring (endIndex + 5).trim();
  55482. mainText = mainText.substring (0, endIndex);
  55483. }
  55484. getLookAndFeel()
  55485. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55486. itemInfo.isSeparator,
  55487. itemInfo.active,
  55488. isHighlighted,
  55489. itemInfo.isTicked,
  55490. itemInfo.subMenu != 0,
  55491. mainText, endText,
  55492. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55493. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55494. }
  55495. }
  55496. void resized()
  55497. {
  55498. if (getNumChildComponents() > 0)
  55499. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55500. }
  55501. void setHighlighted (bool shouldBeHighlighted)
  55502. {
  55503. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55504. if (isHighlighted != shouldBeHighlighted)
  55505. {
  55506. isHighlighted = shouldBeHighlighted;
  55507. if (itemInfo.customComp != 0)
  55508. {
  55509. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55510. itemInfo.customComp->repaint();
  55511. }
  55512. repaint();
  55513. }
  55514. }
  55515. PopupMenu::Item itemInfo;
  55516. private:
  55517. bool isHighlighted;
  55518. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55519. };
  55520. namespace PopupMenuSettings
  55521. {
  55522. const int scrollZone = 24;
  55523. const int borderSize = 2;
  55524. const int timerInterval = 50;
  55525. const int dismissCommandId = 0x6287345f;
  55526. }
  55527. class PopupMenu::Window : public Component,
  55528. private Timer
  55529. {
  55530. public:
  55531. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55532. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55533. const int minimumWidth_, const int maximumNumColumns_,
  55534. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55535. ApplicationCommandManager** const managerOfChosenCommand_,
  55536. Component* const componentAttachedTo_)
  55537. : Component ("menu"),
  55538. owner (owner_),
  55539. activeSubMenu (0),
  55540. managerOfChosenCommand (managerOfChosenCommand_),
  55541. componentAttachedTo (componentAttachedTo_),
  55542. componentAttachedToOriginal (componentAttachedTo_),
  55543. minimumWidth (minimumWidth_),
  55544. maximumNumColumns (maximumNumColumns_),
  55545. standardItemHeight (standardItemHeight_),
  55546. isOver (false),
  55547. hasBeenOver (false),
  55548. isDown (false),
  55549. needsToScroll (false),
  55550. dismissOnMouseUp (dismissOnMouseUp_),
  55551. hideOnExit (false),
  55552. disableMouseMoves (false),
  55553. hasAnyJuceCompHadFocus (false),
  55554. numColumns (0),
  55555. contentHeight (0),
  55556. childYOffset (0),
  55557. menuCreationTime (Time::getMillisecondCounter()),
  55558. timeEnteredCurrentChildComp (0),
  55559. scrollAcceleration (1.0)
  55560. {
  55561. lastFocused = lastScroll = menuCreationTime;
  55562. setWantsKeyboardFocus (false);
  55563. setMouseClickGrabsKeyboardFocus (false);
  55564. setAlwaysOnTop (true);
  55565. setLookAndFeel (menu.lookAndFeel);
  55566. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55567. for (int i = 0; i < menu.items.size(); ++i)
  55568. {
  55569. PopupMenu::ItemComponent* const itemComp = new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight);
  55570. items.add (itemComp);
  55571. addAndMakeVisible (itemComp);
  55572. itemComp->addMouseListener (this, false);
  55573. }
  55574. calculateWindowPos (target, alignToRectangle);
  55575. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55576. updateYPositions();
  55577. if (itemIdThatMustBeVisible != 0)
  55578. {
  55579. const int y = target.getY() - windowPos.getY();
  55580. ensureItemIsVisible (itemIdThatMustBeVisible,
  55581. (((unsigned int) y) < (unsigned int) windowPos.getHeight()) ? y : -1);
  55582. }
  55583. resizeToBestWindowPos();
  55584. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55585. getActiveWindows().add (this);
  55586. Desktop::getInstance().addGlobalMouseListener (this);
  55587. }
  55588. ~Window()
  55589. {
  55590. getActiveWindows().removeValue (this);
  55591. Desktop::getInstance().removeGlobalMouseListener (this);
  55592. activeSubMenu = 0;
  55593. items.clear();
  55594. }
  55595. static Window* create (const PopupMenu& menu,
  55596. bool dismissOnMouseUp,
  55597. Window* const owner_,
  55598. const Rectangle<int>& target,
  55599. int minimumWidth,
  55600. int maximumNumColumns,
  55601. int standardItemHeight,
  55602. bool alignToRectangle,
  55603. int itemIdThatMustBeVisible,
  55604. ApplicationCommandManager** managerOfChosenCommand,
  55605. Component* componentAttachedTo)
  55606. {
  55607. if (menu.items.size() > 0)
  55608. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55609. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55610. managerOfChosenCommand, componentAttachedTo);
  55611. return 0;
  55612. }
  55613. void paint (Graphics& g)
  55614. {
  55615. if (isOpaque())
  55616. g.fillAll (Colours::white);
  55617. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55618. }
  55619. void paintOverChildren (Graphics& g)
  55620. {
  55621. if (isScrolling())
  55622. {
  55623. LookAndFeel& lf = getLookAndFeel();
  55624. if (isScrollZoneActive (false))
  55625. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55626. if (isScrollZoneActive (true))
  55627. {
  55628. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55629. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55630. }
  55631. }
  55632. }
  55633. bool isScrollZoneActive (bool bottomOne) const
  55634. {
  55635. return isScrolling()
  55636. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55637. : childYOffset > 0);
  55638. }
  55639. // hide this and all sub-comps
  55640. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55641. {
  55642. if (isVisible())
  55643. {
  55644. activeSubMenu = 0;
  55645. currentChild = 0;
  55646. exitModalState (item != 0 ? item->itemId : 0);
  55647. if (makeInvisible)
  55648. setVisible (false);
  55649. if (item != 0
  55650. && item->commandManager != 0
  55651. && item->itemId != 0)
  55652. {
  55653. *managerOfChosenCommand = item->commandManager;
  55654. }
  55655. }
  55656. }
  55657. void dismissMenu (const PopupMenu::Item* const item)
  55658. {
  55659. if (owner != 0)
  55660. {
  55661. owner->dismissMenu (item);
  55662. }
  55663. else
  55664. {
  55665. if (item != 0)
  55666. {
  55667. // need a copy of this on the stack as the one passed in will get deleted during this call
  55668. const PopupMenu::Item mi (*item);
  55669. hide (&mi, false);
  55670. }
  55671. else
  55672. {
  55673. hide (0, false);
  55674. }
  55675. }
  55676. }
  55677. void mouseMove (const MouseEvent&) { timerCallback(); }
  55678. void mouseDown (const MouseEvent&) { timerCallback(); }
  55679. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55680. void mouseUp (const MouseEvent&) { timerCallback(); }
  55681. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55682. {
  55683. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55684. lastMouse = Point<int> (-1, -1);
  55685. }
  55686. bool keyPressed (const KeyPress& key)
  55687. {
  55688. if (key.isKeyCode (KeyPress::downKey))
  55689. {
  55690. selectNextItem (1);
  55691. }
  55692. else if (key.isKeyCode (KeyPress::upKey))
  55693. {
  55694. selectNextItem (-1);
  55695. }
  55696. else if (key.isKeyCode (KeyPress::leftKey))
  55697. {
  55698. if (owner != 0)
  55699. {
  55700. Component::SafePointer<Window> parentWindow (owner);
  55701. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55702. hide (0, true);
  55703. if (parentWindow != 0)
  55704. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55705. disableTimerUntilMouseMoves();
  55706. }
  55707. else if (componentAttachedTo != 0)
  55708. {
  55709. componentAttachedTo->keyPressed (key);
  55710. }
  55711. }
  55712. else if (key.isKeyCode (KeyPress::rightKey))
  55713. {
  55714. disableTimerUntilMouseMoves();
  55715. if (showSubMenuFor (currentChild))
  55716. {
  55717. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55718. activeSubMenu->selectNextItem (1);
  55719. }
  55720. else if (componentAttachedTo != 0)
  55721. {
  55722. componentAttachedTo->keyPressed (key);
  55723. }
  55724. }
  55725. else if (key.isKeyCode (KeyPress::returnKey))
  55726. {
  55727. triggerCurrentlyHighlightedItem();
  55728. }
  55729. else if (key.isKeyCode (KeyPress::escapeKey))
  55730. {
  55731. dismissMenu (0);
  55732. }
  55733. else
  55734. {
  55735. return false;
  55736. }
  55737. return true;
  55738. }
  55739. void inputAttemptWhenModal()
  55740. {
  55741. Component::SafePointer<Component> deletionChecker (this);
  55742. timerCallback();
  55743. if (deletionChecker != 0 && ! isOverAnyMenu())
  55744. {
  55745. if (componentAttachedTo != 0)
  55746. {
  55747. // we want to dismiss the menu, but if we do it synchronously, then
  55748. // the mouse-click will be allowed to pass through. That's good, except
  55749. // when the user clicks on the button that orginally popped the menu up,
  55750. // as they'll expect the menu to go away, and in fact it'll just
  55751. // come back. So only dismiss synchronously if they're not on the original
  55752. // comp that we're attached to.
  55753. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55754. if (componentAttachedTo->reallyContains (mousePos, true))
  55755. {
  55756. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55757. return;
  55758. }
  55759. }
  55760. dismissMenu (0);
  55761. }
  55762. }
  55763. void handleCommandMessage (int commandId)
  55764. {
  55765. Component::handleCommandMessage (commandId);
  55766. if (commandId == PopupMenuSettings::dismissCommandId)
  55767. dismissMenu (0);
  55768. }
  55769. void timerCallback()
  55770. {
  55771. if (! isVisible())
  55772. return;
  55773. if (componentAttachedTo != componentAttachedToOriginal)
  55774. {
  55775. dismissMenu (0);
  55776. return;
  55777. }
  55778. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55779. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55780. return;
  55781. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55782. // move rather than a real timer callback
  55783. const Point<int> globalMousePos (Desktop::getMousePosition());
  55784. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  55785. const uint32 now = Time::getMillisecondCounter();
  55786. if (now > timeEnteredCurrentChildComp + 100
  55787. && reallyContains (localMousePos, true)
  55788. && currentChild != 0
  55789. && (! disableMouseMoves)
  55790. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55791. {
  55792. showSubMenuFor (currentChild);
  55793. }
  55794. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55795. {
  55796. highlightItemUnderMouse (globalMousePos, localMousePos);
  55797. }
  55798. bool overScrollArea = false;
  55799. if (isScrolling()
  55800. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55801. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55802. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55803. {
  55804. if (now > lastScroll + 20)
  55805. {
  55806. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55807. int amount = 0;
  55808. for (int i = 0; i < items.size() && amount == 0; ++i)
  55809. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  55810. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55811. lastScroll = now;
  55812. }
  55813. overScrollArea = true;
  55814. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55815. }
  55816. else
  55817. {
  55818. scrollAcceleration = 1.0;
  55819. }
  55820. const bool wasDown = isDown;
  55821. bool isOverAny = isOverAnyMenu();
  55822. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55823. {
  55824. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55825. isOverAny = isOverAnyMenu();
  55826. }
  55827. if (hideOnExit && hasBeenOver && ! isOverAny)
  55828. {
  55829. hide (0, true);
  55830. }
  55831. else
  55832. {
  55833. isDown = hasBeenOver
  55834. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55835. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55836. bool anyFocused = Process::isForegroundProcess();
  55837. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55838. {
  55839. // because no component at all may have focus, our test here will
  55840. // only be triggered when something has focus and then loses it.
  55841. anyFocused = ! hasAnyJuceCompHadFocus;
  55842. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55843. {
  55844. if (ComponentPeer::getPeer (i)->isFocused())
  55845. {
  55846. anyFocused = true;
  55847. hasAnyJuceCompHadFocus = true;
  55848. break;
  55849. }
  55850. }
  55851. }
  55852. if (! anyFocused)
  55853. {
  55854. if (now > lastFocused + 10)
  55855. {
  55856. wasHiddenBecauseOfAppChange() = true;
  55857. dismissMenu (0);
  55858. return; // may have been deleted by the previous call..
  55859. }
  55860. }
  55861. else if (wasDown && now > menuCreationTime + 250
  55862. && ! (isDown || overScrollArea))
  55863. {
  55864. isOver = reallyContains (localMousePos, true);
  55865. if (isOver)
  55866. {
  55867. triggerCurrentlyHighlightedItem();
  55868. }
  55869. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55870. {
  55871. dismissMenu (0);
  55872. }
  55873. return; // may have been deleted by the previous calls..
  55874. }
  55875. else
  55876. {
  55877. lastFocused = now;
  55878. }
  55879. }
  55880. }
  55881. static Array<Window*>& getActiveWindows()
  55882. {
  55883. static Array<Window*> activeMenuWindows;
  55884. return activeMenuWindows;
  55885. }
  55886. static bool& wasHiddenBecauseOfAppChange() throw()
  55887. {
  55888. static bool b = false;
  55889. return b;
  55890. }
  55891. private:
  55892. Window* owner;
  55893. OwnedArray <PopupMenu::ItemComponent> items;
  55894. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  55895. ScopedPointer <Window> activeSubMenu;
  55896. ApplicationCommandManager** managerOfChosenCommand;
  55897. Component::SafePointer<Component> componentAttachedTo;
  55898. Component* componentAttachedToOriginal;
  55899. Rectangle<int> windowPos;
  55900. Point<int> lastMouse;
  55901. int minimumWidth, maximumNumColumns, standardItemHeight;
  55902. bool isOver, hasBeenOver, isDown, needsToScroll;
  55903. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55904. int numColumns, contentHeight, childYOffset;
  55905. Array <int> columnWidths;
  55906. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55907. double scrollAcceleration;
  55908. bool overlaps (const Rectangle<int>& r) const
  55909. {
  55910. return r.intersects (getBounds())
  55911. || (owner != 0 && owner->overlaps (r));
  55912. }
  55913. bool isOverAnyMenu() const
  55914. {
  55915. return (owner != 0) ? owner->isOverAnyMenu()
  55916. : isOverChildren();
  55917. }
  55918. bool isOverChildren() const
  55919. {
  55920. return isVisible()
  55921. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55922. }
  55923. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55924. {
  55925. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  55926. isOver = reallyContains (relPos, true);
  55927. if (activeSubMenu != 0)
  55928. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55929. }
  55930. bool treeContains (const Window* const window) const throw()
  55931. {
  55932. const Window* mw = this;
  55933. while (mw->owner != 0)
  55934. mw = mw->owner;
  55935. while (mw != 0)
  55936. {
  55937. if (mw == window)
  55938. return true;
  55939. mw = mw->activeSubMenu;
  55940. }
  55941. return false;
  55942. }
  55943. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  55944. {
  55945. const Rectangle<int> mon (Desktop::getInstance()
  55946. .getMonitorAreaContaining (target.getCentre(),
  55947. #if JUCE_MAC
  55948. true));
  55949. #else
  55950. false)); // on windows, don't stop the menu overlapping the taskbar
  55951. #endif
  55952. int x, y, widthToUse, heightToUse;
  55953. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55954. if (alignToRectangle)
  55955. {
  55956. x = target.getX();
  55957. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  55958. const int spaceOver = target.getY() - mon.getY();
  55959. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55960. y = target.getBottom();
  55961. else
  55962. y = target.getY() - heightToUse;
  55963. }
  55964. else
  55965. {
  55966. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  55967. if (owner != 0)
  55968. {
  55969. if (owner->owner != 0)
  55970. {
  55971. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55972. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55973. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  55974. tendTowardsRight = true;
  55975. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  55976. tendTowardsRight = false;
  55977. }
  55978. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  55979. {
  55980. tendTowardsRight = true;
  55981. }
  55982. }
  55983. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  55984. target.getX() - mon.getX()) - 32;
  55985. if (biggestSpace < widthToUse)
  55986. {
  55987. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  55988. if (numColumns > 1)
  55989. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55990. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  55991. }
  55992. if (tendTowardsRight)
  55993. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  55994. else
  55995. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  55996. y = target.getY();
  55997. if (target.getCentreY() > mon.getCentreY())
  55998. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  55999. }
  56000. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56001. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56002. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56003. // sets this flag if it's big enough to obscure any of its parent menus
  56004. hideOnExit = (owner != 0)
  56005. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56006. }
  56007. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56008. {
  56009. numColumns = 0;
  56010. contentHeight = 0;
  56011. const int maxMenuH = getParentHeight() - 24;
  56012. int totalW;
  56013. do
  56014. {
  56015. ++numColumns;
  56016. totalW = workOutBestSize (maxMenuW);
  56017. if (totalW > maxMenuW)
  56018. {
  56019. numColumns = jmax (1, numColumns - 1);
  56020. totalW = workOutBestSize (maxMenuW); // to update col widths
  56021. break;
  56022. }
  56023. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56024. {
  56025. break;
  56026. }
  56027. } while (numColumns < maximumNumColumns);
  56028. const int actualH = jmin (contentHeight, maxMenuH);
  56029. needsToScroll = contentHeight > actualH;
  56030. width = updateYPositions();
  56031. height = actualH + PopupMenuSettings::borderSize * 2;
  56032. }
  56033. int workOutBestSize (const int maxMenuW)
  56034. {
  56035. int totalW = 0;
  56036. contentHeight = 0;
  56037. int childNum = 0;
  56038. for (int col = 0; col < numColumns; ++col)
  56039. {
  56040. int i, colW = 50, colH = 0;
  56041. const int numChildren = jmin (items.size() - childNum,
  56042. (items.size() + numColumns - 1) / numColumns);
  56043. for (i = numChildren; --i >= 0;)
  56044. {
  56045. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56046. colH += items.getUnchecked (childNum + i)->getHeight();
  56047. }
  56048. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56049. columnWidths.set (col, colW);
  56050. totalW += colW;
  56051. contentHeight = jmax (contentHeight, colH);
  56052. childNum += numChildren;
  56053. }
  56054. if (totalW < minimumWidth)
  56055. {
  56056. totalW = minimumWidth;
  56057. for (int col = 0; col < numColumns; ++col)
  56058. columnWidths.set (0, totalW / numColumns);
  56059. }
  56060. return totalW;
  56061. }
  56062. void ensureItemIsVisible (const int itemId, int wantedY)
  56063. {
  56064. jassert (itemId != 0)
  56065. for (int i = items.size(); --i >= 0;)
  56066. {
  56067. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56068. if (m != 0
  56069. && m->itemInfo.itemId == itemId
  56070. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56071. {
  56072. const int currentY = m->getY();
  56073. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56074. {
  56075. if (wantedY < 0)
  56076. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56077. jmax (PopupMenuSettings::scrollZone,
  56078. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56079. currentY);
  56080. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56081. int deltaY = wantedY - currentY;
  56082. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56083. jmin (windowPos.getHeight(), mon.getHeight()));
  56084. const int newY = jlimit (mon.getY(),
  56085. mon.getBottom() - windowPos.getHeight(),
  56086. windowPos.getY() + deltaY);
  56087. deltaY -= newY - windowPos.getY();
  56088. childYOffset -= deltaY;
  56089. windowPos.setPosition (windowPos.getX(), newY);
  56090. updateYPositions();
  56091. }
  56092. break;
  56093. }
  56094. }
  56095. }
  56096. void resizeToBestWindowPos()
  56097. {
  56098. Rectangle<int> r (windowPos);
  56099. if (childYOffset < 0)
  56100. {
  56101. r.setBounds (r.getX(), r.getY() - childYOffset,
  56102. r.getWidth(), r.getHeight() + childYOffset);
  56103. }
  56104. else if (childYOffset > 0)
  56105. {
  56106. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56107. if (spaceAtBottom > 0)
  56108. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56109. }
  56110. setBounds (r);
  56111. updateYPositions();
  56112. }
  56113. void alterChildYPos (const int delta)
  56114. {
  56115. if (isScrolling())
  56116. {
  56117. childYOffset += delta;
  56118. if (delta < 0)
  56119. {
  56120. childYOffset = jmax (childYOffset, 0);
  56121. }
  56122. else if (delta > 0)
  56123. {
  56124. childYOffset = jmin (childYOffset,
  56125. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56126. }
  56127. updateYPositions();
  56128. }
  56129. else
  56130. {
  56131. childYOffset = 0;
  56132. }
  56133. resizeToBestWindowPos();
  56134. repaint();
  56135. }
  56136. int updateYPositions()
  56137. {
  56138. int x = 0;
  56139. int childNum = 0;
  56140. for (int col = 0; col < numColumns; ++col)
  56141. {
  56142. const int numChildren = jmin (items.size() - childNum,
  56143. (items.size() + numColumns - 1) / numColumns);
  56144. const int colW = columnWidths [col];
  56145. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56146. for (int i = 0; i < numChildren; ++i)
  56147. {
  56148. Component* const c = items.getUnchecked (childNum + i);
  56149. c->setBounds (x, y, colW, c->getHeight());
  56150. y += c->getHeight();
  56151. }
  56152. x += colW;
  56153. childNum += numChildren;
  56154. }
  56155. return x;
  56156. }
  56157. bool isScrolling() const throw()
  56158. {
  56159. return childYOffset != 0 || needsToScroll;
  56160. }
  56161. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56162. {
  56163. if (currentChild != 0)
  56164. currentChild->setHighlighted (false);
  56165. currentChild = child;
  56166. if (currentChild != 0)
  56167. {
  56168. currentChild->setHighlighted (true);
  56169. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56170. }
  56171. }
  56172. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56173. {
  56174. activeSubMenu = 0;
  56175. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56176. {
  56177. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56178. dismissOnMouseUp,
  56179. this,
  56180. childComp->getScreenBounds(),
  56181. 0, maximumNumColumns,
  56182. standardItemHeight,
  56183. false, 0, managerOfChosenCommand,
  56184. componentAttachedTo);
  56185. if (activeSubMenu != 0)
  56186. {
  56187. activeSubMenu->setVisible (true);
  56188. activeSubMenu->enterModalState (false);
  56189. activeSubMenu->toFront (false);
  56190. return true;
  56191. }
  56192. }
  56193. return false;
  56194. }
  56195. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56196. {
  56197. isOver = reallyContains (localMousePos, true);
  56198. if (isOver)
  56199. hasBeenOver = true;
  56200. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56201. {
  56202. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56203. if (disableMouseMoves && isOver)
  56204. disableMouseMoves = false;
  56205. }
  56206. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56207. return;
  56208. bool isMovingTowardsMenu = false;
  56209. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56210. {
  56211. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56212. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56213. // extends from the last mouse pos to the submenu's rectangle..
  56214. float subX = (float) activeSubMenu->getScreenX();
  56215. if (activeSubMenu->getX() > getX())
  56216. {
  56217. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56218. }
  56219. else
  56220. {
  56221. lastMouse += Point<int> (2, 0);
  56222. subX += activeSubMenu->getWidth();
  56223. }
  56224. Path areaTowardsSubMenu;
  56225. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56226. subX, (float) activeSubMenu->getScreenY(),
  56227. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56228. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56229. }
  56230. lastMouse = globalMousePos;
  56231. if (! isMovingTowardsMenu)
  56232. {
  56233. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56234. if (c == this)
  56235. c = 0;
  56236. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56237. if (mic == 0 && c != 0)
  56238. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56239. if (mic != currentChild
  56240. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56241. {
  56242. if (isOver && (c != 0) && (activeSubMenu != 0))
  56243. {
  56244. activeSubMenu->hide (0, true);
  56245. }
  56246. if (! isOver)
  56247. mic = 0;
  56248. setCurrentlyHighlightedChild (mic);
  56249. }
  56250. }
  56251. }
  56252. void triggerCurrentlyHighlightedItem()
  56253. {
  56254. if (currentChild != 0
  56255. && currentChild->itemInfo.canBeTriggered()
  56256. && (currentChild->itemInfo.customComp == 0
  56257. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56258. {
  56259. dismissMenu (&currentChild->itemInfo);
  56260. }
  56261. }
  56262. void selectNextItem (const int delta)
  56263. {
  56264. disableTimerUntilMouseMoves();
  56265. PopupMenu::ItemComponent* mic = 0;
  56266. bool wasLastOne = (currentChild == 0);
  56267. const int numItems = items.size();
  56268. for (int i = 0; i < numItems + 1; ++i)
  56269. {
  56270. int index = (delta > 0) ? i : (numItems - 1 - i);
  56271. index = (index + numItems) % numItems;
  56272. mic = items.getUnchecked (index);
  56273. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56274. && wasLastOne)
  56275. break;
  56276. if (mic == currentChild)
  56277. wasLastOne = true;
  56278. }
  56279. setCurrentlyHighlightedChild (mic);
  56280. }
  56281. void disableTimerUntilMouseMoves()
  56282. {
  56283. disableMouseMoves = true;
  56284. if (owner != 0)
  56285. owner->disableTimerUntilMouseMoves();
  56286. }
  56287. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56288. };
  56289. PopupMenu::PopupMenu()
  56290. : lookAndFeel (0),
  56291. separatorPending (false)
  56292. {
  56293. }
  56294. PopupMenu::PopupMenu (const PopupMenu& other)
  56295. : lookAndFeel (other.lookAndFeel),
  56296. separatorPending (false)
  56297. {
  56298. items.addCopiesOf (other.items);
  56299. }
  56300. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56301. {
  56302. if (this != &other)
  56303. {
  56304. lookAndFeel = other.lookAndFeel;
  56305. clear();
  56306. items.addCopiesOf (other.items);
  56307. }
  56308. return *this;
  56309. }
  56310. PopupMenu::~PopupMenu()
  56311. {
  56312. clear();
  56313. }
  56314. void PopupMenu::clear()
  56315. {
  56316. items.clear();
  56317. separatorPending = false;
  56318. }
  56319. void PopupMenu::addSeparatorIfPending()
  56320. {
  56321. if (separatorPending)
  56322. {
  56323. separatorPending = false;
  56324. if (items.size() > 0)
  56325. items.add (new Item());
  56326. }
  56327. }
  56328. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56329. const bool isActive, const bool isTicked, const Image& iconToUse)
  56330. {
  56331. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56332. // didn't pick anything, so you shouldn't use it as the id
  56333. // for an item..
  56334. addSeparatorIfPending();
  56335. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56336. Colours::black, false, 0, 0, 0));
  56337. }
  56338. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56339. const int commandID,
  56340. const String& displayName)
  56341. {
  56342. jassert (commandManager != 0 && commandID != 0);
  56343. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56344. if (registeredInfo != 0)
  56345. {
  56346. ApplicationCommandInfo info (*registeredInfo);
  56347. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56348. addSeparatorIfPending();
  56349. items.add (new Item (commandID,
  56350. displayName.isNotEmpty() ? displayName
  56351. : info.shortName,
  56352. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56353. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56354. Image::null,
  56355. Colours::black,
  56356. false,
  56357. 0, 0,
  56358. commandManager));
  56359. }
  56360. }
  56361. void PopupMenu::addColouredItem (const int itemResultId,
  56362. const String& itemText,
  56363. const Colour& itemTextColour,
  56364. const bool isActive,
  56365. const bool isTicked,
  56366. const Image& iconToUse)
  56367. {
  56368. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56369. // didn't pick anything, so you shouldn't use it as the id
  56370. // for an item..
  56371. addSeparatorIfPending();
  56372. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56373. itemTextColour, true, 0, 0, 0));
  56374. }
  56375. void PopupMenu::addCustomItem (const int itemResultId,
  56376. PopupMenuCustomComponent* const customComponent)
  56377. {
  56378. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56379. // didn't pick anything, so you shouldn't use it as the id
  56380. // for an item..
  56381. addSeparatorIfPending();
  56382. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56383. Colours::black, false, customComponent, 0, 0));
  56384. }
  56385. class NormalComponentWrapper : public PopupMenuCustomComponent
  56386. {
  56387. public:
  56388. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56389. const bool triggerMenuItemAutomaticallyWhenClicked)
  56390. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56391. width (w), height (h)
  56392. {
  56393. addAndMakeVisible (comp);
  56394. }
  56395. ~NormalComponentWrapper() {}
  56396. void getIdealSize (int& idealWidth, int& idealHeight)
  56397. {
  56398. idealWidth = width;
  56399. idealHeight = height;
  56400. }
  56401. void resized()
  56402. {
  56403. if (getChildComponent(0) != 0)
  56404. getChildComponent(0)->setBounds (getLocalBounds());
  56405. }
  56406. private:
  56407. const int width, height;
  56408. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56409. };
  56410. void PopupMenu::addCustomItem (const int itemResultId,
  56411. Component* customComponent,
  56412. int idealWidth, int idealHeight,
  56413. const bool triggerMenuItemAutomaticallyWhenClicked)
  56414. {
  56415. addCustomItem (itemResultId,
  56416. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56417. triggerMenuItemAutomaticallyWhenClicked));
  56418. }
  56419. void PopupMenu::addSubMenu (const String& subMenuName,
  56420. const PopupMenu& subMenu,
  56421. const bool isActive,
  56422. const Image& iconToUse,
  56423. const bool isTicked)
  56424. {
  56425. addSeparatorIfPending();
  56426. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56427. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56428. }
  56429. void PopupMenu::addSeparator()
  56430. {
  56431. separatorPending = true;
  56432. }
  56433. class HeaderItemComponent : public PopupMenuCustomComponent
  56434. {
  56435. public:
  56436. HeaderItemComponent (const String& name)
  56437. : PopupMenuCustomComponent (false)
  56438. {
  56439. setName (name);
  56440. }
  56441. void paint (Graphics& g)
  56442. {
  56443. Font f (getLookAndFeel().getPopupMenuFont());
  56444. f.setBold (true);
  56445. g.setFont (f);
  56446. g.setColour (findColour (PopupMenu::headerTextColourId));
  56447. g.drawFittedText (getName(),
  56448. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56449. Justification::bottomLeft, 1);
  56450. }
  56451. void getIdealSize (int& idealWidth,
  56452. int& idealHeight)
  56453. {
  56454. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56455. idealHeight += idealHeight / 2;
  56456. idealWidth += idealWidth / 4;
  56457. }
  56458. private:
  56459. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56460. };
  56461. void PopupMenu::addSectionHeader (const String& title)
  56462. {
  56463. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56464. }
  56465. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56466. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56467. {
  56468. public:
  56469. PopupMenuCompletionCallback()
  56470. : managerOfChosenCommand (0)
  56471. {
  56472. }
  56473. void modalStateFinished (int result)
  56474. {
  56475. if (managerOfChosenCommand != 0 && result != 0)
  56476. {
  56477. ApplicationCommandTarget::InvocationInfo info (result);
  56478. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56479. managerOfChosenCommand->invoke (info, true);
  56480. }
  56481. // (this would be the place to fade out the component, if that's what's required)
  56482. component = 0;
  56483. }
  56484. ApplicationCommandManager* managerOfChosenCommand;
  56485. ScopedPointer<Component> component;
  56486. private:
  56487. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56488. };
  56489. int PopupMenu::showMenu (const Rectangle<int>& target,
  56490. const int itemIdThatMustBeVisible,
  56491. const int minimumWidth,
  56492. const int maximumNumColumns,
  56493. const int standardItemHeight,
  56494. Component* const componentAttachedTo,
  56495. ModalComponentManager::Callback* userCallback)
  56496. {
  56497. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56498. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56499. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56500. Window::wasHiddenBecauseOfAppChange() = false;
  56501. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56502. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56503. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56504. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56505. standardItemHeight, ! target.isEmpty(), itemIdThatMustBeVisible,
  56506. &callback->managerOfChosenCommand, componentAttachedTo);
  56507. if (callback->component == 0)
  56508. return 0;
  56509. callback->component->enterModalState (false, userCallbackDeleter.release());
  56510. callback->component->toFront (false); // need to do this after making it modal, or it could
  56511. // be stuck behind other comps that are already modal..
  56512. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56513. callbackDeleter.release();
  56514. if (userCallback != 0)
  56515. return 0;
  56516. const int result = callback->component->runModalLoop();
  56517. if (! Window::wasHiddenBecauseOfAppChange())
  56518. {
  56519. if (prevTopLevel != 0)
  56520. prevTopLevel->toFront (true);
  56521. if (prevFocused != 0)
  56522. prevFocused->grabKeyboardFocus();
  56523. }
  56524. return result;
  56525. }
  56526. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56527. const int minimumWidth, const int maximumNumColumns,
  56528. const int standardItemHeight,
  56529. ModalComponentManager::Callback* callback)
  56530. {
  56531. return showMenu (Rectangle<int>().withPosition (Desktop::getMousePosition()),
  56532. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56533. standardItemHeight, 0, callback);
  56534. }
  56535. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56536. const int itemIdThatMustBeVisible,
  56537. const int minimumWidth, const int maximumNumColumns,
  56538. const int standardItemHeight,
  56539. ModalComponentManager::Callback* callback)
  56540. {
  56541. return showMenu (screenAreaToAttachTo,
  56542. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56543. standardItemHeight, 0, callback);
  56544. }
  56545. int PopupMenu::showAt (Component* componentToAttachTo,
  56546. const int itemIdThatMustBeVisible,
  56547. const int minimumWidth, const int maximumNumColumns,
  56548. const int standardItemHeight,
  56549. ModalComponentManager::Callback* callback)
  56550. {
  56551. if (componentToAttachTo != 0)
  56552. {
  56553. return showMenu (componentToAttachTo->getScreenBounds(),
  56554. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56555. standardItemHeight, componentToAttachTo, callback);
  56556. }
  56557. else
  56558. {
  56559. return show (itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56560. standardItemHeight, callback);
  56561. }
  56562. }
  56563. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56564. {
  56565. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56566. {
  56567. Window* const pmw = Window::getActiveWindows()[i];
  56568. if (pmw != 0)
  56569. pmw->dismissMenu (0);
  56570. }
  56571. }
  56572. int PopupMenu::getNumItems() const throw()
  56573. {
  56574. int num = 0;
  56575. for (int i = items.size(); --i >= 0;)
  56576. if (! (items.getUnchecked(i))->isSeparator)
  56577. ++num;
  56578. return num;
  56579. }
  56580. bool PopupMenu::containsCommandItem (const int commandID) const
  56581. {
  56582. for (int i = items.size(); --i >= 0;)
  56583. {
  56584. const Item* mi = items.getUnchecked (i);
  56585. if ((mi->itemId == commandID && mi->commandManager != 0)
  56586. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56587. {
  56588. return true;
  56589. }
  56590. }
  56591. return false;
  56592. }
  56593. bool PopupMenu::containsAnyActiveItems() const throw()
  56594. {
  56595. for (int i = items.size(); --i >= 0;)
  56596. {
  56597. const Item* const mi = items.getUnchecked (i);
  56598. if (mi->subMenu != 0)
  56599. {
  56600. if (mi->subMenu->containsAnyActiveItems())
  56601. return true;
  56602. }
  56603. else if (mi->active)
  56604. {
  56605. return true;
  56606. }
  56607. }
  56608. return false;
  56609. }
  56610. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56611. {
  56612. lookAndFeel = newLookAndFeel;
  56613. }
  56614. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56615. : isHighlighted (false),
  56616. isTriggeredAutomatically (isTriggeredAutomatically_)
  56617. {
  56618. }
  56619. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56620. {
  56621. }
  56622. void PopupMenuCustomComponent::triggerMenuItem()
  56623. {
  56624. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56625. if (mic != 0)
  56626. {
  56627. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56628. if (pmw != 0)
  56629. {
  56630. pmw->dismissMenu (&mic->itemInfo);
  56631. }
  56632. else
  56633. {
  56634. // something must have gone wrong with the component hierarchy if this happens..
  56635. jassertfalse;
  56636. }
  56637. }
  56638. else
  56639. {
  56640. // why isn't this component inside a menu? Not much point triggering the item if
  56641. // there's no menu.
  56642. jassertfalse;
  56643. }
  56644. }
  56645. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56646. : subMenu (0),
  56647. itemId (0),
  56648. isSeparator (false),
  56649. isTicked (false),
  56650. isEnabled (false),
  56651. isCustomComponent (false),
  56652. isSectionHeader (false),
  56653. customColour (0),
  56654. customImage (0),
  56655. menu (menu_),
  56656. index (0)
  56657. {
  56658. }
  56659. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56660. {
  56661. }
  56662. bool PopupMenu::MenuItemIterator::next()
  56663. {
  56664. if (index >= menu.items.size())
  56665. return false;
  56666. const Item* const item = menu.items.getUnchecked (index);
  56667. ++index;
  56668. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56669. subMenu = item->subMenu;
  56670. itemId = item->itemId;
  56671. isSeparator = item->isSeparator;
  56672. isTicked = item->isTicked;
  56673. isEnabled = item->active;
  56674. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <PopupMenuCustomComponent*> (item->customComp)) != 0;
  56675. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56676. customColour = item->usesColour ? &(item->textColour) : 0;
  56677. customImage = item->image;
  56678. commandManager = item->commandManager;
  56679. return true;
  56680. }
  56681. END_JUCE_NAMESPACE
  56682. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56683. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56684. BEGIN_JUCE_NAMESPACE
  56685. ComponentDragger::ComponentDragger()
  56686. {
  56687. }
  56688. ComponentDragger::~ComponentDragger()
  56689. {
  56690. }
  56691. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  56692. {
  56693. jassert (componentToDrag != 0);
  56694. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56695. if (componentToDrag != 0)
  56696. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  56697. }
  56698. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  56699. ComponentBoundsConstrainer* const constrainer)
  56700. {
  56701. jassert (componentToDrag != 0);
  56702. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56703. if (componentToDrag != 0)
  56704. {
  56705. Rectangle<int> bounds (componentToDrag->getBounds());
  56706. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  56707. if (constrainer != 0)
  56708. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56709. else
  56710. componentToDrag->setBounds (bounds);
  56711. }
  56712. }
  56713. END_JUCE_NAMESPACE
  56714. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56715. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56716. BEGIN_JUCE_NAMESPACE
  56717. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56718. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56719. class DragImageComponent : public Component,
  56720. public Timer
  56721. {
  56722. public:
  56723. DragImageComponent (const Image& im,
  56724. const String& desc,
  56725. Component* const sourceComponent,
  56726. Component* const mouseDragSource_,
  56727. DragAndDropContainer* const o,
  56728. const Point<int>& imageOffset_)
  56729. : image (im),
  56730. source (sourceComponent),
  56731. mouseDragSource (mouseDragSource_),
  56732. owner (o),
  56733. dragDesc (desc),
  56734. imageOffset (imageOffset_),
  56735. hasCheckedForExternalDrag (false),
  56736. drawImage (true)
  56737. {
  56738. setSize (im.getWidth(), im.getHeight());
  56739. if (mouseDragSource == 0)
  56740. mouseDragSource = source;
  56741. mouseDragSource->addMouseListener (this, false);
  56742. startTimer (200);
  56743. setInterceptsMouseClicks (false, false);
  56744. setAlwaysOnTop (true);
  56745. }
  56746. ~DragImageComponent()
  56747. {
  56748. if (owner->dragImageComponent == this)
  56749. owner->dragImageComponent.release();
  56750. if (mouseDragSource != 0)
  56751. {
  56752. mouseDragSource->removeMouseListener (this);
  56753. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56754. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56755. }
  56756. }
  56757. void paint (Graphics& g)
  56758. {
  56759. if (isOpaque())
  56760. g.fillAll (Colours::white);
  56761. if (drawImage)
  56762. {
  56763. g.setOpacity (1.0f);
  56764. g.drawImageAt (image, 0, 0);
  56765. }
  56766. }
  56767. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56768. {
  56769. Component* hit = getParentComponent();
  56770. if (hit == 0)
  56771. {
  56772. hit = Desktop::getInstance().findComponentAt (screenPos);
  56773. }
  56774. else
  56775. {
  56776. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  56777. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56778. }
  56779. // (note: use a local copy of the dragDesc member in case the callback runs
  56780. // a modal loop and deletes this object before the method completes)
  56781. const String dragDescLocal (dragDesc);
  56782. while (hit != 0)
  56783. {
  56784. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56785. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56786. {
  56787. relativePos = hit->getLocalPoint (0, screenPos);
  56788. return ddt;
  56789. }
  56790. hit = hit->getParentComponent();
  56791. }
  56792. return 0;
  56793. }
  56794. void mouseUp (const MouseEvent& e)
  56795. {
  56796. if (e.originalComponent != this)
  56797. {
  56798. if (mouseDragSource != 0)
  56799. mouseDragSource->removeMouseListener (this);
  56800. bool dropAccepted = false;
  56801. DragAndDropTarget* ddt = 0;
  56802. Point<int> relPos;
  56803. if (isVisible())
  56804. {
  56805. setVisible (false);
  56806. ddt = findTarget (e.getScreenPosition(), relPos);
  56807. // fade this component and remove it - it'll be deleted later by the timer callback
  56808. dropAccepted = ddt != 0;
  56809. setVisible (true);
  56810. if (dropAccepted || source == 0)
  56811. {
  56812. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  56813. }
  56814. else
  56815. {
  56816. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  56817. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  56818. Desktop::getInstance().getAnimator().animateComponent (this,
  56819. getBounds() + (target - ourCentre),
  56820. 0.0f, 120,
  56821. true, 1.0, 1.0);
  56822. }
  56823. }
  56824. if (getParentComponent() != 0)
  56825. getParentComponent()->removeChildComponent (this);
  56826. if (dropAccepted && ddt != 0)
  56827. {
  56828. // (note: use a local copy of the dragDesc member in case the callback runs
  56829. // a modal loop and deletes this object before the method completes)
  56830. const String dragDescLocal (dragDesc);
  56831. currentlyOverComp = 0;
  56832. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56833. }
  56834. // careful - this object could now be deleted..
  56835. }
  56836. }
  56837. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56838. {
  56839. // (note: use a local copy of the dragDesc member in case the callback runs
  56840. // a modal loop and deletes this object before it returns)
  56841. const String dragDescLocal (dragDesc);
  56842. Point<int> newPos (screenPos + imageOffset);
  56843. if (getParentComponent() != 0)
  56844. newPos = getParentComponent()->getLocalPoint (0, newPos);
  56845. //if (newX != getX() || newY != getY())
  56846. {
  56847. setTopLeftPosition (newPos.getX(), newPos.getY());
  56848. Point<int> relPos;
  56849. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56850. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56851. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56852. if (ddtComp != currentlyOverComp)
  56853. {
  56854. if (currentlyOverComp != 0 && source != 0
  56855. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56856. {
  56857. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56858. }
  56859. currentlyOverComp = ddtComp;
  56860. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56861. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56862. }
  56863. DragAndDropTarget* target = getCurrentlyOver();
  56864. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56865. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56866. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56867. {
  56868. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56869. {
  56870. hasCheckedForExternalDrag = true;
  56871. StringArray files;
  56872. bool canMoveFiles = false;
  56873. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56874. && files.size() > 0)
  56875. {
  56876. Component::SafePointer<Component> cdw (this);
  56877. setVisible (false);
  56878. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56879. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56880. if (cdw != 0)
  56881. delete this;
  56882. return;
  56883. }
  56884. }
  56885. }
  56886. }
  56887. }
  56888. void mouseDrag (const MouseEvent& e)
  56889. {
  56890. if (e.originalComponent != this)
  56891. updateLocation (true, e.getScreenPosition());
  56892. }
  56893. void timerCallback()
  56894. {
  56895. if (source == 0)
  56896. {
  56897. delete this;
  56898. }
  56899. else if (! isMouseButtonDownAnywhere())
  56900. {
  56901. if (mouseDragSource != 0)
  56902. mouseDragSource->removeMouseListener (this);
  56903. delete this;
  56904. }
  56905. }
  56906. private:
  56907. Image image;
  56908. Component::SafePointer<Component> source;
  56909. Component::SafePointer<Component> mouseDragSource;
  56910. DragAndDropContainer* const owner;
  56911. Component::SafePointer<Component> currentlyOverComp;
  56912. DragAndDropTarget* getCurrentlyOver()
  56913. {
  56914. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56915. }
  56916. String dragDesc;
  56917. const Point<int> imageOffset;
  56918. bool hasCheckedForExternalDrag, drawImage;
  56919. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  56920. };
  56921. DragAndDropContainer::DragAndDropContainer()
  56922. {
  56923. }
  56924. DragAndDropContainer::~DragAndDropContainer()
  56925. {
  56926. dragImageComponent = 0;
  56927. }
  56928. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56929. Component* sourceComponent,
  56930. const Image& dragImage_,
  56931. const bool allowDraggingToExternalWindows,
  56932. const Point<int>* imageOffsetFromMouse)
  56933. {
  56934. Image dragImage (dragImage_);
  56935. if (dragImageComponent == 0)
  56936. {
  56937. Component* const thisComp = dynamic_cast <Component*> (this);
  56938. if (thisComp == 0)
  56939. {
  56940. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56941. return;
  56942. }
  56943. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56944. if (draggingSource == 0 || ! draggingSource->isDragging())
  56945. {
  56946. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56947. return;
  56948. }
  56949. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56950. Point<int> imageOffset;
  56951. if (dragImage.isNull())
  56952. {
  56953. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56954. .convertedToFormat (Image::ARGB);
  56955. dragImage.multiplyAllAlphas (0.6f);
  56956. const int lo = 150;
  56957. const int hi = 400;
  56958. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  56959. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56960. for (int y = dragImage.getHeight(); --y >= 0;)
  56961. {
  56962. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56963. for (int x = dragImage.getWidth(); --x >= 0;)
  56964. {
  56965. const int dx = x - clipped.getX();
  56966. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56967. if (distance > lo)
  56968. {
  56969. const float alpha = (distance > hi) ? 0
  56970. : (hi - distance) / (float) (hi - lo)
  56971. + Random::getSystemRandom().nextFloat() * 0.008f;
  56972. dragImage.multiplyAlphaAt (x, y, alpha);
  56973. }
  56974. }
  56975. }
  56976. imageOffset = -clipped;
  56977. }
  56978. else
  56979. {
  56980. if (imageOffsetFromMouse == 0)
  56981. imageOffset = -dragImage.getBounds().getCentre();
  56982. else
  56983. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56984. }
  56985. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56986. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56987. currentDragDesc = sourceDescription;
  56988. if (allowDraggingToExternalWindows)
  56989. {
  56990. if (! Desktop::canUseSemiTransparentWindows())
  56991. dragImageComponent->setOpaque (true);
  56992. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56993. | ComponentPeer::windowIsTemporary
  56994. | ComponentPeer::windowIgnoresKeyPresses);
  56995. }
  56996. else
  56997. thisComp->addChildComponent (dragImageComponent);
  56998. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56999. dragImageComponent->setVisible (true);
  57000. }
  57001. }
  57002. bool DragAndDropContainer::isDragAndDropActive() const
  57003. {
  57004. return dragImageComponent != 0;
  57005. }
  57006. const String DragAndDropContainer::getCurrentDragDescription() const
  57007. {
  57008. return (dragImageComponent != 0) ? currentDragDesc
  57009. : String::empty;
  57010. }
  57011. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57012. {
  57013. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57014. }
  57015. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57016. {
  57017. return false;
  57018. }
  57019. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57020. {
  57021. }
  57022. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57023. {
  57024. }
  57025. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57026. {
  57027. }
  57028. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57029. {
  57030. return true;
  57031. }
  57032. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57033. {
  57034. }
  57035. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57036. {
  57037. }
  57038. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57039. {
  57040. }
  57041. END_JUCE_NAMESPACE
  57042. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57043. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57044. BEGIN_JUCE_NAMESPACE
  57045. class MouseCursor::SharedCursorHandle
  57046. {
  57047. public:
  57048. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57049. : handle (createStandardMouseCursor (type)),
  57050. refCount (1),
  57051. standardType (type),
  57052. isStandard (true)
  57053. {
  57054. }
  57055. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57056. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57057. refCount (1),
  57058. standardType (MouseCursor::NormalCursor),
  57059. isStandard (false)
  57060. {
  57061. }
  57062. ~SharedCursorHandle()
  57063. {
  57064. deleteMouseCursor (handle, isStandard);
  57065. }
  57066. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57067. {
  57068. const ScopedLock sl (getLock());
  57069. for (int i = 0; i < getCursors().size(); ++i)
  57070. {
  57071. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57072. if (sc->standardType == type)
  57073. return sc->retain();
  57074. }
  57075. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57076. getCursors().add (sc);
  57077. return sc;
  57078. }
  57079. SharedCursorHandle* retain() throw()
  57080. {
  57081. ++refCount;
  57082. return this;
  57083. }
  57084. void release()
  57085. {
  57086. if (--refCount == 0)
  57087. {
  57088. if (isStandard)
  57089. {
  57090. const ScopedLock sl (getLock());
  57091. getCursors().removeValue (this);
  57092. }
  57093. delete this;
  57094. }
  57095. }
  57096. void* getHandle() const throw() { return handle; }
  57097. private:
  57098. void* const handle;
  57099. Atomic <int> refCount;
  57100. const MouseCursor::StandardCursorType standardType;
  57101. const bool isStandard;
  57102. static CriticalSection& getLock()
  57103. {
  57104. static CriticalSection lock;
  57105. return lock;
  57106. }
  57107. static Array <SharedCursorHandle*>& getCursors()
  57108. {
  57109. static Array <SharedCursorHandle*> cursors;
  57110. return cursors;
  57111. }
  57112. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57113. };
  57114. MouseCursor::MouseCursor()
  57115. : cursorHandle (0)
  57116. {
  57117. }
  57118. MouseCursor::MouseCursor (const StandardCursorType type)
  57119. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57120. {
  57121. }
  57122. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57123. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57124. {
  57125. }
  57126. MouseCursor::MouseCursor (const MouseCursor& other)
  57127. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57128. {
  57129. }
  57130. MouseCursor::~MouseCursor()
  57131. {
  57132. if (cursorHandle != 0)
  57133. cursorHandle->release();
  57134. }
  57135. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57136. {
  57137. if (other.cursorHandle != 0)
  57138. other.cursorHandle->retain();
  57139. if (cursorHandle != 0)
  57140. cursorHandle->release();
  57141. cursorHandle = other.cursorHandle;
  57142. return *this;
  57143. }
  57144. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57145. {
  57146. return getHandle() == other.getHandle();
  57147. }
  57148. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57149. {
  57150. return getHandle() != other.getHandle();
  57151. }
  57152. void* MouseCursor::getHandle() const throw()
  57153. {
  57154. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57155. }
  57156. void MouseCursor::showWaitCursor()
  57157. {
  57158. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57159. }
  57160. void MouseCursor::hideWaitCursor()
  57161. {
  57162. Desktop::getInstance().getMainMouseSource().revealCursor();
  57163. }
  57164. END_JUCE_NAMESPACE
  57165. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57166. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57167. BEGIN_JUCE_NAMESPACE
  57168. MouseEvent::MouseEvent (MouseInputSource& source_,
  57169. const Point<int>& position,
  57170. const ModifierKeys& mods_,
  57171. Component* const eventComponent_,
  57172. Component* const originator,
  57173. const Time& eventTime_,
  57174. const Point<int> mouseDownPos_,
  57175. const Time& mouseDownTime_,
  57176. const int numberOfClicks_,
  57177. const bool mouseWasDragged) throw()
  57178. : x (position.getX()),
  57179. y (position.getY()),
  57180. mods (mods_),
  57181. eventComponent (eventComponent_),
  57182. originalComponent (originator),
  57183. eventTime (eventTime_),
  57184. source (source_),
  57185. mouseDownPos (mouseDownPos_),
  57186. mouseDownTime (mouseDownTime_),
  57187. numberOfClicks (numberOfClicks_),
  57188. wasMovedSinceMouseDown (mouseWasDragged)
  57189. {
  57190. }
  57191. MouseEvent::~MouseEvent() throw()
  57192. {
  57193. }
  57194. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57195. {
  57196. if (otherComponent == 0)
  57197. {
  57198. jassertfalse;
  57199. return *this;
  57200. }
  57201. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57202. mods, otherComponent, originalComponent, eventTime,
  57203. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57204. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57205. }
  57206. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57207. {
  57208. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57209. eventTime, mouseDownPos, mouseDownTime,
  57210. numberOfClicks, wasMovedSinceMouseDown);
  57211. }
  57212. bool MouseEvent::mouseWasClicked() const throw()
  57213. {
  57214. return ! wasMovedSinceMouseDown;
  57215. }
  57216. int MouseEvent::getMouseDownX() const throw()
  57217. {
  57218. return mouseDownPos.getX();
  57219. }
  57220. int MouseEvent::getMouseDownY() const throw()
  57221. {
  57222. return mouseDownPos.getY();
  57223. }
  57224. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57225. {
  57226. return mouseDownPos;
  57227. }
  57228. int MouseEvent::getDistanceFromDragStartX() const throw()
  57229. {
  57230. return x - mouseDownPos.getX();
  57231. }
  57232. int MouseEvent::getDistanceFromDragStartY() const throw()
  57233. {
  57234. return y - mouseDownPos.getY();
  57235. }
  57236. int MouseEvent::getDistanceFromDragStart() const throw()
  57237. {
  57238. return mouseDownPos.getDistanceFrom (getPosition());
  57239. }
  57240. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57241. {
  57242. return getPosition() - mouseDownPos;
  57243. }
  57244. int MouseEvent::getLengthOfMousePress() const throw()
  57245. {
  57246. if (mouseDownTime.toMilliseconds() > 0)
  57247. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57248. return 0;
  57249. }
  57250. const Point<int> MouseEvent::getPosition() const throw()
  57251. {
  57252. return Point<int> (x, y);
  57253. }
  57254. int MouseEvent::getScreenX() const
  57255. {
  57256. return getScreenPosition().getX();
  57257. }
  57258. int MouseEvent::getScreenY() const
  57259. {
  57260. return getScreenPosition().getY();
  57261. }
  57262. const Point<int> MouseEvent::getScreenPosition() const
  57263. {
  57264. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57265. }
  57266. int MouseEvent::getMouseDownScreenX() const
  57267. {
  57268. return getMouseDownScreenPosition().getX();
  57269. }
  57270. int MouseEvent::getMouseDownScreenY() const
  57271. {
  57272. return getMouseDownScreenPosition().getY();
  57273. }
  57274. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57275. {
  57276. return eventComponent->localPointToGlobal (mouseDownPos);
  57277. }
  57278. int MouseEvent::doubleClickTimeOutMs = 400;
  57279. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57280. {
  57281. doubleClickTimeOutMs = newTime;
  57282. }
  57283. int MouseEvent::getDoubleClickTimeout() throw()
  57284. {
  57285. return doubleClickTimeOutMs;
  57286. }
  57287. END_JUCE_NAMESPACE
  57288. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57289. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57290. BEGIN_JUCE_NAMESPACE
  57291. class MouseInputSourceInternal : public AsyncUpdater
  57292. {
  57293. public:
  57294. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57295. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57296. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57297. mouseEventCounter (0), lastTime (0)
  57298. {
  57299. }
  57300. ~MouseInputSourceInternal()
  57301. {
  57302. }
  57303. bool isDragging() const throw()
  57304. {
  57305. return buttonState.isAnyMouseButtonDown();
  57306. }
  57307. Component* getComponentUnderMouse() const
  57308. {
  57309. return static_cast <Component*> (componentUnderMouse);
  57310. }
  57311. const ModifierKeys getCurrentModifiers() const
  57312. {
  57313. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57314. }
  57315. ComponentPeer* getPeer()
  57316. {
  57317. if (! ComponentPeer::isValidPeer (lastPeer))
  57318. lastPeer = 0;
  57319. return lastPeer;
  57320. }
  57321. Component* findComponentAt (const Point<int>& screenPos)
  57322. {
  57323. ComponentPeer* const peer = getPeer();
  57324. if (peer != 0)
  57325. {
  57326. Component* const comp = peer->getComponent();
  57327. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57328. // (the contains() call is needed to test for overlapping desktop windows)
  57329. if (comp->contains (relativePos))
  57330. return comp->getComponentAt (relativePos);
  57331. }
  57332. return 0;
  57333. }
  57334. const Point<int> getScreenPosition() const throw()
  57335. {
  57336. return lastScreenPos + unboundedMouseOffset;
  57337. }
  57338. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57339. {
  57340. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57341. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57342. }
  57343. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57344. {
  57345. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57346. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57347. }
  57348. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57349. {
  57350. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57351. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57352. }
  57353. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57354. {
  57355. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57356. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57357. }
  57358. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57359. {
  57360. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57361. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57362. }
  57363. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57364. {
  57365. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57366. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57367. }
  57368. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57369. {
  57370. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57371. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57372. }
  57373. // (returns true if the button change caused a modal event loop)
  57374. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57375. {
  57376. if (buttonState == newButtonState)
  57377. return false;
  57378. setScreenPos (screenPos, time, false);
  57379. // (ignore secondary clicks when there's already a button down)
  57380. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57381. {
  57382. buttonState = newButtonState;
  57383. return false;
  57384. }
  57385. const int lastCounter = mouseEventCounter;
  57386. if (buttonState.isAnyMouseButtonDown())
  57387. {
  57388. Component* const current = getComponentUnderMouse();
  57389. if (current != 0)
  57390. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57391. enableUnboundedMouseMovement (false, false);
  57392. }
  57393. buttonState = newButtonState;
  57394. if (buttonState.isAnyMouseButtonDown())
  57395. {
  57396. Desktop::getInstance().incrementMouseClickCounter();
  57397. Component* const current = getComponentUnderMouse();
  57398. if (current != 0)
  57399. {
  57400. registerMouseDown (screenPos, time, current, buttonState);
  57401. sendMouseDown (current, screenPos, time);
  57402. }
  57403. }
  57404. return lastCounter != mouseEventCounter;
  57405. }
  57406. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57407. {
  57408. Component* current = getComponentUnderMouse();
  57409. if (newComponent != current)
  57410. {
  57411. Component::SafePointer<Component> safeNewComp (newComponent);
  57412. const ModifierKeys originalButtonState (buttonState);
  57413. if (current != 0)
  57414. {
  57415. setButtons (screenPos, time, ModifierKeys());
  57416. sendMouseExit (current, screenPos, time);
  57417. buttonState = originalButtonState;
  57418. }
  57419. componentUnderMouse = safeNewComp;
  57420. current = getComponentUnderMouse();
  57421. if (current != 0)
  57422. sendMouseEnter (current, screenPos, time);
  57423. revealCursor (false);
  57424. setButtons (screenPos, time, originalButtonState);
  57425. }
  57426. }
  57427. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57428. {
  57429. ModifierKeys::updateCurrentModifiers();
  57430. if (newPeer != lastPeer)
  57431. {
  57432. setComponentUnderMouse (0, screenPos, time);
  57433. lastPeer = newPeer;
  57434. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57435. }
  57436. }
  57437. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57438. {
  57439. if (! isDragging())
  57440. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57441. if (newScreenPos != lastScreenPos || forceUpdate)
  57442. {
  57443. cancelPendingUpdate();
  57444. lastScreenPos = newScreenPos;
  57445. Component* const current = getComponentUnderMouse();
  57446. if (current != 0)
  57447. {
  57448. if (isDragging())
  57449. {
  57450. registerMouseDrag (newScreenPos);
  57451. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57452. if (isUnboundedMouseModeOn)
  57453. handleUnboundedDrag (current);
  57454. }
  57455. else
  57456. {
  57457. sendMouseMove (current, newScreenPos, time);
  57458. }
  57459. }
  57460. revealCursor (false);
  57461. }
  57462. }
  57463. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57464. {
  57465. jassert (newPeer != 0);
  57466. lastTime = time;
  57467. ++mouseEventCounter;
  57468. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57469. if (isDragging() && newMods.isAnyMouseButtonDown())
  57470. {
  57471. setScreenPos (screenPos, time, false);
  57472. }
  57473. else
  57474. {
  57475. setPeer (newPeer, screenPos, time);
  57476. ComponentPeer* peer = getPeer();
  57477. if (peer != 0)
  57478. {
  57479. if (setButtons (screenPos, time, newMods))
  57480. return; // some modal events have been dispatched, so the current event is now out-of-date
  57481. peer = getPeer();
  57482. if (peer != 0)
  57483. setScreenPos (screenPos, time, false);
  57484. }
  57485. }
  57486. }
  57487. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57488. {
  57489. jassert (peer != 0);
  57490. lastTime = time;
  57491. ++mouseEventCounter;
  57492. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57493. setPeer (peer, screenPos, time);
  57494. setScreenPos (screenPos, time, false);
  57495. triggerFakeMove();
  57496. if (! isDragging())
  57497. {
  57498. Component* current = getComponentUnderMouse();
  57499. if (current != 0)
  57500. sendMouseWheel (current, screenPos, time, x, y);
  57501. }
  57502. }
  57503. const Time getLastMouseDownTime() const throw()
  57504. {
  57505. return Time (mouseDowns[0].time);
  57506. }
  57507. const Point<int> getLastMouseDownPosition() const throw()
  57508. {
  57509. return mouseDowns[0].position;
  57510. }
  57511. int getNumberOfMultipleClicks() const throw()
  57512. {
  57513. int numClicks = 0;
  57514. if (mouseDowns[0].time != 0)
  57515. {
  57516. if (! mouseMovedSignificantlySincePressed)
  57517. ++numClicks;
  57518. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57519. {
  57520. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57521. ++numClicks;
  57522. else
  57523. break;
  57524. }
  57525. }
  57526. return numClicks;
  57527. }
  57528. bool hasMouseMovedSignificantlySincePressed() const throw()
  57529. {
  57530. return mouseMovedSignificantlySincePressed
  57531. || lastTime > mouseDowns[0].time + 300;
  57532. }
  57533. void triggerFakeMove()
  57534. {
  57535. triggerAsyncUpdate();
  57536. }
  57537. void handleAsyncUpdate()
  57538. {
  57539. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57540. }
  57541. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57542. {
  57543. enable = enable && isDragging();
  57544. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57545. if (enable != isUnboundedMouseModeOn)
  57546. {
  57547. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57548. {
  57549. // when released, return the mouse to within the component's bounds
  57550. Component* current = getComponentUnderMouse();
  57551. if (current != 0)
  57552. Desktop::setMousePosition (current->getScreenBounds()
  57553. .getConstrainedPoint (lastScreenPos));
  57554. }
  57555. isUnboundedMouseModeOn = enable;
  57556. unboundedMouseOffset = Point<int>();
  57557. revealCursor (true);
  57558. }
  57559. }
  57560. void handleUnboundedDrag (Component* current)
  57561. {
  57562. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57563. if (! screenArea.contains (lastScreenPos))
  57564. {
  57565. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57566. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57567. Desktop::setMousePosition (componentCentre);
  57568. }
  57569. else if (isCursorVisibleUntilOffscreen
  57570. && (! unboundedMouseOffset.isOrigin())
  57571. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57572. {
  57573. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57574. unboundedMouseOffset = Point<int>();
  57575. }
  57576. }
  57577. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57578. {
  57579. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57580. {
  57581. cursor = MouseCursor::NoCursor;
  57582. forcedUpdate = true;
  57583. }
  57584. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57585. {
  57586. currentCursorHandle = cursor.getHandle();
  57587. cursor.showInWindow (getPeer());
  57588. }
  57589. }
  57590. void hideCursor()
  57591. {
  57592. showMouseCursor (MouseCursor::NoCursor, true);
  57593. }
  57594. void revealCursor (bool forcedUpdate)
  57595. {
  57596. MouseCursor mc (MouseCursor::NormalCursor);
  57597. Component* current = getComponentUnderMouse();
  57598. if (current != 0)
  57599. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57600. showMouseCursor (mc, forcedUpdate);
  57601. }
  57602. int index;
  57603. bool isMouseDevice;
  57604. Point<int> lastScreenPos;
  57605. ModifierKeys buttonState;
  57606. private:
  57607. MouseInputSource& source;
  57608. Component::SafePointer<Component> componentUnderMouse;
  57609. ComponentPeer* lastPeer;
  57610. Point<int> unboundedMouseOffset;
  57611. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57612. void* currentCursorHandle;
  57613. int mouseEventCounter;
  57614. struct RecentMouseDown
  57615. {
  57616. RecentMouseDown()
  57617. : time (0), component (0)
  57618. {
  57619. }
  57620. Point<int> position;
  57621. int64 time;
  57622. Component* component;
  57623. ModifierKeys buttons;
  57624. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, int maxTimeBetween) const
  57625. {
  57626. return time - other.time < maxTimeBetween
  57627. && abs (position.getX() - other.position.getX()) < 8
  57628. && abs (position.getY() - other.position.getY()) < 8
  57629. && buttons == other.buttons;;
  57630. }
  57631. };
  57632. RecentMouseDown mouseDowns[4];
  57633. bool mouseMovedSignificantlySincePressed;
  57634. int64 lastTime;
  57635. void registerMouseDown (const Point<int>& screenPos, const int64 time,
  57636. Component* const component, const ModifierKeys& modifiers) throw()
  57637. {
  57638. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57639. mouseDowns[i] = mouseDowns[i - 1];
  57640. mouseDowns[0].position = screenPos;
  57641. mouseDowns[0].time = time;
  57642. mouseDowns[0].component = component;
  57643. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57644. mouseMovedSignificantlySincePressed = false;
  57645. }
  57646. void registerMouseDrag (const Point<int>& screenPos) throw()
  57647. {
  57648. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57649. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57650. }
  57651. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  57652. };
  57653. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57654. {
  57655. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57656. }
  57657. MouseInputSource::~MouseInputSource()
  57658. {
  57659. }
  57660. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57661. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57662. bool MouseInputSource::canHover() const { return isMouse(); }
  57663. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57664. int MouseInputSource::getIndex() const { return pimpl->index; }
  57665. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57666. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57667. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57668. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57669. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57670. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57671. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57672. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57673. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57674. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57675. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57676. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57677. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57678. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57679. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57680. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57681. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57682. {
  57683. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57684. }
  57685. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57686. {
  57687. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57688. }
  57689. END_JUCE_NAMESPACE
  57690. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57691. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57692. BEGIN_JUCE_NAMESPACE
  57693. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57694. : source (0),
  57695. hoverTimeMillisecs (hoverTimeMillisecs_),
  57696. hasJustHovered (false)
  57697. {
  57698. internalTimer.owner = this;
  57699. }
  57700. MouseHoverDetector::~MouseHoverDetector()
  57701. {
  57702. setHoverComponent (0);
  57703. }
  57704. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57705. {
  57706. hoverTimeMillisecs = newTimeInMillisecs;
  57707. }
  57708. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57709. {
  57710. if (source != newSourceComponent)
  57711. {
  57712. internalTimer.stopTimer();
  57713. hasJustHovered = false;
  57714. if (source != 0)
  57715. source->removeMouseListener (&internalTimer);
  57716. source = newSourceComponent;
  57717. if (newSourceComponent != 0)
  57718. newSourceComponent->addMouseListener (&internalTimer, false);
  57719. }
  57720. }
  57721. void MouseHoverDetector::hoverTimerCallback()
  57722. {
  57723. internalTimer.stopTimer();
  57724. if (source != 0)
  57725. {
  57726. const Point<int> pos (source->getMouseXYRelative());
  57727. if (source->reallyContains (pos, false))
  57728. {
  57729. hasJustHovered = true;
  57730. mouseHovered (pos.getX(), pos.getY());
  57731. }
  57732. }
  57733. }
  57734. void MouseHoverDetector::checkJustHoveredCallback()
  57735. {
  57736. if (hasJustHovered)
  57737. {
  57738. hasJustHovered = false;
  57739. mouseMovedAfterHover();
  57740. }
  57741. }
  57742. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57743. {
  57744. owner->hoverTimerCallback();
  57745. }
  57746. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57747. {
  57748. stopTimer();
  57749. owner->checkJustHoveredCallback();
  57750. }
  57751. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57752. {
  57753. stopTimer();
  57754. owner->checkJustHoveredCallback();
  57755. }
  57756. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57757. {
  57758. stopTimer();
  57759. owner->checkJustHoveredCallback();
  57760. }
  57761. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57762. {
  57763. stopTimer();
  57764. owner->checkJustHoveredCallback();
  57765. }
  57766. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57767. {
  57768. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57769. {
  57770. lastX = e.x;
  57771. lastY = e.y;
  57772. if (owner->source != 0)
  57773. startTimer (owner->hoverTimeMillisecs);
  57774. owner->checkJustHoveredCallback();
  57775. }
  57776. }
  57777. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57778. {
  57779. stopTimer();
  57780. owner->checkJustHoveredCallback();
  57781. }
  57782. END_JUCE_NAMESPACE
  57783. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57784. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57785. BEGIN_JUCE_NAMESPACE
  57786. void MouseListener::mouseEnter (const MouseEvent&)
  57787. {
  57788. }
  57789. void MouseListener::mouseExit (const MouseEvent&)
  57790. {
  57791. }
  57792. void MouseListener::mouseDown (const MouseEvent&)
  57793. {
  57794. }
  57795. void MouseListener::mouseUp (const MouseEvent&)
  57796. {
  57797. }
  57798. void MouseListener::mouseDrag (const MouseEvent&)
  57799. {
  57800. }
  57801. void MouseListener::mouseMove (const MouseEvent&)
  57802. {
  57803. }
  57804. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57805. {
  57806. }
  57807. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57808. {
  57809. }
  57810. END_JUCE_NAMESPACE
  57811. /*** End of inlined file: juce_MouseListener.cpp ***/
  57812. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57813. BEGIN_JUCE_NAMESPACE
  57814. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57815. const String& buttonTextWhenTrue,
  57816. const String& buttonTextWhenFalse)
  57817. : PropertyComponent (name),
  57818. onText (buttonTextWhenTrue),
  57819. offText (buttonTextWhenFalse)
  57820. {
  57821. addAndMakeVisible (&button);
  57822. button.setClickingTogglesState (false);
  57823. button.addButtonListener (this);
  57824. }
  57825. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57826. const String& name,
  57827. const String& buttonText)
  57828. : PropertyComponent (name),
  57829. onText (buttonText),
  57830. offText (buttonText)
  57831. {
  57832. addAndMakeVisible (&button);
  57833. button.setClickingTogglesState (false);
  57834. button.setButtonText (buttonText);
  57835. button.getToggleStateValue().referTo (valueToControl);
  57836. button.setClickingTogglesState (true);
  57837. }
  57838. BooleanPropertyComponent::~BooleanPropertyComponent()
  57839. {
  57840. }
  57841. void BooleanPropertyComponent::setState (const bool newState)
  57842. {
  57843. button.setToggleState (newState, true);
  57844. }
  57845. bool BooleanPropertyComponent::getState() const
  57846. {
  57847. return button.getToggleState();
  57848. }
  57849. void BooleanPropertyComponent::paint (Graphics& g)
  57850. {
  57851. PropertyComponent::paint (g);
  57852. g.setColour (Colours::white);
  57853. g.fillRect (button.getBounds());
  57854. g.setColour (findColour (ComboBox::outlineColourId));
  57855. g.drawRect (button.getBounds());
  57856. }
  57857. void BooleanPropertyComponent::refresh()
  57858. {
  57859. button.setToggleState (getState(), false);
  57860. button.setButtonText (button.getToggleState() ? onText : offText);
  57861. }
  57862. void BooleanPropertyComponent::buttonClicked (Button*)
  57863. {
  57864. setState (! getState());
  57865. }
  57866. END_JUCE_NAMESPACE
  57867. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57868. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57869. BEGIN_JUCE_NAMESPACE
  57870. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57871. const bool triggerOnMouseDown)
  57872. : PropertyComponent (name)
  57873. {
  57874. addAndMakeVisible (&button);
  57875. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57876. button.addButtonListener (this);
  57877. }
  57878. ButtonPropertyComponent::~ButtonPropertyComponent()
  57879. {
  57880. }
  57881. void ButtonPropertyComponent::refresh()
  57882. {
  57883. button.setButtonText (getButtonText());
  57884. }
  57885. void ButtonPropertyComponent::buttonClicked (Button*)
  57886. {
  57887. buttonClicked();
  57888. }
  57889. END_JUCE_NAMESPACE
  57890. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57891. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57892. BEGIN_JUCE_NAMESPACE
  57893. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57894. public ValueListener
  57895. {
  57896. public:
  57897. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57898. : sourceValue (sourceValue_),
  57899. mappings (mappings_)
  57900. {
  57901. sourceValue.addListener (this);
  57902. }
  57903. ~RemapperValueSource() {}
  57904. const var getValue() const
  57905. {
  57906. return mappings.indexOf (sourceValue.getValue()) + 1;
  57907. }
  57908. void setValue (const var& newValue)
  57909. {
  57910. const var remappedVal (mappings [(int) newValue - 1]);
  57911. if (remappedVal != sourceValue)
  57912. sourceValue = remappedVal;
  57913. }
  57914. void valueChanged (Value&)
  57915. {
  57916. sendChangeMessage (true);
  57917. }
  57918. protected:
  57919. Value sourceValue;
  57920. Array<var> mappings;
  57921. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  57922. };
  57923. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57924. : PropertyComponent (name),
  57925. isCustomClass (true)
  57926. {
  57927. }
  57928. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57929. const String& name,
  57930. const StringArray& choices_,
  57931. const Array <var>& correspondingValues)
  57932. : PropertyComponent (name),
  57933. choices (choices_),
  57934. isCustomClass (false)
  57935. {
  57936. // The array of corresponding values must contain one value for each of the items in
  57937. // the choices array!
  57938. jassert (correspondingValues.size() == choices.size());
  57939. createComboBox();
  57940. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57941. }
  57942. ChoicePropertyComponent::~ChoicePropertyComponent()
  57943. {
  57944. }
  57945. void ChoicePropertyComponent::createComboBox()
  57946. {
  57947. addAndMakeVisible (&comboBox);
  57948. for (int i = 0; i < choices.size(); ++i)
  57949. {
  57950. if (choices[i].isNotEmpty())
  57951. comboBox.addItem (choices[i], i + 1);
  57952. else
  57953. comboBox.addSeparator();
  57954. }
  57955. comboBox.setEditableText (false);
  57956. }
  57957. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57958. {
  57959. jassertfalse; // you need to override this method in your subclass!
  57960. }
  57961. int ChoicePropertyComponent::getIndex() const
  57962. {
  57963. jassertfalse; // you need to override this method in your subclass!
  57964. return -1;
  57965. }
  57966. const StringArray& ChoicePropertyComponent::getChoices() const
  57967. {
  57968. return choices;
  57969. }
  57970. void ChoicePropertyComponent::refresh()
  57971. {
  57972. if (isCustomClass)
  57973. {
  57974. if (! comboBox.isVisible())
  57975. {
  57976. createComboBox();
  57977. comboBox.addListener (this);
  57978. }
  57979. comboBox.setSelectedId (getIndex() + 1, true);
  57980. }
  57981. }
  57982. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57983. {
  57984. if (isCustomClass)
  57985. {
  57986. const int newIndex = comboBox.getSelectedId() - 1;
  57987. if (newIndex != getIndex())
  57988. setIndex (newIndex);
  57989. }
  57990. }
  57991. END_JUCE_NAMESPACE
  57992. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57993. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57994. BEGIN_JUCE_NAMESPACE
  57995. PropertyComponent::PropertyComponent (const String& name,
  57996. const int preferredHeight_)
  57997. : Component (name),
  57998. preferredHeight (preferredHeight_)
  57999. {
  58000. jassert (name.isNotEmpty());
  58001. }
  58002. PropertyComponent::~PropertyComponent()
  58003. {
  58004. }
  58005. void PropertyComponent::paint (Graphics& g)
  58006. {
  58007. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58008. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58009. }
  58010. void PropertyComponent::resized()
  58011. {
  58012. if (getNumChildComponents() > 0)
  58013. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58014. }
  58015. void PropertyComponent::enablementChanged()
  58016. {
  58017. repaint();
  58018. }
  58019. END_JUCE_NAMESPACE
  58020. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58021. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58022. BEGIN_JUCE_NAMESPACE
  58023. class PropertySectionComponent : public Component
  58024. {
  58025. public:
  58026. PropertySectionComponent (const String& sectionTitle,
  58027. const Array <PropertyComponent*>& newProperties,
  58028. const bool sectionIsOpen_)
  58029. : Component (sectionTitle),
  58030. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58031. sectionIsOpen (sectionIsOpen_)
  58032. {
  58033. propertyComps.addArray (newProperties);
  58034. for (int i = propertyComps.size(); --i >= 0;)
  58035. {
  58036. addAndMakeVisible (propertyComps.getUnchecked(i));
  58037. propertyComps.getUnchecked(i)->refresh();
  58038. }
  58039. }
  58040. ~PropertySectionComponent()
  58041. {
  58042. propertyComps.clear();
  58043. }
  58044. void paint (Graphics& g)
  58045. {
  58046. if (titleHeight > 0)
  58047. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58048. }
  58049. void resized()
  58050. {
  58051. int y = titleHeight;
  58052. for (int i = 0; i < propertyComps.size(); ++i)
  58053. {
  58054. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  58055. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  58056. y = pec->getBottom();
  58057. }
  58058. }
  58059. int getPreferredHeight() const
  58060. {
  58061. int y = titleHeight;
  58062. if (isOpen())
  58063. {
  58064. for (int i = propertyComps.size(); --i >= 0;)
  58065. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  58066. }
  58067. return y;
  58068. }
  58069. void setOpen (const bool open)
  58070. {
  58071. if (sectionIsOpen != open)
  58072. {
  58073. sectionIsOpen = open;
  58074. for (int i = propertyComps.size(); --i >= 0;)
  58075. propertyComps.getUnchecked(i)->setVisible (open);
  58076. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58077. if (pp != 0)
  58078. pp->resized();
  58079. }
  58080. }
  58081. bool isOpen() const
  58082. {
  58083. return sectionIsOpen;
  58084. }
  58085. void refreshAll() const
  58086. {
  58087. for (int i = propertyComps.size(); --i >= 0;)
  58088. propertyComps.getUnchecked (i)->refresh();
  58089. }
  58090. void mouseUp (const MouseEvent& e)
  58091. {
  58092. if (e.getMouseDownX() < titleHeight
  58093. && e.x < titleHeight
  58094. && e.y < titleHeight
  58095. && e.getNumberOfClicks() != 2)
  58096. {
  58097. setOpen (! isOpen());
  58098. }
  58099. }
  58100. void mouseDoubleClick (const MouseEvent& e)
  58101. {
  58102. if (e.y < titleHeight)
  58103. setOpen (! isOpen());
  58104. }
  58105. private:
  58106. OwnedArray <PropertyComponent> propertyComps;
  58107. int titleHeight;
  58108. bool sectionIsOpen;
  58109. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  58110. };
  58111. class PropertyPanel::PropertyHolderComponent : public Component
  58112. {
  58113. public:
  58114. PropertyHolderComponent() {}
  58115. void paint (Graphics&) {}
  58116. void updateLayout (int width)
  58117. {
  58118. int y = 0;
  58119. for (int i = 0; i < sections.size(); ++i)
  58120. {
  58121. PropertySectionComponent* const section = sections.getUnchecked(i);
  58122. section->setBounds (0, y, width, section->getPreferredHeight());
  58123. y = section->getBottom();
  58124. }
  58125. setSize (width, y);
  58126. repaint();
  58127. }
  58128. void refreshAll() const
  58129. {
  58130. for (int i = 0; i < sections.size(); ++i)
  58131. sections.getUnchecked(i)->refreshAll();
  58132. }
  58133. void clear()
  58134. {
  58135. sections.clear();
  58136. }
  58137. void addSection (PropertySectionComponent* newSection)
  58138. {
  58139. sections.add (newSection);
  58140. addAndMakeVisible (newSection, 0);
  58141. }
  58142. int getNumSections() const throw() { return sections.size(); }
  58143. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58144. private:
  58145. OwnedArray<PropertySectionComponent> sections;
  58146. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  58147. };
  58148. PropertyPanel::PropertyPanel()
  58149. {
  58150. messageWhenEmpty = TRANS("(nothing selected)");
  58151. addAndMakeVisible (&viewport);
  58152. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58153. viewport.setFocusContainer (true);
  58154. }
  58155. PropertyPanel::~PropertyPanel()
  58156. {
  58157. clear();
  58158. }
  58159. void PropertyPanel::paint (Graphics& g)
  58160. {
  58161. if (propertyHolderComponent->getNumSections() == 0)
  58162. {
  58163. g.setColour (Colours::black.withAlpha (0.5f));
  58164. g.setFont (14.0f);
  58165. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58166. Justification::centred, true);
  58167. }
  58168. }
  58169. void PropertyPanel::resized()
  58170. {
  58171. viewport.setBounds (getLocalBounds());
  58172. updatePropHolderLayout();
  58173. }
  58174. void PropertyPanel::clear()
  58175. {
  58176. if (propertyHolderComponent->getNumSections() > 0)
  58177. {
  58178. propertyHolderComponent->clear();
  58179. repaint();
  58180. }
  58181. }
  58182. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58183. {
  58184. if (propertyHolderComponent->getNumSections() == 0)
  58185. repaint();
  58186. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58187. updatePropHolderLayout();
  58188. }
  58189. void PropertyPanel::addSection (const String& sectionTitle,
  58190. const Array <PropertyComponent*>& newProperties,
  58191. const bool shouldBeOpen)
  58192. {
  58193. jassert (sectionTitle.isNotEmpty());
  58194. if (propertyHolderComponent->getNumSections() == 0)
  58195. repaint();
  58196. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58197. updatePropHolderLayout();
  58198. }
  58199. void PropertyPanel::updatePropHolderLayout() const
  58200. {
  58201. const int maxWidth = viewport.getMaximumVisibleWidth();
  58202. propertyHolderComponent->updateLayout (maxWidth);
  58203. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58204. if (maxWidth != newMaxWidth)
  58205. {
  58206. // need to do this twice because of scrollbars changing the size, etc.
  58207. propertyHolderComponent->updateLayout (newMaxWidth);
  58208. }
  58209. }
  58210. void PropertyPanel::refreshAll() const
  58211. {
  58212. propertyHolderComponent->refreshAll();
  58213. }
  58214. const StringArray PropertyPanel::getSectionNames() const
  58215. {
  58216. StringArray s;
  58217. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58218. {
  58219. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58220. if (section->getName().isNotEmpty())
  58221. s.add (section->getName());
  58222. }
  58223. return s;
  58224. }
  58225. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58226. {
  58227. int index = 0;
  58228. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58229. {
  58230. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58231. if (section->getName().isNotEmpty())
  58232. {
  58233. if (index == sectionIndex)
  58234. return section->isOpen();
  58235. ++index;
  58236. }
  58237. }
  58238. return false;
  58239. }
  58240. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58241. {
  58242. int index = 0;
  58243. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58244. {
  58245. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58246. if (section->getName().isNotEmpty())
  58247. {
  58248. if (index == sectionIndex)
  58249. {
  58250. section->setOpen (shouldBeOpen);
  58251. break;
  58252. }
  58253. ++index;
  58254. }
  58255. }
  58256. }
  58257. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58258. {
  58259. int index = 0;
  58260. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58261. {
  58262. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58263. if (section->getName().isNotEmpty())
  58264. {
  58265. if (index == sectionIndex)
  58266. {
  58267. section->setEnabled (shouldBeEnabled);
  58268. break;
  58269. }
  58270. ++index;
  58271. }
  58272. }
  58273. }
  58274. XmlElement* PropertyPanel::getOpennessState() const
  58275. {
  58276. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58277. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58278. const StringArray sections (getSectionNames());
  58279. for (int i = 0; i < sections.size(); ++i)
  58280. {
  58281. if (sections[i].isNotEmpty())
  58282. {
  58283. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58284. e->setAttribute ("name", sections[i]);
  58285. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58286. }
  58287. }
  58288. return xml;
  58289. }
  58290. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58291. {
  58292. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58293. {
  58294. const StringArray sections (getSectionNames());
  58295. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58296. {
  58297. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58298. e->getBoolAttribute ("open"));
  58299. }
  58300. viewport.setViewPosition (viewport.getViewPositionX(),
  58301. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58302. }
  58303. }
  58304. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58305. {
  58306. if (messageWhenEmpty != newMessage)
  58307. {
  58308. messageWhenEmpty = newMessage;
  58309. repaint();
  58310. }
  58311. }
  58312. const String& PropertyPanel::getMessageWhenEmpty() const
  58313. {
  58314. return messageWhenEmpty;
  58315. }
  58316. END_JUCE_NAMESPACE
  58317. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58318. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58319. BEGIN_JUCE_NAMESPACE
  58320. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58321. const double rangeMin,
  58322. const double rangeMax,
  58323. const double interval,
  58324. const double skewFactor)
  58325. : PropertyComponent (name)
  58326. {
  58327. addAndMakeVisible (&slider);
  58328. slider.setRange (rangeMin, rangeMax, interval);
  58329. slider.setSkewFactor (skewFactor);
  58330. slider.setSliderStyle (Slider::LinearBar);
  58331. slider.addListener (this);
  58332. }
  58333. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58334. const String& name,
  58335. const double rangeMin,
  58336. const double rangeMax,
  58337. const double interval,
  58338. const double skewFactor)
  58339. : PropertyComponent (name)
  58340. {
  58341. addAndMakeVisible (&slider);
  58342. slider.setRange (rangeMin, rangeMax, interval);
  58343. slider.setSkewFactor (skewFactor);
  58344. slider.setSliderStyle (Slider::LinearBar);
  58345. slider.getValueObject().referTo (valueToControl);
  58346. }
  58347. SliderPropertyComponent::~SliderPropertyComponent()
  58348. {
  58349. }
  58350. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58351. {
  58352. }
  58353. double SliderPropertyComponent::getValue() const
  58354. {
  58355. return slider.getValue();
  58356. }
  58357. void SliderPropertyComponent::refresh()
  58358. {
  58359. slider.setValue (getValue(), false);
  58360. }
  58361. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58362. {
  58363. if (getValue() != slider.getValue())
  58364. setValue (slider.getValue());
  58365. }
  58366. END_JUCE_NAMESPACE
  58367. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58368. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58369. BEGIN_JUCE_NAMESPACE
  58370. class TextPropLabel : public Label
  58371. {
  58372. public:
  58373. TextPropLabel (TextPropertyComponent& owner_,
  58374. const int maxChars_, const bool isMultiline_)
  58375. : Label (String::empty, String::empty),
  58376. owner (owner_),
  58377. maxChars (maxChars_),
  58378. isMultiline (isMultiline_)
  58379. {
  58380. setEditable (true, true, false);
  58381. setColour (backgroundColourId, Colours::white);
  58382. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58383. }
  58384. TextEditor* createEditorComponent()
  58385. {
  58386. TextEditor* const textEditor = Label::createEditorComponent();
  58387. textEditor->setInputRestrictions (maxChars);
  58388. if (isMultiline)
  58389. {
  58390. textEditor->setMultiLine (true, true);
  58391. textEditor->setReturnKeyStartsNewLine (true);
  58392. }
  58393. return textEditor;
  58394. }
  58395. void textWasEdited()
  58396. {
  58397. owner.textWasEdited();
  58398. }
  58399. private:
  58400. TextPropertyComponent& owner;
  58401. int maxChars;
  58402. bool isMultiline;
  58403. };
  58404. TextPropertyComponent::TextPropertyComponent (const String& name,
  58405. const int maxNumChars,
  58406. const bool isMultiLine)
  58407. : PropertyComponent (name)
  58408. {
  58409. createEditor (maxNumChars, isMultiLine);
  58410. }
  58411. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58412. const String& name,
  58413. const int maxNumChars,
  58414. const bool isMultiLine)
  58415. : PropertyComponent (name)
  58416. {
  58417. createEditor (maxNumChars, isMultiLine);
  58418. textEditor->getTextValue().referTo (valueToControl);
  58419. }
  58420. TextPropertyComponent::~TextPropertyComponent()
  58421. {
  58422. }
  58423. void TextPropertyComponent::setText (const String& newText)
  58424. {
  58425. textEditor->setText (newText, true);
  58426. }
  58427. const String TextPropertyComponent::getText() const
  58428. {
  58429. return textEditor->getText();
  58430. }
  58431. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58432. {
  58433. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58434. if (isMultiLine)
  58435. {
  58436. textEditor->setJustificationType (Justification::topLeft);
  58437. preferredHeight = 120;
  58438. }
  58439. }
  58440. void TextPropertyComponent::refresh()
  58441. {
  58442. textEditor->setText (getText(), false);
  58443. }
  58444. void TextPropertyComponent::textWasEdited()
  58445. {
  58446. const String newText (textEditor->getText());
  58447. if (getText() != newText)
  58448. setText (newText);
  58449. }
  58450. END_JUCE_NAMESPACE
  58451. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58452. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58453. BEGIN_JUCE_NAMESPACE
  58454. class SimpleDeviceManagerInputLevelMeter : public Component,
  58455. public Timer
  58456. {
  58457. public:
  58458. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58459. : manager (manager_),
  58460. level (0)
  58461. {
  58462. startTimer (50);
  58463. manager->enableInputLevelMeasurement (true);
  58464. }
  58465. ~SimpleDeviceManagerInputLevelMeter()
  58466. {
  58467. manager->enableInputLevelMeasurement (false);
  58468. }
  58469. void timerCallback()
  58470. {
  58471. const float newLevel = (float) manager->getCurrentInputLevel();
  58472. if (std::abs (level - newLevel) > 0.005f)
  58473. {
  58474. level = newLevel;
  58475. repaint();
  58476. }
  58477. }
  58478. void paint (Graphics& g)
  58479. {
  58480. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58481. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58482. }
  58483. private:
  58484. AudioDeviceManager* const manager;
  58485. float level;
  58486. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58487. };
  58488. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58489. public ListBoxModel
  58490. {
  58491. public:
  58492. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58493. const String& noItemsMessage_,
  58494. const int minNumber_,
  58495. const int maxNumber_)
  58496. : ListBox (String::empty, 0),
  58497. deviceManager (deviceManager_),
  58498. noItemsMessage (noItemsMessage_),
  58499. minNumber (minNumber_),
  58500. maxNumber (maxNumber_)
  58501. {
  58502. items = MidiInput::getDevices();
  58503. setModel (this);
  58504. setOutlineThickness (1);
  58505. }
  58506. ~MidiInputSelectorComponentListBox()
  58507. {
  58508. }
  58509. int getNumRows()
  58510. {
  58511. return items.size();
  58512. }
  58513. void paintListBoxItem (int row,
  58514. Graphics& g,
  58515. int width, int height,
  58516. bool rowIsSelected)
  58517. {
  58518. if (((unsigned int) row) < (unsigned int) items.size())
  58519. {
  58520. if (rowIsSelected)
  58521. g.fillAll (findColour (TextEditor::highlightColourId)
  58522. .withMultipliedAlpha (0.3f));
  58523. const String item (items [row]);
  58524. bool enabled = deviceManager.isMidiInputEnabled (item);
  58525. const int x = getTickX();
  58526. const float tickW = height * 0.75f;
  58527. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58528. enabled, true, true, false);
  58529. g.setFont (height * 0.6f);
  58530. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58531. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58532. }
  58533. }
  58534. void listBoxItemClicked (int row, const MouseEvent& e)
  58535. {
  58536. selectRow (row);
  58537. if (e.x < getTickX())
  58538. flipEnablement (row);
  58539. }
  58540. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58541. {
  58542. flipEnablement (row);
  58543. }
  58544. void returnKeyPressed (int row)
  58545. {
  58546. flipEnablement (row);
  58547. }
  58548. void paint (Graphics& g)
  58549. {
  58550. ListBox::paint (g);
  58551. if (items.size() == 0)
  58552. {
  58553. g.setColour (Colours::grey);
  58554. g.setFont (13.0f);
  58555. g.drawText (noItemsMessage,
  58556. 0, 0, getWidth(), getHeight() / 2,
  58557. Justification::centred, true);
  58558. }
  58559. }
  58560. int getBestHeight (const int preferredHeight)
  58561. {
  58562. const int extra = getOutlineThickness() * 2;
  58563. return jmax (getRowHeight() * 2 + extra,
  58564. jmin (getRowHeight() * getNumRows() + extra,
  58565. preferredHeight));
  58566. }
  58567. private:
  58568. AudioDeviceManager& deviceManager;
  58569. const String noItemsMessage;
  58570. StringArray items;
  58571. int minNumber, maxNumber;
  58572. void flipEnablement (const int row)
  58573. {
  58574. if (((unsigned int) row) < (unsigned int) items.size())
  58575. {
  58576. const String item (items [row]);
  58577. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58578. }
  58579. }
  58580. int getTickX() const
  58581. {
  58582. return getRowHeight() + 5;
  58583. }
  58584. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58585. };
  58586. class AudioDeviceSettingsPanel : public Component,
  58587. public ChangeListener,
  58588. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58589. public ButtonListener
  58590. {
  58591. public:
  58592. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58593. AudioIODeviceType::DeviceSetupDetails& setup_,
  58594. const bool hideAdvancedOptionsWithButton)
  58595. : type (type_),
  58596. setup (setup_)
  58597. {
  58598. if (hideAdvancedOptionsWithButton)
  58599. {
  58600. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58601. showAdvancedSettingsButton->addButtonListener (this);
  58602. }
  58603. type->scanForDevices();
  58604. setup.manager->addChangeListener (this);
  58605. changeListenerCallback (0);
  58606. }
  58607. ~AudioDeviceSettingsPanel()
  58608. {
  58609. setup.manager->removeChangeListener (this);
  58610. }
  58611. void resized()
  58612. {
  58613. const int lx = proportionOfWidth (0.35f);
  58614. const int w = proportionOfWidth (0.4f);
  58615. const int h = 24;
  58616. const int space = 6;
  58617. const int dh = h + space;
  58618. int y = 0;
  58619. if (outputDeviceDropDown != 0)
  58620. {
  58621. outputDeviceDropDown->setBounds (lx, y, w, h);
  58622. if (testButton != 0)
  58623. testButton->setBounds (proportionOfWidth (0.77f),
  58624. outputDeviceDropDown->getY(),
  58625. proportionOfWidth (0.18f),
  58626. h);
  58627. y += dh;
  58628. }
  58629. if (inputDeviceDropDown != 0)
  58630. {
  58631. inputDeviceDropDown->setBounds (lx, y, w, h);
  58632. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58633. inputDeviceDropDown->getY(),
  58634. proportionOfWidth (0.18f),
  58635. h);
  58636. y += dh;
  58637. }
  58638. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58639. if (outputChanList != 0)
  58640. {
  58641. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58642. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58643. y += bh + space;
  58644. }
  58645. if (inputChanList != 0)
  58646. {
  58647. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58648. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58649. y += bh + space;
  58650. }
  58651. y += space * 2;
  58652. if (showAdvancedSettingsButton != 0)
  58653. {
  58654. showAdvancedSettingsButton->changeWidthToFitText (h);
  58655. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58656. }
  58657. if (sampleRateDropDown != 0)
  58658. {
  58659. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58660. || ! showAdvancedSettingsButton->isVisible());
  58661. sampleRateDropDown->setBounds (lx, y, w, h);
  58662. y += dh;
  58663. }
  58664. if (bufferSizeDropDown != 0)
  58665. {
  58666. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58667. || ! showAdvancedSettingsButton->isVisible());
  58668. bufferSizeDropDown->setBounds (lx, y, w, h);
  58669. y += dh;
  58670. }
  58671. if (showUIButton != 0)
  58672. {
  58673. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58674. || ! showAdvancedSettingsButton->isVisible());
  58675. showUIButton->changeWidthToFitText (h);
  58676. showUIButton->setTopLeftPosition (lx, y);
  58677. }
  58678. }
  58679. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58680. {
  58681. if (comboBoxThatHasChanged == 0)
  58682. return;
  58683. AudioDeviceManager::AudioDeviceSetup config;
  58684. setup.manager->getAudioDeviceSetup (config);
  58685. String error;
  58686. if (comboBoxThatHasChanged == outputDeviceDropDown
  58687. || comboBoxThatHasChanged == inputDeviceDropDown)
  58688. {
  58689. if (outputDeviceDropDown != 0)
  58690. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58691. : outputDeviceDropDown->getText();
  58692. if (inputDeviceDropDown != 0)
  58693. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58694. : inputDeviceDropDown->getText();
  58695. if (! type->hasSeparateInputsAndOutputs())
  58696. config.inputDeviceName = config.outputDeviceName;
  58697. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58698. config.useDefaultInputChannels = true;
  58699. else
  58700. config.useDefaultOutputChannels = true;
  58701. error = setup.manager->setAudioDeviceSetup (config, true);
  58702. showCorrectDeviceName (inputDeviceDropDown, true);
  58703. showCorrectDeviceName (outputDeviceDropDown, false);
  58704. updateControlPanelButton();
  58705. resized();
  58706. }
  58707. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58708. {
  58709. if (sampleRateDropDown->getSelectedId() > 0)
  58710. {
  58711. config.sampleRate = sampleRateDropDown->getSelectedId();
  58712. error = setup.manager->setAudioDeviceSetup (config, true);
  58713. }
  58714. }
  58715. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58716. {
  58717. if (bufferSizeDropDown->getSelectedId() > 0)
  58718. {
  58719. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58720. error = setup.manager->setAudioDeviceSetup (config, true);
  58721. }
  58722. }
  58723. if (error.isNotEmpty())
  58724. {
  58725. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58726. "Error when trying to open audio device!",
  58727. error);
  58728. }
  58729. }
  58730. void buttonClicked (Button* button)
  58731. {
  58732. if (button == showAdvancedSettingsButton)
  58733. {
  58734. showAdvancedSettingsButton->setVisible (false);
  58735. resized();
  58736. }
  58737. else if (button == showUIButton)
  58738. {
  58739. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58740. if (device != 0 && device->showControlPanel())
  58741. {
  58742. setup.manager->closeAudioDevice();
  58743. setup.manager->restartLastAudioDevice();
  58744. getTopLevelComponent()->toFront (true);
  58745. }
  58746. }
  58747. else if (button == testButton && testButton != 0)
  58748. {
  58749. setup.manager->playTestSound();
  58750. }
  58751. }
  58752. void updateControlPanelButton()
  58753. {
  58754. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58755. showUIButton = 0;
  58756. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58757. {
  58758. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58759. TRANS ("opens the device's own control panel")));
  58760. showUIButton->addButtonListener (this);
  58761. }
  58762. resized();
  58763. }
  58764. void changeListenerCallback (ChangeBroadcaster*)
  58765. {
  58766. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58767. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58768. {
  58769. if (outputDeviceDropDown == 0)
  58770. {
  58771. outputDeviceDropDown = new ComboBox (String::empty);
  58772. outputDeviceDropDown->addListener (this);
  58773. addAndMakeVisible (outputDeviceDropDown);
  58774. outputDeviceLabel = new Label (String::empty,
  58775. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58776. : TRANS ("device:"));
  58777. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58778. if (setup.maxNumOutputChannels > 0)
  58779. {
  58780. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58781. testButton->addButtonListener (this);
  58782. }
  58783. }
  58784. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58785. }
  58786. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58787. {
  58788. if (inputDeviceDropDown == 0)
  58789. {
  58790. inputDeviceDropDown = new ComboBox (String::empty);
  58791. inputDeviceDropDown->addListener (this);
  58792. addAndMakeVisible (inputDeviceDropDown);
  58793. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58794. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58795. addAndMakeVisible (inputLevelMeter
  58796. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58797. }
  58798. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58799. }
  58800. updateControlPanelButton();
  58801. showCorrectDeviceName (inputDeviceDropDown, true);
  58802. showCorrectDeviceName (outputDeviceDropDown, false);
  58803. if (currentDevice != 0)
  58804. {
  58805. if (setup.maxNumOutputChannels > 0
  58806. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58807. {
  58808. if (outputChanList == 0)
  58809. {
  58810. addAndMakeVisible (outputChanList
  58811. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58812. TRANS ("(no audio output channels found)")));
  58813. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58814. outputChanLabel->attachToComponent (outputChanList, true);
  58815. }
  58816. outputChanList->refresh();
  58817. }
  58818. else
  58819. {
  58820. outputChanLabel = 0;
  58821. outputChanList = 0;
  58822. }
  58823. if (setup.maxNumInputChannels > 0
  58824. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58825. {
  58826. if (inputChanList == 0)
  58827. {
  58828. addAndMakeVisible (inputChanList
  58829. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58830. TRANS ("(no audio input channels found)")));
  58831. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58832. inputChanLabel->attachToComponent (inputChanList, true);
  58833. }
  58834. inputChanList->refresh();
  58835. }
  58836. else
  58837. {
  58838. inputChanLabel = 0;
  58839. inputChanList = 0;
  58840. }
  58841. // sample rate..
  58842. {
  58843. if (sampleRateDropDown == 0)
  58844. {
  58845. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58846. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58847. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58848. }
  58849. else
  58850. {
  58851. sampleRateDropDown->clear();
  58852. sampleRateDropDown->removeListener (this);
  58853. }
  58854. const int numRates = currentDevice->getNumSampleRates();
  58855. for (int i = 0; i < numRates; ++i)
  58856. {
  58857. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58858. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58859. }
  58860. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58861. sampleRateDropDown->addListener (this);
  58862. }
  58863. // buffer size
  58864. {
  58865. if (bufferSizeDropDown == 0)
  58866. {
  58867. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58868. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58869. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58870. }
  58871. else
  58872. {
  58873. bufferSizeDropDown->clear();
  58874. bufferSizeDropDown->removeListener (this);
  58875. }
  58876. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58877. double currentRate = currentDevice->getCurrentSampleRate();
  58878. if (currentRate == 0)
  58879. currentRate = 48000.0;
  58880. for (int i = 0; i < numBufferSizes; ++i)
  58881. {
  58882. const int bs = currentDevice->getBufferSizeSamples (i);
  58883. bufferSizeDropDown->addItem (String (bs)
  58884. + " samples ("
  58885. + String (bs * 1000.0 / currentRate, 1)
  58886. + " ms)",
  58887. bs);
  58888. }
  58889. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58890. bufferSizeDropDown->addListener (this);
  58891. }
  58892. }
  58893. else
  58894. {
  58895. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58896. sampleRateLabel = 0;
  58897. bufferSizeLabel = 0;
  58898. sampleRateDropDown = 0;
  58899. bufferSizeDropDown = 0;
  58900. if (outputDeviceDropDown != 0)
  58901. outputDeviceDropDown->setSelectedId (-1, true);
  58902. if (inputDeviceDropDown != 0)
  58903. inputDeviceDropDown->setSelectedId (-1, true);
  58904. }
  58905. resized();
  58906. setSize (getWidth(), getLowestY() + 4);
  58907. }
  58908. private:
  58909. AudioIODeviceType* const type;
  58910. const AudioIODeviceType::DeviceSetupDetails setup;
  58911. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58912. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58913. ScopedPointer<TextButton> testButton;
  58914. ScopedPointer<Component> inputLevelMeter;
  58915. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58916. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58917. {
  58918. if (box != 0)
  58919. {
  58920. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58921. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58922. box->setSelectedId (index + 1, true);
  58923. if (testButton != 0 && ! isInput)
  58924. testButton->setEnabled (index >= 0);
  58925. }
  58926. }
  58927. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58928. {
  58929. const StringArray devs (type->getDeviceNames (isInputs));
  58930. combo.clear (true);
  58931. for (int i = 0; i < devs.size(); ++i)
  58932. combo.addItem (devs[i], i + 1);
  58933. combo.addItem (TRANS("<< none >>"), -1);
  58934. combo.setSelectedId (-1, true);
  58935. }
  58936. int getLowestY() const
  58937. {
  58938. int y = 0;
  58939. for (int i = getNumChildComponents(); --i >= 0;)
  58940. y = jmax (y, getChildComponent (i)->getBottom());
  58941. return y;
  58942. }
  58943. public:
  58944. class ChannelSelectorListBox : public ListBox,
  58945. public ListBoxModel
  58946. {
  58947. public:
  58948. enum BoxType
  58949. {
  58950. audioInputType,
  58951. audioOutputType
  58952. };
  58953. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58954. const BoxType type_,
  58955. const String& noItemsMessage_)
  58956. : ListBox (String::empty, 0),
  58957. setup (setup_),
  58958. type (type_),
  58959. noItemsMessage (noItemsMessage_)
  58960. {
  58961. refresh();
  58962. setModel (this);
  58963. setOutlineThickness (1);
  58964. }
  58965. ~ChannelSelectorListBox()
  58966. {
  58967. }
  58968. void refresh()
  58969. {
  58970. items.clear();
  58971. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58972. if (currentDevice != 0)
  58973. {
  58974. if (type == audioInputType)
  58975. items = currentDevice->getInputChannelNames();
  58976. else if (type == audioOutputType)
  58977. items = currentDevice->getOutputChannelNames();
  58978. if (setup.useStereoPairs)
  58979. {
  58980. StringArray pairs;
  58981. for (int i = 0; i < items.size(); i += 2)
  58982. {
  58983. const String name (items[i]);
  58984. const String name2 (items[i + 1]);
  58985. String commonBit;
  58986. for (int j = 0; j < name.length(); ++j)
  58987. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58988. commonBit = name.substring (0, j);
  58989. // Make sure we only split the name at a space, because otherwise, things
  58990. // like "input 11" + "input 12" would become "input 11 + 2"
  58991. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58992. commonBit = commonBit.dropLastCharacters (1);
  58993. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58994. }
  58995. items = pairs;
  58996. }
  58997. }
  58998. updateContent();
  58999. repaint();
  59000. }
  59001. int getNumRows()
  59002. {
  59003. return items.size();
  59004. }
  59005. void paintListBoxItem (int row,
  59006. Graphics& g,
  59007. int width, int height,
  59008. bool rowIsSelected)
  59009. {
  59010. if (((unsigned int) row) < (unsigned int) items.size())
  59011. {
  59012. if (rowIsSelected)
  59013. g.fillAll (findColour (TextEditor::highlightColourId)
  59014. .withMultipliedAlpha (0.3f));
  59015. const String item (items [row]);
  59016. bool enabled = false;
  59017. AudioDeviceManager::AudioDeviceSetup config;
  59018. setup.manager->getAudioDeviceSetup (config);
  59019. if (setup.useStereoPairs)
  59020. {
  59021. if (type == audioInputType)
  59022. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59023. else if (type == audioOutputType)
  59024. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59025. }
  59026. else
  59027. {
  59028. if (type == audioInputType)
  59029. enabled = config.inputChannels [row];
  59030. else if (type == audioOutputType)
  59031. enabled = config.outputChannels [row];
  59032. }
  59033. const int x = getTickX();
  59034. const float tickW = height * 0.75f;
  59035. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59036. enabled, true, true, false);
  59037. g.setFont (height * 0.6f);
  59038. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59039. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59040. }
  59041. }
  59042. void listBoxItemClicked (int row, const MouseEvent& e)
  59043. {
  59044. selectRow (row);
  59045. if (e.x < getTickX())
  59046. flipEnablement (row);
  59047. }
  59048. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59049. {
  59050. flipEnablement (row);
  59051. }
  59052. void returnKeyPressed (int row)
  59053. {
  59054. flipEnablement (row);
  59055. }
  59056. void paint (Graphics& g)
  59057. {
  59058. ListBox::paint (g);
  59059. if (items.size() == 0)
  59060. {
  59061. g.setColour (Colours::grey);
  59062. g.setFont (13.0f);
  59063. g.drawText (noItemsMessage,
  59064. 0, 0, getWidth(), getHeight() / 2,
  59065. Justification::centred, true);
  59066. }
  59067. }
  59068. int getBestHeight (int maxHeight)
  59069. {
  59070. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59071. getNumRows())
  59072. + getOutlineThickness() * 2;
  59073. }
  59074. private:
  59075. const AudioIODeviceType::DeviceSetupDetails setup;
  59076. const BoxType type;
  59077. const String noItemsMessage;
  59078. StringArray items;
  59079. void flipEnablement (const int row)
  59080. {
  59081. jassert (type == audioInputType || type == audioOutputType);
  59082. if (((unsigned int) row) < (unsigned int) items.size())
  59083. {
  59084. AudioDeviceManager::AudioDeviceSetup config;
  59085. setup.manager->getAudioDeviceSetup (config);
  59086. if (setup.useStereoPairs)
  59087. {
  59088. BigInteger bits;
  59089. BigInteger& original = (type == audioInputType ? config.inputChannels
  59090. : config.outputChannels);
  59091. int i;
  59092. for (i = 0; i < 256; i += 2)
  59093. bits.setBit (i / 2, original [i] || original [i + 1]);
  59094. if (type == audioInputType)
  59095. {
  59096. config.useDefaultInputChannels = false;
  59097. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59098. }
  59099. else
  59100. {
  59101. config.useDefaultOutputChannels = false;
  59102. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59103. }
  59104. for (i = 0; i < 256; ++i)
  59105. original.setBit (i, bits [i / 2]);
  59106. }
  59107. else
  59108. {
  59109. if (type == audioInputType)
  59110. {
  59111. config.useDefaultInputChannels = false;
  59112. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59113. }
  59114. else
  59115. {
  59116. config.useDefaultOutputChannels = false;
  59117. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59118. }
  59119. }
  59120. String error (setup.manager->setAudioDeviceSetup (config, true));
  59121. if (! error.isEmpty())
  59122. {
  59123. //xxx
  59124. }
  59125. }
  59126. }
  59127. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59128. {
  59129. const int numActive = chans.countNumberOfSetBits();
  59130. if (chans [index])
  59131. {
  59132. if (numActive > minNumber)
  59133. chans.setBit (index, false);
  59134. }
  59135. else
  59136. {
  59137. if (numActive >= maxNumber)
  59138. {
  59139. const int firstActiveChan = chans.findNextSetBit();
  59140. chans.setBit (index > firstActiveChan
  59141. ? firstActiveChan : chans.getHighestBit(),
  59142. false);
  59143. }
  59144. chans.setBit (index, true);
  59145. }
  59146. }
  59147. int getTickX() const
  59148. {
  59149. return getRowHeight() + 5;
  59150. }
  59151. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  59152. };
  59153. private:
  59154. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59155. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  59156. };
  59157. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59158. const int minInputChannels_,
  59159. const int maxInputChannels_,
  59160. const int minOutputChannels_,
  59161. const int maxOutputChannels_,
  59162. const bool showMidiInputOptions,
  59163. const bool showMidiOutputSelector,
  59164. const bool showChannelsAsStereoPairs_,
  59165. const bool hideAdvancedOptionsWithButton_)
  59166. : deviceManager (deviceManager_),
  59167. deviceTypeDropDown (0),
  59168. deviceTypeDropDownLabel (0),
  59169. minOutputChannels (minOutputChannels_),
  59170. maxOutputChannels (maxOutputChannels_),
  59171. minInputChannels (minInputChannels_),
  59172. maxInputChannels (maxInputChannels_),
  59173. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59174. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59175. {
  59176. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59177. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59178. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59179. {
  59180. deviceTypeDropDown = new ComboBox (String::empty);
  59181. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59182. {
  59183. deviceTypeDropDown
  59184. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59185. i + 1);
  59186. }
  59187. addAndMakeVisible (deviceTypeDropDown);
  59188. deviceTypeDropDown->addListener (this);
  59189. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59190. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59191. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59192. }
  59193. if (showMidiInputOptions)
  59194. {
  59195. addAndMakeVisible (midiInputsList
  59196. = new MidiInputSelectorComponentListBox (deviceManager,
  59197. TRANS("(no midi inputs available)"),
  59198. 0, 0));
  59199. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59200. midiInputsLabel->setJustificationType (Justification::topRight);
  59201. midiInputsLabel->attachToComponent (midiInputsList, true);
  59202. }
  59203. else
  59204. {
  59205. midiInputsList = 0;
  59206. midiInputsLabel = 0;
  59207. }
  59208. if (showMidiOutputSelector)
  59209. {
  59210. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59211. midiOutputSelector->addListener (this);
  59212. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59213. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59214. }
  59215. else
  59216. {
  59217. midiOutputSelector = 0;
  59218. midiOutputLabel = 0;
  59219. }
  59220. deviceManager_.addChangeListener (this);
  59221. changeListenerCallback (0);
  59222. }
  59223. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59224. {
  59225. deviceManager.removeChangeListener (this);
  59226. }
  59227. void AudioDeviceSelectorComponent::resized()
  59228. {
  59229. const int lx = proportionOfWidth (0.35f);
  59230. const int w = proportionOfWidth (0.4f);
  59231. const int h = 24;
  59232. const int space = 6;
  59233. const int dh = h + space;
  59234. int y = 15;
  59235. if (deviceTypeDropDown != 0)
  59236. {
  59237. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59238. y += dh + space * 2;
  59239. }
  59240. if (audioDeviceSettingsComp != 0)
  59241. {
  59242. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59243. y += audioDeviceSettingsComp->getHeight() + space;
  59244. }
  59245. if (midiInputsList != 0)
  59246. {
  59247. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59248. midiInputsList->setBounds (lx, y, w, bh);
  59249. y += bh + space;
  59250. }
  59251. if (midiOutputSelector != 0)
  59252. midiOutputSelector->setBounds (lx, y, w, h);
  59253. }
  59254. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59255. {
  59256. if (child == audioDeviceSettingsComp)
  59257. resized();
  59258. }
  59259. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59260. {
  59261. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59262. if (device != 0 && device->hasControlPanel())
  59263. {
  59264. if (device->showControlPanel())
  59265. deviceManager.restartLastAudioDevice();
  59266. getTopLevelComponent()->toFront (true);
  59267. }
  59268. }
  59269. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59270. {
  59271. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59272. {
  59273. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59274. if (type != 0)
  59275. {
  59276. audioDeviceSettingsComp = 0;
  59277. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59278. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59279. }
  59280. }
  59281. else if (comboBoxThatHasChanged == midiOutputSelector)
  59282. {
  59283. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59284. }
  59285. }
  59286. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59287. {
  59288. if (deviceTypeDropDown != 0)
  59289. {
  59290. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59291. }
  59292. if (audioDeviceSettingsComp == 0
  59293. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59294. {
  59295. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59296. audioDeviceSettingsComp = 0;
  59297. AudioIODeviceType* const type
  59298. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59299. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59300. if (type != 0)
  59301. {
  59302. AudioIODeviceType::DeviceSetupDetails details;
  59303. details.manager = &deviceManager;
  59304. details.minNumInputChannels = minInputChannels;
  59305. details.maxNumInputChannels = maxInputChannels;
  59306. details.minNumOutputChannels = minOutputChannels;
  59307. details.maxNumOutputChannels = maxOutputChannels;
  59308. details.useStereoPairs = showChannelsAsStereoPairs;
  59309. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59310. if (audioDeviceSettingsComp != 0)
  59311. {
  59312. addAndMakeVisible (audioDeviceSettingsComp);
  59313. audioDeviceSettingsComp->resized();
  59314. }
  59315. }
  59316. }
  59317. if (midiInputsList != 0)
  59318. {
  59319. midiInputsList->updateContent();
  59320. midiInputsList->repaint();
  59321. }
  59322. if (midiOutputSelector != 0)
  59323. {
  59324. midiOutputSelector->clear();
  59325. const StringArray midiOuts (MidiOutput::getDevices());
  59326. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59327. midiOutputSelector->addSeparator();
  59328. for (int i = 0; i < midiOuts.size(); ++i)
  59329. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59330. int current = -1;
  59331. if (deviceManager.getDefaultMidiOutput() != 0)
  59332. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59333. midiOutputSelector->setSelectedId (current, true);
  59334. }
  59335. resized();
  59336. }
  59337. END_JUCE_NAMESPACE
  59338. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59339. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59340. BEGIN_JUCE_NAMESPACE
  59341. BubbleComponent::BubbleComponent()
  59342. : side (0),
  59343. allowablePlacements (above | below | left | right),
  59344. arrowTipX (0.0f),
  59345. arrowTipY (0.0f)
  59346. {
  59347. setInterceptsMouseClicks (false, false);
  59348. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59349. setComponentEffect (&shadow);
  59350. }
  59351. BubbleComponent::~BubbleComponent()
  59352. {
  59353. }
  59354. void BubbleComponent::paint (Graphics& g)
  59355. {
  59356. int x = content.getX();
  59357. int y = content.getY();
  59358. int w = content.getWidth();
  59359. int h = content.getHeight();
  59360. int cw, ch;
  59361. getContentSize (cw, ch);
  59362. if (side == 3)
  59363. x += w - cw;
  59364. else if (side != 1)
  59365. x += (w - cw) / 2;
  59366. w = cw;
  59367. if (side == 2)
  59368. y += h - ch;
  59369. else if (side != 0)
  59370. y += (h - ch) / 2;
  59371. h = ch;
  59372. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59373. (float) x, (float) y,
  59374. (float) w, (float) h);
  59375. const int cx = x + (w - cw) / 2;
  59376. const int cy = y + (h - ch) / 2;
  59377. const int indent = 3;
  59378. g.setOrigin (cx + indent, cy + indent);
  59379. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59380. paintContent (g, cw - indent * 2, ch - indent * 2);
  59381. }
  59382. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59383. {
  59384. allowablePlacements = newPlacement;
  59385. }
  59386. void BubbleComponent::setPosition (Component* componentToPointTo)
  59387. {
  59388. jassert (componentToPointTo != 0);
  59389. Point<int> pos;
  59390. if (getParentComponent() != 0)
  59391. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59392. else
  59393. pos = componentToPointTo->localPointToGlobal (pos);
  59394. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59395. }
  59396. void BubbleComponent::setPosition (const int arrowTipX_,
  59397. const int arrowTipY_)
  59398. {
  59399. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59400. }
  59401. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59402. {
  59403. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59404. : getParentMonitorArea());
  59405. int x = 0;
  59406. int y = 0;
  59407. int w = 150;
  59408. int h = 30;
  59409. getContentSize (w, h);
  59410. w += 30;
  59411. h += 30;
  59412. const float edgeIndent = 2.0f;
  59413. const int arrowLength = jmin (10, h / 3, w / 3);
  59414. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59415. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59416. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59417. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59418. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59419. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59420. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59421. {
  59422. spaceLeft = spaceRight = 0;
  59423. }
  59424. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59425. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59426. {
  59427. spaceAbove = spaceBelow = 0;
  59428. }
  59429. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59430. {
  59431. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59432. arrowTipX = w * 0.5f;
  59433. content.setSize (w, h - arrowLength);
  59434. if (spaceAbove >= spaceBelow)
  59435. {
  59436. // above
  59437. y = rectangleToPointTo.getY() - h;
  59438. content.setPosition (0, 0);
  59439. arrowTipY = h - edgeIndent;
  59440. side = 2;
  59441. }
  59442. else
  59443. {
  59444. // below
  59445. y = rectangleToPointTo.getBottom();
  59446. content.setPosition (0, arrowLength);
  59447. arrowTipY = edgeIndent;
  59448. side = 0;
  59449. }
  59450. }
  59451. else
  59452. {
  59453. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59454. arrowTipY = h * 0.5f;
  59455. content.setSize (w - arrowLength, h);
  59456. if (spaceLeft > spaceRight)
  59457. {
  59458. // on the left
  59459. x = rectangleToPointTo.getX() - w;
  59460. content.setPosition (0, 0);
  59461. arrowTipX = w - edgeIndent;
  59462. side = 3;
  59463. }
  59464. else
  59465. {
  59466. // on the right
  59467. x = rectangleToPointTo.getRight();
  59468. content.setPosition (arrowLength, 0);
  59469. arrowTipX = edgeIndent;
  59470. side = 1;
  59471. }
  59472. }
  59473. setBounds (x, y, w, h);
  59474. }
  59475. END_JUCE_NAMESPACE
  59476. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59477. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59478. BEGIN_JUCE_NAMESPACE
  59479. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59480. : fadeOutLength (fadeOutLengthMs),
  59481. deleteAfterUse (false)
  59482. {
  59483. }
  59484. BubbleMessageComponent::~BubbleMessageComponent()
  59485. {
  59486. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59487. }
  59488. void BubbleMessageComponent::showAt (int x, int y,
  59489. const String& text,
  59490. const int numMillisecondsBeforeRemoving,
  59491. const bool removeWhenMouseClicked,
  59492. const bool deleteSelfAfterUse)
  59493. {
  59494. textLayout.clear();
  59495. textLayout.setText (text, Font (14.0f));
  59496. textLayout.layout (256, Justification::centredLeft, true);
  59497. setPosition (x, y);
  59498. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59499. }
  59500. void BubbleMessageComponent::showAt (Component* const component,
  59501. const String& text,
  59502. const int numMillisecondsBeforeRemoving,
  59503. const bool removeWhenMouseClicked,
  59504. const bool deleteSelfAfterUse)
  59505. {
  59506. textLayout.clear();
  59507. textLayout.setText (text, Font (14.0f));
  59508. textLayout.layout (256, Justification::centredLeft, true);
  59509. setPosition (component);
  59510. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59511. }
  59512. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59513. const bool removeWhenMouseClicked,
  59514. const bool deleteSelfAfterUse)
  59515. {
  59516. setVisible (true);
  59517. deleteAfterUse = deleteSelfAfterUse;
  59518. if (numMillisecondsBeforeRemoving > 0)
  59519. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59520. else
  59521. expiryTime = 0;
  59522. startTimer (77);
  59523. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59524. if (! (removeWhenMouseClicked && isShowing()))
  59525. mouseClickCounter += 0xfffff;
  59526. repaint();
  59527. }
  59528. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59529. {
  59530. w = textLayout.getWidth() + 16;
  59531. h = textLayout.getHeight() + 16;
  59532. }
  59533. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59534. {
  59535. g.setColour (findColour (TooltipWindow::textColourId));
  59536. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59537. }
  59538. void BubbleMessageComponent::timerCallback()
  59539. {
  59540. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59541. {
  59542. stopTimer();
  59543. setVisible (false);
  59544. if (deleteAfterUse)
  59545. delete this;
  59546. }
  59547. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59548. {
  59549. stopTimer();
  59550. if (deleteAfterUse)
  59551. delete this;
  59552. else
  59553. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59554. }
  59555. }
  59556. END_JUCE_NAMESPACE
  59557. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59558. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59559. BEGIN_JUCE_NAMESPACE
  59560. class ColourComponentSlider : public Slider
  59561. {
  59562. public:
  59563. ColourComponentSlider (const String& name)
  59564. : Slider (name)
  59565. {
  59566. setRange (0.0, 255.0, 1.0);
  59567. }
  59568. const String getTextFromValue (double value)
  59569. {
  59570. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59571. }
  59572. double getValueFromText (const String& text)
  59573. {
  59574. return (double) text.getHexValue32();
  59575. }
  59576. private:
  59577. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59578. };
  59579. class ColourSpaceMarker : public Component
  59580. {
  59581. public:
  59582. ColourSpaceMarker()
  59583. {
  59584. setInterceptsMouseClicks (false, false);
  59585. }
  59586. void paint (Graphics& g)
  59587. {
  59588. g.setColour (Colour::greyLevel (0.1f));
  59589. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59590. g.setColour (Colour::greyLevel (0.9f));
  59591. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59592. }
  59593. private:
  59594. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59595. };
  59596. class ColourSelector::ColourSpaceView : public Component
  59597. {
  59598. public:
  59599. ColourSpaceView (ColourSelector& owner_,
  59600. float& h_, float& s_, float& v_,
  59601. const int edgeSize)
  59602. : owner (owner_),
  59603. h (h_), s (s_), v (v_),
  59604. lastHue (0.0f),
  59605. edge (edgeSize)
  59606. {
  59607. addAndMakeVisible (&marker);
  59608. setMouseCursor (MouseCursor::CrosshairCursor);
  59609. }
  59610. void paint (Graphics& g)
  59611. {
  59612. if (colours.isNull())
  59613. {
  59614. const int width = getWidth() / 2;
  59615. const int height = getHeight() / 2;
  59616. colours = Image (Image::RGB, width, height, false);
  59617. Image::BitmapData pixels (colours, true);
  59618. for (int y = 0; y < height; ++y)
  59619. {
  59620. const float val = 1.0f - y / (float) height;
  59621. for (int x = 0; x < width; ++x)
  59622. {
  59623. const float sat = x / (float) width;
  59624. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59625. }
  59626. }
  59627. }
  59628. g.setOpacity (1.0f);
  59629. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59630. 0, 0, colours.getWidth(), colours.getHeight());
  59631. }
  59632. void mouseDown (const MouseEvent& e)
  59633. {
  59634. mouseDrag (e);
  59635. }
  59636. void mouseDrag (const MouseEvent& e)
  59637. {
  59638. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59639. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59640. owner.setSV (sat, val);
  59641. }
  59642. void updateIfNeeded()
  59643. {
  59644. if (lastHue != h)
  59645. {
  59646. lastHue = h;
  59647. colours = Image::null;
  59648. repaint();
  59649. }
  59650. updateMarker();
  59651. }
  59652. void resized()
  59653. {
  59654. colours = Image::null;
  59655. updateMarker();
  59656. }
  59657. private:
  59658. ColourSelector& owner;
  59659. float& h;
  59660. float& s;
  59661. float& v;
  59662. float lastHue;
  59663. ColourSpaceMarker marker;
  59664. const int edge;
  59665. Image colours;
  59666. void updateMarker()
  59667. {
  59668. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59669. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59670. edge * 2, edge * 2);
  59671. }
  59672. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59673. };
  59674. class HueSelectorMarker : public Component
  59675. {
  59676. public:
  59677. HueSelectorMarker()
  59678. {
  59679. setInterceptsMouseClicks (false, false);
  59680. }
  59681. void paint (Graphics& g)
  59682. {
  59683. Path p;
  59684. p.addTriangle (1.0f, 1.0f,
  59685. getWidth() * 0.3f, getHeight() * 0.5f,
  59686. 1.0f, getHeight() - 1.0f);
  59687. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59688. getWidth() * 0.7f, getHeight() * 0.5f,
  59689. getWidth() - 1.0f, getHeight() - 1.0f);
  59690. g.setColour (Colours::white.withAlpha (0.75f));
  59691. g.fillPath (p);
  59692. g.setColour (Colours::black.withAlpha (0.75f));
  59693. g.strokePath (p, PathStrokeType (1.2f));
  59694. }
  59695. private:
  59696. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59697. };
  59698. class ColourSelector::HueSelectorComp : public Component
  59699. {
  59700. public:
  59701. HueSelectorComp (ColourSelector& owner_,
  59702. float& h_, float& s_, float& v_,
  59703. const int edgeSize)
  59704. : owner (owner_),
  59705. h (h_), s (s_), v (v_),
  59706. lastHue (0.0f),
  59707. edge (edgeSize)
  59708. {
  59709. addAndMakeVisible (&marker);
  59710. }
  59711. void paint (Graphics& g)
  59712. {
  59713. const float yScale = 1.0f / (getHeight() - edge * 2);
  59714. const Rectangle<int> clip (g.getClipBounds());
  59715. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59716. {
  59717. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59718. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59719. }
  59720. }
  59721. void resized()
  59722. {
  59723. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59724. getWidth(), edge * 2);
  59725. }
  59726. void mouseDown (const MouseEvent& e)
  59727. {
  59728. mouseDrag (e);
  59729. }
  59730. void mouseDrag (const MouseEvent& e)
  59731. {
  59732. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59733. }
  59734. void updateIfNeeded()
  59735. {
  59736. resized();
  59737. }
  59738. private:
  59739. ColourSelector& owner;
  59740. float& h;
  59741. float& s;
  59742. float& v;
  59743. float lastHue;
  59744. HueSelectorMarker marker;
  59745. const int edge;
  59746. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  59747. };
  59748. class ColourSelector::SwatchComponent : public Component
  59749. {
  59750. public:
  59751. SwatchComponent (ColourSelector& owner_, int index_)
  59752. : owner (owner_), index (index_)
  59753. {
  59754. }
  59755. void paint (Graphics& g)
  59756. {
  59757. const Colour colour (owner.getSwatchColour (index));
  59758. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59759. Colour (0xffdddddd).overlaidWith (colour),
  59760. Colour (0xffffffff).overlaidWith (colour));
  59761. }
  59762. void mouseDown (const MouseEvent&)
  59763. {
  59764. PopupMenu m;
  59765. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59766. m.addSeparator();
  59767. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59768. const int r = m.showAt (this);
  59769. if (r == 1)
  59770. {
  59771. owner.setCurrentColour (owner.getSwatchColour (index));
  59772. }
  59773. else if (r == 2)
  59774. {
  59775. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  59776. {
  59777. owner.setSwatchColour (index, owner.getCurrentColour());
  59778. repaint();
  59779. }
  59780. }
  59781. }
  59782. private:
  59783. ColourSelector& owner;
  59784. const int index;
  59785. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  59786. };
  59787. ColourSelector::ColourSelector (const int flags_,
  59788. const int edgeGap_,
  59789. const int gapAroundColourSpaceComponent)
  59790. : colour (Colours::white),
  59791. flags (flags_),
  59792. edgeGap (edgeGap_)
  59793. {
  59794. // not much point having a selector with no components in it!
  59795. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59796. updateHSV();
  59797. if ((flags & showSliders) != 0)
  59798. {
  59799. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59800. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59801. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59802. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59803. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59804. for (int i = 4; --i >= 0;)
  59805. sliders[i]->addListener (this);
  59806. }
  59807. if ((flags & showColourspace) != 0)
  59808. {
  59809. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  59810. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  59811. }
  59812. update();
  59813. }
  59814. ColourSelector::~ColourSelector()
  59815. {
  59816. dispatchPendingMessages();
  59817. swatchComponents.clear();
  59818. }
  59819. const Colour ColourSelector::getCurrentColour() const
  59820. {
  59821. return ((flags & showAlphaChannel) != 0) ? colour
  59822. : colour.withAlpha ((uint8) 0xff);
  59823. }
  59824. void ColourSelector::setCurrentColour (const Colour& c)
  59825. {
  59826. if (c != colour)
  59827. {
  59828. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59829. updateHSV();
  59830. update();
  59831. }
  59832. }
  59833. void ColourSelector::setHue (float newH)
  59834. {
  59835. newH = jlimit (0.0f, 1.0f, newH);
  59836. if (h != newH)
  59837. {
  59838. h = newH;
  59839. colour = Colour (h, s, v, colour.getFloatAlpha());
  59840. update();
  59841. }
  59842. }
  59843. void ColourSelector::setSV (float newS, float newV)
  59844. {
  59845. newS = jlimit (0.0f, 1.0f, newS);
  59846. newV = jlimit (0.0f, 1.0f, newV);
  59847. if (s != newS || v != newV)
  59848. {
  59849. s = newS;
  59850. v = newV;
  59851. colour = Colour (h, s, v, colour.getFloatAlpha());
  59852. update();
  59853. }
  59854. }
  59855. void ColourSelector::updateHSV()
  59856. {
  59857. colour.getHSB (h, s, v);
  59858. }
  59859. void ColourSelector::update()
  59860. {
  59861. if (sliders[0] != 0)
  59862. {
  59863. sliders[0]->setValue ((int) colour.getRed());
  59864. sliders[1]->setValue ((int) colour.getGreen());
  59865. sliders[2]->setValue ((int) colour.getBlue());
  59866. sliders[3]->setValue ((int) colour.getAlpha());
  59867. }
  59868. if (colourSpace != 0)
  59869. {
  59870. colourSpace->updateIfNeeded();
  59871. hueSelector->updateIfNeeded();
  59872. }
  59873. if ((flags & showColourAtTop) != 0)
  59874. repaint (previewArea);
  59875. sendChangeMessage();
  59876. }
  59877. void ColourSelector::paint (Graphics& g)
  59878. {
  59879. g.fillAll (findColour (backgroundColourId));
  59880. if ((flags & showColourAtTop) != 0)
  59881. {
  59882. const Colour currentColour (getCurrentColour());
  59883. g.fillCheckerBoard (previewArea, 10, 10,
  59884. Colour (0xffdddddd).overlaidWith (currentColour),
  59885. Colour (0xffffffff).overlaidWith (currentColour));
  59886. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59887. g.setFont (14.0f, true);
  59888. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59889. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59890. Justification::centred, false);
  59891. }
  59892. if ((flags & showSliders) != 0)
  59893. {
  59894. g.setColour (findColour (labelTextColourId));
  59895. g.setFont (11.0f);
  59896. for (int i = 4; --i >= 0;)
  59897. {
  59898. if (sliders[i]->isVisible())
  59899. g.drawText (sliders[i]->getName() + ":",
  59900. 0, sliders[i]->getY(),
  59901. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59902. Justification::centredRight, false);
  59903. }
  59904. }
  59905. }
  59906. void ColourSelector::resized()
  59907. {
  59908. const int swatchesPerRow = 8;
  59909. const int swatchHeight = 22;
  59910. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59911. const int numSwatches = getNumSwatches();
  59912. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59913. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59914. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59915. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59916. int y = topSpace;
  59917. if ((flags & showColourspace) != 0)
  59918. {
  59919. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59920. colourSpace->setBounds (edgeGap, y,
  59921. getWidth() - hueWidth - edgeGap - 4,
  59922. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59923. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59924. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59925. colourSpace->getHeight());
  59926. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59927. }
  59928. if ((flags & showSliders) != 0)
  59929. {
  59930. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59931. for (int i = 0; i < numSliders; ++i)
  59932. {
  59933. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59934. proportionOfWidth (0.72f), sliderHeight - 2);
  59935. y += sliderHeight;
  59936. }
  59937. }
  59938. if (numSwatches > 0)
  59939. {
  59940. const int startX = 8;
  59941. const int xGap = 4;
  59942. const int yGap = 4;
  59943. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59944. y += edgeGap;
  59945. if (swatchComponents.size() != numSwatches)
  59946. {
  59947. swatchComponents.clear();
  59948. for (int i = 0; i < numSwatches; ++i)
  59949. {
  59950. SwatchComponent* const sc = new SwatchComponent (*this, i);
  59951. swatchComponents.add (sc);
  59952. addAndMakeVisible (sc);
  59953. }
  59954. }
  59955. int x = startX;
  59956. for (int i = 0; i < swatchComponents.size(); ++i)
  59957. {
  59958. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59959. sc->setBounds (x + xGap / 2,
  59960. y + yGap / 2,
  59961. swatchWidth - xGap,
  59962. swatchHeight - yGap);
  59963. if (((i + 1) % swatchesPerRow) == 0)
  59964. {
  59965. x = startX;
  59966. y += swatchHeight;
  59967. }
  59968. else
  59969. {
  59970. x += swatchWidth;
  59971. }
  59972. }
  59973. }
  59974. }
  59975. void ColourSelector::sliderValueChanged (Slider*)
  59976. {
  59977. if (sliders[0] != 0)
  59978. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59979. (uint8) sliders[1]->getValue(),
  59980. (uint8) sliders[2]->getValue(),
  59981. (uint8) sliders[3]->getValue()));
  59982. }
  59983. int ColourSelector::getNumSwatches() const
  59984. {
  59985. return 0;
  59986. }
  59987. const Colour ColourSelector::getSwatchColour (const int) const
  59988. {
  59989. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59990. return Colours::black;
  59991. }
  59992. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59993. {
  59994. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59995. }
  59996. END_JUCE_NAMESPACE
  59997. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59998. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59999. BEGIN_JUCE_NAMESPACE
  60000. class ShadowWindow : public Component
  60001. {
  60002. Component* owner;
  60003. Image shadowImageSections [12];
  60004. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60005. public:
  60006. ShadowWindow (Component* const owner_,
  60007. const int type_,
  60008. const Image shadowImageSections_ [12])
  60009. : owner (owner_),
  60010. type (type_)
  60011. {
  60012. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60013. shadowImageSections [i] = shadowImageSections_ [i];
  60014. setInterceptsMouseClicks (false, false);
  60015. if (owner_->isOnDesktop())
  60016. {
  60017. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60018. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60019. | ComponentPeer::windowIsTemporary
  60020. | ComponentPeer::windowIgnoresKeyPresses);
  60021. }
  60022. else if (owner_->getParentComponent() != 0)
  60023. {
  60024. owner_->getParentComponent()->addChildComponent (this);
  60025. }
  60026. }
  60027. ~ShadowWindow()
  60028. {
  60029. }
  60030. void paint (Graphics& g)
  60031. {
  60032. const Image& topLeft = shadowImageSections [type * 3];
  60033. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60034. const Image& filler = shadowImageSections [type * 3 + 2];
  60035. g.setOpacity (1.0f);
  60036. if (type < 2)
  60037. {
  60038. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60039. g.drawImage (topLeft,
  60040. 0, 0, topLeft.getWidth(), imH,
  60041. 0, 0, topLeft.getWidth(), imH);
  60042. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60043. g.drawImage (bottomRight,
  60044. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60045. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60046. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60047. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60048. }
  60049. else
  60050. {
  60051. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60052. g.drawImage (topLeft,
  60053. 0, 0, imW, topLeft.getHeight(),
  60054. 0, 0, imW, topLeft.getHeight());
  60055. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60056. g.drawImage (bottomRight,
  60057. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60058. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60059. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60060. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60061. }
  60062. }
  60063. void resized()
  60064. {
  60065. repaint(); // (needed for correct repainting)
  60066. }
  60067. private:
  60068. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  60069. };
  60070. DropShadower::DropShadower (const float alpha_,
  60071. const int xOffset_,
  60072. const int yOffset_,
  60073. const float blurRadius_)
  60074. : owner (0),
  60075. numShadows (0),
  60076. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60077. xOffset (xOffset_),
  60078. yOffset (yOffset_),
  60079. alpha (alpha_),
  60080. blurRadius (blurRadius_),
  60081. inDestructor (false),
  60082. reentrant (false)
  60083. {
  60084. }
  60085. DropShadower::~DropShadower()
  60086. {
  60087. if (owner != 0)
  60088. owner->removeComponentListener (this);
  60089. inDestructor = true;
  60090. deleteShadowWindows();
  60091. }
  60092. void DropShadower::deleteShadowWindows()
  60093. {
  60094. if (numShadows > 0)
  60095. {
  60096. int i;
  60097. for (i = numShadows; --i >= 0;)
  60098. delete shadowWindows[i];
  60099. numShadows = 0;
  60100. }
  60101. }
  60102. void DropShadower::setOwner (Component* componentToFollow)
  60103. {
  60104. if (componentToFollow != owner)
  60105. {
  60106. if (owner != 0)
  60107. owner->removeComponentListener (this);
  60108. // (the component can't be null)
  60109. jassert (componentToFollow != 0);
  60110. owner = componentToFollow;
  60111. jassert (owner != 0);
  60112. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60113. owner->addComponentListener (this);
  60114. updateShadows();
  60115. }
  60116. }
  60117. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60118. {
  60119. updateShadows();
  60120. }
  60121. void DropShadower::componentBroughtToFront (Component&)
  60122. {
  60123. bringShadowWindowsToFront();
  60124. }
  60125. void DropShadower::componentChildrenChanged (Component&)
  60126. {
  60127. }
  60128. void DropShadower::componentParentHierarchyChanged (Component&)
  60129. {
  60130. deleteShadowWindows();
  60131. updateShadows();
  60132. }
  60133. void DropShadower::componentVisibilityChanged (Component&)
  60134. {
  60135. updateShadows();
  60136. }
  60137. void DropShadower::updateShadows()
  60138. {
  60139. if (reentrant || inDestructor || (owner == 0))
  60140. return;
  60141. reentrant = true;
  60142. ComponentPeer* const nw = owner->getPeer();
  60143. const bool isOwnerVisible = owner->isVisible()
  60144. && (nw == 0 || ! nw->isMinimised());
  60145. const bool createShadowWindows = numShadows == 0
  60146. && owner->getWidth() > 0
  60147. && owner->getHeight() > 0
  60148. && isOwnerVisible
  60149. && (Desktop::canUseSemiTransparentWindows()
  60150. || owner->getParentComponent() != 0);
  60151. if (createShadowWindows)
  60152. {
  60153. // keep a cached version of the image to save doing the gaussian too often
  60154. String imageId;
  60155. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60156. const int hash = imageId.hashCode();
  60157. Image bigIm (ImageCache::getFromHashCode (hash));
  60158. if (bigIm.isNull())
  60159. {
  60160. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60161. Graphics bigG (bigIm);
  60162. bigG.setColour (Colours::black.withAlpha (alpha));
  60163. bigG.fillRect (shadowEdge + xOffset,
  60164. shadowEdge + yOffset,
  60165. bigIm.getWidth() - (shadowEdge * 2),
  60166. bigIm.getHeight() - (shadowEdge * 2));
  60167. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60168. blurKernel.createGaussianBlur (blurRadius);
  60169. blurKernel.applyToImage (bigIm, bigIm,
  60170. Rectangle<int> (xOffset, yOffset,
  60171. bigIm.getWidth(), bigIm.getHeight()));
  60172. ImageCache::addImageToCache (bigIm, hash);
  60173. }
  60174. const int iw = bigIm.getWidth();
  60175. const int ih = bigIm.getHeight();
  60176. const int shadowEdge2 = shadowEdge * 2;
  60177. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60178. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60179. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60180. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60181. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60182. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60183. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60184. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60185. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60186. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60187. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60188. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60189. for (int i = 0; i < 4; ++i)
  60190. {
  60191. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60192. ++numShadows;
  60193. }
  60194. }
  60195. if (numShadows > 0)
  60196. {
  60197. for (int i = numShadows; --i >= 0;)
  60198. {
  60199. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60200. shadowWindows[i]->setVisible (isOwnerVisible);
  60201. }
  60202. const int x = owner->getX();
  60203. const int y = owner->getY() - shadowEdge;
  60204. const int w = owner->getWidth();
  60205. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60206. shadowWindows[0]->setBounds (x - shadowEdge,
  60207. y,
  60208. shadowEdge,
  60209. h);
  60210. shadowWindows[1]->setBounds (x + w,
  60211. y,
  60212. shadowEdge,
  60213. h);
  60214. shadowWindows[2]->setBounds (x,
  60215. y,
  60216. w,
  60217. shadowEdge);
  60218. shadowWindows[3]->setBounds (x,
  60219. owner->getBottom(),
  60220. w,
  60221. shadowEdge);
  60222. }
  60223. reentrant = false;
  60224. if (createShadowWindows)
  60225. bringShadowWindowsToFront();
  60226. }
  60227. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60228. const int sx, const int sy)
  60229. {
  60230. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60231. Graphics g (shadowImageSections[num]);
  60232. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60233. }
  60234. void DropShadower::bringShadowWindowsToFront()
  60235. {
  60236. if (! (inDestructor || reentrant))
  60237. {
  60238. updateShadows();
  60239. reentrant = true;
  60240. for (int i = numShadows; --i >= 0;)
  60241. shadowWindows[i]->toBehind (owner);
  60242. reentrant = false;
  60243. }
  60244. }
  60245. END_JUCE_NAMESPACE
  60246. /*** End of inlined file: juce_DropShadower.cpp ***/
  60247. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60248. BEGIN_JUCE_NAMESPACE
  60249. class MagnifyingPeer : public ComponentPeer
  60250. {
  60251. public:
  60252. MagnifyingPeer (Component* const component_,
  60253. MagnifierComponent* const magnifierComp_)
  60254. : ComponentPeer (component_, 0),
  60255. magnifierComp (magnifierComp_)
  60256. {
  60257. }
  60258. ~MagnifyingPeer()
  60259. {
  60260. }
  60261. void* getNativeHandle() const { return 0; }
  60262. void setVisible (bool) {}
  60263. void setTitle (const String&) {}
  60264. void setPosition (int, int) {}
  60265. void setSize (int, int) {}
  60266. void setBounds (int, int, int, int, bool) {}
  60267. void setMinimised (bool) {}
  60268. void setAlpha (float /*newAlpha*/) {}
  60269. bool isMinimised() const { return false; }
  60270. void setFullScreen (bool) {}
  60271. bool isFullScreen() const { return false; }
  60272. const BorderSize getFrameSize() const { return BorderSize (0); }
  60273. bool setAlwaysOnTop (bool) { return true; }
  60274. void toFront (bool) {}
  60275. void toBehind (ComponentPeer*) {}
  60276. void setIcon (const Image&) {}
  60277. bool isFocused() const
  60278. {
  60279. return magnifierComp->hasKeyboardFocus (true);
  60280. }
  60281. void grabFocus()
  60282. {
  60283. ComponentPeer* peer = magnifierComp->getPeer();
  60284. if (peer != 0)
  60285. peer->grabFocus();
  60286. }
  60287. void textInputRequired (const Point<int>& position)
  60288. {
  60289. ComponentPeer* peer = magnifierComp->getPeer();
  60290. if (peer != 0)
  60291. peer->textInputRequired (position);
  60292. }
  60293. const Rectangle<int> getBounds() const
  60294. {
  60295. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60296. component->getWidth(), component->getHeight());
  60297. }
  60298. const Point<int> getScreenPosition() const
  60299. {
  60300. return magnifierComp->getScreenPosition();
  60301. }
  60302. const Point<int> localToGlobal (const Point<int>& relativePosition)
  60303. {
  60304. const double zoom = magnifierComp->getScaleFactor();
  60305. return magnifierComp->localPointToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60306. roundToInt (relativePosition.getY() * zoom)));
  60307. }
  60308. const Point<int> globalToLocal (const Point<int>& screenPosition)
  60309. {
  60310. const Point<int> p (magnifierComp->getLocalPoint (0, screenPosition));
  60311. const double zoom = magnifierComp->getScaleFactor();
  60312. return Point<int> (roundToInt (p.getX() / zoom),
  60313. roundToInt (p.getY() / zoom));
  60314. }
  60315. bool contains (const Point<int>& position, bool) const
  60316. {
  60317. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60318. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60319. }
  60320. void repaint (const Rectangle<int>& area)
  60321. {
  60322. const double zoom = magnifierComp->getScaleFactor();
  60323. magnifierComp->repaint ((int) (area.getX() * zoom),
  60324. (int) (area.getY() * zoom),
  60325. roundToInt (area.getWidth() * zoom) + 1,
  60326. roundToInt (area.getHeight() * zoom) + 1);
  60327. }
  60328. void performAnyPendingRepaintsNow()
  60329. {
  60330. }
  60331. private:
  60332. MagnifierComponent* const magnifierComp;
  60333. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MagnifyingPeer);
  60334. };
  60335. class PeerHolderComp : public Component
  60336. {
  60337. public:
  60338. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60339. : magnifierComp (magnifierComp_)
  60340. {
  60341. setVisible (true);
  60342. }
  60343. ~PeerHolderComp()
  60344. {
  60345. }
  60346. ComponentPeer* createNewPeer (int, void*)
  60347. {
  60348. return new MagnifyingPeer (this, magnifierComp);
  60349. }
  60350. void childBoundsChanged (Component* c)
  60351. {
  60352. if (c != 0)
  60353. {
  60354. setSize (c->getWidth(), c->getHeight());
  60355. magnifierComp->childBoundsChanged (this);
  60356. }
  60357. }
  60358. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60359. {
  60360. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60361. Component* const p = magnifierComp->getParentComponent();
  60362. if (p != 0)
  60363. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60364. }
  60365. private:
  60366. MagnifierComponent* const magnifierComp;
  60367. JUCE_DECLARE_NON_COPYABLE (PeerHolderComp);
  60368. };
  60369. MagnifierComponent::MagnifierComponent (Component* const content_,
  60370. const bool deleteContentCompWhenNoLongerNeeded)
  60371. : content (content_),
  60372. scaleFactor (0.0),
  60373. peer (0),
  60374. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60375. quality (Graphics::lowResamplingQuality),
  60376. mouseSource (0, true)
  60377. {
  60378. holderComp = new PeerHolderComp (this);
  60379. setScaleFactor (1.0);
  60380. }
  60381. MagnifierComponent::~MagnifierComponent()
  60382. {
  60383. delete holderComp;
  60384. if (deleteContent)
  60385. delete content;
  60386. }
  60387. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60388. {
  60389. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60390. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60391. if (scaleFactor != newScaleFactor)
  60392. {
  60393. scaleFactor = newScaleFactor;
  60394. if (scaleFactor == 1.0)
  60395. {
  60396. holderComp->removeFromDesktop();
  60397. peer = 0;
  60398. addChildComponent (content);
  60399. childBoundsChanged (content);
  60400. }
  60401. else
  60402. {
  60403. holderComp->addAndMakeVisible (content);
  60404. holderComp->childBoundsChanged (content);
  60405. childBoundsChanged (holderComp);
  60406. holderComp->addToDesktop (0);
  60407. peer = holderComp->getPeer();
  60408. }
  60409. repaint();
  60410. }
  60411. }
  60412. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60413. {
  60414. quality = newQuality;
  60415. }
  60416. void MagnifierComponent::paint (Graphics& g)
  60417. {
  60418. const int w = holderComp->getWidth();
  60419. const int h = holderComp->getHeight();
  60420. if (w == 0 || h == 0)
  60421. return;
  60422. const Rectangle<int> r (g.getClipBounds());
  60423. const int srcX = (int) (r.getX() / scaleFactor);
  60424. const int srcY = (int) (r.getY() / scaleFactor);
  60425. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60426. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60427. if (scaleFactor >= 1.0)
  60428. {
  60429. ++srcW;
  60430. ++srcH;
  60431. }
  60432. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60433. const Rectangle<int> area (srcX, srcY, srcW, srcH);
  60434. temp.clear (area);
  60435. {
  60436. Graphics g2 (temp);
  60437. g2.reduceClipRegion (area);
  60438. holderComp->paintEntireComponent (g2, false);
  60439. }
  60440. g.setImageResamplingQuality (quality);
  60441. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60442. }
  60443. void MagnifierComponent::childBoundsChanged (Component* c)
  60444. {
  60445. if (c != 0)
  60446. setSize (roundToInt (c->getWidth() * scaleFactor),
  60447. roundToInt (c->getHeight() * scaleFactor));
  60448. }
  60449. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60450. {
  60451. if (peer != 0)
  60452. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60453. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60454. }
  60455. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60456. {
  60457. passOnMouseEventToPeer (e);
  60458. }
  60459. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60460. {
  60461. passOnMouseEventToPeer (e);
  60462. }
  60463. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60464. {
  60465. passOnMouseEventToPeer (e);
  60466. }
  60467. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60468. {
  60469. passOnMouseEventToPeer (e);
  60470. }
  60471. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60472. {
  60473. passOnMouseEventToPeer (e);
  60474. }
  60475. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60476. {
  60477. passOnMouseEventToPeer (e);
  60478. }
  60479. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60480. {
  60481. if (peer != 0)
  60482. peer->handleMouseWheel (e.source.getIndex(),
  60483. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60484. ix * 256.0f, iy * 256.0f);
  60485. else
  60486. Component::mouseWheelMove (e, ix, iy);
  60487. }
  60488. int MagnifierComponent::scaleInt (const int n) const
  60489. {
  60490. return roundToInt (n / scaleFactor);
  60491. }
  60492. END_JUCE_NAMESPACE
  60493. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60494. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60495. BEGIN_JUCE_NAMESPACE
  60496. class MidiKeyboardUpDownButton : public Button
  60497. {
  60498. public:
  60499. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60500. : Button (String::empty),
  60501. owner (owner_),
  60502. delta (delta_)
  60503. {
  60504. setOpaque (true);
  60505. }
  60506. void clicked()
  60507. {
  60508. int note = owner.getLowestVisibleKey();
  60509. if (delta < 0)
  60510. note = (note - 1) / 12;
  60511. else
  60512. note = note / 12 + 1;
  60513. owner.setLowestVisibleKey (note * 12);
  60514. }
  60515. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60516. {
  60517. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60518. isMouseOverButton, isButtonDown,
  60519. delta > 0);
  60520. }
  60521. private:
  60522. MidiKeyboardComponent& owner;
  60523. const int delta;
  60524. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60525. };
  60526. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60527. const Orientation orientation_)
  60528. : state (state_),
  60529. xOffset (0),
  60530. blackNoteLength (1),
  60531. keyWidth (16.0f),
  60532. orientation (orientation_),
  60533. midiChannel (1),
  60534. midiInChannelMask (0xffff),
  60535. velocity (1.0f),
  60536. noteUnderMouse (-1),
  60537. mouseDownNote (-1),
  60538. rangeStart (0),
  60539. rangeEnd (127),
  60540. firstKey (12 * 4),
  60541. canScroll (true),
  60542. mouseDragging (false),
  60543. useMousePositionForVelocity (true),
  60544. keyMappingOctave (6),
  60545. octaveNumForMiddleC (3)
  60546. {
  60547. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60548. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60549. // initialise with a default set of querty key-mappings..
  60550. const char* const keymap = "awsedftgyhujkolp;";
  60551. for (int i = String (keymap).length(); --i >= 0;)
  60552. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60553. setOpaque (true);
  60554. setWantsKeyboardFocus (true);
  60555. state.addListener (this);
  60556. }
  60557. MidiKeyboardComponent::~MidiKeyboardComponent()
  60558. {
  60559. state.removeListener (this);
  60560. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60561. }
  60562. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60563. {
  60564. keyWidth = widthInPixels;
  60565. resized();
  60566. }
  60567. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60568. {
  60569. if (orientation != newOrientation)
  60570. {
  60571. orientation = newOrientation;
  60572. resized();
  60573. }
  60574. }
  60575. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60576. const int highestNote)
  60577. {
  60578. jassert (lowestNote >= 0 && lowestNote <= 127);
  60579. jassert (highestNote >= 0 && highestNote <= 127);
  60580. jassert (lowestNote <= highestNote);
  60581. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60582. {
  60583. rangeStart = jlimit (0, 127, lowestNote);
  60584. rangeEnd = jlimit (0, 127, highestNote);
  60585. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60586. resized();
  60587. }
  60588. }
  60589. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60590. {
  60591. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60592. if (noteNumber != firstKey)
  60593. {
  60594. firstKey = noteNumber;
  60595. sendChangeMessage();
  60596. resized();
  60597. }
  60598. }
  60599. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60600. {
  60601. if (canScroll != canScroll_)
  60602. {
  60603. canScroll = canScroll_;
  60604. resized();
  60605. }
  60606. }
  60607. void MidiKeyboardComponent::colourChanged()
  60608. {
  60609. repaint();
  60610. }
  60611. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60612. {
  60613. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60614. if (midiChannel != midiChannelNumber)
  60615. {
  60616. resetAnyKeysInUse();
  60617. midiChannel = jlimit (1, 16, midiChannelNumber);
  60618. }
  60619. }
  60620. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60621. {
  60622. midiInChannelMask = midiChannelMask;
  60623. triggerAsyncUpdate();
  60624. }
  60625. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60626. {
  60627. velocity = jlimit (0.0f, 1.0f, velocity_);
  60628. useMousePositionForVelocity = useMousePositionForVelocity_;
  60629. }
  60630. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60631. {
  60632. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60633. static const float blackNoteWidth = 0.7f;
  60634. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60635. 1.0f, 2 - blackNoteWidth * 0.4f,
  60636. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60637. 4.0f, 5 - blackNoteWidth * 0.5f,
  60638. 5.0f, 6 - blackNoteWidth * 0.3f,
  60639. 6.0f };
  60640. static const float widths[] = { 1.0f, blackNoteWidth,
  60641. 1.0f, blackNoteWidth,
  60642. 1.0f, 1.0f, blackNoteWidth,
  60643. 1.0f, blackNoteWidth,
  60644. 1.0f, blackNoteWidth,
  60645. 1.0f };
  60646. const int octave = midiNoteNumber / 12;
  60647. const int note = midiNoteNumber % 12;
  60648. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60649. w = roundToInt (widths [note] * keyWidth_);
  60650. }
  60651. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60652. {
  60653. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60654. int rx, rw;
  60655. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60656. x -= xOffset + rx;
  60657. }
  60658. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60659. {
  60660. int x, y;
  60661. getKeyPos (midiNoteNumber, x, y);
  60662. return x;
  60663. }
  60664. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60665. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60666. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60667. {
  60668. if (! reallyContains (pos, false))
  60669. return -1;
  60670. Point<int> p (pos);
  60671. if (orientation != horizontalKeyboard)
  60672. {
  60673. p = Point<int> (p.getY(), p.getX());
  60674. if (orientation == verticalKeyboardFacingLeft)
  60675. p = Point<int> (p.getX(), getWidth() - p.getY());
  60676. else
  60677. p = Point<int> (getHeight() - p.getX(), p.getY());
  60678. }
  60679. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60680. }
  60681. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60682. {
  60683. if (pos.getY() < blackNoteLength)
  60684. {
  60685. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60686. {
  60687. for (int i = 0; i < 5; ++i)
  60688. {
  60689. const int note = octaveStart + blackNotes [i];
  60690. if (note >= rangeStart && note <= rangeEnd)
  60691. {
  60692. int kx, kw;
  60693. getKeyPos (note, kx, kw);
  60694. kx += xOffset;
  60695. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60696. {
  60697. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60698. return note;
  60699. }
  60700. }
  60701. }
  60702. }
  60703. }
  60704. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60705. {
  60706. for (int i = 0; i < 7; ++i)
  60707. {
  60708. const int note = octaveStart + whiteNotes [i];
  60709. if (note >= rangeStart && note <= rangeEnd)
  60710. {
  60711. int kx, kw;
  60712. getKeyPos (note, kx, kw);
  60713. kx += xOffset;
  60714. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60715. {
  60716. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60717. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60718. return note;
  60719. }
  60720. }
  60721. }
  60722. }
  60723. mousePositionVelocity = 0;
  60724. return -1;
  60725. }
  60726. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60727. {
  60728. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60729. {
  60730. int x, w;
  60731. getKeyPos (noteNum, x, w);
  60732. if (orientation == horizontalKeyboard)
  60733. repaint (x, 0, w, getHeight());
  60734. else if (orientation == verticalKeyboardFacingLeft)
  60735. repaint (0, x, getWidth(), w);
  60736. else if (orientation == verticalKeyboardFacingRight)
  60737. repaint (0, getHeight() - x - w, getWidth(), w);
  60738. }
  60739. }
  60740. void MidiKeyboardComponent::paint (Graphics& g)
  60741. {
  60742. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60743. const Colour lineColour (findColour (keySeparatorLineColourId));
  60744. const Colour textColour (findColour (textLabelColourId));
  60745. int x, w, octave;
  60746. for (octave = 0; octave < 128; octave += 12)
  60747. {
  60748. for (int white = 0; white < 7; ++white)
  60749. {
  60750. const int noteNum = octave + whiteNotes [white];
  60751. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60752. {
  60753. getKeyPos (noteNum, x, w);
  60754. if (orientation == horizontalKeyboard)
  60755. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60756. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60757. noteUnderMouse == noteNum,
  60758. lineColour, textColour);
  60759. else if (orientation == verticalKeyboardFacingLeft)
  60760. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60761. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60762. noteUnderMouse == noteNum,
  60763. lineColour, textColour);
  60764. else if (orientation == verticalKeyboardFacingRight)
  60765. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60766. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60767. noteUnderMouse == noteNum,
  60768. lineColour, textColour);
  60769. }
  60770. }
  60771. }
  60772. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60773. if (orientation == verticalKeyboardFacingLeft)
  60774. {
  60775. x1 = getWidth() - 1.0f;
  60776. x2 = getWidth() - 5.0f;
  60777. }
  60778. else if (orientation == verticalKeyboardFacingRight)
  60779. x2 = 5.0f;
  60780. else
  60781. y2 = 5.0f;
  60782. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60783. Colours::transparentBlack, x2, y2, false));
  60784. getKeyPos (rangeEnd, x, w);
  60785. x += w;
  60786. if (orientation == verticalKeyboardFacingLeft)
  60787. g.fillRect (getWidth() - 5, 0, 5, x);
  60788. else if (orientation == verticalKeyboardFacingRight)
  60789. g.fillRect (0, 0, 5, x);
  60790. else
  60791. g.fillRect (0, 0, x, 5);
  60792. g.setColour (lineColour);
  60793. if (orientation == verticalKeyboardFacingLeft)
  60794. g.fillRect (0, 0, 1, x);
  60795. else if (orientation == verticalKeyboardFacingRight)
  60796. g.fillRect (getWidth() - 1, 0, 1, x);
  60797. else
  60798. g.fillRect (0, getHeight() - 1, x, 1);
  60799. const Colour blackNoteColour (findColour (blackNoteColourId));
  60800. for (octave = 0; octave < 128; octave += 12)
  60801. {
  60802. for (int black = 0; black < 5; ++black)
  60803. {
  60804. const int noteNum = octave + blackNotes [black];
  60805. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60806. {
  60807. getKeyPos (noteNum, x, w);
  60808. if (orientation == horizontalKeyboard)
  60809. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60810. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60811. noteUnderMouse == noteNum,
  60812. blackNoteColour);
  60813. else if (orientation == verticalKeyboardFacingLeft)
  60814. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60815. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60816. noteUnderMouse == noteNum,
  60817. blackNoteColour);
  60818. else if (orientation == verticalKeyboardFacingRight)
  60819. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60820. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60821. noteUnderMouse == noteNum,
  60822. blackNoteColour);
  60823. }
  60824. }
  60825. }
  60826. }
  60827. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60828. Graphics& g, int x, int y, int w, int h,
  60829. bool isDown, bool isOver,
  60830. const Colour& lineColour,
  60831. const Colour& textColour)
  60832. {
  60833. Colour c (Colours::transparentWhite);
  60834. if (isDown)
  60835. c = findColour (keyDownOverlayColourId);
  60836. if (isOver)
  60837. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60838. g.setColour (c);
  60839. g.fillRect (x, y, w, h);
  60840. const String text (getWhiteNoteText (midiNoteNumber));
  60841. if (! text.isEmpty())
  60842. {
  60843. g.setColour (textColour);
  60844. Font f (jmin (12.0f, keyWidth * 0.9f));
  60845. f.setHorizontalScale (0.8f);
  60846. g.setFont (f);
  60847. Justification justification (Justification::centredBottom);
  60848. if (orientation == verticalKeyboardFacingLeft)
  60849. justification = Justification::centredLeft;
  60850. else if (orientation == verticalKeyboardFacingRight)
  60851. justification = Justification::centredRight;
  60852. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60853. }
  60854. g.setColour (lineColour);
  60855. if (orientation == horizontalKeyboard)
  60856. g.fillRect (x, y, 1, h);
  60857. else if (orientation == verticalKeyboardFacingLeft)
  60858. g.fillRect (x, y, w, 1);
  60859. else if (orientation == verticalKeyboardFacingRight)
  60860. g.fillRect (x, y + h - 1, w, 1);
  60861. if (midiNoteNumber == rangeEnd)
  60862. {
  60863. if (orientation == horizontalKeyboard)
  60864. g.fillRect (x + w, y, 1, h);
  60865. else if (orientation == verticalKeyboardFacingLeft)
  60866. g.fillRect (x, y + h, w, 1);
  60867. else if (orientation == verticalKeyboardFacingRight)
  60868. g.fillRect (x, y - 1, w, 1);
  60869. }
  60870. }
  60871. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60872. Graphics& g, int x, int y, int w, int h,
  60873. bool isDown, bool isOver,
  60874. const Colour& noteFillColour)
  60875. {
  60876. Colour c (noteFillColour);
  60877. if (isDown)
  60878. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60879. if (isOver)
  60880. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60881. g.setColour (c);
  60882. g.fillRect (x, y, w, h);
  60883. if (isDown)
  60884. {
  60885. g.setColour (noteFillColour);
  60886. g.drawRect (x, y, w, h);
  60887. }
  60888. else
  60889. {
  60890. const int xIndent = jmax (1, jmin (w, h) / 8);
  60891. g.setColour (c.brighter());
  60892. if (orientation == horizontalKeyboard)
  60893. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60894. else if (orientation == verticalKeyboardFacingLeft)
  60895. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60896. else if (orientation == verticalKeyboardFacingRight)
  60897. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60898. }
  60899. }
  60900. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60901. {
  60902. octaveNumForMiddleC = octaveNumForMiddleC_;
  60903. repaint();
  60904. }
  60905. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60906. {
  60907. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60908. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60909. return String::empty;
  60910. }
  60911. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60912. const bool isMouseOver_,
  60913. const bool isButtonDown,
  60914. const bool movesOctavesUp)
  60915. {
  60916. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60917. float angle;
  60918. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60919. angle = movesOctavesUp ? 0.0f : 0.5f;
  60920. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60921. angle = movesOctavesUp ? 0.25f : 0.75f;
  60922. else
  60923. angle = movesOctavesUp ? 0.75f : 0.25f;
  60924. Path path;
  60925. path.lineTo (0.0f, 1.0f);
  60926. path.lineTo (1.0f, 0.5f);
  60927. path.closeSubPath();
  60928. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60929. g.setColour (findColour (upDownButtonArrowColourId)
  60930. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60931. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60932. w - 2.0f,
  60933. h - 2.0f,
  60934. true));
  60935. }
  60936. void MidiKeyboardComponent::resized()
  60937. {
  60938. int w = getWidth();
  60939. int h = getHeight();
  60940. if (w > 0 && h > 0)
  60941. {
  60942. if (orientation != horizontalKeyboard)
  60943. swapVariables (w, h);
  60944. blackNoteLength = roundToInt (h * 0.7f);
  60945. int kx2, kw2;
  60946. getKeyPos (rangeEnd, kx2, kw2);
  60947. kx2 += kw2;
  60948. if (firstKey != rangeStart)
  60949. {
  60950. int kx1, kw1;
  60951. getKeyPos (rangeStart, kx1, kw1);
  60952. if (kx2 - kx1 <= w)
  60953. {
  60954. firstKey = rangeStart;
  60955. sendChangeMessage();
  60956. repaint();
  60957. }
  60958. }
  60959. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60960. scrollDown->setVisible (showScrollButtons);
  60961. scrollUp->setVisible (showScrollButtons);
  60962. xOffset = 0;
  60963. if (showScrollButtons)
  60964. {
  60965. const int scrollButtonW = jmin (12, w / 2);
  60966. if (orientation == horizontalKeyboard)
  60967. {
  60968. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60969. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60970. }
  60971. else if (orientation == verticalKeyboardFacingLeft)
  60972. {
  60973. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60974. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60975. }
  60976. else if (orientation == verticalKeyboardFacingRight)
  60977. {
  60978. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60979. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60980. }
  60981. int endOfLastKey, kw;
  60982. getKeyPos (rangeEnd, endOfLastKey, kw);
  60983. endOfLastKey += kw;
  60984. float mousePositionVelocity;
  60985. const int spaceAvailable = w - scrollButtonW * 2;
  60986. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60987. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60988. {
  60989. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60990. sendChangeMessage();
  60991. }
  60992. int newOffset = 0;
  60993. getKeyPos (firstKey, newOffset, kw);
  60994. xOffset = newOffset - scrollButtonW;
  60995. }
  60996. else
  60997. {
  60998. firstKey = rangeStart;
  60999. }
  61000. timerCallback();
  61001. repaint();
  61002. }
  61003. }
  61004. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61005. {
  61006. triggerAsyncUpdate();
  61007. }
  61008. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61009. {
  61010. triggerAsyncUpdate();
  61011. }
  61012. void MidiKeyboardComponent::handleAsyncUpdate()
  61013. {
  61014. for (int i = rangeStart; i <= rangeEnd; ++i)
  61015. {
  61016. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61017. {
  61018. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61019. repaintNote (i);
  61020. }
  61021. }
  61022. }
  61023. void MidiKeyboardComponent::resetAnyKeysInUse()
  61024. {
  61025. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61026. {
  61027. state.allNotesOff (midiChannel);
  61028. keysPressed.clear();
  61029. mouseDownNote = -1;
  61030. }
  61031. }
  61032. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61033. {
  61034. float mousePositionVelocity = 0.0f;
  61035. const int newNote = (mouseDragging || isMouseOver())
  61036. ? xyToNote (pos, mousePositionVelocity) : -1;
  61037. if (noteUnderMouse != newNote)
  61038. {
  61039. if (mouseDownNote >= 0)
  61040. {
  61041. state.noteOff (midiChannel, mouseDownNote);
  61042. mouseDownNote = -1;
  61043. }
  61044. if (mouseDragging && newNote >= 0)
  61045. {
  61046. if (! useMousePositionForVelocity)
  61047. mousePositionVelocity = 1.0f;
  61048. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61049. mouseDownNote = newNote;
  61050. }
  61051. repaintNote (noteUnderMouse);
  61052. noteUnderMouse = newNote;
  61053. repaintNote (noteUnderMouse);
  61054. }
  61055. else if (mouseDownNote >= 0 && ! mouseDragging)
  61056. {
  61057. state.noteOff (midiChannel, mouseDownNote);
  61058. mouseDownNote = -1;
  61059. }
  61060. }
  61061. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61062. {
  61063. updateNoteUnderMouse (e.getPosition());
  61064. stopTimer();
  61065. }
  61066. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61067. {
  61068. float mousePositionVelocity;
  61069. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61070. if (newNote >= 0)
  61071. mouseDraggedToKey (newNote, e);
  61072. updateNoteUnderMouse (e.getPosition());
  61073. }
  61074. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61075. {
  61076. return true;
  61077. }
  61078. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61079. {
  61080. }
  61081. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61082. {
  61083. float mousePositionVelocity;
  61084. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61085. mouseDragging = false;
  61086. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61087. {
  61088. repaintNote (noteUnderMouse);
  61089. noteUnderMouse = -1;
  61090. mouseDragging = true;
  61091. updateNoteUnderMouse (e.getPosition());
  61092. startTimer (500);
  61093. }
  61094. }
  61095. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61096. {
  61097. mouseDragging = false;
  61098. updateNoteUnderMouse (e.getPosition());
  61099. stopTimer();
  61100. }
  61101. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61102. {
  61103. updateNoteUnderMouse (e.getPosition());
  61104. }
  61105. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61106. {
  61107. updateNoteUnderMouse (e.getPosition());
  61108. }
  61109. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61110. {
  61111. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61112. }
  61113. void MidiKeyboardComponent::timerCallback()
  61114. {
  61115. updateNoteUnderMouse (getMouseXYRelative());
  61116. }
  61117. void MidiKeyboardComponent::clearKeyMappings()
  61118. {
  61119. resetAnyKeysInUse();
  61120. keyPressNotes.clear();
  61121. keyPresses.clear();
  61122. }
  61123. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61124. const int midiNoteOffsetFromC)
  61125. {
  61126. removeKeyPressForNote (midiNoteOffsetFromC);
  61127. keyPressNotes.add (midiNoteOffsetFromC);
  61128. keyPresses.add (key);
  61129. }
  61130. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61131. {
  61132. for (int i = keyPressNotes.size(); --i >= 0;)
  61133. {
  61134. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61135. {
  61136. keyPressNotes.remove (i);
  61137. keyPresses.remove (i);
  61138. }
  61139. }
  61140. }
  61141. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61142. {
  61143. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61144. keyMappingOctave = newOctaveNumber;
  61145. }
  61146. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61147. {
  61148. bool keyPressUsed = false;
  61149. for (int i = keyPresses.size(); --i >= 0;)
  61150. {
  61151. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61152. if (keyPresses.getReference(i).isCurrentlyDown())
  61153. {
  61154. if (! keysPressed [note])
  61155. {
  61156. keysPressed.setBit (note);
  61157. state.noteOn (midiChannel, note, velocity);
  61158. keyPressUsed = true;
  61159. }
  61160. }
  61161. else
  61162. {
  61163. if (keysPressed [note])
  61164. {
  61165. keysPressed.clearBit (note);
  61166. state.noteOff (midiChannel, note);
  61167. keyPressUsed = true;
  61168. }
  61169. }
  61170. }
  61171. return keyPressUsed;
  61172. }
  61173. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61174. {
  61175. resetAnyKeysInUse();
  61176. }
  61177. END_JUCE_NAMESPACE
  61178. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61179. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61180. #if JUCE_OPENGL
  61181. BEGIN_JUCE_NAMESPACE
  61182. extern void juce_glViewport (const int w, const int h);
  61183. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61184. const int alphaBits_,
  61185. const int depthBufferBits_,
  61186. const int stencilBufferBits_)
  61187. : redBits (bitsPerRGBComponent),
  61188. greenBits (bitsPerRGBComponent),
  61189. blueBits (bitsPerRGBComponent),
  61190. alphaBits (alphaBits_),
  61191. depthBufferBits (depthBufferBits_),
  61192. stencilBufferBits (stencilBufferBits_),
  61193. accumulationBufferRedBits (0),
  61194. accumulationBufferGreenBits (0),
  61195. accumulationBufferBlueBits (0),
  61196. accumulationBufferAlphaBits (0),
  61197. fullSceneAntiAliasingNumSamples (0)
  61198. {
  61199. }
  61200. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61201. : redBits (other.redBits),
  61202. greenBits (other.greenBits),
  61203. blueBits (other.blueBits),
  61204. alphaBits (other.alphaBits),
  61205. depthBufferBits (other.depthBufferBits),
  61206. stencilBufferBits (other.stencilBufferBits),
  61207. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61208. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61209. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61210. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61211. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61212. {
  61213. }
  61214. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61215. {
  61216. redBits = other.redBits;
  61217. greenBits = other.greenBits;
  61218. blueBits = other.blueBits;
  61219. alphaBits = other.alphaBits;
  61220. depthBufferBits = other.depthBufferBits;
  61221. stencilBufferBits = other.stencilBufferBits;
  61222. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61223. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61224. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61225. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61226. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61227. return *this;
  61228. }
  61229. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61230. {
  61231. return redBits == other.redBits
  61232. && greenBits == other.greenBits
  61233. && blueBits == other.blueBits
  61234. && alphaBits == other.alphaBits
  61235. && depthBufferBits == other.depthBufferBits
  61236. && stencilBufferBits == other.stencilBufferBits
  61237. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61238. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61239. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61240. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61241. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61242. }
  61243. static Array<OpenGLContext*> knownContexts;
  61244. OpenGLContext::OpenGLContext() throw()
  61245. {
  61246. knownContexts.add (this);
  61247. }
  61248. OpenGLContext::~OpenGLContext()
  61249. {
  61250. knownContexts.removeValue (this);
  61251. }
  61252. OpenGLContext* OpenGLContext::getCurrentContext()
  61253. {
  61254. for (int i = knownContexts.size(); --i >= 0;)
  61255. {
  61256. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61257. if (oglc->isActive())
  61258. return oglc;
  61259. }
  61260. return 0;
  61261. }
  61262. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61263. {
  61264. public:
  61265. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61266. : ComponentMovementWatcher (owner_),
  61267. owner (owner_),
  61268. wasShowing (false)
  61269. {
  61270. }
  61271. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61272. {
  61273. owner->updateContextPosition();
  61274. }
  61275. void componentPeerChanged()
  61276. {
  61277. const ScopedLock sl (owner->getContextLock());
  61278. owner->deleteContext();
  61279. }
  61280. void componentVisibilityChanged (Component&)
  61281. {
  61282. const bool isShowingNow = owner->isShowing();
  61283. if (wasShowing != isShowingNow)
  61284. {
  61285. wasShowing = isShowingNow;
  61286. if (! isShowingNow)
  61287. {
  61288. const ScopedLock sl (owner->getContextLock());
  61289. owner->deleteContext();
  61290. }
  61291. }
  61292. }
  61293. private:
  61294. OpenGLComponent* const owner;
  61295. bool wasShowing;
  61296. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  61297. };
  61298. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61299. : type (type_),
  61300. contextToShareListsWith (0),
  61301. needToUpdateViewport (true)
  61302. {
  61303. setOpaque (true);
  61304. componentWatcher = new OpenGLComponentWatcher (this);
  61305. }
  61306. OpenGLComponent::~OpenGLComponent()
  61307. {
  61308. deleteContext();
  61309. componentWatcher = 0;
  61310. }
  61311. void OpenGLComponent::deleteContext()
  61312. {
  61313. const ScopedLock sl (contextLock);
  61314. context = 0;
  61315. }
  61316. void OpenGLComponent::updateContextPosition()
  61317. {
  61318. needToUpdateViewport = true;
  61319. if (getWidth() > 0 && getHeight() > 0)
  61320. {
  61321. Component* const topComp = getTopLevelComponent();
  61322. if (topComp->getPeer() != 0)
  61323. {
  61324. const ScopedLock sl (contextLock);
  61325. if (context != 0)
  61326. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61327. getScreenY() - topComp->getScreenY(),
  61328. getWidth(),
  61329. getHeight(),
  61330. topComp->getHeight());
  61331. }
  61332. }
  61333. }
  61334. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61335. {
  61336. OpenGLPixelFormat pf;
  61337. const ScopedLock sl (contextLock);
  61338. if (context != 0)
  61339. pf = context->getPixelFormat();
  61340. return pf;
  61341. }
  61342. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61343. {
  61344. if (! (preferredPixelFormat == formatToUse))
  61345. {
  61346. const ScopedLock sl (contextLock);
  61347. deleteContext();
  61348. preferredPixelFormat = formatToUse;
  61349. }
  61350. }
  61351. void OpenGLComponent::shareWith (OpenGLContext* c)
  61352. {
  61353. if (contextToShareListsWith != c)
  61354. {
  61355. const ScopedLock sl (contextLock);
  61356. deleteContext();
  61357. contextToShareListsWith = c;
  61358. }
  61359. }
  61360. bool OpenGLComponent::makeCurrentContextActive()
  61361. {
  61362. if (context == 0)
  61363. {
  61364. const ScopedLock sl (contextLock);
  61365. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61366. {
  61367. context = createContext();
  61368. if (context != 0)
  61369. {
  61370. updateContextPosition();
  61371. if (context->makeActive())
  61372. newOpenGLContextCreated();
  61373. }
  61374. }
  61375. }
  61376. return context != 0 && context->makeActive();
  61377. }
  61378. void OpenGLComponent::makeCurrentContextInactive()
  61379. {
  61380. if (context != 0)
  61381. context->makeInactive();
  61382. }
  61383. bool OpenGLComponent::isActiveContext() const throw()
  61384. {
  61385. return context != 0 && context->isActive();
  61386. }
  61387. void OpenGLComponent::swapBuffers()
  61388. {
  61389. if (context != 0)
  61390. context->swapBuffers();
  61391. }
  61392. void OpenGLComponent::paint (Graphics&)
  61393. {
  61394. if (renderAndSwapBuffers())
  61395. {
  61396. ComponentPeer* const peer = getPeer();
  61397. if (peer != 0)
  61398. {
  61399. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61400. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61401. }
  61402. }
  61403. }
  61404. bool OpenGLComponent::renderAndSwapBuffers()
  61405. {
  61406. const ScopedLock sl (contextLock);
  61407. if (! makeCurrentContextActive())
  61408. return false;
  61409. if (needToUpdateViewport)
  61410. {
  61411. needToUpdateViewport = false;
  61412. juce_glViewport (getWidth(), getHeight());
  61413. }
  61414. renderOpenGL();
  61415. swapBuffers();
  61416. return true;
  61417. }
  61418. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61419. {
  61420. Component::internalRepaint (x, y, w, h);
  61421. if (context != 0)
  61422. context->repaint();
  61423. }
  61424. END_JUCE_NAMESPACE
  61425. #endif
  61426. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61427. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61428. BEGIN_JUCE_NAMESPACE
  61429. PreferencesPanel::PreferencesPanel()
  61430. : buttonSize (70)
  61431. {
  61432. }
  61433. PreferencesPanel::~PreferencesPanel()
  61434. {
  61435. }
  61436. void PreferencesPanel::addSettingsPage (const String& title,
  61437. const Drawable* icon,
  61438. const Drawable* overIcon,
  61439. const Drawable* downIcon)
  61440. {
  61441. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61442. buttons.add (button);
  61443. button->setImages (icon, overIcon, downIcon);
  61444. button->setRadioGroupId (1);
  61445. button->addButtonListener (this);
  61446. button->setClickingTogglesState (true);
  61447. button->setWantsKeyboardFocus (false);
  61448. addAndMakeVisible (button);
  61449. resized();
  61450. if (currentPage == 0)
  61451. setCurrentPage (title);
  61452. }
  61453. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61454. {
  61455. DrawableImage icon, iconOver, iconDown;
  61456. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61457. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61458. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61459. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61460. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61461. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61462. }
  61463. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61464. {
  61465. setSize (dialogWidth, dialogHeight);
  61466. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61467. }
  61468. void PreferencesPanel::resized()
  61469. {
  61470. for (int i = 0; i < buttons.size(); ++i)
  61471. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61472. if (currentPage != 0)
  61473. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61474. }
  61475. void PreferencesPanel::paint (Graphics& g)
  61476. {
  61477. g.setColour (Colours::grey);
  61478. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61479. }
  61480. void PreferencesPanel::setCurrentPage (const String& pageName)
  61481. {
  61482. if (currentPageName != pageName)
  61483. {
  61484. currentPageName = pageName;
  61485. currentPage = 0;
  61486. currentPage = createComponentForPage (pageName);
  61487. if (currentPage != 0)
  61488. {
  61489. addAndMakeVisible (currentPage);
  61490. currentPage->toBack();
  61491. resized();
  61492. }
  61493. for (int i = 0; i < buttons.size(); ++i)
  61494. {
  61495. if (buttons.getUnchecked(i)->getName() == pageName)
  61496. {
  61497. buttons.getUnchecked(i)->setToggleState (true, false);
  61498. break;
  61499. }
  61500. }
  61501. }
  61502. }
  61503. void PreferencesPanel::buttonClicked (Button*)
  61504. {
  61505. for (int i = 0; i < buttons.size(); ++i)
  61506. {
  61507. if (buttons.getUnchecked(i)->getToggleState())
  61508. {
  61509. setCurrentPage (buttons.getUnchecked(i)->getName());
  61510. break;
  61511. }
  61512. }
  61513. }
  61514. END_JUCE_NAMESPACE
  61515. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61516. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61517. #if JUCE_WINDOWS || JUCE_LINUX
  61518. BEGIN_JUCE_NAMESPACE
  61519. SystemTrayIconComponent::SystemTrayIconComponent()
  61520. {
  61521. addToDesktop (0);
  61522. }
  61523. SystemTrayIconComponent::~SystemTrayIconComponent()
  61524. {
  61525. }
  61526. END_JUCE_NAMESPACE
  61527. #endif
  61528. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61529. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61530. BEGIN_JUCE_NAMESPACE
  61531. class AlertWindowTextEditor : public TextEditor
  61532. {
  61533. public:
  61534. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61535. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61536. {
  61537. setSelectAllWhenFocused (true);
  61538. }
  61539. ~AlertWindowTextEditor()
  61540. {
  61541. }
  61542. void returnPressed()
  61543. {
  61544. // pass these up the component hierarchy to be trigger the buttons
  61545. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61546. }
  61547. void escapePressed()
  61548. {
  61549. // pass these up the component hierarchy to be trigger the buttons
  61550. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61551. }
  61552. private:
  61553. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61554. static juce_wchar getDefaultPasswordChar() throw()
  61555. {
  61556. #if JUCE_LINUX
  61557. return 0x2022;
  61558. #else
  61559. return 0x25cf;
  61560. #endif
  61561. }
  61562. };
  61563. AlertWindow::AlertWindow (const String& title,
  61564. const String& message,
  61565. AlertIconType iconType,
  61566. Component* associatedComponent_)
  61567. : TopLevelWindow (title, true),
  61568. alertIconType (iconType),
  61569. associatedComponent (associatedComponent_)
  61570. {
  61571. if (message.isEmpty())
  61572. text = " "; // to force an update if the message is empty
  61573. setMessage (message);
  61574. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61575. {
  61576. Component* const c = Desktop::getInstance().getComponent (i);
  61577. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61578. {
  61579. setAlwaysOnTop (true);
  61580. break;
  61581. }
  61582. }
  61583. if (! JUCEApplication::isStandaloneApp())
  61584. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61585. lookAndFeelChanged();
  61586. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61587. }
  61588. AlertWindow::~AlertWindow()
  61589. {
  61590. removeAllChildren();
  61591. }
  61592. void AlertWindow::userTriedToCloseWindow()
  61593. {
  61594. exitModalState (0);
  61595. }
  61596. void AlertWindow::setMessage (const String& message)
  61597. {
  61598. const String newMessage (message.substring (0, 2048));
  61599. if (text != newMessage)
  61600. {
  61601. text = newMessage;
  61602. font.setHeight (15.0f);
  61603. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61604. textLayout.setText (getName() + "\n\n", titleFont);
  61605. textLayout.appendText (text, font);
  61606. updateLayout (true);
  61607. repaint();
  61608. }
  61609. }
  61610. void AlertWindow::buttonClicked (Button* button)
  61611. {
  61612. if (button->getParentComponent() != 0)
  61613. button->getParentComponent()->exitModalState (button->getCommandID());
  61614. }
  61615. void AlertWindow::addButton (const String& name,
  61616. const int returnValue,
  61617. const KeyPress& shortcutKey1,
  61618. const KeyPress& shortcutKey2)
  61619. {
  61620. TextButton* const b = new TextButton (name, String::empty);
  61621. buttons.add (b);
  61622. b->setWantsKeyboardFocus (true);
  61623. b->setMouseClickGrabsKeyboardFocus (false);
  61624. b->setCommandToTrigger (0, returnValue, false);
  61625. b->addShortcut (shortcutKey1);
  61626. b->addShortcut (shortcutKey2);
  61627. b->addButtonListener (this);
  61628. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61629. addAndMakeVisible (b, 0);
  61630. updateLayout (false);
  61631. }
  61632. int AlertWindow::getNumButtons() const
  61633. {
  61634. return buttons.size();
  61635. }
  61636. void AlertWindow::triggerButtonClick (const String& buttonName)
  61637. {
  61638. for (int i = buttons.size(); --i >= 0;)
  61639. {
  61640. TextButton* const b = buttons.getUnchecked(i);
  61641. if (buttonName == b->getName())
  61642. {
  61643. b->triggerClick();
  61644. break;
  61645. }
  61646. }
  61647. }
  61648. void AlertWindow::addTextEditor (const String& name,
  61649. const String& initialContents,
  61650. const String& onScreenLabel,
  61651. const bool isPasswordBox)
  61652. {
  61653. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61654. textBoxes.add (tc);
  61655. allComps.add (tc);
  61656. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61657. tc->setFont (font);
  61658. tc->setText (initialContents);
  61659. tc->setCaretPosition (initialContents.length());
  61660. addAndMakeVisible (tc);
  61661. textboxNames.add (onScreenLabel);
  61662. updateLayout (false);
  61663. }
  61664. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61665. {
  61666. for (int i = textBoxes.size(); --i >= 0;)
  61667. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61668. return textBoxes.getUnchecked(i);
  61669. return 0;
  61670. }
  61671. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61672. {
  61673. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61674. return t != 0 ? t->getText() : String::empty;
  61675. }
  61676. void AlertWindow::addComboBox (const String& name,
  61677. const StringArray& items,
  61678. const String& onScreenLabel)
  61679. {
  61680. ComboBox* const cb = new ComboBox (name);
  61681. comboBoxes.add (cb);
  61682. allComps.add (cb);
  61683. for (int i = 0; i < items.size(); ++i)
  61684. cb->addItem (items[i], i + 1);
  61685. addAndMakeVisible (cb);
  61686. cb->setSelectedItemIndex (0);
  61687. comboBoxNames.add (onScreenLabel);
  61688. updateLayout (false);
  61689. }
  61690. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61691. {
  61692. for (int i = comboBoxes.size(); --i >= 0;)
  61693. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61694. return comboBoxes.getUnchecked(i);
  61695. return 0;
  61696. }
  61697. class AlertTextComp : public TextEditor
  61698. {
  61699. public:
  61700. AlertTextComp (const String& message,
  61701. const Font& font)
  61702. {
  61703. setReadOnly (true);
  61704. setMultiLine (true, true);
  61705. setCaretVisible (false);
  61706. setScrollbarsShown (true);
  61707. lookAndFeelChanged();
  61708. setWantsKeyboardFocus (false);
  61709. setFont (font);
  61710. setText (message, false);
  61711. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61712. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61713. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61714. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61715. }
  61716. ~AlertTextComp()
  61717. {
  61718. }
  61719. int getPreferredWidth() const throw() { return bestWidth; }
  61720. void updateLayout (const int width)
  61721. {
  61722. TextLayout text;
  61723. text.appendText (getText(), getFont());
  61724. text.layout (width - 8, Justification::topLeft, true);
  61725. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61726. }
  61727. private:
  61728. int bestWidth;
  61729. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61730. };
  61731. void AlertWindow::addTextBlock (const String& textBlock)
  61732. {
  61733. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61734. textBlocks.add (c);
  61735. allComps.add (c);
  61736. addAndMakeVisible (c);
  61737. updateLayout (false);
  61738. }
  61739. void AlertWindow::addProgressBarComponent (double& progressValue)
  61740. {
  61741. ProgressBar* const pb = new ProgressBar (progressValue);
  61742. progressBars.add (pb);
  61743. allComps.add (pb);
  61744. addAndMakeVisible (pb);
  61745. updateLayout (false);
  61746. }
  61747. void AlertWindow::addCustomComponent (Component* const component)
  61748. {
  61749. customComps.add (component);
  61750. allComps.add (component);
  61751. addAndMakeVisible (component);
  61752. updateLayout (false);
  61753. }
  61754. int AlertWindow::getNumCustomComponents() const
  61755. {
  61756. return customComps.size();
  61757. }
  61758. Component* AlertWindow::getCustomComponent (const int index) const
  61759. {
  61760. return customComps [index];
  61761. }
  61762. Component* AlertWindow::removeCustomComponent (const int index)
  61763. {
  61764. Component* const c = getCustomComponent (index);
  61765. if (c != 0)
  61766. {
  61767. customComps.removeValue (c);
  61768. allComps.removeValue (c);
  61769. removeChildComponent (c);
  61770. updateLayout (false);
  61771. }
  61772. return c;
  61773. }
  61774. void AlertWindow::paint (Graphics& g)
  61775. {
  61776. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61777. g.setColour (findColour (textColourId));
  61778. g.setFont (getLookAndFeel().getAlertWindowFont());
  61779. int i;
  61780. for (i = textBoxes.size(); --i >= 0;)
  61781. {
  61782. const TextEditor* const te = textBoxes.getUnchecked(i);
  61783. g.drawFittedText (textboxNames[i],
  61784. te->getX(), te->getY() - 14,
  61785. te->getWidth(), 14,
  61786. Justification::centredLeft, 1);
  61787. }
  61788. for (i = comboBoxNames.size(); --i >= 0;)
  61789. {
  61790. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61791. g.drawFittedText (comboBoxNames[i],
  61792. cb->getX(), cb->getY() - 14,
  61793. cb->getWidth(), 14,
  61794. Justification::centredLeft, 1);
  61795. }
  61796. for (i = customComps.size(); --i >= 0;)
  61797. {
  61798. const Component* const c = customComps.getUnchecked(i);
  61799. g.drawFittedText (c->getName(),
  61800. c->getX(), c->getY() - 14,
  61801. c->getWidth(), 14,
  61802. Justification::centredLeft, 1);
  61803. }
  61804. }
  61805. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61806. {
  61807. const int titleH = 24;
  61808. const int iconWidth = 80;
  61809. const int wid = jmax (font.getStringWidth (text),
  61810. font.getStringWidth (getName()));
  61811. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61812. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61813. const int edgeGap = 10;
  61814. const int labelHeight = 18;
  61815. int iconSpace;
  61816. if (alertIconType == NoIcon)
  61817. {
  61818. textLayout.layout (w, Justification::horizontallyCentred, true);
  61819. iconSpace = 0;
  61820. }
  61821. else
  61822. {
  61823. textLayout.layout (w, Justification::left, true);
  61824. iconSpace = iconWidth;
  61825. }
  61826. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61827. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61828. const int textLayoutH = textLayout.getHeight();
  61829. const int textBottom = 16 + titleH + textLayoutH;
  61830. int h = textBottom;
  61831. int buttonW = 40;
  61832. int i;
  61833. for (i = 0; i < buttons.size(); ++i)
  61834. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61835. w = jmax (buttonW, w);
  61836. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61837. if (buttons.size() > 0)
  61838. h += 20 + buttons.getUnchecked(0)->getHeight();
  61839. for (i = customComps.size(); --i >= 0;)
  61840. {
  61841. Component* c = customComps.getUnchecked(i);
  61842. w = jmax (w, (c->getWidth() * 100) / 80);
  61843. h += 10 + c->getHeight();
  61844. if (c->getName().isNotEmpty())
  61845. h += labelHeight;
  61846. }
  61847. for (i = textBlocks.size(); --i >= 0;)
  61848. {
  61849. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61850. w = jmax (w, ac->getPreferredWidth());
  61851. }
  61852. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61853. for (i = textBlocks.size(); --i >= 0;)
  61854. {
  61855. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61856. ac->updateLayout ((int) (w * 0.8f));
  61857. h += ac->getHeight() + 10;
  61858. }
  61859. h = jmin (getParentHeight() - 50, h);
  61860. if (onlyIncreaseSize)
  61861. {
  61862. w = jmax (w, getWidth());
  61863. h = jmax (h, getHeight());
  61864. }
  61865. if (! isVisible())
  61866. {
  61867. centreAroundComponent (associatedComponent, w, h);
  61868. }
  61869. else
  61870. {
  61871. const int cx = getX() + getWidth() / 2;
  61872. const int cy = getY() + getHeight() / 2;
  61873. setBounds (cx - w / 2,
  61874. cy - h / 2,
  61875. w, h);
  61876. }
  61877. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61878. const int spacer = 16;
  61879. int totalWidth = -spacer;
  61880. for (i = buttons.size(); --i >= 0;)
  61881. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61882. int x = (w - totalWidth) / 2;
  61883. int y = (int) (getHeight() * 0.95f);
  61884. for (i = 0; i < buttons.size(); ++i)
  61885. {
  61886. TextButton* const c = buttons.getUnchecked(i);
  61887. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61888. c->setTopLeftPosition (x, ny);
  61889. if (ny < y)
  61890. y = ny;
  61891. x += c->getWidth() + spacer;
  61892. c->toFront (false);
  61893. }
  61894. y = textBottom;
  61895. for (i = 0; i < allComps.size(); ++i)
  61896. {
  61897. Component* const c = allComps.getUnchecked(i);
  61898. h = 22;
  61899. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61900. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61901. y += labelHeight;
  61902. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61903. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61904. y += labelHeight;
  61905. if (customComps.contains (c))
  61906. {
  61907. if (c->getName().isNotEmpty())
  61908. y += labelHeight;
  61909. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61910. h = c->getHeight();
  61911. }
  61912. else if (textBlocks.contains (c))
  61913. {
  61914. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61915. h = c->getHeight();
  61916. }
  61917. else
  61918. {
  61919. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61920. }
  61921. y += h + 10;
  61922. }
  61923. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61924. }
  61925. bool AlertWindow::containsAnyExtraComponents() const
  61926. {
  61927. return allComps.size() > 0;
  61928. }
  61929. void AlertWindow::mouseDown (const MouseEvent& e)
  61930. {
  61931. dragger.startDraggingComponent (this, e);
  61932. }
  61933. void AlertWindow::mouseDrag (const MouseEvent& e)
  61934. {
  61935. dragger.dragComponent (this, e, &constrainer);
  61936. }
  61937. bool AlertWindow::keyPressed (const KeyPress& key)
  61938. {
  61939. for (int i = buttons.size(); --i >= 0;)
  61940. {
  61941. TextButton* const b = buttons.getUnchecked(i);
  61942. if (b->isRegisteredForShortcut (key))
  61943. {
  61944. b->triggerClick();
  61945. return true;
  61946. }
  61947. }
  61948. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61949. {
  61950. exitModalState (0);
  61951. return true;
  61952. }
  61953. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61954. {
  61955. buttons.getUnchecked(0)->triggerClick();
  61956. return true;
  61957. }
  61958. return false;
  61959. }
  61960. void AlertWindow::lookAndFeelChanged()
  61961. {
  61962. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61963. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61964. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61965. }
  61966. int AlertWindow::getDesktopWindowStyleFlags() const
  61967. {
  61968. return getLookAndFeel().getAlertBoxWindowFlags();
  61969. }
  61970. class AlertWindowInfo
  61971. {
  61972. public:
  61973. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  61974. AlertWindow::AlertIconType iconType_, int numButtons_)
  61975. : title (title_), message (message_), iconType (iconType_),
  61976. numButtons (numButtons_), returnValue (0), associatedComponent (component)
  61977. {
  61978. }
  61979. String title, message, button1, button2, button3;
  61980. AlertWindow::AlertIconType iconType;
  61981. int numButtons, returnValue;
  61982. Component::SafePointer<Component> associatedComponent;
  61983. int showModal() const
  61984. {
  61985. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61986. return returnValue;
  61987. }
  61988. private:
  61989. void show()
  61990. {
  61991. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61992. : LookAndFeel::getDefaultLookAndFeel();
  61993. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61994. iconType, numButtons, associatedComponent));
  61995. jassert (alertBox != 0); // you have to return one of these!
  61996. returnValue = alertBox->runModalLoop();
  61997. }
  61998. static void* showCallback (void* userData)
  61999. {
  62000. static_cast <AlertWindowInfo*> (userData)->show();
  62001. return 0;
  62002. }
  62003. };
  62004. void AlertWindow::showMessageBox (AlertIconType iconType,
  62005. const String& title,
  62006. const String& message,
  62007. const String& buttonText,
  62008. Component* associatedComponent)
  62009. {
  62010. AlertWindowInfo info (title, message, associatedComponent, iconType, 1);
  62011. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62012. info.showModal();
  62013. }
  62014. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62015. const String& title,
  62016. const String& message,
  62017. const String& button1Text,
  62018. const String& button2Text,
  62019. Component* associatedComponent)
  62020. {
  62021. AlertWindowInfo info (title, message, associatedComponent, iconType, 2);
  62022. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62023. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62024. return info.showModal() != 0;
  62025. }
  62026. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62027. const String& title,
  62028. const String& message,
  62029. const String& button1Text,
  62030. const String& button2Text,
  62031. const String& button3Text,
  62032. Component* associatedComponent)
  62033. {
  62034. AlertWindowInfo info (title, message, associatedComponent, iconType, 3);
  62035. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62036. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62037. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62038. return info.showModal();
  62039. }
  62040. END_JUCE_NAMESPACE
  62041. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62042. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62043. BEGIN_JUCE_NAMESPACE
  62044. CallOutBox::CallOutBox (Component& contentComponent,
  62045. Component& componentToPointTo,
  62046. Component* const parentComponent)
  62047. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62048. {
  62049. addAndMakeVisible (&content);
  62050. if (parentComponent != 0)
  62051. {
  62052. parentComponent->addChildComponent (this);
  62053. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  62054. parentComponent->getLocalBounds());
  62055. setVisible (true);
  62056. }
  62057. else
  62058. {
  62059. if (! JUCEApplication::isStandaloneApp())
  62060. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62061. updatePosition (componentToPointTo.getScreenBounds(),
  62062. componentToPointTo.getParentMonitorArea());
  62063. addToDesktop (ComponentPeer::windowIsTemporary);
  62064. }
  62065. }
  62066. CallOutBox::~CallOutBox()
  62067. {
  62068. }
  62069. void CallOutBox::setArrowSize (const float newSize)
  62070. {
  62071. arrowSize = newSize;
  62072. borderSpace = jmax (20, (int) arrowSize);
  62073. refreshPath();
  62074. }
  62075. void CallOutBox::paint (Graphics& g)
  62076. {
  62077. if (background.isNull())
  62078. {
  62079. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62080. Graphics g (background);
  62081. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62082. }
  62083. g.setColour (Colours::black);
  62084. g.drawImageAt (background, 0, 0);
  62085. }
  62086. void CallOutBox::resized()
  62087. {
  62088. content.setTopLeftPosition (borderSpace, borderSpace);
  62089. refreshPath();
  62090. }
  62091. void CallOutBox::moved()
  62092. {
  62093. refreshPath();
  62094. }
  62095. void CallOutBox::childBoundsChanged (Component*)
  62096. {
  62097. updatePosition (targetArea, availableArea);
  62098. }
  62099. bool CallOutBox::hitTest (int x, int y)
  62100. {
  62101. return outline.contains ((float) x, (float) y);
  62102. }
  62103. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62104. void CallOutBox::inputAttemptWhenModal()
  62105. {
  62106. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62107. if (targetArea.contains (mousePos))
  62108. {
  62109. // if you click on the area that originally popped-up the callout, you expect it
  62110. // to get rid of the box, but deleting the box here allows the click to pass through and
  62111. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62112. postCommandMessage (callOutBoxDismissCommandId);
  62113. }
  62114. else
  62115. {
  62116. exitModalState (0);
  62117. setVisible (false);
  62118. }
  62119. }
  62120. void CallOutBox::handleCommandMessage (int commandId)
  62121. {
  62122. Component::handleCommandMessage (commandId);
  62123. if (commandId == callOutBoxDismissCommandId)
  62124. {
  62125. exitModalState (0);
  62126. setVisible (false);
  62127. }
  62128. }
  62129. bool CallOutBox::keyPressed (const KeyPress& key)
  62130. {
  62131. if (key.isKeyCode (KeyPress::escapeKey))
  62132. {
  62133. inputAttemptWhenModal();
  62134. return true;
  62135. }
  62136. return false;
  62137. }
  62138. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62139. {
  62140. targetArea = newAreaToPointTo;
  62141. availableArea = newAreaToFitIn;
  62142. Rectangle<int> bounds (0, 0,
  62143. content.getWidth() + borderSpace * 2,
  62144. content.getHeight() + borderSpace * 2);
  62145. const int hw = bounds.getWidth() / 2;
  62146. const int hh = bounds.getHeight() / 2;
  62147. const float hwReduced = (float) (hw - borderSpace * 3);
  62148. const float hhReduced = (float) (hh - borderSpace * 3);
  62149. const float arrowIndent = borderSpace - arrowSize;
  62150. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62151. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62152. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62153. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62154. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62155. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62156. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62157. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62158. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62159. float nearest = 1.0e9f;
  62160. for (int i = 0; i < 4; ++i)
  62161. {
  62162. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62163. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62164. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62165. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62166. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62167. distanceFromCentre *= 2.0f;
  62168. if (distanceFromCentre < nearest)
  62169. {
  62170. nearest = distanceFromCentre;
  62171. targetPoint = targets[i];
  62172. bounds.setPosition ((int) (centre.getX() - hw),
  62173. (int) (centre.getY() - hh));
  62174. }
  62175. }
  62176. setBounds (bounds);
  62177. }
  62178. void CallOutBox::refreshPath()
  62179. {
  62180. repaint();
  62181. background = Image::null;
  62182. outline.clear();
  62183. const float gap = 4.5f;
  62184. const float cornerSize = 9.0f;
  62185. const float cornerSize2 = 2.0f * cornerSize;
  62186. const float arrowBaseWidth = arrowSize * 0.7f;
  62187. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62188. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62189. outline.startNewSubPath (left + cornerSize, top);
  62190. if (targetY <= top)
  62191. {
  62192. outline.lineTo (targetX - arrowBaseWidth, top);
  62193. outline.lineTo (targetX, targetY);
  62194. outline.lineTo (targetX + arrowBaseWidth, top);
  62195. }
  62196. outline.lineTo (right - cornerSize, top);
  62197. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62198. if (targetX >= right)
  62199. {
  62200. outline.lineTo (right, targetY - arrowBaseWidth);
  62201. outline.lineTo (targetX, targetY);
  62202. outline.lineTo (right, targetY + arrowBaseWidth);
  62203. }
  62204. outline.lineTo (right, bottom - cornerSize);
  62205. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62206. if (targetY >= bottom)
  62207. {
  62208. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62209. outline.lineTo (targetX, targetY);
  62210. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62211. }
  62212. outline.lineTo (left + cornerSize, bottom);
  62213. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62214. if (targetX <= left)
  62215. {
  62216. outline.lineTo (left, targetY + arrowBaseWidth);
  62217. outline.lineTo (targetX, targetY);
  62218. outline.lineTo (left, targetY - arrowBaseWidth);
  62219. }
  62220. outline.lineTo (left, top + cornerSize);
  62221. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62222. outline.closeSubPath();
  62223. }
  62224. END_JUCE_NAMESPACE
  62225. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62226. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62227. BEGIN_JUCE_NAMESPACE
  62228. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62229. static Array <ComponentPeer*> heavyweightPeers;
  62230. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62231. : component (component_),
  62232. styleFlags (styleFlags_),
  62233. lastPaintTime (0),
  62234. constrainer (0),
  62235. lastDragAndDropCompUnderMouse (0),
  62236. fakeMouseMessageSent (false),
  62237. isWindowMinimised (false)
  62238. {
  62239. heavyweightPeers.add (this);
  62240. }
  62241. ComponentPeer::~ComponentPeer()
  62242. {
  62243. heavyweightPeers.removeValue (this);
  62244. Desktop::getInstance().triggerFocusCallback();
  62245. }
  62246. int ComponentPeer::getNumPeers() throw()
  62247. {
  62248. return heavyweightPeers.size();
  62249. }
  62250. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62251. {
  62252. return heavyweightPeers [index];
  62253. }
  62254. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62255. {
  62256. for (int i = heavyweightPeers.size(); --i >= 0;)
  62257. {
  62258. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62259. if (peer->getComponent() == component)
  62260. return peer;
  62261. }
  62262. return 0;
  62263. }
  62264. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62265. {
  62266. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62267. }
  62268. void ComponentPeer::updateCurrentModifiers() throw()
  62269. {
  62270. ModifierKeys::updateCurrentModifiers();
  62271. }
  62272. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62273. {
  62274. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62275. jassert (mouse != 0); // not enough sources!
  62276. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62277. }
  62278. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62279. {
  62280. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62281. jassert (mouse != 0); // not enough sources!
  62282. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62283. }
  62284. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62285. {
  62286. Graphics g (&contextToPaintTo);
  62287. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62288. g.saveState();
  62289. #endif
  62290. JUCE_TRY
  62291. {
  62292. component->paintEntireComponent (g, true);
  62293. }
  62294. JUCE_CATCH_EXCEPTION
  62295. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62296. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62297. // clearly when things are being repainted.
  62298. {
  62299. g.restoreState();
  62300. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62301. (uint8) Random::getSystemRandom().nextInt (255),
  62302. (uint8) Random::getSystemRandom().nextInt (255),
  62303. (uint8) 0x50));
  62304. }
  62305. #endif
  62306. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62307. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62308. mess up a lot of the calculations that the library needs to do.
  62309. */
  62310. jassert (roundToInt (10.1f) == 10);
  62311. }
  62312. bool ComponentPeer::handleKeyPress (const int keyCode,
  62313. const juce_wchar textCharacter)
  62314. {
  62315. updateCurrentModifiers();
  62316. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62317. ? Component::getCurrentlyFocusedComponent()
  62318. : component;
  62319. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62320. {
  62321. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62322. if (currentModalComp != 0)
  62323. target = currentModalComp;
  62324. }
  62325. const KeyPress keyInfo (keyCode,
  62326. ModifierKeys::getCurrentModifiers().getRawFlags()
  62327. & ModifierKeys::allKeyboardModifiers,
  62328. textCharacter);
  62329. bool keyWasUsed = false;
  62330. while (target != 0)
  62331. {
  62332. const Component::SafePointer<Component> deletionChecker (target);
  62333. if (target->keyListeners_ != 0)
  62334. {
  62335. for (int i = target->keyListeners_->size(); --i >= 0;)
  62336. {
  62337. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62338. if (keyWasUsed || deletionChecker == 0)
  62339. return keyWasUsed;
  62340. i = jmin (i, target->keyListeners_->size());
  62341. }
  62342. }
  62343. keyWasUsed = target->keyPressed (keyInfo);
  62344. if (keyWasUsed || deletionChecker == 0)
  62345. break;
  62346. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62347. {
  62348. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62349. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62350. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62351. break;
  62352. }
  62353. target = target->parentComponent_;
  62354. }
  62355. return keyWasUsed;
  62356. }
  62357. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62358. {
  62359. updateCurrentModifiers();
  62360. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62361. ? Component::getCurrentlyFocusedComponent()
  62362. : component;
  62363. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62364. {
  62365. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62366. if (currentModalComp != 0)
  62367. target = currentModalComp;
  62368. }
  62369. bool keyWasUsed = false;
  62370. while (target != 0)
  62371. {
  62372. const Component::SafePointer<Component> deletionChecker (target);
  62373. keyWasUsed = target->keyStateChanged (isKeyDown);
  62374. if (keyWasUsed || deletionChecker == 0)
  62375. break;
  62376. if (target->keyListeners_ != 0)
  62377. {
  62378. for (int i = target->keyListeners_->size(); --i >= 0;)
  62379. {
  62380. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62381. if (keyWasUsed || deletionChecker == 0)
  62382. return keyWasUsed;
  62383. i = jmin (i, target->keyListeners_->size());
  62384. }
  62385. }
  62386. target = target->parentComponent_;
  62387. }
  62388. return keyWasUsed;
  62389. }
  62390. void ComponentPeer::handleModifierKeysChange()
  62391. {
  62392. updateCurrentModifiers();
  62393. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62394. if (target == 0)
  62395. target = Component::getCurrentlyFocusedComponent();
  62396. if (target == 0)
  62397. target = component;
  62398. if (target != 0)
  62399. target->internalModifierKeysChanged();
  62400. }
  62401. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62402. {
  62403. Component* const c = Component::getCurrentlyFocusedComponent();
  62404. if (component->isParentOf (c))
  62405. {
  62406. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62407. if (ti != 0 && ti->isTextInputActive())
  62408. return ti;
  62409. }
  62410. return 0;
  62411. }
  62412. void ComponentPeer::handleBroughtToFront()
  62413. {
  62414. updateCurrentModifiers();
  62415. if (component != 0)
  62416. component->internalBroughtToFront();
  62417. }
  62418. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62419. {
  62420. constrainer = newConstrainer;
  62421. }
  62422. void ComponentPeer::handleMovedOrResized()
  62423. {
  62424. updateCurrentModifiers();
  62425. const bool nowMinimised = isMinimised();
  62426. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62427. {
  62428. const Component::SafePointer<Component> deletionChecker (component);
  62429. const Rectangle<int> newBounds (getBounds());
  62430. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62431. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62432. if (wasMoved || wasResized)
  62433. {
  62434. component->bounds_ = newBounds;
  62435. if (wasResized)
  62436. component->repaint();
  62437. component->sendMovedResizedMessages (wasMoved, wasResized);
  62438. if (deletionChecker == 0)
  62439. return;
  62440. }
  62441. }
  62442. if (isWindowMinimised != nowMinimised)
  62443. {
  62444. isWindowMinimised = nowMinimised;
  62445. component->minimisationStateChanged (nowMinimised);
  62446. component->sendVisibilityChangeMessage();
  62447. }
  62448. if (! isFullScreen())
  62449. lastNonFullscreenBounds = component->getBounds();
  62450. }
  62451. void ComponentPeer::handleFocusGain()
  62452. {
  62453. updateCurrentModifiers();
  62454. if (component->isParentOf (lastFocusedComponent))
  62455. {
  62456. Component::currentlyFocusedComponent = lastFocusedComponent;
  62457. Desktop::getInstance().triggerFocusCallback();
  62458. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62459. }
  62460. else
  62461. {
  62462. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62463. component->grabKeyboardFocus();
  62464. else
  62465. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62466. }
  62467. }
  62468. void ComponentPeer::handleFocusLoss()
  62469. {
  62470. updateCurrentModifiers();
  62471. if (component->hasKeyboardFocus (true))
  62472. {
  62473. lastFocusedComponent = Component::currentlyFocusedComponent;
  62474. if (lastFocusedComponent != 0)
  62475. {
  62476. Component::currentlyFocusedComponent = 0;
  62477. Desktop::getInstance().triggerFocusCallback();
  62478. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62479. }
  62480. }
  62481. }
  62482. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62483. {
  62484. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62485. ? static_cast <Component*> (lastFocusedComponent)
  62486. : component;
  62487. }
  62488. void ComponentPeer::handleScreenSizeChange()
  62489. {
  62490. updateCurrentModifiers();
  62491. component->parentSizeChanged();
  62492. handleMovedOrResized();
  62493. }
  62494. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62495. {
  62496. lastNonFullscreenBounds = newBounds;
  62497. }
  62498. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62499. {
  62500. return lastNonFullscreenBounds;
  62501. }
  62502. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62503. {
  62504. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62505. }
  62506. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62507. {
  62508. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62509. }
  62510. namespace ComponentPeerHelpers
  62511. {
  62512. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62513. const StringArray& files,
  62514. FileDragAndDropTarget* const lastOne)
  62515. {
  62516. while (c != 0)
  62517. {
  62518. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62519. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62520. return t;
  62521. c = c->getParentComponent();
  62522. }
  62523. return 0;
  62524. }
  62525. }
  62526. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62527. {
  62528. updateCurrentModifiers();
  62529. FileDragAndDropTarget* lastTarget
  62530. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62531. FileDragAndDropTarget* newTarget = 0;
  62532. Component* const compUnderMouse = component->getComponentAt (position);
  62533. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62534. {
  62535. lastDragAndDropCompUnderMouse = compUnderMouse;
  62536. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62537. if (newTarget != lastTarget)
  62538. {
  62539. if (lastTarget != 0)
  62540. lastTarget->fileDragExit (files);
  62541. dragAndDropTargetComponent = 0;
  62542. if (newTarget != 0)
  62543. {
  62544. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62545. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62546. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62547. }
  62548. }
  62549. }
  62550. else
  62551. {
  62552. newTarget = lastTarget;
  62553. }
  62554. if (newTarget != 0)
  62555. {
  62556. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62557. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62558. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62559. }
  62560. }
  62561. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62562. {
  62563. handleFileDragMove (files, Point<int> (-1, -1));
  62564. jassert (dragAndDropTargetComponent == 0);
  62565. lastDragAndDropCompUnderMouse = 0;
  62566. }
  62567. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62568. {
  62569. handleFileDragMove (files, position);
  62570. if (dragAndDropTargetComponent != 0)
  62571. {
  62572. FileDragAndDropTarget* const target
  62573. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62574. dragAndDropTargetComponent = 0;
  62575. lastDragAndDropCompUnderMouse = 0;
  62576. if (target != 0)
  62577. {
  62578. Component* const targetComp = dynamic_cast <Component*> (target);
  62579. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62580. {
  62581. targetComp->internalModalInputAttempt();
  62582. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62583. return;
  62584. }
  62585. // We'll use an async message to deliver the drop, because if the target decides
  62586. // to run a modal loop, it can gum-up the operating system..
  62587. class AsyncFileDropMessage : public CallbackMessage
  62588. {
  62589. public:
  62590. AsyncFileDropMessage (Component* target_, const Point<int>& position_, const StringArray& files_)
  62591. : target (target_), position (position_), files (files_)
  62592. {
  62593. }
  62594. void messageCallback()
  62595. {
  62596. if (target != 0)
  62597. target->filesDropped (files, position.getX(), position.getY());
  62598. }
  62599. private:
  62600. Component::SafePointer<Component> target;
  62601. Point<int> position;
  62602. StringArray files;
  62603. JUCE_DECLARE_NON_COPYABLE (AsyncFileDropMessage);
  62604. };
  62605. (new AsyncFileDropMessage (targetComp, targetComp->getLocalPoint (component, position), files))->post();
  62606. }
  62607. }
  62608. }
  62609. void ComponentPeer::handleUserClosingWindow()
  62610. {
  62611. updateCurrentModifiers();
  62612. component->userTriedToCloseWindow();
  62613. }
  62614. void ComponentPeer::clearMaskedRegion()
  62615. {
  62616. maskedRegion.clear();
  62617. }
  62618. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62619. {
  62620. maskedRegion.add (x, y, w, h);
  62621. }
  62622. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62623. {
  62624. StringArray s;
  62625. s.add ("Software Renderer");
  62626. return s;
  62627. }
  62628. int ComponentPeer::getCurrentRenderingEngine() throw()
  62629. {
  62630. return 0;
  62631. }
  62632. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62633. {
  62634. }
  62635. END_JUCE_NAMESPACE
  62636. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62637. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62638. BEGIN_JUCE_NAMESPACE
  62639. DialogWindow::DialogWindow (const String& name,
  62640. const Colour& backgroundColour_,
  62641. const bool escapeKeyTriggersCloseButton_,
  62642. const bool addToDesktop_)
  62643. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62644. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62645. {
  62646. }
  62647. DialogWindow::~DialogWindow()
  62648. {
  62649. }
  62650. void DialogWindow::resized()
  62651. {
  62652. DocumentWindow::resized();
  62653. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62654. if (escapeKeyTriggersCloseButton
  62655. && getCloseButton() != 0
  62656. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62657. {
  62658. getCloseButton()->addShortcut (esc);
  62659. }
  62660. }
  62661. int DialogWindow::showModalDialog (const String& dialogTitle,
  62662. Component* contentComponent,
  62663. Component* componentToCentreAround,
  62664. const Colour& colour,
  62665. const bool escapeKeyTriggersCloseButton,
  62666. const bool shouldBeResizable,
  62667. const bool useBottomRightCornerResizer)
  62668. {
  62669. class TempDialogWindow : public DialogWindow
  62670. {
  62671. public:
  62672. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62673. : DialogWindow (title, colour, escapeCloses, true)
  62674. {
  62675. if (! JUCEApplication::isStandaloneApp())
  62676. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62677. }
  62678. void closeButtonPressed()
  62679. {
  62680. setVisible (false);
  62681. }
  62682. private:
  62683. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62684. };
  62685. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62686. dw.setContentComponent (contentComponent, true, true);
  62687. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62688. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62689. const int result = dw.runModalLoop();
  62690. dw.setContentComponent (0, false);
  62691. return result;
  62692. }
  62693. END_JUCE_NAMESPACE
  62694. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62695. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62696. BEGIN_JUCE_NAMESPACE
  62697. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62698. {
  62699. public:
  62700. ButtonListenerProxy (DocumentWindow& owner_)
  62701. : owner (owner_)
  62702. {
  62703. }
  62704. void buttonClicked (Button* button)
  62705. {
  62706. if (button == owner.getMinimiseButton())
  62707. owner.minimiseButtonPressed();
  62708. else if (button == owner.getMaximiseButton())
  62709. owner.maximiseButtonPressed();
  62710. else if (button == owner.getCloseButton())
  62711. owner.closeButtonPressed();
  62712. }
  62713. private:
  62714. DocumentWindow& owner;
  62715. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62716. };
  62717. DocumentWindow::DocumentWindow (const String& title,
  62718. const Colour& backgroundColour,
  62719. const int requiredButtons_,
  62720. const bool addToDesktop_)
  62721. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62722. titleBarHeight (26),
  62723. menuBarHeight (24),
  62724. requiredButtons (requiredButtons_),
  62725. #if JUCE_MAC
  62726. positionTitleBarButtonsOnLeft (true),
  62727. #else
  62728. positionTitleBarButtonsOnLeft (false),
  62729. #endif
  62730. drawTitleTextCentred (true),
  62731. menuBarModel (0)
  62732. {
  62733. setResizeLimits (128, 128, 32768, 32768);
  62734. lookAndFeelChanged();
  62735. }
  62736. DocumentWindow::~DocumentWindow()
  62737. {
  62738. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62739. titleBarButtons[i] = 0;
  62740. menuBar = 0;
  62741. }
  62742. void DocumentWindow::repaintTitleBar()
  62743. {
  62744. repaint (getTitleBarArea());
  62745. }
  62746. void DocumentWindow::setName (const String& newName)
  62747. {
  62748. if (newName != getName())
  62749. {
  62750. Component::setName (newName);
  62751. repaintTitleBar();
  62752. }
  62753. }
  62754. void DocumentWindow::setIcon (const Image& imageToUse)
  62755. {
  62756. titleBarIcon = imageToUse;
  62757. repaintTitleBar();
  62758. }
  62759. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62760. {
  62761. titleBarHeight = newHeight;
  62762. resized();
  62763. repaintTitleBar();
  62764. }
  62765. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62766. const bool positionTitleBarButtonsOnLeft_)
  62767. {
  62768. requiredButtons = requiredButtons_;
  62769. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62770. lookAndFeelChanged();
  62771. }
  62772. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62773. {
  62774. drawTitleTextCentred = textShouldBeCentred;
  62775. repaintTitleBar();
  62776. }
  62777. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62778. const int menuBarHeight_)
  62779. {
  62780. if (menuBarModel != menuBarModel_)
  62781. {
  62782. menuBar = 0;
  62783. menuBarModel = menuBarModel_;
  62784. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62785. : getLookAndFeel().getDefaultMenuBarHeight();
  62786. if (menuBarModel != 0)
  62787. {
  62788. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62789. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62790. menuBar->setEnabled (isActiveWindow());
  62791. }
  62792. resized();
  62793. }
  62794. }
  62795. void DocumentWindow::closeButtonPressed()
  62796. {
  62797. /* If you've got a close button, you have to override this method to get
  62798. rid of your window!
  62799. If the window is just a pop-up, you should override this method and make
  62800. it delete the window in whatever way is appropriate for your app. E.g. you
  62801. might just want to call "delete this".
  62802. If your app is centred around this window such that the whole app should quit when
  62803. the window is closed, then you will probably want to use this method as an opportunity
  62804. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62805. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62806. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62807. or closing it via the taskbar icon on Windows).
  62808. */
  62809. jassertfalse;
  62810. }
  62811. void DocumentWindow::minimiseButtonPressed()
  62812. {
  62813. setMinimised (true);
  62814. }
  62815. void DocumentWindow::maximiseButtonPressed()
  62816. {
  62817. setFullScreen (! isFullScreen());
  62818. }
  62819. void DocumentWindow::paint (Graphics& g)
  62820. {
  62821. ResizableWindow::paint (g);
  62822. if (resizableBorder == 0)
  62823. {
  62824. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62825. const BorderSize border (getBorderThickness());
  62826. g.fillRect (0, 0, getWidth(), border.getTop());
  62827. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62828. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62829. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62830. }
  62831. const Rectangle<int> titleBarArea (getTitleBarArea());
  62832. g.reduceClipRegion (titleBarArea);
  62833. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62834. int titleSpaceX1 = 6;
  62835. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62836. for (int i = 0; i < 3; ++i)
  62837. {
  62838. if (titleBarButtons[i] != 0)
  62839. {
  62840. if (positionTitleBarButtonsOnLeft)
  62841. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62842. else
  62843. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62844. }
  62845. }
  62846. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62847. titleBarArea.getWidth(),
  62848. titleBarArea.getHeight(),
  62849. titleSpaceX1,
  62850. jmax (1, titleSpaceX2 - titleSpaceX1),
  62851. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62852. ! drawTitleTextCentred);
  62853. }
  62854. void DocumentWindow::resized()
  62855. {
  62856. ResizableWindow::resized();
  62857. if (titleBarButtons[1] != 0)
  62858. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62859. const Rectangle<int> titleBarArea (getTitleBarArea());
  62860. getLookAndFeel()
  62861. .positionDocumentWindowButtons (*this,
  62862. titleBarArea.getX(), titleBarArea.getY(),
  62863. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62864. titleBarButtons[0],
  62865. titleBarButtons[1],
  62866. titleBarButtons[2],
  62867. positionTitleBarButtonsOnLeft);
  62868. if (menuBar != 0)
  62869. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62870. titleBarArea.getWidth(), menuBarHeight);
  62871. }
  62872. const BorderSize DocumentWindow::getBorderThickness()
  62873. {
  62874. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62875. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62876. }
  62877. const BorderSize DocumentWindow::getContentComponentBorder()
  62878. {
  62879. BorderSize border (getBorderThickness());
  62880. border.setTop (border.getTop()
  62881. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62882. + (menuBar != 0 ? menuBarHeight : 0));
  62883. return border;
  62884. }
  62885. int DocumentWindow::getTitleBarHeight() const
  62886. {
  62887. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62888. }
  62889. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62890. {
  62891. const BorderSize border (getBorderThickness());
  62892. return Rectangle<int> (border.getLeft(), border.getTop(),
  62893. getWidth() - border.getLeftAndRight(),
  62894. getTitleBarHeight());
  62895. }
  62896. Button* DocumentWindow::getCloseButton() const throw()
  62897. {
  62898. return titleBarButtons[2];
  62899. }
  62900. Button* DocumentWindow::getMinimiseButton() const throw()
  62901. {
  62902. return titleBarButtons[0];
  62903. }
  62904. Button* DocumentWindow::getMaximiseButton() const throw()
  62905. {
  62906. return titleBarButtons[1];
  62907. }
  62908. int DocumentWindow::getDesktopWindowStyleFlags() const
  62909. {
  62910. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62911. if ((requiredButtons & minimiseButton) != 0)
  62912. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62913. if ((requiredButtons & maximiseButton) != 0)
  62914. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62915. if ((requiredButtons & closeButton) != 0)
  62916. styleFlags |= ComponentPeer::windowHasCloseButton;
  62917. return styleFlags;
  62918. }
  62919. void DocumentWindow::lookAndFeelChanged()
  62920. {
  62921. int i;
  62922. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62923. titleBarButtons[i] = 0;
  62924. if (! isUsingNativeTitleBar())
  62925. {
  62926. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62927. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62928. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62929. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62930. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62931. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62932. for (i = 0; i < 3; ++i)
  62933. {
  62934. if (titleBarButtons[i] != 0)
  62935. {
  62936. if (buttonListener == 0)
  62937. buttonListener = new ButtonListenerProxy (*this);
  62938. titleBarButtons[i]->addButtonListener (buttonListener);
  62939. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62940. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62941. Component::addAndMakeVisible (titleBarButtons[i]);
  62942. }
  62943. }
  62944. if (getCloseButton() != 0)
  62945. {
  62946. #if JUCE_MAC
  62947. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62948. #else
  62949. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62950. #endif
  62951. }
  62952. }
  62953. activeWindowStatusChanged();
  62954. ResizableWindow::lookAndFeelChanged();
  62955. }
  62956. void DocumentWindow::parentHierarchyChanged()
  62957. {
  62958. lookAndFeelChanged();
  62959. }
  62960. void DocumentWindow::activeWindowStatusChanged()
  62961. {
  62962. ResizableWindow::activeWindowStatusChanged();
  62963. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62964. if (titleBarButtons[i] != 0)
  62965. titleBarButtons[i]->setEnabled (isActiveWindow());
  62966. if (menuBar != 0)
  62967. menuBar->setEnabled (isActiveWindow());
  62968. }
  62969. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62970. {
  62971. if (getTitleBarArea().contains (e.x, e.y)
  62972. && getMaximiseButton() != 0)
  62973. {
  62974. getMaximiseButton()->triggerClick();
  62975. }
  62976. }
  62977. void DocumentWindow::userTriedToCloseWindow()
  62978. {
  62979. closeButtonPressed();
  62980. }
  62981. END_JUCE_NAMESPACE
  62982. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62983. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62984. BEGIN_JUCE_NAMESPACE
  62985. ResizableWindow::ResizableWindow (const String& name,
  62986. const bool addToDesktop_)
  62987. : TopLevelWindow (name, addToDesktop_),
  62988. resizeToFitContent (false),
  62989. fullscreen (false),
  62990. lastNonFullScreenPos (50, 50, 256, 256),
  62991. constrainer (0)
  62992. #if JUCE_DEBUG
  62993. , hasBeenResized (false)
  62994. #endif
  62995. {
  62996. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62997. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62998. if (addToDesktop_)
  62999. Component::addToDesktop (getDesktopWindowStyleFlags());
  63000. }
  63001. ResizableWindow::ResizableWindow (const String& name,
  63002. const Colour& backgroundColour_,
  63003. const bool addToDesktop_)
  63004. : TopLevelWindow (name, addToDesktop_),
  63005. resizeToFitContent (false),
  63006. fullscreen (false),
  63007. lastNonFullScreenPos (50, 50, 256, 256),
  63008. constrainer (0)
  63009. #if JUCE_DEBUG
  63010. , hasBeenResized (false)
  63011. #endif
  63012. {
  63013. setBackgroundColour (backgroundColour_);
  63014. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63015. if (addToDesktop_)
  63016. Component::addToDesktop (getDesktopWindowStyleFlags());
  63017. }
  63018. ResizableWindow::~ResizableWindow()
  63019. {
  63020. // Don't delete or remove the resizer components yourself! They're managed by the
  63021. // ResizableWindow, and you should leave them alone! You may have deleted them
  63022. // accidentally by careless use of deleteAllChildren()..?
  63023. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  63024. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  63025. resizableCorner = 0;
  63026. resizableBorder = 0;
  63027. contentComponent.deleteAndZero();
  63028. // have you been adding your own components directly to this window..? tut tut tut.
  63029. // Read the instructions for using a ResizableWindow!
  63030. jassert (getNumChildComponents() == 0);
  63031. }
  63032. int ResizableWindow::getDesktopWindowStyleFlags() const
  63033. {
  63034. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63035. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63036. styleFlags |= ComponentPeer::windowIsResizable;
  63037. return styleFlags;
  63038. }
  63039. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63040. const bool deleteOldOne,
  63041. const bool resizeToFit)
  63042. {
  63043. resizeToFitContent = resizeToFit;
  63044. if (newContentComponent != static_cast <Component*> (contentComponent))
  63045. {
  63046. if (deleteOldOne)
  63047. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63048. // external deletion of the content comp)
  63049. else
  63050. removeChildComponent (contentComponent);
  63051. contentComponent = newContentComponent;
  63052. Component::addAndMakeVisible (contentComponent);
  63053. }
  63054. if (resizeToFit)
  63055. childBoundsChanged (contentComponent);
  63056. resized(); // must always be called to position the new content comp
  63057. }
  63058. void ResizableWindow::setContentComponentSize (int width, int height)
  63059. {
  63060. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63061. const BorderSize border (getContentComponentBorder());
  63062. setSize (width + border.getLeftAndRight(),
  63063. height + border.getTopAndBottom());
  63064. }
  63065. const BorderSize ResizableWindow::getBorderThickness()
  63066. {
  63067. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63068. }
  63069. const BorderSize ResizableWindow::getContentComponentBorder()
  63070. {
  63071. return getBorderThickness();
  63072. }
  63073. void ResizableWindow::moved()
  63074. {
  63075. updateLastPos();
  63076. }
  63077. void ResizableWindow::visibilityChanged()
  63078. {
  63079. TopLevelWindow::visibilityChanged();
  63080. updateLastPos();
  63081. }
  63082. void ResizableWindow::resized()
  63083. {
  63084. if (resizableBorder != 0)
  63085. {
  63086. #if JUCE_WINDOWS || JUCE_LINUX
  63087. // hide the resizable border if the OS already provides one..
  63088. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63089. #else
  63090. resizableBorder->setVisible (! isFullScreen());
  63091. #endif
  63092. resizableBorder->setBorderThickness (getBorderThickness());
  63093. resizableBorder->setSize (getWidth(), getHeight());
  63094. resizableBorder->toBack();
  63095. }
  63096. if (resizableCorner != 0)
  63097. {
  63098. #if JUCE_MAC
  63099. // hide the resizable border if the OS already provides one..
  63100. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63101. #else
  63102. resizableCorner->setVisible (! isFullScreen());
  63103. #endif
  63104. const int resizerSize = 18;
  63105. resizableCorner->setBounds (getWidth() - resizerSize,
  63106. getHeight() - resizerSize,
  63107. resizerSize, resizerSize);
  63108. }
  63109. if (contentComponent != 0)
  63110. contentComponent->setBoundsInset (getContentComponentBorder());
  63111. updateLastPos();
  63112. #if JUCE_DEBUG
  63113. hasBeenResized = true;
  63114. #endif
  63115. }
  63116. void ResizableWindow::childBoundsChanged (Component* child)
  63117. {
  63118. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63119. {
  63120. // not going to look very good if this component has a zero size..
  63121. jassert (child->getWidth() > 0);
  63122. jassert (child->getHeight() > 0);
  63123. const BorderSize borders (getContentComponentBorder());
  63124. setSize (child->getWidth() + borders.getLeftAndRight(),
  63125. child->getHeight() + borders.getTopAndBottom());
  63126. }
  63127. }
  63128. void ResizableWindow::activeWindowStatusChanged()
  63129. {
  63130. const BorderSize border (getContentComponentBorder());
  63131. Rectangle<int> area (getLocalBounds());
  63132. repaint (area.removeFromTop (border.getTop()));
  63133. repaint (area.removeFromLeft (border.getLeft()));
  63134. repaint (area.removeFromRight (border.getRight()));
  63135. repaint (area.removeFromBottom (border.getBottom()));
  63136. }
  63137. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63138. const bool useBottomRightCornerResizer)
  63139. {
  63140. if (shouldBeResizable)
  63141. {
  63142. if (useBottomRightCornerResizer)
  63143. {
  63144. resizableBorder = 0;
  63145. if (resizableCorner == 0)
  63146. {
  63147. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63148. resizableCorner->setAlwaysOnTop (true);
  63149. }
  63150. }
  63151. else
  63152. {
  63153. resizableCorner = 0;
  63154. if (resizableBorder == 0)
  63155. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63156. }
  63157. }
  63158. else
  63159. {
  63160. resizableCorner = 0;
  63161. resizableBorder = 0;
  63162. }
  63163. if (isUsingNativeTitleBar())
  63164. recreateDesktopWindow();
  63165. childBoundsChanged (contentComponent);
  63166. resized();
  63167. }
  63168. bool ResizableWindow::isResizable() const throw()
  63169. {
  63170. return resizableCorner != 0
  63171. || resizableBorder != 0;
  63172. }
  63173. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63174. const int newMinimumHeight,
  63175. const int newMaximumWidth,
  63176. const int newMaximumHeight) throw()
  63177. {
  63178. // if you've set up a custom constrainer then these settings won't have any effect..
  63179. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63180. if (constrainer == 0)
  63181. setConstrainer (&defaultConstrainer);
  63182. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63183. newMaximumWidth, newMaximumHeight);
  63184. setBoundsConstrained (getBounds());
  63185. }
  63186. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63187. {
  63188. if (constrainer != newConstrainer)
  63189. {
  63190. constrainer = newConstrainer;
  63191. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63192. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63193. resizableCorner = 0;
  63194. resizableBorder = 0;
  63195. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63196. ComponentPeer* const peer = getPeer();
  63197. if (peer != 0)
  63198. peer->setConstrainer (newConstrainer);
  63199. }
  63200. }
  63201. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63202. {
  63203. if (constrainer != 0)
  63204. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63205. else
  63206. setBounds (bounds);
  63207. }
  63208. void ResizableWindow::paint (Graphics& g)
  63209. {
  63210. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63211. getBorderThickness(), *this);
  63212. if (! isFullScreen())
  63213. {
  63214. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63215. getBorderThickness(), *this);
  63216. }
  63217. #if JUCE_DEBUG
  63218. /* If this fails, then you've probably written a subclass with a resized()
  63219. callback but forgotten to make it call its parent class's resized() method.
  63220. It's important when you override methods like resized(), moved(),
  63221. etc., that you make sure the base class methods also get called.
  63222. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63223. because your content should all be inside the content component - and it's the
  63224. content component's resized() method that you should be using to do your
  63225. layout.
  63226. */
  63227. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63228. #endif
  63229. }
  63230. void ResizableWindow::lookAndFeelChanged()
  63231. {
  63232. resized();
  63233. if (isOnDesktop())
  63234. {
  63235. Component::addToDesktop (getDesktopWindowStyleFlags());
  63236. ComponentPeer* const peer = getPeer();
  63237. if (peer != 0)
  63238. peer->setConstrainer (constrainer);
  63239. }
  63240. }
  63241. const Colour ResizableWindow::getBackgroundColour() const throw()
  63242. {
  63243. return findColour (backgroundColourId, false);
  63244. }
  63245. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63246. {
  63247. Colour backgroundColour (newColour);
  63248. if (! Desktop::canUseSemiTransparentWindows())
  63249. backgroundColour = newColour.withAlpha (1.0f);
  63250. setColour (backgroundColourId, backgroundColour);
  63251. setOpaque (backgroundColour.isOpaque());
  63252. repaint();
  63253. }
  63254. bool ResizableWindow::isFullScreen() const
  63255. {
  63256. if (isOnDesktop())
  63257. {
  63258. ComponentPeer* const peer = getPeer();
  63259. return peer != 0 && peer->isFullScreen();
  63260. }
  63261. return fullscreen;
  63262. }
  63263. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63264. {
  63265. if (shouldBeFullScreen != isFullScreen())
  63266. {
  63267. updateLastPos();
  63268. fullscreen = shouldBeFullScreen;
  63269. if (isOnDesktop())
  63270. {
  63271. ComponentPeer* const peer = getPeer();
  63272. if (peer != 0)
  63273. {
  63274. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63275. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63276. peer->setFullScreen (shouldBeFullScreen);
  63277. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63278. setBounds (lastPos);
  63279. }
  63280. else
  63281. {
  63282. jassertfalse;
  63283. }
  63284. }
  63285. else
  63286. {
  63287. if (shouldBeFullScreen)
  63288. setBounds (0, 0, getParentWidth(), getParentHeight());
  63289. else
  63290. setBounds (lastNonFullScreenPos);
  63291. }
  63292. resized();
  63293. }
  63294. }
  63295. bool ResizableWindow::isMinimised() const
  63296. {
  63297. ComponentPeer* const peer = getPeer();
  63298. return (peer != 0) && peer->isMinimised();
  63299. }
  63300. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63301. {
  63302. if (shouldMinimise != isMinimised())
  63303. {
  63304. ComponentPeer* const peer = getPeer();
  63305. if (peer != 0)
  63306. {
  63307. updateLastPos();
  63308. peer->setMinimised (shouldMinimise);
  63309. }
  63310. else
  63311. {
  63312. jassertfalse;
  63313. }
  63314. }
  63315. }
  63316. void ResizableWindow::updateLastPos()
  63317. {
  63318. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63319. {
  63320. lastNonFullScreenPos = getBounds();
  63321. }
  63322. }
  63323. void ResizableWindow::parentSizeChanged()
  63324. {
  63325. if (isFullScreen() && getParentComponent() != 0)
  63326. {
  63327. setBounds (0, 0, getParentWidth(), getParentHeight());
  63328. }
  63329. }
  63330. const String ResizableWindow::getWindowStateAsString()
  63331. {
  63332. updateLastPos();
  63333. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63334. }
  63335. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63336. {
  63337. StringArray tokens;
  63338. tokens.addTokens (s, false);
  63339. tokens.removeEmptyStrings();
  63340. tokens.trim();
  63341. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63342. const int firstCoord = fs ? 1 : 0;
  63343. if (tokens.size() != firstCoord + 4)
  63344. return false;
  63345. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63346. tokens[firstCoord + 1].getIntValue(),
  63347. tokens[firstCoord + 2].getIntValue(),
  63348. tokens[firstCoord + 3].getIntValue());
  63349. if (newPos.isEmpty())
  63350. return false;
  63351. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63352. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63353. if (peer != 0)
  63354. peer->getFrameSize().addTo (newPos);
  63355. if (! screen.contains (newPos))
  63356. {
  63357. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63358. jmin (newPos.getHeight(), screen.getHeight()));
  63359. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63360. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63361. }
  63362. if (peer != 0)
  63363. {
  63364. peer->getFrameSize().subtractFrom (newPos);
  63365. peer->setNonFullScreenBounds (newPos);
  63366. }
  63367. lastNonFullScreenPos = newPos;
  63368. setFullScreen (fs);
  63369. if (! fs)
  63370. setBoundsConstrained (newPos);
  63371. return true;
  63372. }
  63373. void ResizableWindow::mouseDown (const MouseEvent& e)
  63374. {
  63375. if (! isFullScreen())
  63376. dragger.startDraggingComponent (this, e);
  63377. }
  63378. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63379. {
  63380. if (! isFullScreen())
  63381. dragger.dragComponent (this, e, constrainer);
  63382. }
  63383. #if JUCE_DEBUG
  63384. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63385. {
  63386. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63387. manages its child components automatically, and if you add your own it'll cause
  63388. trouble. Instead, use setContentComponent() to give it a component which
  63389. will be automatically resized and kept in the right place - then you can add
  63390. subcomponents to the content comp. See the notes for the ResizableWindow class
  63391. for more info.
  63392. If you really know what you're doing and want to avoid this assertion, just call
  63393. Component::addChildComponent directly.
  63394. */
  63395. jassertfalse;
  63396. Component::addChildComponent (child, zOrder);
  63397. }
  63398. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63399. {
  63400. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63401. manages its child components automatically, and if you add your own it'll cause
  63402. trouble. Instead, use setContentComponent() to give it a component which
  63403. will be automatically resized and kept in the right place - then you can add
  63404. subcomponents to the content comp. See the notes for the ResizableWindow class
  63405. for more info.
  63406. If you really know what you're doing and want to avoid this assertion, just call
  63407. Component::addAndMakeVisible directly.
  63408. */
  63409. jassertfalse;
  63410. Component::addAndMakeVisible (child, zOrder);
  63411. }
  63412. #endif
  63413. END_JUCE_NAMESPACE
  63414. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63415. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63416. BEGIN_JUCE_NAMESPACE
  63417. SplashScreen::SplashScreen()
  63418. {
  63419. setOpaque (true);
  63420. }
  63421. SplashScreen::~SplashScreen()
  63422. {
  63423. }
  63424. void SplashScreen::show (const String& title,
  63425. const Image& backgroundImage_,
  63426. const int minimumTimeToDisplayFor,
  63427. const bool useDropShadow,
  63428. const bool removeOnMouseClick)
  63429. {
  63430. backgroundImage = backgroundImage_;
  63431. jassert (backgroundImage_.isValid());
  63432. if (backgroundImage_.isValid())
  63433. {
  63434. setOpaque (! backgroundImage_.hasAlphaChannel());
  63435. show (title,
  63436. backgroundImage_.getWidth(),
  63437. backgroundImage_.getHeight(),
  63438. minimumTimeToDisplayFor,
  63439. useDropShadow,
  63440. removeOnMouseClick);
  63441. }
  63442. }
  63443. void SplashScreen::show (const String& title,
  63444. const int width,
  63445. const int height,
  63446. const int minimumTimeToDisplayFor,
  63447. const bool useDropShadow,
  63448. const bool removeOnMouseClick)
  63449. {
  63450. setName (title);
  63451. setAlwaysOnTop (true);
  63452. setVisible (true);
  63453. centreWithSize (width, height);
  63454. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63455. toFront (false);
  63456. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63457. repaint();
  63458. originalClickCounter = removeOnMouseClick
  63459. ? Desktop::getMouseButtonClickCounter()
  63460. : std::numeric_limits<int>::max();
  63461. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63462. startTimer (50);
  63463. }
  63464. void SplashScreen::paint (Graphics& g)
  63465. {
  63466. g.setOpacity (1.0f);
  63467. g.drawImage (backgroundImage,
  63468. 0, 0, getWidth(), getHeight(),
  63469. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63470. }
  63471. void SplashScreen::timerCallback()
  63472. {
  63473. if (Time::getCurrentTime() > earliestTimeToDelete
  63474. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63475. {
  63476. delete this;
  63477. }
  63478. }
  63479. END_JUCE_NAMESPACE
  63480. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63481. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63482. BEGIN_JUCE_NAMESPACE
  63483. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63484. const bool hasProgressBar,
  63485. const bool hasCancelButton,
  63486. const int timeOutMsWhenCancelling_,
  63487. const String& cancelButtonText)
  63488. : Thread ("Juce Progress Window"),
  63489. progress (0.0),
  63490. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63491. {
  63492. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63493. .createAlertWindow (title, String::empty, cancelButtonText,
  63494. String::empty, String::empty,
  63495. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63496. if (hasProgressBar)
  63497. alertWindow->addProgressBarComponent (progress);
  63498. }
  63499. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63500. {
  63501. stopThread (timeOutMsWhenCancelling);
  63502. }
  63503. bool ThreadWithProgressWindow::runThread (const int priority)
  63504. {
  63505. startThread (priority);
  63506. startTimer (100);
  63507. {
  63508. const ScopedLock sl (messageLock);
  63509. alertWindow->setMessage (message);
  63510. }
  63511. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63512. stopThread (timeOutMsWhenCancelling);
  63513. alertWindow->setVisible (false);
  63514. return finishedNaturally;
  63515. }
  63516. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63517. {
  63518. progress = newProgress;
  63519. }
  63520. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63521. {
  63522. const ScopedLock sl (messageLock);
  63523. message = newStatusMessage;
  63524. }
  63525. void ThreadWithProgressWindow::timerCallback()
  63526. {
  63527. if (! isThreadRunning())
  63528. {
  63529. // thread has finished normally..
  63530. alertWindow->exitModalState (1);
  63531. alertWindow->setVisible (false);
  63532. }
  63533. else
  63534. {
  63535. const ScopedLock sl (messageLock);
  63536. alertWindow->setMessage (message);
  63537. }
  63538. }
  63539. END_JUCE_NAMESPACE
  63540. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63541. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63542. BEGIN_JUCE_NAMESPACE
  63543. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63544. const int millisecondsBeforeTipAppears_)
  63545. : Component ("tooltip"),
  63546. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63547. mouseClicks (0),
  63548. lastHideTime (0),
  63549. lastComponentUnderMouse (0),
  63550. changedCompsSinceShown (true)
  63551. {
  63552. if (Desktop::getInstance().getMainMouseSource().canHover())
  63553. startTimer (123);
  63554. setAlwaysOnTop (true);
  63555. setOpaque (true);
  63556. if (parentComponent != 0)
  63557. parentComponent->addChildComponent (this);
  63558. }
  63559. TooltipWindow::~TooltipWindow()
  63560. {
  63561. hide();
  63562. }
  63563. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63564. {
  63565. millisecondsBeforeTipAppears = newTimeMs;
  63566. }
  63567. void TooltipWindow::paint (Graphics& g)
  63568. {
  63569. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63570. }
  63571. void TooltipWindow::mouseEnter (const MouseEvent&)
  63572. {
  63573. hide();
  63574. }
  63575. void TooltipWindow::showFor (const String& tip)
  63576. {
  63577. jassert (tip.isNotEmpty());
  63578. if (tipShowing != tip)
  63579. repaint();
  63580. tipShowing = tip;
  63581. Point<int> mousePos (Desktop::getMousePosition());
  63582. if (getParentComponent() != 0)
  63583. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63584. int x, y, w, h;
  63585. getLookAndFeel().getTooltipSize (tip, w, h);
  63586. if (mousePos.getX() > getParentWidth() / 2)
  63587. x = mousePos.getX() - (w + 12);
  63588. else
  63589. x = mousePos.getX() + 24;
  63590. if (mousePos.getY() > getParentHeight() / 2)
  63591. y = mousePos.getY() - (h + 6);
  63592. else
  63593. y = mousePos.getY() + 6;
  63594. setBounds (x, y, w, h);
  63595. setVisible (true);
  63596. if (getParentComponent() == 0)
  63597. {
  63598. addToDesktop (ComponentPeer::windowHasDropShadow
  63599. | ComponentPeer::windowIsTemporary
  63600. | ComponentPeer::windowIgnoresKeyPresses);
  63601. }
  63602. toFront (false);
  63603. }
  63604. const String TooltipWindow::getTipFor (Component* const c)
  63605. {
  63606. if (c != 0
  63607. && Process::isForegroundProcess()
  63608. && ! Component::isMouseButtonDownAnywhere())
  63609. {
  63610. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63611. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63612. return ttc->getTooltip();
  63613. }
  63614. return String::empty;
  63615. }
  63616. void TooltipWindow::hide()
  63617. {
  63618. tipShowing = String::empty;
  63619. removeFromDesktop();
  63620. setVisible (false);
  63621. }
  63622. void TooltipWindow::timerCallback()
  63623. {
  63624. const unsigned int now = Time::getApproximateMillisecondCounter();
  63625. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63626. const String newTip (getTipFor (newComp));
  63627. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63628. lastComponentUnderMouse = newComp;
  63629. lastTipUnderMouse = newTip;
  63630. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63631. const bool mouseWasClicked = clickCount > mouseClicks;
  63632. mouseClicks = clickCount;
  63633. const Point<int> mousePos (Desktop::getMousePosition());
  63634. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63635. lastMousePos = mousePos;
  63636. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63637. lastCompChangeTime = now;
  63638. if (isVisible() || now < lastHideTime + 500)
  63639. {
  63640. // if a tip is currently visible (or has just disappeared), update to a new one
  63641. // immediately if needed..
  63642. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63643. {
  63644. if (isVisible())
  63645. {
  63646. lastHideTime = now;
  63647. hide();
  63648. }
  63649. }
  63650. else if (tipChanged)
  63651. {
  63652. showFor (newTip);
  63653. }
  63654. }
  63655. else
  63656. {
  63657. // if there isn't currently a tip, but one is needed, only let it
  63658. // appear after a timeout..
  63659. if (newTip.isNotEmpty()
  63660. && newTip != tipShowing
  63661. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63662. {
  63663. showFor (newTip);
  63664. }
  63665. }
  63666. }
  63667. END_JUCE_NAMESPACE
  63668. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63669. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63670. BEGIN_JUCE_NAMESPACE
  63671. /** Keeps track of the active top level window.
  63672. */
  63673. class TopLevelWindowManager : public Timer,
  63674. public DeletedAtShutdown
  63675. {
  63676. public:
  63677. TopLevelWindowManager()
  63678. : currentActive (0)
  63679. {
  63680. }
  63681. ~TopLevelWindowManager()
  63682. {
  63683. clearSingletonInstance();
  63684. }
  63685. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63686. void timerCallback()
  63687. {
  63688. startTimer (jmin (1731, getTimerInterval() * 2));
  63689. TopLevelWindow* active = 0;
  63690. if (Process::isForegroundProcess())
  63691. {
  63692. active = currentActive;
  63693. Component* const c = Component::getCurrentlyFocusedComponent();
  63694. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63695. if (tlw == 0 && c != 0)
  63696. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63697. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63698. if (tlw != 0)
  63699. active = tlw;
  63700. }
  63701. if (active != currentActive)
  63702. {
  63703. currentActive = active;
  63704. for (int i = windows.size(); --i >= 0;)
  63705. {
  63706. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63707. tlw->setWindowActive (isWindowActive (tlw));
  63708. i = jmin (i, windows.size() - 1);
  63709. }
  63710. Desktop::getInstance().triggerFocusCallback();
  63711. }
  63712. }
  63713. bool addWindow (TopLevelWindow* const w)
  63714. {
  63715. windows.add (w);
  63716. startTimer (10);
  63717. return isWindowActive (w);
  63718. }
  63719. void removeWindow (TopLevelWindow* const w)
  63720. {
  63721. startTimer (10);
  63722. if (currentActive == w)
  63723. currentActive = 0;
  63724. windows.removeValue (w);
  63725. if (windows.size() == 0)
  63726. deleteInstance();
  63727. }
  63728. Array <TopLevelWindow*> windows;
  63729. private:
  63730. TopLevelWindow* currentActive;
  63731. bool isWindowActive (TopLevelWindow* const tlw) const
  63732. {
  63733. return (tlw == currentActive
  63734. || tlw->isParentOf (currentActive)
  63735. || tlw->hasKeyboardFocus (true))
  63736. && tlw->isShowing();
  63737. }
  63738. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63739. };
  63740. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63741. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63742. {
  63743. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63744. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63745. }
  63746. TopLevelWindow::TopLevelWindow (const String& name,
  63747. const bool addToDesktop_)
  63748. : Component (name),
  63749. useDropShadow (true),
  63750. useNativeTitleBar (false),
  63751. windowIsActive_ (false)
  63752. {
  63753. setOpaque (true);
  63754. if (addToDesktop_)
  63755. Component::addToDesktop (getDesktopWindowStyleFlags());
  63756. else
  63757. setDropShadowEnabled (true);
  63758. setWantsKeyboardFocus (true);
  63759. setBroughtToFrontOnMouseClick (true);
  63760. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63761. }
  63762. TopLevelWindow::~TopLevelWindow()
  63763. {
  63764. shadower = 0;
  63765. TopLevelWindowManager::getInstance()->removeWindow (this);
  63766. }
  63767. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63768. {
  63769. if (hasKeyboardFocus (true))
  63770. TopLevelWindowManager::getInstance()->timerCallback();
  63771. else
  63772. TopLevelWindowManager::getInstance()->startTimer (10);
  63773. }
  63774. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63775. {
  63776. if (windowIsActive_ != isNowActive)
  63777. {
  63778. windowIsActive_ = isNowActive;
  63779. activeWindowStatusChanged();
  63780. }
  63781. }
  63782. void TopLevelWindow::activeWindowStatusChanged()
  63783. {
  63784. }
  63785. void TopLevelWindow::parentHierarchyChanged()
  63786. {
  63787. setDropShadowEnabled (useDropShadow);
  63788. }
  63789. void TopLevelWindow::visibilityChanged()
  63790. {
  63791. if (isShowing())
  63792. toFront (true);
  63793. }
  63794. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63795. {
  63796. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63797. if (useDropShadow)
  63798. styleFlags |= ComponentPeer::windowHasDropShadow;
  63799. if (useNativeTitleBar)
  63800. styleFlags |= ComponentPeer::windowHasTitleBar;
  63801. return styleFlags;
  63802. }
  63803. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63804. {
  63805. useDropShadow = useShadow;
  63806. if (isOnDesktop())
  63807. {
  63808. shadower = 0;
  63809. Component::addToDesktop (getDesktopWindowStyleFlags());
  63810. }
  63811. else
  63812. {
  63813. if (useShadow && isOpaque())
  63814. {
  63815. if (shadower == 0)
  63816. {
  63817. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63818. if (shadower != 0)
  63819. shadower->setOwner (this);
  63820. }
  63821. }
  63822. else
  63823. {
  63824. shadower = 0;
  63825. }
  63826. }
  63827. }
  63828. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63829. {
  63830. if (useNativeTitleBar != useNativeTitleBar_)
  63831. {
  63832. useNativeTitleBar = useNativeTitleBar_;
  63833. recreateDesktopWindow();
  63834. sendLookAndFeelChange();
  63835. }
  63836. }
  63837. void TopLevelWindow::recreateDesktopWindow()
  63838. {
  63839. if (isOnDesktop())
  63840. {
  63841. Component::addToDesktop (getDesktopWindowStyleFlags());
  63842. toFront (true);
  63843. }
  63844. }
  63845. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63846. {
  63847. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63848. because this class needs to make sure its layout corresponds with settings like whether
  63849. it's got a native title bar or not.
  63850. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63851. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63852. method, then add or remove whatever flags are necessary from this value before returning it.
  63853. */
  63854. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63855. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63856. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63857. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63858. sendLookAndFeelChange();
  63859. }
  63860. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63861. {
  63862. if (c == 0)
  63863. c = TopLevelWindow::getActiveTopLevelWindow();
  63864. if (c == 0)
  63865. {
  63866. centreWithSize (width, height);
  63867. }
  63868. else
  63869. {
  63870. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63871. Rectangle<int> parentArea (c->getParentMonitorArea());
  63872. if (getParentComponent() != 0)
  63873. {
  63874. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63875. parentArea = getParentComponent()->getLocalBounds();
  63876. }
  63877. parentArea.reduce (12, 12);
  63878. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63879. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63880. width, height);
  63881. }
  63882. }
  63883. int TopLevelWindow::getNumTopLevelWindows() throw()
  63884. {
  63885. return TopLevelWindowManager::getInstance()->windows.size();
  63886. }
  63887. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63888. {
  63889. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63890. }
  63891. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63892. {
  63893. TopLevelWindow* best = 0;
  63894. int bestNumTWLParents = -1;
  63895. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63896. {
  63897. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63898. if (tlw->isActiveWindow())
  63899. {
  63900. int numTWLParents = 0;
  63901. const Component* c = tlw->getParentComponent();
  63902. while (c != 0)
  63903. {
  63904. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63905. ++numTWLParents;
  63906. c = c->getParentComponent();
  63907. }
  63908. if (bestNumTWLParents < numTWLParents)
  63909. {
  63910. best = tlw;
  63911. bestNumTWLParents = numTWLParents;
  63912. }
  63913. }
  63914. }
  63915. return best;
  63916. }
  63917. END_JUCE_NAMESPACE
  63918. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63919. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63920. BEGIN_JUCE_NAMESPACE
  63921. namespace RelativeCoordinateHelpers
  63922. {
  63923. void skipComma (const juce_wchar* const s, int& i)
  63924. {
  63925. while (CharacterFunctions::isWhitespace (s[i]))
  63926. ++i;
  63927. if (s[i] == ',')
  63928. ++i;
  63929. }
  63930. }
  63931. const String RelativeCoordinate::Strings::parent ("parent");
  63932. const String RelativeCoordinate::Strings::left ("left");
  63933. const String RelativeCoordinate::Strings::right ("right");
  63934. const String RelativeCoordinate::Strings::top ("top");
  63935. const String RelativeCoordinate::Strings::bottom ("bottom");
  63936. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  63937. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  63938. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  63939. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  63940. RelativeCoordinate::RelativeCoordinate()
  63941. {
  63942. }
  63943. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  63944. : term (term_)
  63945. {
  63946. }
  63947. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  63948. : term (other.term)
  63949. {
  63950. }
  63951. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  63952. {
  63953. term = other.term;
  63954. return *this;
  63955. }
  63956. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63957. : term (absoluteDistanceFromOrigin)
  63958. {
  63959. }
  63960. RelativeCoordinate::RelativeCoordinate (const String& s)
  63961. {
  63962. try
  63963. {
  63964. term = Expression (s);
  63965. }
  63966. catch (...)
  63967. {}
  63968. }
  63969. RelativeCoordinate::~RelativeCoordinate()
  63970. {
  63971. }
  63972. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  63973. {
  63974. return term.toString() == other.term.toString();
  63975. }
  63976. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  63977. {
  63978. return ! operator== (other);
  63979. }
  63980. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  63981. {
  63982. try
  63983. {
  63984. if (context != 0)
  63985. return term.evaluate (*context);
  63986. else
  63987. return term.evaluate();
  63988. }
  63989. catch (...)
  63990. {}
  63991. return 0.0;
  63992. }
  63993. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  63994. {
  63995. try
  63996. {
  63997. if (context != 0)
  63998. term.evaluate (*context);
  63999. else
  64000. term.evaluate();
  64001. }
  64002. catch (...)
  64003. {
  64004. return true;
  64005. }
  64006. return false;
  64007. }
  64008. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64009. {
  64010. try
  64011. {
  64012. if (context != 0)
  64013. {
  64014. term = term.adjustedToGiveNewResult (newPos, *context);
  64015. }
  64016. else
  64017. {
  64018. Expression::EvaluationContext defaultContext;
  64019. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64020. }
  64021. }
  64022. catch (...)
  64023. {}
  64024. }
  64025. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64026. {
  64027. try
  64028. {
  64029. return term.referencesSymbol (coordName, context);
  64030. }
  64031. catch (...)
  64032. {}
  64033. return false;
  64034. }
  64035. bool RelativeCoordinate::isDynamic() const
  64036. {
  64037. return term.usesAnySymbols();
  64038. }
  64039. const String RelativeCoordinate::toString() const
  64040. {
  64041. return term.toString();
  64042. }
  64043. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64044. {
  64045. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64046. if (term.referencesSymbol (oldName, 0))
  64047. term = term.withRenamedSymbol (oldName, newName);
  64048. }
  64049. RelativePoint::RelativePoint()
  64050. {
  64051. }
  64052. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64053. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64054. {
  64055. }
  64056. RelativePoint::RelativePoint (const float x_, const float y_)
  64057. : x (x_), y (y_)
  64058. {
  64059. }
  64060. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64061. : x (x_), y (y_)
  64062. {
  64063. }
  64064. RelativePoint::RelativePoint (const String& s)
  64065. {
  64066. int i = 0;
  64067. x = RelativeCoordinate (Expression::parse (s, i));
  64068. RelativeCoordinateHelpers::skipComma (s, i);
  64069. y = RelativeCoordinate (Expression::parse (s, i));
  64070. }
  64071. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64072. {
  64073. return x == other.x && y == other.y;
  64074. }
  64075. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64076. {
  64077. return ! operator== (other);
  64078. }
  64079. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64080. {
  64081. return Point<float> ((float) x.resolve (context),
  64082. (float) y.resolve (context));
  64083. }
  64084. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64085. {
  64086. x.moveToAbsolute (newPos.getX(), context);
  64087. y.moveToAbsolute (newPos.getY(), context);
  64088. }
  64089. const String RelativePoint::toString() const
  64090. {
  64091. return x.toString() + ", " + y.toString();
  64092. }
  64093. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64094. {
  64095. x.renameSymbolIfUsed (oldName, newName);
  64096. y.renameSymbolIfUsed (oldName, newName);
  64097. }
  64098. bool RelativePoint::isDynamic() const
  64099. {
  64100. return x.isDynamic() || y.isDynamic();
  64101. }
  64102. RelativeRectangle::RelativeRectangle()
  64103. {
  64104. }
  64105. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64106. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64107. : left (left_), right (right_), top (top_), bottom (bottom_)
  64108. {
  64109. }
  64110. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64111. : left (rect.getX()),
  64112. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64113. top (rect.getY()),
  64114. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64115. {
  64116. }
  64117. RelativeRectangle::RelativeRectangle (const String& s)
  64118. {
  64119. int i = 0;
  64120. left = RelativeCoordinate (Expression::parse (s, i));
  64121. RelativeCoordinateHelpers::skipComma (s, i);
  64122. top = RelativeCoordinate (Expression::parse (s, i));
  64123. RelativeCoordinateHelpers::skipComma (s, i);
  64124. right = RelativeCoordinate (Expression::parse (s, i));
  64125. RelativeCoordinateHelpers::skipComma (s, i);
  64126. bottom = RelativeCoordinate (Expression::parse (s, i));
  64127. }
  64128. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64129. {
  64130. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64131. }
  64132. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64133. {
  64134. return ! operator== (other);
  64135. }
  64136. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64137. {
  64138. const double l = left.resolve (context);
  64139. const double r = right.resolve (context);
  64140. const double t = top.resolve (context);
  64141. const double b = bottom.resolve (context);
  64142. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64143. }
  64144. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64145. {
  64146. left.moveToAbsolute (newPos.getX(), context);
  64147. right.moveToAbsolute (newPos.getRight(), context);
  64148. top.moveToAbsolute (newPos.getY(), context);
  64149. bottom.moveToAbsolute (newPos.getBottom(), context);
  64150. }
  64151. const String RelativeRectangle::toString() const
  64152. {
  64153. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64154. }
  64155. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64156. {
  64157. left.renameSymbolIfUsed (oldName, newName);
  64158. right.renameSymbolIfUsed (oldName, newName);
  64159. top.renameSymbolIfUsed (oldName, newName);
  64160. bottom.renameSymbolIfUsed (oldName, newName);
  64161. }
  64162. RelativePointPath::RelativePointPath()
  64163. : usesNonZeroWinding (true),
  64164. containsDynamicPoints (false)
  64165. {
  64166. }
  64167. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64168. : usesNonZeroWinding (true),
  64169. containsDynamicPoints (false)
  64170. {
  64171. ValueTree state (DrawablePath::valueTreeType);
  64172. other.writeTo (state, 0);
  64173. parse (state);
  64174. }
  64175. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64176. : usesNonZeroWinding (true),
  64177. containsDynamicPoints (false)
  64178. {
  64179. parse (drawable);
  64180. }
  64181. RelativePointPath::RelativePointPath (const Path& path)
  64182. {
  64183. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64184. Path::Iterator i (path);
  64185. while (i.next())
  64186. {
  64187. switch (i.elementType)
  64188. {
  64189. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64190. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64191. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64192. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64193. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64194. default: jassertfalse; break;
  64195. }
  64196. }
  64197. }
  64198. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64199. {
  64200. DrawablePath::ValueTreeWrapper wrapper (state);
  64201. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64202. ValueTree pathTree (wrapper.getPathState());
  64203. pathTree.removeAllChildren (undoManager);
  64204. for (int i = 0; i < elements.size(); ++i)
  64205. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64206. }
  64207. void RelativePointPath::parse (const ValueTree& state)
  64208. {
  64209. DrawablePath::ValueTreeWrapper wrapper (state);
  64210. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64211. RelativePoint points[3];
  64212. const ValueTree pathTree (wrapper.getPathState());
  64213. const int num = pathTree.getNumChildren();
  64214. for (int i = 0; i < num; ++i)
  64215. {
  64216. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64217. const int numCps = e.getNumControlPoints();
  64218. for (int j = 0; j < numCps; ++j)
  64219. {
  64220. points[j] = e.getControlPoint (j);
  64221. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64222. }
  64223. const Identifier type (e.getType());
  64224. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64225. elements.add (new StartSubPath (points[0]));
  64226. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64227. elements.add (new CloseSubPath());
  64228. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64229. elements.add (new LineTo (points[0]));
  64230. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64231. elements.add (new QuadraticTo (points[0], points[1]));
  64232. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64233. elements.add (new CubicTo (points[0], points[1], points[2]));
  64234. else
  64235. jassertfalse;
  64236. }
  64237. }
  64238. RelativePointPath::~RelativePointPath()
  64239. {
  64240. }
  64241. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64242. {
  64243. elements.swapWithArray (other.elements);
  64244. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64245. }
  64246. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64247. {
  64248. for (int i = 0; i < elements.size(); ++i)
  64249. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64250. }
  64251. bool RelativePointPath::containsAnyDynamicPoints() const
  64252. {
  64253. return containsDynamicPoints;
  64254. }
  64255. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64256. {
  64257. }
  64258. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64259. : ElementBase (startSubPathElement), startPos (pos)
  64260. {
  64261. }
  64262. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64263. {
  64264. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64265. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64266. return v;
  64267. }
  64268. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64269. {
  64270. path.startNewSubPath (startPos.resolve (coordFinder));
  64271. }
  64272. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64273. {
  64274. numPoints = 1;
  64275. return &startPos;
  64276. }
  64277. RelativePointPath::CloseSubPath::CloseSubPath()
  64278. : ElementBase (closeSubPathElement)
  64279. {
  64280. }
  64281. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64282. {
  64283. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64284. }
  64285. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64286. {
  64287. path.closeSubPath();
  64288. }
  64289. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64290. {
  64291. numPoints = 0;
  64292. return 0;
  64293. }
  64294. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64295. : ElementBase (lineToElement), endPoint (endPoint_)
  64296. {
  64297. }
  64298. const ValueTree RelativePointPath::LineTo::createTree() const
  64299. {
  64300. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64301. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64302. return v;
  64303. }
  64304. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64305. {
  64306. path.lineTo (endPoint.resolve (coordFinder));
  64307. }
  64308. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64309. {
  64310. numPoints = 1;
  64311. return &endPoint;
  64312. }
  64313. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64314. : ElementBase (quadraticToElement)
  64315. {
  64316. controlPoints[0] = controlPoint;
  64317. controlPoints[1] = endPoint;
  64318. }
  64319. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64320. {
  64321. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64322. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64323. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64324. return v;
  64325. }
  64326. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64327. {
  64328. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64329. controlPoints[1].resolve (coordFinder));
  64330. }
  64331. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64332. {
  64333. numPoints = 2;
  64334. return controlPoints;
  64335. }
  64336. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64337. : ElementBase (cubicToElement)
  64338. {
  64339. controlPoints[0] = controlPoint1;
  64340. controlPoints[1] = controlPoint2;
  64341. controlPoints[2] = endPoint;
  64342. }
  64343. const ValueTree RelativePointPath::CubicTo::createTree() const
  64344. {
  64345. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64346. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64347. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64348. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64349. return v;
  64350. }
  64351. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64352. {
  64353. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64354. controlPoints[1].resolve (coordFinder),
  64355. controlPoints[2].resolve (coordFinder));
  64356. }
  64357. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64358. {
  64359. numPoints = 3;
  64360. return controlPoints;
  64361. }
  64362. RelativeParallelogram::RelativeParallelogram()
  64363. {
  64364. }
  64365. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64366. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64367. {
  64368. }
  64369. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64370. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64371. {
  64372. }
  64373. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64374. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64375. {
  64376. }
  64377. RelativeParallelogram::~RelativeParallelogram()
  64378. {
  64379. }
  64380. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64381. {
  64382. points[0] = topLeft.resolve (coordFinder);
  64383. points[1] = topRight.resolve (coordFinder);
  64384. points[2] = bottomLeft.resolve (coordFinder);
  64385. }
  64386. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64387. {
  64388. resolveThreePoints (points, coordFinder);
  64389. points[3] = points[1] + (points[2] - points[0]);
  64390. }
  64391. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64392. {
  64393. Point<float> points[4];
  64394. resolveFourCorners (points, coordFinder);
  64395. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64396. }
  64397. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64398. {
  64399. Point<float> points[4];
  64400. resolveFourCorners (points, coordFinder);
  64401. path.startNewSubPath (points[0]);
  64402. path.lineTo (points[1]);
  64403. path.lineTo (points[3]);
  64404. path.lineTo (points[2]);
  64405. path.closeSubPath();
  64406. }
  64407. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64408. {
  64409. Point<float> corners[3];
  64410. resolveThreePoints (corners, coordFinder);
  64411. const Line<float> top (corners[0], corners[1]);
  64412. const Line<float> left (corners[0], corners[2]);
  64413. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64414. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64415. topRight.moveToAbsolute (newTopRight, coordFinder);
  64416. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64417. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64418. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64419. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64420. }
  64421. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64422. {
  64423. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64424. }
  64425. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64426. {
  64427. return ! operator== (other);
  64428. }
  64429. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64430. {
  64431. const Point<float> tr (corners[1] - corners[0]);
  64432. const Point<float> bl (corners[2] - corners[0]);
  64433. target -= corners[0];
  64434. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64435. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64436. }
  64437. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64438. {
  64439. return corners[0]
  64440. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64441. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64442. }
  64443. END_JUCE_NAMESPACE
  64444. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64445. #endif
  64446. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64447. /*** Start of inlined file: juce_Colour.cpp ***/
  64448. BEGIN_JUCE_NAMESPACE
  64449. namespace ColourHelpers
  64450. {
  64451. uint8 floatAlphaToInt (const float alpha) throw()
  64452. {
  64453. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64454. }
  64455. void convertHSBtoRGB (float h, float s, float v,
  64456. uint8& r, uint8& g, uint8& b) throw()
  64457. {
  64458. v = jlimit (0.0f, 1.0f, v);
  64459. v *= 255.0f;
  64460. const uint8 intV = (uint8) roundToInt (v);
  64461. if (s <= 0)
  64462. {
  64463. r = intV;
  64464. g = intV;
  64465. b = intV;
  64466. }
  64467. else
  64468. {
  64469. s = jmin (1.0f, s);
  64470. h = jlimit (0.0f, 1.0f, h);
  64471. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64472. const float f = h - std::floor (h);
  64473. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64474. const float y = v * (1.0f - s * f);
  64475. const float z = v * (1.0f - (s * (1.0f - f)));
  64476. if (h < 1.0f)
  64477. {
  64478. r = intV;
  64479. g = (uint8) roundToInt (z);
  64480. b = x;
  64481. }
  64482. else if (h < 2.0f)
  64483. {
  64484. r = (uint8) roundToInt (y);
  64485. g = intV;
  64486. b = x;
  64487. }
  64488. else if (h < 3.0f)
  64489. {
  64490. r = x;
  64491. g = intV;
  64492. b = (uint8) roundToInt (z);
  64493. }
  64494. else if (h < 4.0f)
  64495. {
  64496. r = x;
  64497. g = (uint8) roundToInt (y);
  64498. b = intV;
  64499. }
  64500. else if (h < 5.0f)
  64501. {
  64502. r = (uint8) roundToInt (z);
  64503. g = x;
  64504. b = intV;
  64505. }
  64506. else if (h < 6.0f)
  64507. {
  64508. r = intV;
  64509. g = x;
  64510. b = (uint8) roundToInt (y);
  64511. }
  64512. else
  64513. {
  64514. r = 0;
  64515. g = 0;
  64516. b = 0;
  64517. }
  64518. }
  64519. }
  64520. }
  64521. Colour::Colour() throw()
  64522. : argb (0)
  64523. {
  64524. }
  64525. Colour::Colour (const Colour& other) throw()
  64526. : argb (other.argb)
  64527. {
  64528. }
  64529. Colour& Colour::operator= (const Colour& other) throw()
  64530. {
  64531. argb = other.argb;
  64532. return *this;
  64533. }
  64534. bool Colour::operator== (const Colour& other) const throw()
  64535. {
  64536. return argb.getARGB() == other.argb.getARGB();
  64537. }
  64538. bool Colour::operator!= (const Colour& other) const throw()
  64539. {
  64540. return argb.getARGB() != other.argb.getARGB();
  64541. }
  64542. Colour::Colour (const uint32 argb_) throw()
  64543. : argb (argb_)
  64544. {
  64545. }
  64546. Colour::Colour (const uint8 red,
  64547. const uint8 green,
  64548. const uint8 blue) throw()
  64549. {
  64550. argb.setARGB (0xff, red, green, blue);
  64551. }
  64552. const Colour Colour::fromRGB (const uint8 red,
  64553. const uint8 green,
  64554. const uint8 blue) throw()
  64555. {
  64556. return Colour (red, green, blue);
  64557. }
  64558. Colour::Colour (const uint8 red,
  64559. const uint8 green,
  64560. const uint8 blue,
  64561. const uint8 alpha) throw()
  64562. {
  64563. argb.setARGB (alpha, red, green, blue);
  64564. }
  64565. const Colour Colour::fromRGBA (const uint8 red,
  64566. const uint8 green,
  64567. const uint8 blue,
  64568. const uint8 alpha) throw()
  64569. {
  64570. return Colour (red, green, blue, alpha);
  64571. }
  64572. Colour::Colour (const uint8 red,
  64573. const uint8 green,
  64574. const uint8 blue,
  64575. const float alpha) throw()
  64576. {
  64577. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64578. }
  64579. const Colour Colour::fromRGBAFloat (const uint8 red,
  64580. const uint8 green,
  64581. const uint8 blue,
  64582. const float alpha) throw()
  64583. {
  64584. return Colour (red, green, blue, alpha);
  64585. }
  64586. Colour::Colour (const float hue,
  64587. const float saturation,
  64588. const float brightness,
  64589. const float alpha) throw()
  64590. {
  64591. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64592. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64593. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64594. }
  64595. const Colour Colour::fromHSV (const float hue,
  64596. const float saturation,
  64597. const float brightness,
  64598. const float alpha) throw()
  64599. {
  64600. return Colour (hue, saturation, brightness, alpha);
  64601. }
  64602. Colour::Colour (const float hue,
  64603. const float saturation,
  64604. const float brightness,
  64605. const uint8 alpha) throw()
  64606. {
  64607. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64608. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64609. argb.setARGB (alpha, r, g, b);
  64610. }
  64611. Colour::~Colour() throw()
  64612. {
  64613. }
  64614. const PixelARGB Colour::getPixelARGB() const throw()
  64615. {
  64616. PixelARGB p (argb);
  64617. p.premultiply();
  64618. return p;
  64619. }
  64620. uint32 Colour::getARGB() const throw()
  64621. {
  64622. return argb.getARGB();
  64623. }
  64624. bool Colour::isTransparent() const throw()
  64625. {
  64626. return getAlpha() == 0;
  64627. }
  64628. bool Colour::isOpaque() const throw()
  64629. {
  64630. return getAlpha() == 0xff;
  64631. }
  64632. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64633. {
  64634. PixelARGB newCol (argb);
  64635. newCol.setAlpha (newAlpha);
  64636. return Colour (newCol.getARGB());
  64637. }
  64638. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64639. {
  64640. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64641. PixelARGB newCol (argb);
  64642. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64643. return Colour (newCol.getARGB());
  64644. }
  64645. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64646. {
  64647. jassert (alphaMultiplier >= 0);
  64648. PixelARGB newCol (argb);
  64649. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64650. return Colour (newCol.getARGB());
  64651. }
  64652. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64653. {
  64654. const int destAlpha = getAlpha();
  64655. if (destAlpha > 0)
  64656. {
  64657. const int invA = 0xff - (int) src.getAlpha();
  64658. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64659. if (resA > 0)
  64660. {
  64661. const int da = (invA * destAlpha) / resA;
  64662. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64663. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64664. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64665. (uint8) resA);
  64666. }
  64667. return *this;
  64668. }
  64669. else
  64670. {
  64671. return src;
  64672. }
  64673. }
  64674. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64675. {
  64676. if (proportionOfOther <= 0)
  64677. return *this;
  64678. if (proportionOfOther >= 1.0f)
  64679. return other;
  64680. PixelARGB c1 (getPixelARGB());
  64681. const PixelARGB c2 (other.getPixelARGB());
  64682. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64683. c1.unpremultiply();
  64684. return Colour (c1.getARGB());
  64685. }
  64686. float Colour::getFloatRed() const throw()
  64687. {
  64688. return getRed() / 255.0f;
  64689. }
  64690. float Colour::getFloatGreen() const throw()
  64691. {
  64692. return getGreen() / 255.0f;
  64693. }
  64694. float Colour::getFloatBlue() const throw()
  64695. {
  64696. return getBlue() / 255.0f;
  64697. }
  64698. float Colour::getFloatAlpha() const throw()
  64699. {
  64700. return getAlpha() / 255.0f;
  64701. }
  64702. void Colour::getHSB (float& h, float& s, float& v) const throw()
  64703. {
  64704. const int r = getRed();
  64705. const int g = getGreen();
  64706. const int b = getBlue();
  64707. const int hi = jmax (r, g, b);
  64708. const int lo = jmin (r, g, b);
  64709. if (hi != 0)
  64710. {
  64711. s = (hi - lo) / (float) hi;
  64712. if (s != 0)
  64713. {
  64714. const float invDiff = 1.0f / (hi - lo);
  64715. const float red = (hi - r) * invDiff;
  64716. const float green = (hi - g) * invDiff;
  64717. const float blue = (hi - b) * invDiff;
  64718. if (r == hi)
  64719. h = blue - green;
  64720. else if (g == hi)
  64721. h = 2.0f + red - blue;
  64722. else
  64723. h = 4.0f + green - red;
  64724. h *= 1.0f / 6.0f;
  64725. if (h < 0)
  64726. ++h;
  64727. }
  64728. else
  64729. {
  64730. h = 0;
  64731. }
  64732. }
  64733. else
  64734. {
  64735. s = 0;
  64736. h = 0;
  64737. }
  64738. v = hi / 255.0f;
  64739. }
  64740. float Colour::getHue() const throw()
  64741. {
  64742. float h, s, b;
  64743. getHSB (h, s, b);
  64744. return h;
  64745. }
  64746. const Colour Colour::withHue (const float hue) const throw()
  64747. {
  64748. float h, s, b;
  64749. getHSB (h, s, b);
  64750. return Colour (hue, s, b, getAlpha());
  64751. }
  64752. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  64753. {
  64754. float h, s, b;
  64755. getHSB (h, s, b);
  64756. h += amountToRotate;
  64757. h -= std::floor (h);
  64758. return Colour (h, s, b, getAlpha());
  64759. }
  64760. float Colour::getSaturation() const throw()
  64761. {
  64762. float h, s, b;
  64763. getHSB (h, s, b);
  64764. return s;
  64765. }
  64766. const Colour Colour::withSaturation (const float saturation) const throw()
  64767. {
  64768. float h, s, b;
  64769. getHSB (h, s, b);
  64770. return Colour (h, saturation, b, getAlpha());
  64771. }
  64772. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  64773. {
  64774. float h, s, b;
  64775. getHSB (h, s, b);
  64776. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  64777. }
  64778. float Colour::getBrightness() const throw()
  64779. {
  64780. float h, s, b;
  64781. getHSB (h, s, b);
  64782. return b;
  64783. }
  64784. const Colour Colour::withBrightness (const float brightness) const throw()
  64785. {
  64786. float h, s, b;
  64787. getHSB (h, s, b);
  64788. return Colour (h, s, brightness, getAlpha());
  64789. }
  64790. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  64791. {
  64792. float h, s, b;
  64793. getHSB (h, s, b);
  64794. b *= amount;
  64795. if (b > 1.0f)
  64796. b = 1.0f;
  64797. return Colour (h, s, b, getAlpha());
  64798. }
  64799. const Colour Colour::brighter (float amount) const throw()
  64800. {
  64801. amount = 1.0f / (1.0f + amount);
  64802. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  64803. (uint8) (255 - (amount * (255 - getGreen()))),
  64804. (uint8) (255 - (amount * (255 - getBlue()))),
  64805. getAlpha());
  64806. }
  64807. const Colour Colour::darker (float amount) const throw()
  64808. {
  64809. amount = 1.0f / (1.0f + amount);
  64810. return Colour ((uint8) (amount * getRed()),
  64811. (uint8) (amount * getGreen()),
  64812. (uint8) (amount * getBlue()),
  64813. getAlpha());
  64814. }
  64815. const Colour Colour::greyLevel (const float brightness) throw()
  64816. {
  64817. const uint8 level
  64818. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  64819. return Colour (level, level, level);
  64820. }
  64821. const Colour Colour::contrasting (const float amount) const throw()
  64822. {
  64823. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  64824. ? Colours::black
  64825. : Colours::white).withAlpha (amount));
  64826. }
  64827. const Colour Colour::contrasting (const Colour& colour1,
  64828. const Colour& colour2) throw()
  64829. {
  64830. const float b1 = colour1.getBrightness();
  64831. const float b2 = colour2.getBrightness();
  64832. float best = 0.0f;
  64833. float bestDist = 0.0f;
  64834. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  64835. {
  64836. const float d1 = std::abs (i - b1);
  64837. const float d2 = std::abs (i - b2);
  64838. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  64839. if (dist > bestDist)
  64840. {
  64841. best = i;
  64842. bestDist = dist;
  64843. }
  64844. }
  64845. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  64846. .withBrightness (best);
  64847. }
  64848. const String Colour::toString() const
  64849. {
  64850. return String::toHexString ((int) argb.getARGB());
  64851. }
  64852. const Colour Colour::fromString (const String& encodedColourString)
  64853. {
  64854. return Colour ((uint32) encodedColourString.getHexValue32());
  64855. }
  64856. const String Colour::toDisplayString (const bool includeAlphaValue) const
  64857. {
  64858. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  64859. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  64860. .toUpperCase();
  64861. }
  64862. END_JUCE_NAMESPACE
  64863. /*** End of inlined file: juce_Colour.cpp ***/
  64864. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  64865. BEGIN_JUCE_NAMESPACE
  64866. ColourGradient::ColourGradient() throw()
  64867. {
  64868. #if JUCE_DEBUG
  64869. point1.setX (987654.0f);
  64870. #endif
  64871. }
  64872. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  64873. const Colour& colour2, const float x2_, const float y2_,
  64874. const bool isRadial_)
  64875. : point1 (x1_, y1_),
  64876. point2 (x2_, y2_),
  64877. isRadial (isRadial_)
  64878. {
  64879. colours.add (ColourPoint (0.0, colour1));
  64880. colours.add (ColourPoint (1.0, colour2));
  64881. }
  64882. ColourGradient::~ColourGradient()
  64883. {
  64884. }
  64885. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  64886. {
  64887. return point1 == other.point1 && point2 == other.point2
  64888. && isRadial == other.isRadial
  64889. && colours == other.colours;
  64890. }
  64891. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  64892. {
  64893. return ! operator== (other);
  64894. }
  64895. void ColourGradient::clearColours()
  64896. {
  64897. colours.clear();
  64898. }
  64899. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  64900. {
  64901. // must be within the two end-points
  64902. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  64903. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  64904. int i;
  64905. for (i = 0; i < colours.size(); ++i)
  64906. if (colours.getReference(i).position > pos)
  64907. break;
  64908. colours.insert (i, ColourPoint (pos, colour));
  64909. return i;
  64910. }
  64911. void ColourGradient::removeColour (int index)
  64912. {
  64913. jassert (index > 0 && index < colours.size() - 1);
  64914. colours.remove (index);
  64915. }
  64916. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  64917. {
  64918. for (int i = 0; i < colours.size(); ++i)
  64919. {
  64920. Colour& c = colours.getReference(i).colour;
  64921. c = c.withMultipliedAlpha (multiplier);
  64922. }
  64923. }
  64924. int ColourGradient::getNumColours() const throw()
  64925. {
  64926. return colours.size();
  64927. }
  64928. double ColourGradient::getColourPosition (const int index) const throw()
  64929. {
  64930. if (((unsigned int) index) < (unsigned int) colours.size())
  64931. return colours.getReference (index).position;
  64932. return 0;
  64933. }
  64934. const Colour ColourGradient::getColour (const int index) const throw()
  64935. {
  64936. if (((unsigned int) index) < (unsigned int) colours.size())
  64937. return colours.getReference (index).colour;
  64938. return Colour();
  64939. }
  64940. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  64941. {
  64942. if (((unsigned int) index) < (unsigned int) colours.size())
  64943. colours.getReference (index).colour = newColour;
  64944. }
  64945. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  64946. {
  64947. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64948. if (position <= 0 || colours.size() <= 1)
  64949. return colours.getReference(0).colour;
  64950. int i = colours.size() - 1;
  64951. while (position < colours.getReference(i).position)
  64952. --i;
  64953. const ColourPoint& p1 = colours.getReference (i);
  64954. if (i >= colours.size() - 1)
  64955. return p1.colour;
  64956. const ColourPoint& p2 = colours.getReference (i + 1);
  64957. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  64958. }
  64959. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  64960. {
  64961. #if JUCE_DEBUG
  64962. // trying to use the object without setting its co-ordinates? Have a careful read of
  64963. // the comments for the constructors.
  64964. jassert (point1.getX() != 987654.0f);
  64965. #endif
  64966. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  64967. 3 * (int) point1.transformedBy (transform)
  64968. .getDistanceFrom (point2.transformedBy (transform)));
  64969. lookupTable.malloc (numEntries);
  64970. if (colours.size() >= 2)
  64971. {
  64972. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64973. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  64974. int index = 0;
  64975. for (int j = 1; j < colours.size(); ++j)
  64976. {
  64977. const ColourPoint& p = colours.getReference (j);
  64978. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  64979. const PixelARGB pix2 (p.colour.getPixelARGB());
  64980. for (int i = 0; i < numToDo; ++i)
  64981. {
  64982. jassert (index >= 0 && index < numEntries);
  64983. lookupTable[index] = pix1;
  64984. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  64985. ++index;
  64986. }
  64987. pix1 = pix2;
  64988. }
  64989. while (index < numEntries)
  64990. lookupTable [index++] = pix1;
  64991. }
  64992. else
  64993. {
  64994. jassertfalse; // no colours specified!
  64995. }
  64996. return numEntries;
  64997. }
  64998. bool ColourGradient::isOpaque() const throw()
  64999. {
  65000. for (int i = 0; i < colours.size(); ++i)
  65001. if (! colours.getReference(i).colour.isOpaque())
  65002. return false;
  65003. return true;
  65004. }
  65005. bool ColourGradient::isInvisible() const throw()
  65006. {
  65007. for (int i = 0; i < colours.size(); ++i)
  65008. if (! colours.getReference(i).colour.isTransparent())
  65009. return false;
  65010. return true;
  65011. }
  65012. END_JUCE_NAMESPACE
  65013. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65014. /*** Start of inlined file: juce_Colours.cpp ***/
  65015. BEGIN_JUCE_NAMESPACE
  65016. const Colour Colours::transparentBlack (0);
  65017. const Colour Colours::transparentWhite (0x00ffffff);
  65018. const Colour Colours::aliceblue (0xfff0f8ff);
  65019. const Colour Colours::antiquewhite (0xfffaebd7);
  65020. const Colour Colours::aqua (0xff00ffff);
  65021. const Colour Colours::aquamarine (0xff7fffd4);
  65022. const Colour Colours::azure (0xfff0ffff);
  65023. const Colour Colours::beige (0xfff5f5dc);
  65024. const Colour Colours::bisque (0xffffe4c4);
  65025. const Colour Colours::black (0xff000000);
  65026. const Colour Colours::blanchedalmond (0xffffebcd);
  65027. const Colour Colours::blue (0xff0000ff);
  65028. const Colour Colours::blueviolet (0xff8a2be2);
  65029. const Colour Colours::brown (0xffa52a2a);
  65030. const Colour Colours::burlywood (0xffdeb887);
  65031. const Colour Colours::cadetblue (0xff5f9ea0);
  65032. const Colour Colours::chartreuse (0xff7fff00);
  65033. const Colour Colours::chocolate (0xffd2691e);
  65034. const Colour Colours::coral (0xffff7f50);
  65035. const Colour Colours::cornflowerblue (0xff6495ed);
  65036. const Colour Colours::cornsilk (0xfffff8dc);
  65037. const Colour Colours::crimson (0xffdc143c);
  65038. const Colour Colours::cyan (0xff00ffff);
  65039. const Colour Colours::darkblue (0xff00008b);
  65040. const Colour Colours::darkcyan (0xff008b8b);
  65041. const Colour Colours::darkgoldenrod (0xffb8860b);
  65042. const Colour Colours::darkgrey (0xff555555);
  65043. const Colour Colours::darkgreen (0xff006400);
  65044. const Colour Colours::darkkhaki (0xffbdb76b);
  65045. const Colour Colours::darkmagenta (0xff8b008b);
  65046. const Colour Colours::darkolivegreen (0xff556b2f);
  65047. const Colour Colours::darkorange (0xffff8c00);
  65048. const Colour Colours::darkorchid (0xff9932cc);
  65049. const Colour Colours::darkred (0xff8b0000);
  65050. const Colour Colours::darksalmon (0xffe9967a);
  65051. const Colour Colours::darkseagreen (0xff8fbc8f);
  65052. const Colour Colours::darkslateblue (0xff483d8b);
  65053. const Colour Colours::darkslategrey (0xff2f4f4f);
  65054. const Colour Colours::darkturquoise (0xff00ced1);
  65055. const Colour Colours::darkviolet (0xff9400d3);
  65056. const Colour Colours::deeppink (0xffff1493);
  65057. const Colour Colours::deepskyblue (0xff00bfff);
  65058. const Colour Colours::dimgrey (0xff696969);
  65059. const Colour Colours::dodgerblue (0xff1e90ff);
  65060. const Colour Colours::firebrick (0xffb22222);
  65061. const Colour Colours::floralwhite (0xfffffaf0);
  65062. const Colour Colours::forestgreen (0xff228b22);
  65063. const Colour Colours::fuchsia (0xffff00ff);
  65064. const Colour Colours::gainsboro (0xffdcdcdc);
  65065. const Colour Colours::gold (0xffffd700);
  65066. const Colour Colours::goldenrod (0xffdaa520);
  65067. const Colour Colours::grey (0xff808080);
  65068. const Colour Colours::green (0xff008000);
  65069. const Colour Colours::greenyellow (0xffadff2f);
  65070. const Colour Colours::honeydew (0xfff0fff0);
  65071. const Colour Colours::hotpink (0xffff69b4);
  65072. const Colour Colours::indianred (0xffcd5c5c);
  65073. const Colour Colours::indigo (0xff4b0082);
  65074. const Colour Colours::ivory (0xfffffff0);
  65075. const Colour Colours::khaki (0xfff0e68c);
  65076. const Colour Colours::lavender (0xffe6e6fa);
  65077. const Colour Colours::lavenderblush (0xfffff0f5);
  65078. const Colour Colours::lemonchiffon (0xfffffacd);
  65079. const Colour Colours::lightblue (0xffadd8e6);
  65080. const Colour Colours::lightcoral (0xfff08080);
  65081. const Colour Colours::lightcyan (0xffe0ffff);
  65082. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65083. const Colour Colours::lightgreen (0xff90ee90);
  65084. const Colour Colours::lightgrey (0xffd3d3d3);
  65085. const Colour Colours::lightpink (0xffffb6c1);
  65086. const Colour Colours::lightsalmon (0xffffa07a);
  65087. const Colour Colours::lightseagreen (0xff20b2aa);
  65088. const Colour Colours::lightskyblue (0xff87cefa);
  65089. const Colour Colours::lightslategrey (0xff778899);
  65090. const Colour Colours::lightsteelblue (0xffb0c4de);
  65091. const Colour Colours::lightyellow (0xffffffe0);
  65092. const Colour Colours::lime (0xff00ff00);
  65093. const Colour Colours::limegreen (0xff32cd32);
  65094. const Colour Colours::linen (0xfffaf0e6);
  65095. const Colour Colours::magenta (0xffff00ff);
  65096. const Colour Colours::maroon (0xff800000);
  65097. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65098. const Colour Colours::mediumblue (0xff0000cd);
  65099. const Colour Colours::mediumorchid (0xffba55d3);
  65100. const Colour Colours::mediumpurple (0xff9370db);
  65101. const Colour Colours::mediumseagreen (0xff3cb371);
  65102. const Colour Colours::mediumslateblue (0xff7b68ee);
  65103. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65104. const Colour Colours::mediumturquoise (0xff48d1cc);
  65105. const Colour Colours::mediumvioletred (0xffc71585);
  65106. const Colour Colours::midnightblue (0xff191970);
  65107. const Colour Colours::mintcream (0xfff5fffa);
  65108. const Colour Colours::mistyrose (0xffffe4e1);
  65109. const Colour Colours::navajowhite (0xffffdead);
  65110. const Colour Colours::navy (0xff000080);
  65111. const Colour Colours::oldlace (0xfffdf5e6);
  65112. const Colour Colours::olive (0xff808000);
  65113. const Colour Colours::olivedrab (0xff6b8e23);
  65114. const Colour Colours::orange (0xffffa500);
  65115. const Colour Colours::orangered (0xffff4500);
  65116. const Colour Colours::orchid (0xffda70d6);
  65117. const Colour Colours::palegoldenrod (0xffeee8aa);
  65118. const Colour Colours::palegreen (0xff98fb98);
  65119. const Colour Colours::paleturquoise (0xffafeeee);
  65120. const Colour Colours::palevioletred (0xffdb7093);
  65121. const Colour Colours::papayawhip (0xffffefd5);
  65122. const Colour Colours::peachpuff (0xffffdab9);
  65123. const Colour Colours::peru (0xffcd853f);
  65124. const Colour Colours::pink (0xffffc0cb);
  65125. const Colour Colours::plum (0xffdda0dd);
  65126. const Colour Colours::powderblue (0xffb0e0e6);
  65127. const Colour Colours::purple (0xff800080);
  65128. const Colour Colours::red (0xffff0000);
  65129. const Colour Colours::rosybrown (0xffbc8f8f);
  65130. const Colour Colours::royalblue (0xff4169e1);
  65131. const Colour Colours::saddlebrown (0xff8b4513);
  65132. const Colour Colours::salmon (0xfffa8072);
  65133. const Colour Colours::sandybrown (0xfff4a460);
  65134. const Colour Colours::seagreen (0xff2e8b57);
  65135. const Colour Colours::seashell (0xfffff5ee);
  65136. const Colour Colours::sienna (0xffa0522d);
  65137. const Colour Colours::silver (0xffc0c0c0);
  65138. const Colour Colours::skyblue (0xff87ceeb);
  65139. const Colour Colours::slateblue (0xff6a5acd);
  65140. const Colour Colours::slategrey (0xff708090);
  65141. const Colour Colours::snow (0xfffffafa);
  65142. const Colour Colours::springgreen (0xff00ff7f);
  65143. const Colour Colours::steelblue (0xff4682b4);
  65144. const Colour Colours::tan (0xffd2b48c);
  65145. const Colour Colours::teal (0xff008080);
  65146. const Colour Colours::thistle (0xffd8bfd8);
  65147. const Colour Colours::tomato (0xffff6347);
  65148. const Colour Colours::turquoise (0xff40e0d0);
  65149. const Colour Colours::violet (0xffee82ee);
  65150. const Colour Colours::wheat (0xfff5deb3);
  65151. const Colour Colours::white (0xffffffff);
  65152. const Colour Colours::whitesmoke (0xfff5f5f5);
  65153. const Colour Colours::yellow (0xffffff00);
  65154. const Colour Colours::yellowgreen (0xff9acd32);
  65155. const Colour Colours::findColourForName (const String& colourName,
  65156. const Colour& defaultColour)
  65157. {
  65158. static const int presets[] =
  65159. {
  65160. // (first value is the string's hashcode, second is ARGB)
  65161. 0x05978fff, 0xff000000, /* black */
  65162. 0x06bdcc29, 0xffffffff, /* white */
  65163. 0x002e305a, 0xff0000ff, /* blue */
  65164. 0x00308adf, 0xff808080, /* grey */
  65165. 0x05e0cf03, 0xff008000, /* green */
  65166. 0x0001b891, 0xffff0000, /* red */
  65167. 0xd43c6474, 0xffffff00, /* yellow */
  65168. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65169. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65170. 0x002dcebc, 0xff00ffff, /* aqua */
  65171. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65172. 0x0590228f, 0xfff0ffff, /* azure */
  65173. 0x05947fe4, 0xfff5f5dc, /* beige */
  65174. 0xad388e35, 0xffffe4c4, /* bisque */
  65175. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65176. 0x39129959, 0xff8a2be2, /* blueviolet */
  65177. 0x059a8136, 0xffa52a2a, /* brown */
  65178. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65179. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65180. 0x6b748956, 0xff7fff00, /* chartreuse */
  65181. 0x2903623c, 0xffd2691e, /* chocolate */
  65182. 0x05a74431, 0xffff7f50, /* coral */
  65183. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65184. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65185. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65186. 0x002ed323, 0xff00ffff, /* cyan */
  65187. 0x67cc74d0, 0xff00008b, /* darkblue */
  65188. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65189. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65190. 0x67cecf55, 0xff555555, /* darkgrey */
  65191. 0x920b194d, 0xff006400, /* darkgreen */
  65192. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65193. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65194. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65195. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65196. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65197. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65198. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65199. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65200. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65201. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65202. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65203. 0xc8769375, 0xff9400d3, /* darkviolet */
  65204. 0x25832862, 0xffff1493, /* deeppink */
  65205. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65206. 0x634c8b67, 0xff696969, /* dimgrey */
  65207. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65208. 0xef19e3cb, 0xffb22222, /* firebrick */
  65209. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65210. 0xd086fd06, 0xff228b22, /* forestgreen */
  65211. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65212. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65213. 0x00308060, 0xffffd700, /* gold */
  65214. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65215. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65216. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65217. 0x41892743, 0xffff69b4, /* hotpink */
  65218. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65219. 0xb969fed2, 0xff4b0082, /* indigo */
  65220. 0x05fef6a9, 0xfffffff0, /* ivory */
  65221. 0x06149302, 0xfff0e68c, /* khaki */
  65222. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65223. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65224. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65225. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65226. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65227. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65228. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65229. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65230. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65231. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65232. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65233. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65234. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65235. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65236. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65237. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65238. 0x0032afd5, 0xff00ff00, /* lime */
  65239. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65240. 0x06234efa, 0xfffaf0e6, /* linen */
  65241. 0x316858a9, 0xffff00ff, /* magenta */
  65242. 0xbf8ca470, 0xff800000, /* maroon */
  65243. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65244. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65245. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65246. 0x07556b71, 0xff9370db, /* mediumpurple */
  65247. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65248. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65249. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65250. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65251. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65252. 0x168eb32a, 0xff191970, /* midnightblue */
  65253. 0x4306b960, 0xfff5fffa, /* mintcream */
  65254. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65255. 0xe97218a6, 0xffffdead, /* navajowhite */
  65256. 0x00337bb6, 0xff000080, /* navy */
  65257. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65258. 0x064ee1db, 0xff808000, /* olive */
  65259. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65260. 0xc3de262e, 0xffffa500, /* orange */
  65261. 0x58bebba3, 0xffff4500, /* orangered */
  65262. 0xc3def8a3, 0xffda70d6, /* orchid */
  65263. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65264. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65265. 0x74022737, 0xffafeeee, /* paleturquoise */
  65266. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65267. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65268. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65269. 0x003472f8, 0xffcd853f, /* peru */
  65270. 0x00348176, 0xffffc0cb, /* pink */
  65271. 0x00348d94, 0xffdda0dd, /* plum */
  65272. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65273. 0xc5c507bc, 0xff800080, /* purple */
  65274. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65275. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65276. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65277. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65278. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65279. 0x34636c14, 0xff2e8b57, /* seagreen */
  65280. 0x3507fb41, 0xfffff5ee, /* seashell */
  65281. 0xca348772, 0xffa0522d, /* sienna */
  65282. 0xca37d30d, 0xffc0c0c0, /* silver */
  65283. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65284. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65285. 0x44ab37f8, 0xff708090, /* slategrey */
  65286. 0x0035f183, 0xfffffafa, /* snow */
  65287. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65288. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65289. 0x0001bfa1, 0xffd2b48c, /* tan */
  65290. 0x0036425c, 0xff008080, /* teal */
  65291. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65292. 0xcc41600a, 0xffff6347, /* tomato */
  65293. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65294. 0xcf57947f, 0xffee82ee, /* violet */
  65295. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65296. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65297. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65298. };
  65299. const int hash = colourName.trim().toLowerCase().hashCode();
  65300. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65301. if (presets [i] == hash)
  65302. return Colour (presets [i + 1]);
  65303. return defaultColour;
  65304. }
  65305. END_JUCE_NAMESPACE
  65306. /*** End of inlined file: juce_Colours.cpp ***/
  65307. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65308. BEGIN_JUCE_NAMESPACE
  65309. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65310. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65311. const Path& path, const AffineTransform& transform)
  65312. : bounds (bounds_),
  65313. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65314. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65315. needToCheckEmptinesss (true)
  65316. {
  65317. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65318. int* t = table;
  65319. for (int i = bounds.getHeight(); --i >= 0;)
  65320. {
  65321. *t = 0;
  65322. t += lineStrideElements;
  65323. }
  65324. const int topLimit = bounds.getY() << 8;
  65325. const int heightLimit = bounds.getHeight() << 8;
  65326. const int leftLimit = bounds.getX() << 8;
  65327. const int rightLimit = bounds.getRight() << 8;
  65328. PathFlatteningIterator iter (path, transform);
  65329. while (iter.next())
  65330. {
  65331. int y1 = roundToInt (iter.y1 * 256.0f);
  65332. int y2 = roundToInt (iter.y2 * 256.0f);
  65333. if (y1 != y2)
  65334. {
  65335. y1 -= topLimit;
  65336. y2 -= topLimit;
  65337. const int startY = y1;
  65338. int direction = -1;
  65339. if (y1 > y2)
  65340. {
  65341. swapVariables (y1, y2);
  65342. direction = 1;
  65343. }
  65344. if (y1 < 0)
  65345. y1 = 0;
  65346. if (y2 > heightLimit)
  65347. y2 = heightLimit;
  65348. if (y1 < y2)
  65349. {
  65350. const double startX = 256.0f * iter.x1;
  65351. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65352. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65353. do
  65354. {
  65355. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65356. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65357. if (x < leftLimit)
  65358. x = leftLimit;
  65359. else if (x >= rightLimit)
  65360. x = rightLimit - 1;
  65361. addEdgePoint (x, y1 >> 8, direction * step);
  65362. y1 += step;
  65363. }
  65364. while (y1 < y2);
  65365. }
  65366. }
  65367. }
  65368. sanitiseLevels (path.isUsingNonZeroWinding());
  65369. }
  65370. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65371. : bounds (rectangleToAdd),
  65372. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65373. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65374. needToCheckEmptinesss (true)
  65375. {
  65376. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65377. table[0] = 0;
  65378. const int x1 = rectangleToAdd.getX() << 8;
  65379. const int x2 = rectangleToAdd.getRight() << 8;
  65380. int* t = table;
  65381. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65382. {
  65383. t[0] = 2;
  65384. t[1] = x1;
  65385. t[2] = 255;
  65386. t[3] = x2;
  65387. t[4] = 0;
  65388. t += lineStrideElements;
  65389. }
  65390. }
  65391. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65392. : bounds (rectanglesToAdd.getBounds()),
  65393. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65394. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65395. needToCheckEmptinesss (true)
  65396. {
  65397. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65398. int* t = table;
  65399. for (int i = bounds.getHeight(); --i >= 0;)
  65400. {
  65401. *t = 0;
  65402. t += lineStrideElements;
  65403. }
  65404. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65405. {
  65406. const Rectangle<int>* const r = iter.getRectangle();
  65407. const int x1 = r->getX() << 8;
  65408. const int x2 = r->getRight() << 8;
  65409. int y = r->getY() - bounds.getY();
  65410. for (int j = r->getHeight(); --j >= 0;)
  65411. {
  65412. addEdgePoint (x1, y, 255);
  65413. addEdgePoint (x2, y, -255);
  65414. ++y;
  65415. }
  65416. }
  65417. sanitiseLevels (true);
  65418. }
  65419. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65420. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65421. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65422. 2 + (int) rectangleToAdd.getWidth(),
  65423. 2 + (int) rectangleToAdd.getHeight())),
  65424. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65425. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65426. needToCheckEmptinesss (true)
  65427. {
  65428. jassert (! rectangleToAdd.isEmpty());
  65429. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65430. table[0] = 0;
  65431. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65432. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65433. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65434. jassert (y1 < 256);
  65435. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65436. if (x2 <= x1 || y2 <= y1)
  65437. {
  65438. bounds.setHeight (0);
  65439. return;
  65440. }
  65441. int lineY = 0;
  65442. int* t = table;
  65443. if ((y1 >> 8) == (y2 >> 8))
  65444. {
  65445. t[0] = 2;
  65446. t[1] = x1;
  65447. t[2] = y2 - y1;
  65448. t[3] = x2;
  65449. t[4] = 0;
  65450. ++lineY;
  65451. t += lineStrideElements;
  65452. }
  65453. else
  65454. {
  65455. t[0] = 2;
  65456. t[1] = x1;
  65457. t[2] = 255 - (y1 & 255);
  65458. t[3] = x2;
  65459. t[4] = 0;
  65460. ++lineY;
  65461. t += lineStrideElements;
  65462. while (lineY < (y2 >> 8))
  65463. {
  65464. t[0] = 2;
  65465. t[1] = x1;
  65466. t[2] = 255;
  65467. t[3] = x2;
  65468. t[4] = 0;
  65469. ++lineY;
  65470. t += lineStrideElements;
  65471. }
  65472. jassert (lineY < bounds.getHeight());
  65473. t[0] = 2;
  65474. t[1] = x1;
  65475. t[2] = y2 & 255;
  65476. t[3] = x2;
  65477. t[4] = 0;
  65478. ++lineY;
  65479. t += lineStrideElements;
  65480. }
  65481. while (lineY < bounds.getHeight())
  65482. {
  65483. t[0] = 0;
  65484. t += lineStrideElements;
  65485. ++lineY;
  65486. }
  65487. }
  65488. EdgeTable::EdgeTable (const EdgeTable& other)
  65489. {
  65490. operator= (other);
  65491. }
  65492. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65493. {
  65494. bounds = other.bounds;
  65495. maxEdgesPerLine = other.maxEdgesPerLine;
  65496. lineStrideElements = other.lineStrideElements;
  65497. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65498. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65499. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65500. return *this;
  65501. }
  65502. EdgeTable::~EdgeTable()
  65503. {
  65504. }
  65505. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65506. {
  65507. while (--numLines >= 0)
  65508. {
  65509. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65510. src += srcLineStride;
  65511. dest += destLineStride;
  65512. }
  65513. }
  65514. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65515. {
  65516. // Convert the table from relative windings to absolute levels..
  65517. int* lineStart = table;
  65518. for (int i = bounds.getHeight(); --i >= 0;)
  65519. {
  65520. int* line = lineStart;
  65521. lineStart += lineStrideElements;
  65522. int num = *line;
  65523. if (num == 0)
  65524. continue;
  65525. int level = 0;
  65526. if (useNonZeroWinding)
  65527. {
  65528. while (--num > 0)
  65529. {
  65530. line += 2;
  65531. level += *line;
  65532. int corrected = abs (level);
  65533. if (corrected >> 8)
  65534. corrected = 255;
  65535. *line = corrected;
  65536. }
  65537. }
  65538. else
  65539. {
  65540. while (--num > 0)
  65541. {
  65542. line += 2;
  65543. level += *line;
  65544. int corrected = abs (level);
  65545. if (corrected >> 8)
  65546. {
  65547. corrected &= 511;
  65548. if (corrected >> 8)
  65549. corrected = 511 - corrected;
  65550. }
  65551. *line = corrected;
  65552. }
  65553. }
  65554. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65555. }
  65556. }
  65557. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  65558. {
  65559. if (newNumEdgesPerLine != maxEdgesPerLine)
  65560. {
  65561. maxEdgesPerLine = newNumEdgesPerLine;
  65562. jassert (bounds.getHeight() > 0);
  65563. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65564. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65565. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65566. table.swapWith (newTable);
  65567. lineStrideElements = newLineStrideElements;
  65568. }
  65569. }
  65570. void EdgeTable::optimiseTable()
  65571. {
  65572. int maxLineElements = 0;
  65573. for (int i = bounds.getHeight(); --i >= 0;)
  65574. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65575. remapTableForNumEdges (maxLineElements);
  65576. }
  65577. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  65578. {
  65579. jassert (y >= 0 && y < bounds.getHeight());
  65580. int* line = table + lineStrideElements * y;
  65581. const int numPoints = line[0];
  65582. int n = numPoints << 1;
  65583. if (n > 0)
  65584. {
  65585. while (n > 0)
  65586. {
  65587. const int cx = line [n - 1];
  65588. if (cx <= x)
  65589. {
  65590. if (cx == x)
  65591. {
  65592. line [n] += winding;
  65593. return;
  65594. }
  65595. break;
  65596. }
  65597. n -= 2;
  65598. }
  65599. if (numPoints >= maxEdgesPerLine)
  65600. {
  65601. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65602. jassert (numPoints < maxEdgesPerLine);
  65603. line = table + lineStrideElements * y;
  65604. }
  65605. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65606. }
  65607. line [n + 1] = x;
  65608. line [n + 2] = winding;
  65609. line[0]++;
  65610. }
  65611. void EdgeTable::translate (float dx, const int dy) throw()
  65612. {
  65613. bounds.translate ((int) std::floor (dx), dy);
  65614. int* lineStart = table;
  65615. const int intDx = (int) (dx * 256.0f);
  65616. for (int i = bounds.getHeight(); --i >= 0;)
  65617. {
  65618. int* line = lineStart;
  65619. lineStart += lineStrideElements;
  65620. int num = *line++;
  65621. while (--num >= 0)
  65622. {
  65623. *line += intDx;
  65624. line += 2;
  65625. }
  65626. }
  65627. }
  65628. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  65629. {
  65630. jassert (y >= 0 && y < bounds.getHeight());
  65631. int* dest = table + lineStrideElements * y;
  65632. if (dest[0] == 0)
  65633. return;
  65634. int otherNumPoints = *otherLine;
  65635. if (otherNumPoints == 0)
  65636. {
  65637. *dest = 0;
  65638. return;
  65639. }
  65640. const int right = bounds.getRight() << 8;
  65641. // optimise for the common case where our line lies entirely within a
  65642. // single pair of points, as happens when clipping to a simple rect.
  65643. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65644. {
  65645. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65646. return;
  65647. }
  65648. ++otherLine;
  65649. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65650. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65651. memcpy (temp, dest, lineSizeBytes);
  65652. const int* src1 = temp;
  65653. int srcNum1 = *src1++;
  65654. int x1 = *src1++;
  65655. const int* src2 = otherLine;
  65656. int srcNum2 = otherNumPoints;
  65657. int x2 = *src2++;
  65658. int destIndex = 0, destTotal = 0;
  65659. int level1 = 0, level2 = 0;
  65660. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65661. while (srcNum1 > 0 && srcNum2 > 0)
  65662. {
  65663. int nextX;
  65664. if (x1 < x2)
  65665. {
  65666. nextX = x1;
  65667. level1 = *src1++;
  65668. x1 = *src1++;
  65669. --srcNum1;
  65670. }
  65671. else if (x1 == x2)
  65672. {
  65673. nextX = x1;
  65674. level1 = *src1++;
  65675. level2 = *src2++;
  65676. x1 = *src1++;
  65677. x2 = *src2++;
  65678. --srcNum1;
  65679. --srcNum2;
  65680. }
  65681. else
  65682. {
  65683. nextX = x2;
  65684. level2 = *src2++;
  65685. x2 = *src2++;
  65686. --srcNum2;
  65687. }
  65688. if (nextX > lastX)
  65689. {
  65690. if (nextX >= right)
  65691. break;
  65692. lastX = nextX;
  65693. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  65694. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  65695. if (nextLevel != lastLevel)
  65696. {
  65697. if (destTotal >= maxEdgesPerLine)
  65698. {
  65699. dest[0] = destTotal;
  65700. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65701. dest = table + lineStrideElements * y;
  65702. }
  65703. ++destTotal;
  65704. lastLevel = nextLevel;
  65705. dest[++destIndex] = nextX;
  65706. dest[++destIndex] = nextLevel;
  65707. }
  65708. }
  65709. }
  65710. if (lastLevel > 0)
  65711. {
  65712. if (destTotal >= maxEdgesPerLine)
  65713. {
  65714. dest[0] = destTotal;
  65715. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65716. dest = table + lineStrideElements * y;
  65717. }
  65718. ++destTotal;
  65719. dest[++destIndex] = right;
  65720. dest[++destIndex] = 0;
  65721. }
  65722. dest[0] = destTotal;
  65723. #if JUCE_DEBUG
  65724. int last = std::numeric_limits<int>::min();
  65725. for (int i = 0; i < dest[0]; ++i)
  65726. {
  65727. jassert (dest[i * 2 + 1] > last);
  65728. last = dest[i * 2 + 1];
  65729. }
  65730. jassert (dest [dest[0] * 2] == 0);
  65731. #endif
  65732. }
  65733. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  65734. {
  65735. int* lastItem = dest + (dest[0] * 2 - 1);
  65736. if (x2 < lastItem[0])
  65737. {
  65738. if (x2 <= dest[1])
  65739. {
  65740. dest[0] = 0;
  65741. return;
  65742. }
  65743. while (x2 < lastItem[-2])
  65744. {
  65745. --(dest[0]);
  65746. lastItem -= 2;
  65747. }
  65748. lastItem[0] = x2;
  65749. lastItem[1] = 0;
  65750. }
  65751. if (x1 > dest[1])
  65752. {
  65753. while (lastItem[0] > x1)
  65754. lastItem -= 2;
  65755. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  65756. if (itemsRemoved > 0)
  65757. {
  65758. dest[0] -= itemsRemoved;
  65759. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  65760. }
  65761. dest[1] = x1;
  65762. }
  65763. }
  65764. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  65765. {
  65766. const Rectangle<int> clipped (r.getIntersection (bounds));
  65767. if (clipped.isEmpty())
  65768. {
  65769. needToCheckEmptinesss = false;
  65770. bounds.setHeight (0);
  65771. }
  65772. else
  65773. {
  65774. const int top = clipped.getY() - bounds.getY();
  65775. const int bottom = clipped.getBottom() - bounds.getY();
  65776. if (bottom < bounds.getHeight())
  65777. bounds.setHeight (bottom);
  65778. if (clipped.getRight() < bounds.getRight())
  65779. bounds.setRight (clipped.getRight());
  65780. for (int i = top; --i >= 0;)
  65781. table [lineStrideElements * i] = 0;
  65782. if (clipped.getX() > bounds.getX())
  65783. {
  65784. const int x1 = clipped.getX() << 8;
  65785. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  65786. int* line = table + lineStrideElements * top;
  65787. for (int i = bottom - top; --i >= 0;)
  65788. {
  65789. if (line[0] != 0)
  65790. clipEdgeTableLineToRange (line, x1, x2);
  65791. line += lineStrideElements;
  65792. }
  65793. }
  65794. needToCheckEmptinesss = true;
  65795. }
  65796. }
  65797. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  65798. {
  65799. const Rectangle<int> clipped (r.getIntersection (bounds));
  65800. if (! clipped.isEmpty())
  65801. {
  65802. const int top = clipped.getY() - bounds.getY();
  65803. const int bottom = clipped.getBottom() - bounds.getY();
  65804. //XXX optimise here by shortening the table if it fills top or bottom
  65805. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  65806. clipped.getX() << 8, 0,
  65807. clipped.getRight() << 8, 255,
  65808. std::numeric_limits<int>::max(), 0 };
  65809. for (int i = top; i < bottom; ++i)
  65810. intersectWithEdgeTableLine (i, rectLine);
  65811. needToCheckEmptinesss = true;
  65812. }
  65813. }
  65814. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  65815. {
  65816. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  65817. if (clipped.isEmpty())
  65818. {
  65819. needToCheckEmptinesss = false;
  65820. bounds.setHeight (0);
  65821. }
  65822. else
  65823. {
  65824. const int top = clipped.getY() - bounds.getY();
  65825. const int bottom = clipped.getBottom() - bounds.getY();
  65826. if (bottom < bounds.getHeight())
  65827. bounds.setHeight (bottom);
  65828. if (clipped.getRight() < bounds.getRight())
  65829. bounds.setRight (clipped.getRight());
  65830. int i = 0;
  65831. for (i = top; --i >= 0;)
  65832. table [lineStrideElements * i] = 0;
  65833. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  65834. for (i = top; i < bottom; ++i)
  65835. {
  65836. intersectWithEdgeTableLine (i, otherLine);
  65837. otherLine += other.lineStrideElements;
  65838. }
  65839. needToCheckEmptinesss = true;
  65840. }
  65841. }
  65842. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  65843. {
  65844. y -= bounds.getY();
  65845. if (y < 0 || y >= bounds.getHeight())
  65846. return;
  65847. needToCheckEmptinesss = true;
  65848. if (numPixels <= 0)
  65849. {
  65850. table [lineStrideElements * y] = 0;
  65851. return;
  65852. }
  65853. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  65854. int destIndex = 0, lastLevel = 0;
  65855. while (--numPixels >= 0)
  65856. {
  65857. const int alpha = *mask;
  65858. mask += maskStride;
  65859. if (alpha != lastLevel)
  65860. {
  65861. tempLine[++destIndex] = (x << 8);
  65862. tempLine[++destIndex] = alpha;
  65863. lastLevel = alpha;
  65864. }
  65865. ++x;
  65866. }
  65867. if (lastLevel > 0)
  65868. {
  65869. tempLine[++destIndex] = (x << 8);
  65870. tempLine[++destIndex] = 0;
  65871. }
  65872. tempLine[0] = destIndex >> 1;
  65873. intersectWithEdgeTableLine (y, tempLine);
  65874. }
  65875. bool EdgeTable::isEmpty() throw()
  65876. {
  65877. if (needToCheckEmptinesss)
  65878. {
  65879. needToCheckEmptinesss = false;
  65880. int* t = table;
  65881. for (int i = bounds.getHeight(); --i >= 0;)
  65882. {
  65883. if (t[0] > 1)
  65884. return false;
  65885. t += lineStrideElements;
  65886. }
  65887. bounds.setHeight (0);
  65888. }
  65889. return bounds.getHeight() == 0;
  65890. }
  65891. END_JUCE_NAMESPACE
  65892. /*** End of inlined file: juce_EdgeTable.cpp ***/
  65893. /*** Start of inlined file: juce_FillType.cpp ***/
  65894. BEGIN_JUCE_NAMESPACE
  65895. FillType::FillType() throw()
  65896. : colour (0xff000000), image (0)
  65897. {
  65898. }
  65899. FillType::FillType (const Colour& colour_) throw()
  65900. : colour (colour_), image (0)
  65901. {
  65902. }
  65903. FillType::FillType (const ColourGradient& gradient_)
  65904. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  65905. {
  65906. }
  65907. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  65908. : colour (0xff000000), image (image_), transform (transform_)
  65909. {
  65910. }
  65911. FillType::FillType (const FillType& other)
  65912. : colour (other.colour),
  65913. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  65914. image (other.image), transform (other.transform)
  65915. {
  65916. }
  65917. FillType& FillType::operator= (const FillType& other)
  65918. {
  65919. if (this != &other)
  65920. {
  65921. colour = other.colour;
  65922. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  65923. image = other.image;
  65924. transform = other.transform;
  65925. }
  65926. return *this;
  65927. }
  65928. FillType::~FillType() throw()
  65929. {
  65930. }
  65931. bool FillType::operator== (const FillType& other) const
  65932. {
  65933. return colour == other.colour && image == other.image
  65934. && transform == other.transform
  65935. && (gradient == other.gradient
  65936. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  65937. }
  65938. bool FillType::operator!= (const FillType& other) const
  65939. {
  65940. return ! operator== (other);
  65941. }
  65942. void FillType::setColour (const Colour& newColour) throw()
  65943. {
  65944. gradient = 0;
  65945. image = Image::null;
  65946. colour = newColour;
  65947. }
  65948. void FillType::setGradient (const ColourGradient& newGradient)
  65949. {
  65950. if (gradient != 0)
  65951. {
  65952. *gradient = newGradient;
  65953. }
  65954. else
  65955. {
  65956. image = Image::null;
  65957. gradient = new ColourGradient (newGradient);
  65958. colour = Colours::black;
  65959. }
  65960. }
  65961. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  65962. {
  65963. gradient = 0;
  65964. image = image_;
  65965. transform = transform_;
  65966. colour = Colours::black;
  65967. }
  65968. void FillType::setOpacity (const float newOpacity) throw()
  65969. {
  65970. colour = colour.withAlpha (newOpacity);
  65971. }
  65972. bool FillType::isInvisible() const throw()
  65973. {
  65974. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  65975. }
  65976. END_JUCE_NAMESPACE
  65977. /*** End of inlined file: juce_FillType.cpp ***/
  65978. /*** Start of inlined file: juce_Graphics.cpp ***/
  65979. BEGIN_JUCE_NAMESPACE
  65980. namespace
  65981. {
  65982. template <typename Type>
  65983. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  65984. {
  65985. const int maxVal = 0x3fffffff;
  65986. return (int) x >= -maxVal && (int) x <= maxVal
  65987. && (int) y >= -maxVal && (int) y <= maxVal
  65988. && (int) w >= -maxVal && (int) w <= maxVal
  65989. && (int) h >= -maxVal && (int) h <= maxVal;
  65990. }
  65991. }
  65992. LowLevelGraphicsContext::LowLevelGraphicsContext()
  65993. {
  65994. }
  65995. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  65996. {
  65997. }
  65998. Graphics::Graphics (const Image& imageToDrawOnto)
  65999. : context (imageToDrawOnto.createLowLevelContext()),
  66000. contextToDelete (context),
  66001. saveStatePending (false)
  66002. {
  66003. }
  66004. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66005. : context (internalContext),
  66006. saveStatePending (false)
  66007. {
  66008. }
  66009. Graphics::~Graphics()
  66010. {
  66011. }
  66012. void Graphics::resetToDefaultState()
  66013. {
  66014. saveStateIfPending();
  66015. context->setFill (FillType());
  66016. context->setFont (Font());
  66017. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66018. }
  66019. bool Graphics::isVectorDevice() const
  66020. {
  66021. return context->isVectorDevice();
  66022. }
  66023. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66024. {
  66025. saveStateIfPending();
  66026. return context->clipToRectangle (area);
  66027. }
  66028. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66029. {
  66030. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66031. }
  66032. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66033. {
  66034. saveStateIfPending();
  66035. return context->clipToRectangleList (clipRegion);
  66036. }
  66037. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66038. {
  66039. saveStateIfPending();
  66040. context->clipToPath (path, transform);
  66041. return ! context->isClipEmpty();
  66042. }
  66043. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66044. {
  66045. saveStateIfPending();
  66046. context->clipToImageAlpha (image, transform);
  66047. return ! context->isClipEmpty();
  66048. }
  66049. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66050. {
  66051. saveStateIfPending();
  66052. context->excludeClipRectangle (rectangleToExclude);
  66053. }
  66054. bool Graphics::isClipEmpty() const
  66055. {
  66056. return context->isClipEmpty();
  66057. }
  66058. const Rectangle<int> Graphics::getClipBounds() const
  66059. {
  66060. return context->getClipBounds();
  66061. }
  66062. void Graphics::saveState()
  66063. {
  66064. saveStateIfPending();
  66065. saveStatePending = true;
  66066. }
  66067. void Graphics::restoreState()
  66068. {
  66069. if (saveStatePending)
  66070. saveStatePending = false;
  66071. else
  66072. context->restoreState();
  66073. }
  66074. void Graphics::saveStateIfPending()
  66075. {
  66076. if (saveStatePending)
  66077. {
  66078. saveStatePending = false;
  66079. context->saveState();
  66080. }
  66081. }
  66082. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66083. {
  66084. saveStateIfPending();
  66085. context->setOrigin (newOriginX, newOriginY);
  66086. }
  66087. void Graphics::addTransform (const AffineTransform& transform)
  66088. {
  66089. saveStateIfPending();
  66090. context->addTransform (transform);
  66091. }
  66092. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66093. {
  66094. return context->clipRegionIntersects (area);
  66095. }
  66096. void Graphics::beginTransparencyLayer (float layerOpacity)
  66097. {
  66098. saveStateIfPending();
  66099. context->beginTransparencyLayer (layerOpacity);
  66100. }
  66101. void Graphics::endTransparencyLayer()
  66102. {
  66103. context->endTransparencyLayer();
  66104. }
  66105. void Graphics::setColour (const Colour& newColour)
  66106. {
  66107. saveStateIfPending();
  66108. context->setFill (newColour);
  66109. }
  66110. void Graphics::setOpacity (const float newOpacity)
  66111. {
  66112. saveStateIfPending();
  66113. context->setOpacity (newOpacity);
  66114. }
  66115. void Graphics::setGradientFill (const ColourGradient& gradient)
  66116. {
  66117. setFillType (gradient);
  66118. }
  66119. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66120. {
  66121. saveStateIfPending();
  66122. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66123. context->setOpacity (opacity);
  66124. }
  66125. void Graphics::setFillType (const FillType& newFill)
  66126. {
  66127. saveStateIfPending();
  66128. context->setFill (newFill);
  66129. }
  66130. void Graphics::setFont (const Font& newFont)
  66131. {
  66132. saveStateIfPending();
  66133. context->setFont (newFont);
  66134. }
  66135. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66136. {
  66137. saveStateIfPending();
  66138. Font f (context->getFont());
  66139. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66140. context->setFont (f);
  66141. }
  66142. const Font Graphics::getCurrentFont() const
  66143. {
  66144. return context->getFont();
  66145. }
  66146. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66147. {
  66148. if (text.isNotEmpty()
  66149. && startX < context->getClipBounds().getRight())
  66150. {
  66151. GlyphArrangement arr;
  66152. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66153. arr.draw (*this);
  66154. }
  66155. }
  66156. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66157. {
  66158. if (text.isNotEmpty())
  66159. {
  66160. GlyphArrangement arr;
  66161. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66162. arr.draw (*this, transform);
  66163. }
  66164. }
  66165. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66166. {
  66167. if (text.isNotEmpty()
  66168. && startX < context->getClipBounds().getRight())
  66169. {
  66170. GlyphArrangement arr;
  66171. arr.addJustifiedText (context->getFont(), text,
  66172. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66173. Justification::left);
  66174. arr.draw (*this);
  66175. }
  66176. }
  66177. void Graphics::drawText (const String& text,
  66178. const int x, const int y, const int width, const int height,
  66179. const Justification& justificationType,
  66180. const bool useEllipsesIfTooBig) const
  66181. {
  66182. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66183. {
  66184. GlyphArrangement arr;
  66185. arr.addCurtailedLineOfText (context->getFont(), text,
  66186. 0.0f, 0.0f, (float) width,
  66187. useEllipsesIfTooBig);
  66188. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66189. (float) x, (float) y, (float) width, (float) height,
  66190. justificationType);
  66191. arr.draw (*this);
  66192. }
  66193. }
  66194. void Graphics::drawFittedText (const String& text,
  66195. const int x, const int y, const int width, const int height,
  66196. const Justification& justification,
  66197. const int maximumNumberOfLines,
  66198. const float minimumHorizontalScale) const
  66199. {
  66200. if (text.isNotEmpty()
  66201. && width > 0 && height > 0
  66202. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66203. {
  66204. GlyphArrangement arr;
  66205. arr.addFittedText (context->getFont(), text,
  66206. (float) x, (float) y, (float) width, (float) height,
  66207. justification,
  66208. maximumNumberOfLines,
  66209. minimumHorizontalScale);
  66210. arr.draw (*this);
  66211. }
  66212. }
  66213. void Graphics::fillRect (int x, int y, int width, int height) const
  66214. {
  66215. // passing in a silly number can cause maths problems in rendering!
  66216. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66217. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66218. }
  66219. void Graphics::fillRect (const Rectangle<int>& r) const
  66220. {
  66221. context->fillRect (r, false);
  66222. }
  66223. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66224. {
  66225. // passing in a silly number can cause maths problems in rendering!
  66226. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66227. Path p;
  66228. p.addRectangle (x, y, width, height);
  66229. fillPath (p);
  66230. }
  66231. void Graphics::setPixel (int x, int y) const
  66232. {
  66233. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66234. }
  66235. void Graphics::fillAll() const
  66236. {
  66237. fillRect (context->getClipBounds());
  66238. }
  66239. void Graphics::fillAll (const Colour& colourToUse) const
  66240. {
  66241. if (! colourToUse.isTransparent())
  66242. {
  66243. const Rectangle<int> clip (context->getClipBounds());
  66244. context->saveState();
  66245. context->setFill (colourToUse);
  66246. context->fillRect (clip, false);
  66247. context->restoreState();
  66248. }
  66249. }
  66250. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66251. {
  66252. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66253. context->fillPath (path, transform);
  66254. }
  66255. void Graphics::strokePath (const Path& path,
  66256. const PathStrokeType& strokeType,
  66257. const AffineTransform& transform) const
  66258. {
  66259. Path stroke;
  66260. strokeType.createStrokedPath (stroke, path, transform);
  66261. fillPath (stroke);
  66262. }
  66263. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66264. const int lineThickness) const
  66265. {
  66266. // passing in a silly number can cause maths problems in rendering!
  66267. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66268. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66269. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66270. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66271. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66272. }
  66273. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66274. {
  66275. // passing in a silly number can cause maths problems in rendering!
  66276. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66277. Path p;
  66278. p.addRectangle (x, y, width, lineThickness);
  66279. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66280. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66281. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66282. fillPath (p);
  66283. }
  66284. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66285. {
  66286. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66287. }
  66288. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66289. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66290. const bool useGradient, const bool sharpEdgeOnOutside) const
  66291. {
  66292. // passing in a silly number can cause maths problems in rendering!
  66293. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66294. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66295. {
  66296. context->saveState();
  66297. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66298. const float ramp = oldOpacity / bevelThickness;
  66299. for (int i = bevelThickness; --i >= 0;)
  66300. {
  66301. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66302. : oldOpacity;
  66303. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66304. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66305. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66306. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66307. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66308. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66309. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66310. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66311. }
  66312. context->restoreState();
  66313. }
  66314. }
  66315. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66316. {
  66317. // passing in a silly number can cause maths problems in rendering!
  66318. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66319. Path p;
  66320. p.addEllipse (x, y, width, height);
  66321. fillPath (p);
  66322. }
  66323. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66324. const float lineThickness) const
  66325. {
  66326. // passing in a silly number can cause maths problems in rendering!
  66327. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66328. Path p;
  66329. p.addEllipse (x, y, width, height);
  66330. strokePath (p, PathStrokeType (lineThickness));
  66331. }
  66332. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66333. {
  66334. // passing in a silly number can cause maths problems in rendering!
  66335. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66336. Path p;
  66337. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66338. fillPath (p);
  66339. }
  66340. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66341. {
  66342. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66343. }
  66344. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66345. const float cornerSize, const float lineThickness) const
  66346. {
  66347. // passing in a silly number can cause maths problems in rendering!
  66348. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66349. Path p;
  66350. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66351. strokePath (p, PathStrokeType (lineThickness));
  66352. }
  66353. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66354. {
  66355. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66356. }
  66357. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66358. {
  66359. Path p;
  66360. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66361. fillPath (p);
  66362. }
  66363. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66364. const int checkWidth, const int checkHeight,
  66365. const Colour& colour1, const Colour& colour2) const
  66366. {
  66367. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66368. if (checkWidth > 0 && checkHeight > 0)
  66369. {
  66370. context->saveState();
  66371. if (colour1 == colour2)
  66372. {
  66373. context->setFill (colour1);
  66374. context->fillRect (area, false);
  66375. }
  66376. else
  66377. {
  66378. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66379. if (! clipped.isEmpty())
  66380. {
  66381. context->clipToRectangle (clipped);
  66382. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66383. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66384. const int startX = area.getX() + checkNumX * checkWidth;
  66385. const int startY = area.getY() + checkNumY * checkHeight;
  66386. const int right = clipped.getRight();
  66387. const int bottom = clipped.getBottom();
  66388. for (int i = 0; i < 2; ++i)
  66389. {
  66390. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66391. int cy = i;
  66392. for (int y = startY; y < bottom; y += checkHeight)
  66393. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66394. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66395. }
  66396. }
  66397. }
  66398. context->restoreState();
  66399. }
  66400. }
  66401. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66402. {
  66403. context->drawVerticalLine (x, top, bottom);
  66404. }
  66405. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66406. {
  66407. context->drawHorizontalLine (y, left, right);
  66408. }
  66409. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66410. {
  66411. context->drawLine (Line<float> (x1, y1, x2, y2));
  66412. }
  66413. void Graphics::drawLine (const float startX, const float startY,
  66414. const float endX, const float endY,
  66415. const float lineThickness) const
  66416. {
  66417. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66418. }
  66419. void Graphics::drawLine (const Line<float>& line) const
  66420. {
  66421. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66422. }
  66423. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66424. {
  66425. Path p;
  66426. p.addLineSegment (line, lineThickness);
  66427. fillPath (p);
  66428. }
  66429. void Graphics::drawDashedLine (const float startX, const float startY,
  66430. const float endX, const float endY,
  66431. const float* const dashLengths,
  66432. const int numDashLengths,
  66433. const float lineThickness) const
  66434. {
  66435. const double dx = endX - startX;
  66436. const double dy = endY - startY;
  66437. const double totalLen = juce_hypot (dx, dy);
  66438. if (totalLen >= 0.5)
  66439. {
  66440. const double onePixAlpha = 1.0 / totalLen;
  66441. double alpha = 0.0;
  66442. float x = startX;
  66443. float y = startY;
  66444. int n = 0;
  66445. while (alpha < 1.0f)
  66446. {
  66447. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66448. n = n % numDashLengths;
  66449. const float oldX = x;
  66450. const float oldY = y;
  66451. x = (float) (startX + dx * alpha);
  66452. y = (float) (startY + dy * alpha);
  66453. if ((n & 1) != 0)
  66454. {
  66455. if (lineThickness != 1.0f)
  66456. drawLine (oldX, oldY, x, y, lineThickness);
  66457. else
  66458. drawLine (oldX, oldY, x, y);
  66459. }
  66460. }
  66461. }
  66462. }
  66463. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66464. {
  66465. saveStateIfPending();
  66466. context->setInterpolationQuality (newQuality);
  66467. }
  66468. void Graphics::drawImageAt (const Image& imageToDraw,
  66469. const int topLeftX, const int topLeftY,
  66470. const bool fillAlphaChannelWithCurrentBrush) const
  66471. {
  66472. const int imageW = imageToDraw.getWidth();
  66473. const int imageH = imageToDraw.getHeight();
  66474. drawImage (imageToDraw,
  66475. topLeftX, topLeftY, imageW, imageH,
  66476. 0, 0, imageW, imageH,
  66477. fillAlphaChannelWithCurrentBrush);
  66478. }
  66479. void Graphics::drawImageWithin (const Image& imageToDraw,
  66480. const int destX, const int destY,
  66481. const int destW, const int destH,
  66482. const RectanglePlacement& placementWithinTarget,
  66483. const bool fillAlphaChannelWithCurrentBrush) const
  66484. {
  66485. // passing in a silly number can cause maths problems in rendering!
  66486. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66487. if (imageToDraw.isValid())
  66488. {
  66489. const int imageW = imageToDraw.getWidth();
  66490. const int imageH = imageToDraw.getHeight();
  66491. if (imageW > 0 && imageH > 0)
  66492. {
  66493. double newX = 0.0, newY = 0.0;
  66494. double newW = imageW;
  66495. double newH = imageH;
  66496. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66497. destX, destY, destW, destH);
  66498. if (newW > 0 && newH > 0)
  66499. {
  66500. drawImage (imageToDraw,
  66501. roundToInt (newX), roundToInt (newY),
  66502. roundToInt (newW), roundToInt (newH),
  66503. 0, 0, imageW, imageH,
  66504. fillAlphaChannelWithCurrentBrush);
  66505. }
  66506. }
  66507. }
  66508. }
  66509. void Graphics::drawImage (const Image& imageToDraw,
  66510. int dx, int dy, int dw, int dh,
  66511. int sx, int sy, int sw, int sh,
  66512. const bool fillAlphaChannelWithCurrentBrush) const
  66513. {
  66514. // passing in a silly number can cause maths problems in rendering!
  66515. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66516. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66517. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66518. {
  66519. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66520. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66521. .translated ((float) dx, (float) dy),
  66522. fillAlphaChannelWithCurrentBrush);
  66523. }
  66524. }
  66525. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66526. const AffineTransform& transform,
  66527. const bool fillAlphaChannelWithCurrentBrush) const
  66528. {
  66529. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66530. {
  66531. if (fillAlphaChannelWithCurrentBrush)
  66532. {
  66533. context->saveState();
  66534. context->clipToImageAlpha (imageToDraw, transform);
  66535. fillAll();
  66536. context->restoreState();
  66537. }
  66538. else
  66539. {
  66540. context->drawImage (imageToDraw, transform, false);
  66541. }
  66542. }
  66543. }
  66544. END_JUCE_NAMESPACE
  66545. /*** End of inlined file: juce_Graphics.cpp ***/
  66546. /*** Start of inlined file: juce_Justification.cpp ***/
  66547. BEGIN_JUCE_NAMESPACE
  66548. Justification::Justification (const Justification& other) throw()
  66549. : flags (other.flags)
  66550. {
  66551. }
  66552. Justification& Justification::operator= (const Justification& other) throw()
  66553. {
  66554. flags = other.flags;
  66555. return *this;
  66556. }
  66557. int Justification::getOnlyVerticalFlags() const throw()
  66558. {
  66559. return flags & (top | bottom | verticallyCentred);
  66560. }
  66561. int Justification::getOnlyHorizontalFlags() const throw()
  66562. {
  66563. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66564. }
  66565. void Justification::applyToRectangle (int& x, int& y,
  66566. const int w, const int h,
  66567. const int spaceX, const int spaceY,
  66568. const int spaceW, const int spaceH) const throw()
  66569. {
  66570. if ((flags & horizontallyCentred) != 0)
  66571. x = spaceX + ((spaceW - w) >> 1);
  66572. else if ((flags & right) != 0)
  66573. x = spaceX + spaceW - w;
  66574. else
  66575. x = spaceX;
  66576. if ((flags & verticallyCentred) != 0)
  66577. y = spaceY + ((spaceH - h) >> 1);
  66578. else if ((flags & bottom) != 0)
  66579. y = spaceY + spaceH - h;
  66580. else
  66581. y = spaceY;
  66582. }
  66583. END_JUCE_NAMESPACE
  66584. /*** End of inlined file: juce_Justification.cpp ***/
  66585. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66586. BEGIN_JUCE_NAMESPACE
  66587. // this will throw an assertion if you try to draw something that's not
  66588. // possible in postscript
  66589. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66590. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66591. #define notPossibleInPostscriptAssert jassertfalse
  66592. #else
  66593. #define notPossibleInPostscriptAssert
  66594. #endif
  66595. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66596. const String& documentTitle,
  66597. const int totalWidth_,
  66598. const int totalHeight_)
  66599. : out (resultingPostScript),
  66600. totalWidth (totalWidth_),
  66601. totalHeight (totalHeight_),
  66602. needToClip (true)
  66603. {
  66604. stateStack.add (new SavedState());
  66605. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66606. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66607. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66608. "\n%%BoundingBox: 0 0 600 824"
  66609. "\n%%Pages: 0"
  66610. "\n%%Creator: Raw Material Software JUCE"
  66611. "\n%%Title: " << documentTitle <<
  66612. "\n%%CreationDate: none"
  66613. "\n%%LanguageLevel: 2"
  66614. "\n%%EndComments"
  66615. "\n%%BeginProlog"
  66616. "\n%%BeginResource: JRes"
  66617. "\n/bd {bind def} bind def"
  66618. "\n/c {setrgbcolor} bd"
  66619. "\n/m {moveto} bd"
  66620. "\n/l {lineto} bd"
  66621. "\n/rl {rlineto} bd"
  66622. "\n/ct {curveto} bd"
  66623. "\n/cp {closepath} bd"
  66624. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66625. "\n/doclip {initclip newpath} bd"
  66626. "\n/endclip {clip newpath} bd"
  66627. "\n%%EndResource"
  66628. "\n%%EndProlog"
  66629. "\n%%BeginSetup"
  66630. "\n%%EndSetup"
  66631. "\n%%Page: 1 1"
  66632. "\n%%BeginPageSetup"
  66633. "\n%%EndPageSetup\n\n"
  66634. << "40 800 translate\n"
  66635. << scale << ' ' << scale << " scale\n\n";
  66636. }
  66637. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66638. {
  66639. }
  66640. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66641. {
  66642. return true;
  66643. }
  66644. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66645. {
  66646. if (x != 0 || y != 0)
  66647. {
  66648. stateStack.getLast()->xOffset += x;
  66649. stateStack.getLast()->yOffset += y;
  66650. needToClip = true;
  66651. }
  66652. }
  66653. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  66654. {
  66655. //xxx
  66656. jassertfalse;
  66657. }
  66658. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66659. {
  66660. needToClip = true;
  66661. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66662. }
  66663. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66664. {
  66665. needToClip = true;
  66666. return stateStack.getLast()->clip.clipTo (clipRegion);
  66667. }
  66668. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66669. {
  66670. needToClip = true;
  66671. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66672. }
  66673. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66674. {
  66675. writeClip();
  66676. Path p (path);
  66677. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66678. writePath (p);
  66679. out << "clip\n";
  66680. }
  66681. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66682. {
  66683. needToClip = true;
  66684. jassertfalse; // xxx
  66685. }
  66686. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66687. {
  66688. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66689. }
  66690. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66691. {
  66692. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66693. -stateStack.getLast()->yOffset);
  66694. }
  66695. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66696. {
  66697. return stateStack.getLast()->clip.isEmpty();
  66698. }
  66699. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66700. : xOffset (0),
  66701. yOffset (0)
  66702. {
  66703. }
  66704. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  66705. {
  66706. }
  66707. void LowLevelGraphicsPostScriptRenderer::saveState()
  66708. {
  66709. stateStack.add (new SavedState (*stateStack.getLast()));
  66710. }
  66711. void LowLevelGraphicsPostScriptRenderer::restoreState()
  66712. {
  66713. jassert (stateStack.size() > 0);
  66714. if (stateStack.size() > 0)
  66715. stateStack.removeLast();
  66716. }
  66717. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  66718. {
  66719. }
  66720. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  66721. {
  66722. }
  66723. void LowLevelGraphicsPostScriptRenderer::writeClip()
  66724. {
  66725. if (needToClip)
  66726. {
  66727. needToClip = false;
  66728. out << "doclip ";
  66729. int itemsOnLine = 0;
  66730. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  66731. {
  66732. if (++itemsOnLine == 6)
  66733. {
  66734. itemsOnLine = 0;
  66735. out << '\n';
  66736. }
  66737. const Rectangle<int>& r = *i.getRectangle();
  66738. out << r.getX() << ' ' << -r.getY() << ' '
  66739. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  66740. }
  66741. out << "endclip\n";
  66742. }
  66743. }
  66744. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  66745. {
  66746. Colour c (Colours::white.overlaidWith (colour));
  66747. if (lastColour != c)
  66748. {
  66749. lastColour = c;
  66750. out << String (c.getFloatRed(), 3) << ' '
  66751. << String (c.getFloatGreen(), 3) << ' '
  66752. << String (c.getFloatBlue(), 3) << " c\n";
  66753. }
  66754. }
  66755. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  66756. {
  66757. out << String (x, 2) << ' '
  66758. << String (-y, 2) << ' ';
  66759. }
  66760. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  66761. {
  66762. out << "newpath ";
  66763. float lastX = 0.0f;
  66764. float lastY = 0.0f;
  66765. int itemsOnLine = 0;
  66766. Path::Iterator i (path);
  66767. while (i.next())
  66768. {
  66769. if (++itemsOnLine == 4)
  66770. {
  66771. itemsOnLine = 0;
  66772. out << '\n';
  66773. }
  66774. switch (i.elementType)
  66775. {
  66776. case Path::Iterator::startNewSubPath:
  66777. writeXY (i.x1, i.y1);
  66778. lastX = i.x1;
  66779. lastY = i.y1;
  66780. out << "m ";
  66781. break;
  66782. case Path::Iterator::lineTo:
  66783. writeXY (i.x1, i.y1);
  66784. lastX = i.x1;
  66785. lastY = i.y1;
  66786. out << "l ";
  66787. break;
  66788. case Path::Iterator::quadraticTo:
  66789. {
  66790. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  66791. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  66792. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  66793. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  66794. writeXY (cp1x, cp1y);
  66795. writeXY (cp2x, cp2y);
  66796. writeXY (i.x2, i.y2);
  66797. out << "ct ";
  66798. lastX = i.x2;
  66799. lastY = i.y2;
  66800. }
  66801. break;
  66802. case Path::Iterator::cubicTo:
  66803. writeXY (i.x1, i.y1);
  66804. writeXY (i.x2, i.y2);
  66805. writeXY (i.x3, i.y3);
  66806. out << "ct ";
  66807. lastX = i.x3;
  66808. lastY = i.y3;
  66809. break;
  66810. case Path::Iterator::closePath:
  66811. out << "cp ";
  66812. break;
  66813. default:
  66814. jassertfalse;
  66815. break;
  66816. }
  66817. }
  66818. out << '\n';
  66819. }
  66820. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  66821. {
  66822. out << "[ "
  66823. << trans.mat00 << ' '
  66824. << trans.mat10 << ' '
  66825. << trans.mat01 << ' '
  66826. << trans.mat11 << ' '
  66827. << trans.mat02 << ' '
  66828. << trans.mat12 << " ] concat ";
  66829. }
  66830. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  66831. {
  66832. stateStack.getLast()->fillType = fillType;
  66833. }
  66834. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  66835. {
  66836. }
  66837. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  66838. {
  66839. }
  66840. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  66841. {
  66842. if (stateStack.getLast()->fillType.isColour())
  66843. {
  66844. writeClip();
  66845. writeColour (stateStack.getLast()->fillType.colour);
  66846. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66847. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  66848. }
  66849. else
  66850. {
  66851. Path p;
  66852. p.addRectangle (r);
  66853. fillPath (p, AffineTransform::identity);
  66854. }
  66855. }
  66856. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  66857. {
  66858. if (stateStack.getLast()->fillType.isColour())
  66859. {
  66860. writeClip();
  66861. Path p (path);
  66862. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  66863. (float) stateStack.getLast()->yOffset));
  66864. writePath (p);
  66865. writeColour (stateStack.getLast()->fillType.colour);
  66866. out << "fill\n";
  66867. }
  66868. else if (stateStack.getLast()->fillType.isGradient())
  66869. {
  66870. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  66871. // postscript can't do semi-transparent ones.
  66872. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  66873. writeClip();
  66874. out << "gsave ";
  66875. {
  66876. Path p (path);
  66877. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66878. writePath (p);
  66879. out << "clip\n";
  66880. }
  66881. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  66882. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  66883. // time-being, this just fills it with the average colour..
  66884. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  66885. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  66886. out << "grestore\n";
  66887. }
  66888. }
  66889. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  66890. const int sx, const int sy,
  66891. const int maxW, const int maxH) const
  66892. {
  66893. out << "{<\n";
  66894. const int w = jmin (maxW, im.getWidth());
  66895. const int h = jmin (maxH, im.getHeight());
  66896. int charsOnLine = 0;
  66897. const Image::BitmapData srcData (im, 0, 0, w, h);
  66898. Colour pixel;
  66899. for (int y = h; --y >= 0;)
  66900. {
  66901. for (int x = 0; x < w; ++x)
  66902. {
  66903. const uint8* pixelData = srcData.getPixelPointer (x, y);
  66904. if (x >= sx && y >= sy)
  66905. {
  66906. if (im.isARGB())
  66907. {
  66908. PixelARGB p (*(const PixelARGB*) pixelData);
  66909. p.unpremultiply();
  66910. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  66911. }
  66912. else if (im.isRGB())
  66913. {
  66914. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  66915. }
  66916. else
  66917. {
  66918. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  66919. }
  66920. }
  66921. else
  66922. {
  66923. pixel = Colours::transparentWhite;
  66924. }
  66925. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  66926. out << String::toHexString (pixelValues, 3, 0);
  66927. charsOnLine += 3;
  66928. if (charsOnLine > 100)
  66929. {
  66930. out << '\n';
  66931. charsOnLine = 0;
  66932. }
  66933. }
  66934. }
  66935. out << "\n>}\n";
  66936. }
  66937. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  66938. {
  66939. const int w = sourceImage.getWidth();
  66940. const int h = sourceImage.getHeight();
  66941. writeClip();
  66942. out << "gsave ";
  66943. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  66944. .scaled (1.0f, -1.0f));
  66945. RectangleList imageClip;
  66946. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  66947. out << "newpath ";
  66948. int itemsOnLine = 0;
  66949. for (RectangleList::Iterator i (imageClip); i.next();)
  66950. {
  66951. if (++itemsOnLine == 6)
  66952. {
  66953. out << '\n';
  66954. itemsOnLine = 0;
  66955. }
  66956. const Rectangle<int>& r = *i.getRectangle();
  66957. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  66958. }
  66959. out << " clip newpath\n";
  66960. out << w << ' ' << h << " scale\n";
  66961. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  66962. writeImage (sourceImage, 0, 0, w, h);
  66963. out << "false 3 colorimage grestore\n";
  66964. needToClip = true;
  66965. }
  66966. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  66967. {
  66968. Path p;
  66969. p.addLineSegment (line, 1.0f);
  66970. fillPath (p, AffineTransform::identity);
  66971. }
  66972. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  66973. {
  66974. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  66975. }
  66976. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  66977. {
  66978. drawLine (Line<float> (left, (float) y, right, (float) y));
  66979. }
  66980. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  66981. {
  66982. stateStack.getLast()->font = newFont;
  66983. }
  66984. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  66985. {
  66986. return stateStack.getLast()->font;
  66987. }
  66988. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  66989. {
  66990. Path p;
  66991. Font& font = stateStack.getLast()->font;
  66992. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  66993. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  66994. }
  66995. END_JUCE_NAMESPACE
  66996. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66997. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  66998. BEGIN_JUCE_NAMESPACE
  66999. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67000. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67001. #endif
  67002. #if JUCE_MSVC
  67003. #pragma warning (push)
  67004. #pragma warning (disable: 4127) // "expression is constant" warning
  67005. #if JUCE_DEBUG
  67006. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67007. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67008. #endif
  67009. #endif
  67010. namespace SoftwareRendererClasses
  67011. {
  67012. template <class PixelType, bool replaceExisting = false>
  67013. class SolidColourEdgeTableRenderer
  67014. {
  67015. public:
  67016. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67017. : data (data_),
  67018. sourceColour (colour)
  67019. {
  67020. if (sizeof (PixelType) == 3)
  67021. {
  67022. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67023. && sourceColour.getGreen() == sourceColour.getBlue();
  67024. filler[0].set (sourceColour);
  67025. filler[1].set (sourceColour);
  67026. filler[2].set (sourceColour);
  67027. filler[3].set (sourceColour);
  67028. }
  67029. }
  67030. forcedinline void setEdgeTableYPos (const int y) throw()
  67031. {
  67032. linePixels = (PixelType*) data.getLinePointer (y);
  67033. }
  67034. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67035. {
  67036. if (replaceExisting)
  67037. linePixels[x].set (sourceColour);
  67038. else
  67039. linePixels[x].blend (sourceColour, alphaLevel);
  67040. }
  67041. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67042. {
  67043. if (replaceExisting)
  67044. linePixels[x].set (sourceColour);
  67045. else
  67046. linePixels[x].blend (sourceColour);
  67047. }
  67048. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67049. {
  67050. PixelARGB p (sourceColour);
  67051. p.multiplyAlpha (alphaLevel);
  67052. PixelType* dest = linePixels + x;
  67053. if (replaceExisting || p.getAlpha() >= 0xff)
  67054. replaceLine (dest, p, width);
  67055. else
  67056. blendLine (dest, p, width);
  67057. }
  67058. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67059. {
  67060. PixelType* dest = linePixels + x;
  67061. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67062. replaceLine (dest, sourceColour, width);
  67063. else
  67064. blendLine (dest, sourceColour, width);
  67065. }
  67066. private:
  67067. const Image::BitmapData& data;
  67068. PixelType* linePixels;
  67069. PixelARGB sourceColour;
  67070. PixelRGB filler [4];
  67071. bool areRGBComponentsEqual;
  67072. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67073. {
  67074. do
  67075. {
  67076. dest->blend (colour);
  67077. ++dest;
  67078. } while (--width > 0);
  67079. }
  67080. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67081. {
  67082. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67083. {
  67084. memset (dest, colour.getRed(), width * 3);
  67085. }
  67086. else
  67087. {
  67088. if (width >> 5)
  67089. {
  67090. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67091. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67092. {
  67093. dest->set (colour);
  67094. ++dest;
  67095. --width;
  67096. }
  67097. while (width > 4)
  67098. {
  67099. int* d = reinterpret_cast<int*> (dest);
  67100. *d++ = intFiller[0];
  67101. *d++ = intFiller[1];
  67102. *d++ = intFiller[2];
  67103. dest = reinterpret_cast<PixelRGB*> (d);
  67104. width -= 4;
  67105. }
  67106. }
  67107. while (--width >= 0)
  67108. {
  67109. dest->set (colour);
  67110. ++dest;
  67111. }
  67112. }
  67113. }
  67114. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67115. {
  67116. memset (dest, colour.getAlpha(), width);
  67117. }
  67118. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67119. {
  67120. do
  67121. {
  67122. dest->set (colour);
  67123. ++dest;
  67124. } while (--width > 0);
  67125. }
  67126. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67127. };
  67128. class LinearGradientPixelGenerator
  67129. {
  67130. public:
  67131. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67132. : lookupTable (lookupTable_), numEntries (numEntries_)
  67133. {
  67134. jassert (numEntries_ >= 0);
  67135. Point<float> p1 (gradient.point1);
  67136. Point<float> p2 (gradient.point2);
  67137. if (! transform.isIdentity())
  67138. {
  67139. const Line<float> l (p2, p1);
  67140. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67141. p1.applyTransform (transform);
  67142. p2.applyTransform (transform);
  67143. p3.applyTransform (transform);
  67144. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67145. }
  67146. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67147. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67148. if (vertical)
  67149. {
  67150. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67151. start = roundToInt (p1.getY() * scale);
  67152. }
  67153. else if (horizontal)
  67154. {
  67155. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67156. start = roundToInt (p1.getX() * scale);
  67157. }
  67158. else
  67159. {
  67160. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67161. yTerm = p1.getY() - p1.getX() / grad;
  67162. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67163. grad *= scale;
  67164. }
  67165. }
  67166. forcedinline void setY (const int y) throw()
  67167. {
  67168. if (vertical)
  67169. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67170. else if (! horizontal)
  67171. start = roundToInt ((y - yTerm) * grad);
  67172. }
  67173. inline const PixelARGB getPixel (const int x) const throw()
  67174. {
  67175. return vertical ? linePix
  67176. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67177. }
  67178. private:
  67179. const PixelARGB* const lookupTable;
  67180. const int numEntries;
  67181. PixelARGB linePix;
  67182. int start, scale;
  67183. double grad, yTerm;
  67184. bool vertical, horizontal;
  67185. enum { numScaleBits = 12 };
  67186. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67187. };
  67188. class RadialGradientPixelGenerator
  67189. {
  67190. public:
  67191. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67192. const PixelARGB* const lookupTable_, const int numEntries_)
  67193. : lookupTable (lookupTable_),
  67194. numEntries (numEntries_),
  67195. gx1 (gradient.point1.getX()),
  67196. gy1 (gradient.point1.getY())
  67197. {
  67198. jassert (numEntries_ >= 0);
  67199. const Point<float> diff (gradient.point1 - gradient.point2);
  67200. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67201. invScale = numEntries / std::sqrt (maxDist);
  67202. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67203. }
  67204. forcedinline void setY (const int y) throw()
  67205. {
  67206. dy = y - gy1;
  67207. dy *= dy;
  67208. }
  67209. inline const PixelARGB getPixel (const int px) const throw()
  67210. {
  67211. double x = px - gx1;
  67212. x *= x;
  67213. x += dy;
  67214. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67215. }
  67216. protected:
  67217. const PixelARGB* const lookupTable;
  67218. const int numEntries;
  67219. const double gx1, gy1;
  67220. double maxDist, invScale, dy;
  67221. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67222. };
  67223. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67224. {
  67225. public:
  67226. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67227. const PixelARGB* const lookupTable_, const int numEntries_)
  67228. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67229. inverseTransform (transform.inverted())
  67230. {
  67231. tM10 = inverseTransform.mat10;
  67232. tM00 = inverseTransform.mat00;
  67233. }
  67234. forcedinline void setY (const int y) throw()
  67235. {
  67236. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67237. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67238. }
  67239. inline const PixelARGB getPixel (const int px) const throw()
  67240. {
  67241. double x = px;
  67242. const double y = tM10 * x + lineYM11;
  67243. x = tM00 * x + lineYM01;
  67244. x *= x;
  67245. x += y * y;
  67246. if (x >= maxDist)
  67247. return lookupTable [numEntries];
  67248. else
  67249. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67250. }
  67251. private:
  67252. double tM10, tM00, lineYM01, lineYM11;
  67253. const AffineTransform inverseTransform;
  67254. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67255. };
  67256. template <class PixelType, class GradientType>
  67257. class GradientEdgeTableRenderer : public GradientType
  67258. {
  67259. public:
  67260. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67261. const PixelARGB* const lookupTable_, const int numEntries_)
  67262. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67263. destData (destData_)
  67264. {
  67265. }
  67266. forcedinline void setEdgeTableYPos (const int y) throw()
  67267. {
  67268. linePixels = (PixelType*) destData.getLinePointer (y);
  67269. GradientType::setY (y);
  67270. }
  67271. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67272. {
  67273. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67274. }
  67275. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67276. {
  67277. linePixels[x].blend (GradientType::getPixel (x));
  67278. }
  67279. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67280. {
  67281. PixelType* dest = linePixels + x;
  67282. if (alphaLevel < 0xff)
  67283. {
  67284. do
  67285. {
  67286. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67287. } while (--width > 0);
  67288. }
  67289. else
  67290. {
  67291. do
  67292. {
  67293. (dest++)->blend (GradientType::getPixel (x++));
  67294. } while (--width > 0);
  67295. }
  67296. }
  67297. void handleEdgeTableLineFull (int x, int width) const throw()
  67298. {
  67299. PixelType* dest = linePixels + x;
  67300. do
  67301. {
  67302. (dest++)->blend (GradientType::getPixel (x++));
  67303. } while (--width > 0);
  67304. }
  67305. private:
  67306. const Image::BitmapData& destData;
  67307. PixelType* linePixels;
  67308. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67309. };
  67310. namespace RenderingHelpers
  67311. {
  67312. forcedinline int safeModulo (int n, const int divisor) throw()
  67313. {
  67314. jassert (divisor > 0);
  67315. n %= divisor;
  67316. return (n < 0) ? (n + divisor) : n;
  67317. }
  67318. }
  67319. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67320. class ImageFillEdgeTableRenderer
  67321. {
  67322. public:
  67323. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67324. const Image::BitmapData& srcData_,
  67325. const int extraAlpha_,
  67326. const int x, const int y)
  67327. : destData (destData_),
  67328. srcData (srcData_),
  67329. extraAlpha (extraAlpha_ + 1),
  67330. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67331. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67332. {
  67333. }
  67334. forcedinline void setEdgeTableYPos (int y) throw()
  67335. {
  67336. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67337. y -= yOffset;
  67338. if (repeatPattern)
  67339. {
  67340. jassert (y >= 0);
  67341. y %= srcData.height;
  67342. }
  67343. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67344. }
  67345. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67346. {
  67347. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67348. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67349. }
  67350. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67351. {
  67352. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67353. }
  67354. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67355. {
  67356. DestPixelType* dest = linePixels + x;
  67357. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67358. x -= xOffset;
  67359. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67360. if (alphaLevel < 0xfe)
  67361. {
  67362. do
  67363. {
  67364. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67365. } while (--width > 0);
  67366. }
  67367. else
  67368. {
  67369. if (repeatPattern)
  67370. {
  67371. do
  67372. {
  67373. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67374. } while (--width > 0);
  67375. }
  67376. else
  67377. {
  67378. copyRow (dest, sourceLineStart + x, width);
  67379. }
  67380. }
  67381. }
  67382. void handleEdgeTableLineFull (int x, int width) const throw()
  67383. {
  67384. DestPixelType* dest = linePixels + x;
  67385. x -= xOffset;
  67386. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67387. if (extraAlpha < 0xfe)
  67388. {
  67389. do
  67390. {
  67391. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67392. } while (--width > 0);
  67393. }
  67394. else
  67395. {
  67396. if (repeatPattern)
  67397. {
  67398. do
  67399. {
  67400. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67401. } while (--width > 0);
  67402. }
  67403. else
  67404. {
  67405. copyRow (dest, sourceLineStart + x, width);
  67406. }
  67407. }
  67408. }
  67409. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67410. {
  67411. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67412. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67413. uint8* mask = (uint8*) (s + x - xOffset);
  67414. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67415. mask += PixelARGB::indexA;
  67416. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67417. }
  67418. private:
  67419. const Image::BitmapData& destData;
  67420. const Image::BitmapData& srcData;
  67421. const int extraAlpha, xOffset, yOffset;
  67422. DestPixelType* linePixels;
  67423. SrcPixelType* sourceLineStart;
  67424. template <class PixelType1, class PixelType2>
  67425. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67426. {
  67427. do
  67428. {
  67429. dest++ ->blend (*src++);
  67430. } while (--width > 0);
  67431. }
  67432. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67433. {
  67434. memcpy (dest, src, width * sizeof (PixelRGB));
  67435. }
  67436. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  67437. };
  67438. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67439. class TransformedImageFillEdgeTableRenderer
  67440. {
  67441. public:
  67442. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67443. const Image::BitmapData& srcData_,
  67444. const AffineTransform& transform,
  67445. const int extraAlpha_,
  67446. const bool betterQuality_)
  67447. : interpolator (transform,
  67448. betterQuality_ ? 0.5f : 0.0f,
  67449. betterQuality_ ? -128 : 0),
  67450. destData (destData_),
  67451. srcData (srcData_),
  67452. extraAlpha (extraAlpha_ + 1),
  67453. betterQuality (betterQuality_),
  67454. maxX (srcData_.width - 1),
  67455. maxY (srcData_.height - 1),
  67456. scratchSize (2048)
  67457. {
  67458. scratchBuffer.malloc (scratchSize);
  67459. }
  67460. forcedinline void setEdgeTableYPos (const int newY) throw()
  67461. {
  67462. y = newY;
  67463. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67464. }
  67465. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  67466. {
  67467. SrcPixelType p;
  67468. generate (&p, x, 1);
  67469. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  67470. }
  67471. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67472. {
  67473. SrcPixelType p;
  67474. generate (&p, x, 1);
  67475. linePixels[x].blend (p, extraAlpha);
  67476. }
  67477. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67478. {
  67479. if (width > scratchSize)
  67480. {
  67481. scratchSize = width;
  67482. scratchBuffer.malloc (scratchSize);
  67483. }
  67484. SrcPixelType* span = scratchBuffer;
  67485. generate (span, x, width);
  67486. DestPixelType* dest = linePixels + x;
  67487. alphaLevel *= extraAlpha;
  67488. alphaLevel >>= 8;
  67489. if (alphaLevel < 0xfe)
  67490. {
  67491. do
  67492. {
  67493. dest++ ->blend (*span++, alphaLevel);
  67494. } while (--width > 0);
  67495. }
  67496. else
  67497. {
  67498. do
  67499. {
  67500. dest++ ->blend (*span++);
  67501. } while (--width > 0);
  67502. }
  67503. }
  67504. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67505. {
  67506. handleEdgeTableLine (x, width, 255);
  67507. }
  67508. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67509. {
  67510. if (width > scratchSize)
  67511. {
  67512. scratchSize = width;
  67513. scratchBuffer.malloc (scratchSize);
  67514. }
  67515. y = y_;
  67516. generate (static_cast <SrcPixelType*> (scratchBuffer), x, width);
  67517. et.clipLineToMask (x, y_,
  67518. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67519. sizeof (SrcPixelType), width);
  67520. }
  67521. private:
  67522. template <class PixelType>
  67523. void generate (PixelType* dest, const int x, int numPixels) throw()
  67524. {
  67525. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  67526. do
  67527. {
  67528. int hiResX, hiResY;
  67529. this->interpolator.next (hiResX, hiResY);
  67530. int loResX = hiResX >> 8;
  67531. int loResY = hiResY >> 8;
  67532. if (repeatPattern)
  67533. {
  67534. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  67535. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  67536. }
  67537. if (betterQuality)
  67538. {
  67539. if (((unsigned int) loResX) < (unsigned int) maxX)
  67540. {
  67541. if (((unsigned int) loResY) < (unsigned int) maxY)
  67542. {
  67543. // In the centre of the image..
  67544. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  67545. hiResX & 255, hiResY & 255);
  67546. ++dest;
  67547. continue;
  67548. }
  67549. else
  67550. {
  67551. // At a top or bottom edge..
  67552. if (! repeatPattern)
  67553. {
  67554. if (loResY < 0)
  67555. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255, hiResY & 255);
  67556. else
  67557. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255, 255 - (hiResY & 255));
  67558. ++dest;
  67559. continue;
  67560. }
  67561. }
  67562. }
  67563. else
  67564. {
  67565. if (((unsigned int) loResY) < (unsigned int) maxY)
  67566. {
  67567. // At a left or right hand edge..
  67568. if (! repeatPattern)
  67569. {
  67570. if (loResX < 0)
  67571. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255, hiResX & 255);
  67572. else
  67573. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255, 255 - (hiResX & 255));
  67574. ++dest;
  67575. continue;
  67576. }
  67577. }
  67578. }
  67579. }
  67580. if (! repeatPattern)
  67581. {
  67582. if (loResX < 0) loResX = 0;
  67583. if (loResY < 0) loResY = 0;
  67584. if (loResX > maxX) loResX = maxX;
  67585. if (loResY > maxY) loResY = maxY;
  67586. }
  67587. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  67588. ++dest;
  67589. } while (--numPixels > 0);
  67590. }
  67591. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67592. {
  67593. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67594. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67595. c[0] += weight * src[0];
  67596. c[1] += weight * src[1];
  67597. c[2] += weight * src[2];
  67598. c[3] += weight * src[3];
  67599. weight = subPixelX * (256 - subPixelY);
  67600. c[0] += weight * src[4];
  67601. c[1] += weight * src[5];
  67602. c[2] += weight * src[6];
  67603. c[3] += weight * src[7];
  67604. src += this->srcData.lineStride;
  67605. weight = (256 - subPixelX) * subPixelY;
  67606. c[0] += weight * src[0];
  67607. c[1] += weight * src[1];
  67608. c[2] += weight * src[2];
  67609. c[3] += weight * src[3];
  67610. weight = subPixelX * subPixelY;
  67611. c[0] += weight * src[4];
  67612. c[1] += weight * src[5];
  67613. c[2] += weight * src[6];
  67614. c[3] += weight * src[7];
  67615. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67616. (uint8) (c[PixelARGB::indexR] >> 16),
  67617. (uint8) (c[PixelARGB::indexG] >> 16),
  67618. (uint8) (c[PixelARGB::indexB] >> 16));
  67619. }
  67620. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67621. {
  67622. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67623. uint32 weight = (256 - subPixelX) * alpha;
  67624. c[0] += weight * src[0];
  67625. c[1] += weight * src[1];
  67626. c[2] += weight * src[2];
  67627. c[3] += weight * src[3];
  67628. weight = subPixelX * alpha;
  67629. c[0] += weight * src[4];
  67630. c[1] += weight * src[5];
  67631. c[2] += weight * src[6];
  67632. c[3] += weight * src[7];
  67633. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67634. (uint8) (c[PixelARGB::indexR] >> 16),
  67635. (uint8) (c[PixelARGB::indexG] >> 16),
  67636. (uint8) (c[PixelARGB::indexB] >> 16));
  67637. }
  67638. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67639. {
  67640. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67641. uint32 weight = (256 - subPixelY) * alpha;
  67642. c[0] += weight * src[0];
  67643. c[1] += weight * src[1];
  67644. c[2] += weight * src[2];
  67645. c[3] += weight * src[3];
  67646. src += this->srcData.lineStride;
  67647. weight = subPixelY * alpha;
  67648. c[0] += weight * src[0];
  67649. c[1] += weight * src[1];
  67650. c[2] += weight * src[2];
  67651. c[3] += weight * src[3];
  67652. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67653. (uint8) (c[PixelARGB::indexR] >> 16),
  67654. (uint8) (c[PixelARGB::indexG] >> 16),
  67655. (uint8) (c[PixelARGB::indexB] >> 16));
  67656. }
  67657. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67658. {
  67659. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67660. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67661. c[0] += weight * src[0];
  67662. c[1] += weight * src[1];
  67663. c[2] += weight * src[2];
  67664. weight = subPixelX * (256 - subPixelY);
  67665. c[0] += weight * src[3];
  67666. c[1] += weight * src[4];
  67667. c[2] += weight * src[5];
  67668. src += this->srcData.lineStride;
  67669. weight = (256 - subPixelX) * subPixelY;
  67670. c[0] += weight * src[0];
  67671. c[1] += weight * src[1];
  67672. c[2] += weight * src[2];
  67673. weight = subPixelX * subPixelY;
  67674. c[0] += weight * src[3];
  67675. c[1] += weight * src[4];
  67676. c[2] += weight * src[5];
  67677. dest->setARGB ((uint8) 255,
  67678. (uint8) (c[PixelRGB::indexR] >> 16),
  67679. (uint8) (c[PixelRGB::indexG] >> 16),
  67680. (uint8) (c[PixelRGB::indexB] >> 16));
  67681. }
  67682. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX, const int /*alpha*/) throw()
  67683. {
  67684. uint32 c[3] = { 128, 128, 128 };
  67685. uint32 weight = (256 - subPixelX);
  67686. c[0] += weight * src[0];
  67687. c[1] += weight * src[1];
  67688. c[2] += weight * src[2];
  67689. c[0] += subPixelX * src[3];
  67690. c[1] += subPixelX * src[4];
  67691. c[2] += subPixelX * src[5];
  67692. dest->setARGB ((uint8) 255,
  67693. (uint8) (c[PixelRGB::indexR] >> 8),
  67694. (uint8) (c[PixelRGB::indexG] >> 8),
  67695. (uint8) (c[PixelRGB::indexB] >> 8));
  67696. }
  67697. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY, const int /*alpha*/) throw()
  67698. {
  67699. uint32 c[3] = { 128, 128, 128 };
  67700. uint32 weight = (256 - subPixelY);
  67701. c[0] += weight * src[0];
  67702. c[1] += weight * src[1];
  67703. c[2] += weight * src[2];
  67704. src += this->srcData.lineStride;
  67705. c[0] += subPixelY * src[0];
  67706. c[1] += subPixelY * src[1];
  67707. c[2] += subPixelY * src[2];
  67708. dest->setARGB ((uint8) 255,
  67709. (uint8) (c[PixelRGB::indexR] >> 8),
  67710. (uint8) (c[PixelRGB::indexG] >> 8),
  67711. (uint8) (c[PixelRGB::indexB] >> 8));
  67712. }
  67713. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67714. {
  67715. uint32 c = 256 * 128;
  67716. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  67717. c += src[1] * (subPixelX * (256 - subPixelY));
  67718. src += this->srcData.lineStride;
  67719. c += src[0] * ((256 - subPixelX) * subPixelY);
  67720. c += src[1] * (subPixelX * subPixelY);
  67721. *((uint8*) dest) = (uint8) (c >> 16);
  67722. }
  67723. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67724. {
  67725. uint32 c = 256 * 128;
  67726. c += src[0] * (256 - subPixelX) * alpha;
  67727. c += src[1] * subPixelX * alpha;
  67728. *((uint8*) dest) = (uint8) (c >> 16);
  67729. }
  67730. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67731. {
  67732. uint32 c = 256 * 128;
  67733. c += src[0] * (256 - subPixelY) * alpha;
  67734. src += this->srcData.lineStride;
  67735. c += src[0] * subPixelY * alpha;
  67736. *((uint8*) dest) = (uint8) (c >> 16);
  67737. }
  67738. class TransformedImageSpanInterpolator
  67739. {
  67740. public:
  67741. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  67742. : inverseTransform (transform.inverted()),
  67743. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  67744. {}
  67745. void setStartOfLine (float x, float y, const int numPixels) throw()
  67746. {
  67747. jassert (numPixels > 0);
  67748. x += pixelOffset;
  67749. y += pixelOffset;
  67750. float x1 = x, y1 = y;
  67751. x += numPixels;
  67752. inverseTransform.transformPoints (x1, y1, x, y);
  67753. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  67754. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  67755. }
  67756. void next (int& x, int& y) throw()
  67757. {
  67758. x = xBresenham.n;
  67759. xBresenham.stepToNext();
  67760. y = yBresenham.n;
  67761. yBresenham.stepToNext();
  67762. }
  67763. private:
  67764. class BresenhamInterpolator
  67765. {
  67766. public:
  67767. BresenhamInterpolator() throw() {}
  67768. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  67769. {
  67770. numSteps = numSteps_;
  67771. step = (n2 - n1) / numSteps;
  67772. remainder = modulo = (n2 - n1) % numSteps;
  67773. n = n1 + pixelOffsetInt;
  67774. if (modulo <= 0)
  67775. {
  67776. modulo += numSteps;
  67777. remainder += numSteps;
  67778. --step;
  67779. }
  67780. modulo -= numSteps;
  67781. }
  67782. forcedinline void stepToNext() throw()
  67783. {
  67784. modulo += remainder;
  67785. n += step;
  67786. if (modulo > 0)
  67787. {
  67788. modulo -= numSteps;
  67789. ++n;
  67790. }
  67791. }
  67792. int n;
  67793. private:
  67794. int numSteps, step, modulo, remainder;
  67795. };
  67796. const AffineTransform inverseTransform;
  67797. BresenhamInterpolator xBresenham, yBresenham;
  67798. const float pixelOffset;
  67799. const int pixelOffsetInt;
  67800. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  67801. };
  67802. TransformedImageSpanInterpolator interpolator;
  67803. const Image::BitmapData& destData;
  67804. const Image::BitmapData& srcData;
  67805. const int extraAlpha;
  67806. const bool betterQuality;
  67807. const int maxX, maxY;
  67808. int y;
  67809. DestPixelType* linePixels;
  67810. HeapBlock <SrcPixelType> scratchBuffer;
  67811. int scratchSize;
  67812. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  67813. };
  67814. class ClipRegionBase : public ReferenceCountedObject
  67815. {
  67816. public:
  67817. ClipRegionBase() {}
  67818. virtual ~ClipRegionBase() {}
  67819. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  67820. virtual const Ptr clone() const = 0;
  67821. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  67822. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  67823. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  67824. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  67825. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  67826. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  67827. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  67828. virtual const Ptr translated (const Point<int>& delta) = 0;
  67829. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  67830. virtual const Rectangle<int> getClipBounds() const = 0;
  67831. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  67832. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  67833. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  67834. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  67835. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  67836. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  67837. protected:
  67838. template <class Iterator>
  67839. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  67840. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  67841. {
  67842. switch (destData.pixelFormat)
  67843. {
  67844. case Image::ARGB:
  67845. switch (srcData.pixelFormat)
  67846. {
  67847. case Image::ARGB:
  67848. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67849. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67850. break;
  67851. case Image::RGB:
  67852. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67853. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67854. break;
  67855. default:
  67856. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67857. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67858. break;
  67859. }
  67860. break;
  67861. case Image::RGB:
  67862. switch (srcData.pixelFormat)
  67863. {
  67864. case Image::ARGB:
  67865. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67866. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67867. break;
  67868. case Image::RGB:
  67869. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67870. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67871. break;
  67872. default:
  67873. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67874. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67875. break;
  67876. }
  67877. break;
  67878. default:
  67879. switch (srcData.pixelFormat)
  67880. {
  67881. case Image::ARGB:
  67882. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67883. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67884. break;
  67885. case Image::RGB:
  67886. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67887. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67888. break;
  67889. default:
  67890. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67891. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67892. break;
  67893. }
  67894. break;
  67895. }
  67896. }
  67897. template <class Iterator>
  67898. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  67899. {
  67900. switch (destData.pixelFormat)
  67901. {
  67902. case Image::ARGB:
  67903. switch (srcData.pixelFormat)
  67904. {
  67905. case Image::ARGB:
  67906. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67907. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67908. break;
  67909. case Image::RGB:
  67910. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67911. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67912. break;
  67913. default:
  67914. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67915. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67916. break;
  67917. }
  67918. break;
  67919. case Image::RGB:
  67920. switch (srcData.pixelFormat)
  67921. {
  67922. case Image::ARGB:
  67923. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67924. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67925. break;
  67926. case Image::RGB:
  67927. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67928. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67929. break;
  67930. default:
  67931. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67932. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67933. break;
  67934. }
  67935. break;
  67936. default:
  67937. switch (srcData.pixelFormat)
  67938. {
  67939. case Image::ARGB:
  67940. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67941. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67942. break;
  67943. case Image::RGB:
  67944. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67945. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67946. break;
  67947. default:
  67948. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67949. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67950. break;
  67951. }
  67952. break;
  67953. }
  67954. }
  67955. template <class Iterator, class DestPixelType>
  67956. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  67957. {
  67958. jassert (destData.pixelStride == sizeof (DestPixelType));
  67959. if (replaceContents)
  67960. {
  67961. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  67962. iter.iterate (r);
  67963. }
  67964. else
  67965. {
  67966. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  67967. iter.iterate (r);
  67968. }
  67969. }
  67970. template <class Iterator, class DestPixelType>
  67971. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  67972. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  67973. {
  67974. jassert (destData.pixelStride == sizeof (DestPixelType));
  67975. if (g.isRadial)
  67976. {
  67977. if (isIdentity)
  67978. {
  67979. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67980. iter.iterate (renderer);
  67981. }
  67982. else
  67983. {
  67984. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67985. iter.iterate (renderer);
  67986. }
  67987. }
  67988. else
  67989. {
  67990. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67991. iter.iterate (renderer);
  67992. }
  67993. }
  67994. };
  67995. class ClipRegion_EdgeTable : public ClipRegionBase
  67996. {
  67997. public:
  67998. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  67999. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68000. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68001. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68002. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68003. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68004. ~ClipRegion_EdgeTable() {}
  68005. const Ptr clone() const
  68006. {
  68007. return new ClipRegion_EdgeTable (*this);
  68008. }
  68009. const Ptr applyClipTo (const Ptr& target) const
  68010. {
  68011. return target->clipToEdgeTable (edgeTable);
  68012. }
  68013. const Ptr clipToRectangle (const Rectangle<int>& r)
  68014. {
  68015. edgeTable.clipToRectangle (r);
  68016. return edgeTable.isEmpty() ? 0 : this;
  68017. }
  68018. const Ptr clipToRectangleList (const RectangleList& r)
  68019. {
  68020. RectangleList inverse (edgeTable.getMaximumBounds());
  68021. if (inverse.subtract (r))
  68022. for (RectangleList::Iterator iter (inverse); iter.next();)
  68023. edgeTable.excludeRectangle (*iter.getRectangle());
  68024. return edgeTable.isEmpty() ? 0 : this;
  68025. }
  68026. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68027. {
  68028. edgeTable.excludeRectangle (r);
  68029. return edgeTable.isEmpty() ? 0 : this;
  68030. }
  68031. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68032. {
  68033. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68034. edgeTable.clipToEdgeTable (et);
  68035. return edgeTable.isEmpty() ? 0 : this;
  68036. }
  68037. const Ptr clipToEdgeTable (const EdgeTable& et)
  68038. {
  68039. edgeTable.clipToEdgeTable (et);
  68040. return edgeTable.isEmpty() ? 0 : this;
  68041. }
  68042. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68043. {
  68044. const Image::BitmapData srcData (image, false);
  68045. if (transform.isOnlyTranslation())
  68046. {
  68047. // If our translation doesn't involve any distortion, just use a simple blit..
  68048. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68049. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68050. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68051. {
  68052. const int imageX = ((tx + 128) >> 8);
  68053. const int imageY = ((ty + 128) >> 8);
  68054. if (image.getFormat() == Image::ARGB)
  68055. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68056. else
  68057. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68058. return edgeTable.isEmpty() ? 0 : this;
  68059. }
  68060. }
  68061. if (transform.isSingularity())
  68062. return 0;
  68063. {
  68064. Path p;
  68065. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68066. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68067. edgeTable.clipToEdgeTable (et2);
  68068. }
  68069. if (! edgeTable.isEmpty())
  68070. {
  68071. if (image.getFormat() == Image::ARGB)
  68072. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68073. else
  68074. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68075. }
  68076. return edgeTable.isEmpty() ? 0 : this;
  68077. }
  68078. const Ptr translated (const Point<int>& delta)
  68079. {
  68080. edgeTable.translate ((float) delta.getX(), delta.getY());
  68081. return edgeTable.isEmpty() ? 0 : this;
  68082. }
  68083. bool clipRegionIntersects (const Rectangle<int>& r) const
  68084. {
  68085. return edgeTable.getMaximumBounds().intersects (r);
  68086. }
  68087. const Rectangle<int> getClipBounds() const
  68088. {
  68089. return edgeTable.getMaximumBounds();
  68090. }
  68091. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68092. {
  68093. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68094. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68095. if (! clipped.isEmpty())
  68096. {
  68097. ClipRegion_EdgeTable et (clipped);
  68098. et.edgeTable.clipToEdgeTable (edgeTable);
  68099. et.fillAllWithColour (destData, colour, replaceContents);
  68100. }
  68101. }
  68102. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68103. {
  68104. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68105. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68106. if (! clipped.isEmpty())
  68107. {
  68108. ClipRegion_EdgeTable et (clipped);
  68109. et.edgeTable.clipToEdgeTable (edgeTable);
  68110. et.fillAllWithColour (destData, colour, false);
  68111. }
  68112. }
  68113. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68114. {
  68115. switch (destData.pixelFormat)
  68116. {
  68117. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68118. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68119. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68120. }
  68121. }
  68122. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68123. {
  68124. HeapBlock <PixelARGB> lookupTable;
  68125. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68126. jassert (numLookupEntries > 0);
  68127. switch (destData.pixelFormat)
  68128. {
  68129. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68130. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68131. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68132. }
  68133. }
  68134. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68135. {
  68136. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68137. }
  68138. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68139. {
  68140. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68141. }
  68142. EdgeTable edgeTable;
  68143. private:
  68144. template <class SrcPixelType>
  68145. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68146. {
  68147. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68148. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68149. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68150. edgeTable.getMaximumBounds().getWidth());
  68151. }
  68152. template <class SrcPixelType>
  68153. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68154. {
  68155. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68156. edgeTable.clipToRectangle (r);
  68157. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68158. for (int y = 0; y < r.getHeight(); ++y)
  68159. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68160. }
  68161. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68162. };
  68163. class ClipRegion_RectangleList : public ClipRegionBase
  68164. {
  68165. public:
  68166. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68167. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68168. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68169. ~ClipRegion_RectangleList() {}
  68170. const Ptr clone() const
  68171. {
  68172. return new ClipRegion_RectangleList (*this);
  68173. }
  68174. const Ptr applyClipTo (const Ptr& target) const
  68175. {
  68176. return target->clipToRectangleList (clip);
  68177. }
  68178. const Ptr clipToRectangle (const Rectangle<int>& r)
  68179. {
  68180. clip.clipTo (r);
  68181. return clip.isEmpty() ? 0 : this;
  68182. }
  68183. const Ptr clipToRectangleList (const RectangleList& r)
  68184. {
  68185. clip.clipTo (r);
  68186. return clip.isEmpty() ? 0 : this;
  68187. }
  68188. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68189. {
  68190. clip.subtract (r);
  68191. return clip.isEmpty() ? 0 : this;
  68192. }
  68193. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68194. {
  68195. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68196. }
  68197. const Ptr clipToEdgeTable (const EdgeTable& et)
  68198. {
  68199. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68200. }
  68201. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68202. {
  68203. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68204. }
  68205. const Ptr translated (const Point<int>& delta)
  68206. {
  68207. clip.offsetAll (delta.getX(), delta.getY());
  68208. return clip.isEmpty() ? 0 : this;
  68209. }
  68210. bool clipRegionIntersects (const Rectangle<int>& r) const
  68211. {
  68212. return clip.intersects (r);
  68213. }
  68214. const Rectangle<int> getClipBounds() const
  68215. {
  68216. return clip.getBounds();
  68217. }
  68218. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68219. {
  68220. SubRectangleIterator iter (clip, area);
  68221. switch (destData.pixelFormat)
  68222. {
  68223. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68224. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68225. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68226. }
  68227. }
  68228. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68229. {
  68230. SubRectangleIteratorFloat iter (clip, area);
  68231. switch (destData.pixelFormat)
  68232. {
  68233. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68234. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68235. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68236. }
  68237. }
  68238. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68239. {
  68240. switch (destData.pixelFormat)
  68241. {
  68242. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68243. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68244. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68245. }
  68246. }
  68247. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68248. {
  68249. HeapBlock <PixelARGB> lookupTable;
  68250. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68251. jassert (numLookupEntries > 0);
  68252. switch (destData.pixelFormat)
  68253. {
  68254. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68255. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68256. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68257. }
  68258. }
  68259. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68260. {
  68261. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68262. }
  68263. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68264. {
  68265. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68266. }
  68267. RectangleList clip;
  68268. template <class Renderer>
  68269. void iterate (Renderer& r) const throw()
  68270. {
  68271. RectangleList::Iterator iter (clip);
  68272. while (iter.next())
  68273. {
  68274. const Rectangle<int> rect (*iter.getRectangle());
  68275. const int x = rect.getX();
  68276. const int w = rect.getWidth();
  68277. jassert (w > 0);
  68278. const int bottom = rect.getBottom();
  68279. for (int y = rect.getY(); y < bottom; ++y)
  68280. {
  68281. r.setEdgeTableYPos (y);
  68282. r.handleEdgeTableLineFull (x, w);
  68283. }
  68284. }
  68285. }
  68286. private:
  68287. class SubRectangleIterator
  68288. {
  68289. public:
  68290. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68291. : clip (clip_), area (area_)
  68292. {
  68293. }
  68294. template <class Renderer>
  68295. void iterate (Renderer& r) const throw()
  68296. {
  68297. RectangleList::Iterator iter (clip);
  68298. while (iter.next())
  68299. {
  68300. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68301. if (! rect.isEmpty())
  68302. {
  68303. const int x = rect.getX();
  68304. const int w = rect.getWidth();
  68305. const int bottom = rect.getBottom();
  68306. for (int y = rect.getY(); y < bottom; ++y)
  68307. {
  68308. r.setEdgeTableYPos (y);
  68309. r.handleEdgeTableLineFull (x, w);
  68310. }
  68311. }
  68312. }
  68313. }
  68314. private:
  68315. const RectangleList& clip;
  68316. const Rectangle<int> area;
  68317. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68318. };
  68319. class SubRectangleIteratorFloat
  68320. {
  68321. public:
  68322. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68323. : clip (clip_), area (area_)
  68324. {
  68325. }
  68326. template <class Renderer>
  68327. void iterate (Renderer& r) const throw()
  68328. {
  68329. int left = roundToInt (area.getX() * 256.0f);
  68330. int top = roundToInt (area.getY() * 256.0f);
  68331. int right = roundToInt (area.getRight() * 256.0f);
  68332. int bottom = roundToInt (area.getBottom() * 256.0f);
  68333. int totalTop, totalLeft, totalBottom, totalRight;
  68334. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68335. if ((top >> 8) == (bottom >> 8))
  68336. {
  68337. topAlpha = bottom - top;
  68338. bottomAlpha = 0;
  68339. totalTop = top >> 8;
  68340. totalBottom = bottom = top = totalTop + 1;
  68341. }
  68342. else
  68343. {
  68344. if ((top & 255) == 0)
  68345. {
  68346. topAlpha = 0;
  68347. top = totalTop = (top >> 8);
  68348. }
  68349. else
  68350. {
  68351. topAlpha = 255 - (top & 255);
  68352. totalTop = (top >> 8);
  68353. top = totalTop + 1;
  68354. }
  68355. bottomAlpha = bottom & 255;
  68356. bottom >>= 8;
  68357. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68358. }
  68359. if ((left >> 8) == (right >> 8))
  68360. {
  68361. leftAlpha = right - left;
  68362. rightAlpha = 0;
  68363. totalLeft = (left >> 8);
  68364. totalRight = right = left = totalLeft + 1;
  68365. }
  68366. else
  68367. {
  68368. if ((left & 255) == 0)
  68369. {
  68370. leftAlpha = 0;
  68371. left = totalLeft = (left >> 8);
  68372. }
  68373. else
  68374. {
  68375. leftAlpha = 255 - (left & 255);
  68376. totalLeft = (left >> 8);
  68377. left = totalLeft + 1;
  68378. }
  68379. rightAlpha = right & 255;
  68380. right >>= 8;
  68381. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68382. }
  68383. RectangleList::Iterator iter (clip);
  68384. while (iter.next())
  68385. {
  68386. const int clipLeft = iter.getRectangle()->getX();
  68387. const int clipRight = iter.getRectangle()->getRight();
  68388. const int clipTop = iter.getRectangle()->getY();
  68389. const int clipBottom = iter.getRectangle()->getBottom();
  68390. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68391. {
  68392. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68393. {
  68394. if (topAlpha != 0 && totalTop >= clipTop)
  68395. {
  68396. r.setEdgeTableYPos (totalTop);
  68397. r.handleEdgeTablePixel (left, topAlpha);
  68398. }
  68399. const int endY = jmin (bottom, clipBottom);
  68400. for (int y = jmax (clipTop, top); y < endY; ++y)
  68401. {
  68402. r.setEdgeTableYPos (y);
  68403. r.handleEdgeTablePixelFull (left);
  68404. }
  68405. if (bottomAlpha != 0 && bottom < clipBottom)
  68406. {
  68407. r.setEdgeTableYPos (bottom);
  68408. r.handleEdgeTablePixel (left, bottomAlpha);
  68409. }
  68410. }
  68411. else
  68412. {
  68413. const int clippedLeft = jmax (left, clipLeft);
  68414. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68415. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68416. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68417. if (topAlpha != 0 && totalTop >= clipTop)
  68418. {
  68419. r.setEdgeTableYPos (totalTop);
  68420. if (doLeftAlpha)
  68421. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68422. if (clippedWidth > 0)
  68423. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68424. if (doRightAlpha)
  68425. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68426. }
  68427. const int endY = jmin (bottom, clipBottom);
  68428. for (int y = jmax (clipTop, top); y < endY; ++y)
  68429. {
  68430. r.setEdgeTableYPos (y);
  68431. if (doLeftAlpha)
  68432. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68433. if (clippedWidth > 0)
  68434. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68435. if (doRightAlpha)
  68436. r.handleEdgeTablePixel (right, rightAlpha);
  68437. }
  68438. if (bottomAlpha != 0 && bottom < clipBottom)
  68439. {
  68440. r.setEdgeTableYPos (bottom);
  68441. if (doLeftAlpha)
  68442. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68443. if (clippedWidth > 0)
  68444. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68445. if (doRightAlpha)
  68446. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68447. }
  68448. }
  68449. }
  68450. }
  68451. }
  68452. private:
  68453. const RectangleList& clip;
  68454. const Rectangle<float>& area;
  68455. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  68456. };
  68457. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68458. };
  68459. }
  68460. class LowLevelGraphicsSoftwareRenderer::SavedState
  68461. {
  68462. public:
  68463. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68464. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68465. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68466. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68467. {
  68468. }
  68469. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68470. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68471. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68472. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68473. {
  68474. }
  68475. SavedState (const SavedState& other)
  68476. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  68477. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  68478. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  68479. interpolationQuality (other.interpolationQuality)
  68480. {
  68481. }
  68482. void setOrigin (const int x, const int y) throw()
  68483. {
  68484. if (isOnlyTranslated)
  68485. {
  68486. xOffset += x;
  68487. yOffset += y;
  68488. }
  68489. else
  68490. {
  68491. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  68492. }
  68493. }
  68494. void addTransform (const AffineTransform& t)
  68495. {
  68496. if ((! isOnlyTranslated)
  68497. || (! t.isOnlyTranslation())
  68498. || (int) (t.getTranslationX() * 256.0f) != 0
  68499. || (int) (t.getTranslationY() * 256.0f) != 0)
  68500. {
  68501. complexTransform = getTransformWith (t);
  68502. isOnlyTranslated = false;
  68503. }
  68504. else
  68505. {
  68506. xOffset += (int) t.getTranslationX();
  68507. yOffset += (int) t.getTranslationY();
  68508. }
  68509. }
  68510. bool clipToRectangle (const Rectangle<int>& r)
  68511. {
  68512. if (clip != 0)
  68513. {
  68514. if (isOnlyTranslated)
  68515. {
  68516. cloneClipIfMultiplyReferenced();
  68517. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68518. }
  68519. else
  68520. {
  68521. Path p;
  68522. p.addRectangle (r);
  68523. clipToPath (p, AffineTransform::identity);
  68524. }
  68525. }
  68526. return clip != 0;
  68527. }
  68528. bool clipToRectangleList (const RectangleList& r)
  68529. {
  68530. if (clip != 0)
  68531. {
  68532. if (isOnlyTranslated)
  68533. {
  68534. cloneClipIfMultiplyReferenced();
  68535. RectangleList offsetList (r);
  68536. offsetList.offsetAll (xOffset, yOffset);
  68537. clip = clip->clipToRectangleList (offsetList);
  68538. }
  68539. else
  68540. {
  68541. clipToPath (r.toPath(), AffineTransform::identity);
  68542. }
  68543. }
  68544. return clip != 0;
  68545. }
  68546. bool excludeClipRectangle (const Rectangle<int>& r)
  68547. {
  68548. if (clip != 0)
  68549. {
  68550. cloneClipIfMultiplyReferenced();
  68551. if (isOnlyTranslated)
  68552. {
  68553. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68554. }
  68555. else
  68556. {
  68557. Path p;
  68558. p.addRectangle (r.toFloat());
  68559. p.applyTransform (complexTransform);
  68560. p.addRectangle (clip->getClipBounds().toFloat());
  68561. p.setUsingNonZeroWinding (false);
  68562. clip = clip->clipToPath (p, AffineTransform::identity);
  68563. }
  68564. }
  68565. return clip != 0;
  68566. }
  68567. void clipToPath (const Path& p, const AffineTransform& transform)
  68568. {
  68569. if (clip != 0)
  68570. {
  68571. cloneClipIfMultiplyReferenced();
  68572. clip = clip->clipToPath (p, getTransformWith (transform));
  68573. }
  68574. }
  68575. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68576. {
  68577. if (clip != 0)
  68578. {
  68579. if (image.hasAlphaChannel())
  68580. {
  68581. cloneClipIfMultiplyReferenced();
  68582. clip = clip->clipToImageAlpha (image, getTransformWith (t),
  68583. interpolationQuality != Graphics::lowResamplingQuality);
  68584. }
  68585. else
  68586. {
  68587. Path p;
  68588. p.addRectangle (image.getBounds());
  68589. clipToPath (p, t);
  68590. }
  68591. }
  68592. }
  68593. bool clipRegionIntersects (const Rectangle<int>& r) const
  68594. {
  68595. if (clip != 0)
  68596. {
  68597. if (isOnlyTranslated)
  68598. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68599. else
  68600. return getClipBounds().intersects (r);
  68601. }
  68602. return false;
  68603. }
  68604. const Rectangle<int> getUntransformedClipBounds() const
  68605. {
  68606. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  68607. }
  68608. const Rectangle<int> getClipBounds() const
  68609. {
  68610. if (clip != 0)
  68611. {
  68612. if (isOnlyTranslated)
  68613. return clip->getClipBounds().translated (-xOffset, -yOffset);
  68614. else
  68615. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  68616. }
  68617. return Rectangle<int>();
  68618. }
  68619. SavedState* beginTransparencyLayer (float opacity)
  68620. {
  68621. const Rectangle<int> clip (getUntransformedClipBounds());
  68622. SavedState* s = new SavedState (*this);
  68623. s->image = Image (Image::ARGB, clip.getWidth(), clip.getHeight(), true);
  68624. s->compositionAlpha = opacity;
  68625. if (s->isOnlyTranslated)
  68626. {
  68627. s->xOffset -= clip.getX();
  68628. s->yOffset -= clip.getY();
  68629. }
  68630. else
  68631. {
  68632. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -clip.getX(),
  68633. (float) -clip.getY()));
  68634. }
  68635. s->cloneClipIfMultiplyReferenced();
  68636. s->clip = s->clip->translated (-clip.getPosition());
  68637. return s;
  68638. }
  68639. void endTransparencyLayer (SavedState& layerState)
  68640. {
  68641. const Rectangle<int> clip (getUntransformedClipBounds());
  68642. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  68643. g->setOpacity (layerState.compositionAlpha);
  68644. g->drawImage (layerState.image, AffineTransform::translation ((float) clip.getX(),
  68645. (float) clip.getY()), false);
  68646. }
  68647. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  68648. {
  68649. if (clip != 0)
  68650. {
  68651. if (isOnlyTranslated)
  68652. {
  68653. if (fillType.isColour())
  68654. {
  68655. Image::BitmapData destData (image, true);
  68656. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68657. }
  68658. else
  68659. {
  68660. const Rectangle<int> totalClip (clip->getClipBounds());
  68661. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68662. if (! clipped.isEmpty())
  68663. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68664. }
  68665. }
  68666. else
  68667. {
  68668. Path p;
  68669. p.addRectangle (r);
  68670. fillPath (p, AffineTransform::identity);
  68671. }
  68672. }
  68673. }
  68674. void fillRect (const Rectangle<float>& r)
  68675. {
  68676. if (clip != 0)
  68677. {
  68678. if (isOnlyTranslated)
  68679. {
  68680. if (fillType.isColour())
  68681. {
  68682. Image::BitmapData destData (image, true);
  68683. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68684. }
  68685. else
  68686. {
  68687. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68688. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68689. if (! clipped.isEmpty())
  68690. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68691. }
  68692. }
  68693. else
  68694. {
  68695. Path p;
  68696. p.addRectangle (r);
  68697. fillPath (p, AffineTransform::identity);
  68698. }
  68699. }
  68700. }
  68701. void fillPath (const Path& path, const AffineTransform& transform)
  68702. {
  68703. if (clip != 0)
  68704. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  68705. }
  68706. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  68707. {
  68708. jassert (isOnlyTranslated);
  68709. if (clip != 0)
  68710. {
  68711. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68712. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68713. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68714. fillShape (shapeToFill, false);
  68715. }
  68716. }
  68717. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68718. {
  68719. jassert (clip != 0);
  68720. shapeToFill = clip->applyClipTo (shapeToFill);
  68721. if (shapeToFill != 0)
  68722. {
  68723. Image::BitmapData destData (image, true);
  68724. if (fillType.isGradient())
  68725. {
  68726. jassert (! replaceContents); // that option is just for solid colours
  68727. ColourGradient g2 (*(fillType.gradient));
  68728. g2.multiplyOpacity (fillType.getOpacity());
  68729. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  68730. const bool isIdentity = transform.isOnlyTranslation();
  68731. if (isIdentity)
  68732. {
  68733. // If our translation doesn't involve any distortion, we can speed it up..
  68734. g2.point1.applyTransform (transform);
  68735. g2.point2.applyTransform (transform);
  68736. transform = AffineTransform::identity;
  68737. }
  68738. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68739. }
  68740. else if (fillType.isTiledImage())
  68741. {
  68742. renderImage (fillType.image, fillType.transform, shapeToFill);
  68743. }
  68744. else
  68745. {
  68746. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68747. }
  68748. }
  68749. }
  68750. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68751. {
  68752. const AffineTransform transform (getTransformWith (t));
  68753. const Image::BitmapData destData (image, true);
  68754. const Image::BitmapData srcData (sourceImage, false);
  68755. const int alpha = fillType.colour.getAlpha();
  68756. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68757. if (transform.isOnlyTranslation())
  68758. {
  68759. // If our translation doesn't involve any distortion, just use a simple blit..
  68760. int tx = (int) (transform.getTranslationX() * 256.0f);
  68761. int ty = (int) (transform.getTranslationY() * 256.0f);
  68762. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68763. {
  68764. tx = ((tx + 128) >> 8);
  68765. ty = ((ty + 128) >> 8);
  68766. if (tiledFillClipRegion != 0)
  68767. {
  68768. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68769. }
  68770. else
  68771. {
  68772. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  68773. c = clip->applyClipTo (c);
  68774. if (c != 0)
  68775. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68776. }
  68777. return;
  68778. }
  68779. }
  68780. if (transform.isSingularity())
  68781. return;
  68782. if (tiledFillClipRegion != 0)
  68783. {
  68784. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68785. }
  68786. else
  68787. {
  68788. Path p;
  68789. p.addRectangle (sourceImage.getBounds());
  68790. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68791. c = c->clipToPath (p, transform);
  68792. if (c != 0)
  68793. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68794. }
  68795. }
  68796. Image image;
  68797. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68798. private:
  68799. AffineTransform complexTransform;
  68800. int xOffset, yOffset;
  68801. float compositionAlpha;
  68802. public:
  68803. bool isOnlyTranslated;
  68804. Font font;
  68805. FillType fillType;
  68806. Graphics::ResamplingQuality interpolationQuality;
  68807. private:
  68808. void cloneClipIfMultiplyReferenced()
  68809. {
  68810. if (clip->getReferenceCount() > 1)
  68811. clip = clip->clone();
  68812. }
  68813. const AffineTransform getTransform() const
  68814. {
  68815. if (isOnlyTranslated)
  68816. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  68817. return complexTransform;
  68818. }
  68819. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  68820. {
  68821. if (isOnlyTranslated)
  68822. return userTransform.translated ((float) xOffset, (float) yOffset);
  68823. return userTransform.followedBy (complexTransform);
  68824. }
  68825. SavedState& operator= (const SavedState&);
  68826. };
  68827. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  68828. : image (image_),
  68829. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  68830. {
  68831. }
  68832. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  68833. const RectangleList& initialClip)
  68834. : image (image_),
  68835. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  68836. {
  68837. }
  68838. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  68839. {
  68840. }
  68841. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  68842. {
  68843. return false;
  68844. }
  68845. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  68846. {
  68847. currentState->setOrigin (x, y);
  68848. }
  68849. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  68850. {
  68851. currentState->addTransform (transform);
  68852. }
  68853. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  68854. {
  68855. return currentState->clipToRectangle (r);
  68856. }
  68857. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  68858. {
  68859. return currentState->clipToRectangleList (clipRegion);
  68860. }
  68861. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  68862. {
  68863. currentState->excludeClipRectangle (r);
  68864. }
  68865. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  68866. {
  68867. currentState->clipToPath (path, transform);
  68868. }
  68869. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  68870. {
  68871. currentState->clipToImageAlpha (sourceImage, transform);
  68872. }
  68873. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  68874. {
  68875. return currentState->clipRegionIntersects (r);
  68876. }
  68877. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  68878. {
  68879. return currentState->getClipBounds();
  68880. }
  68881. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  68882. {
  68883. return currentState->clip == 0;
  68884. }
  68885. void LowLevelGraphicsSoftwareRenderer::saveState()
  68886. {
  68887. stateStack.add (new SavedState (*currentState));
  68888. }
  68889. void LowLevelGraphicsSoftwareRenderer::restoreState()
  68890. {
  68891. SavedState* const top = stateStack.getLast();
  68892. if (top != 0)
  68893. {
  68894. currentState = top;
  68895. stateStack.removeLast (1, false);
  68896. }
  68897. else
  68898. {
  68899. jassertfalse; // trying to pop with an empty stack!
  68900. }
  68901. }
  68902. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  68903. {
  68904. saveState();
  68905. currentState = currentState->beginTransparencyLayer (opacity);
  68906. }
  68907. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  68908. {
  68909. const ScopedPointer<SavedState> layer (currentState);
  68910. restoreState();
  68911. currentState->endTransparencyLayer (*layer);
  68912. }
  68913. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  68914. {
  68915. currentState->fillType = fillType;
  68916. }
  68917. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  68918. {
  68919. currentState->fillType.setOpacity (newOpacity);
  68920. }
  68921. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  68922. {
  68923. currentState->interpolationQuality = quality;
  68924. }
  68925. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  68926. {
  68927. currentState->fillRect (r, replaceExistingContents);
  68928. }
  68929. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  68930. {
  68931. currentState->fillPath (path, transform);
  68932. }
  68933. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  68934. {
  68935. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  68936. }
  68937. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  68938. {
  68939. Path p;
  68940. p.addLineSegment (line, 1.0f);
  68941. fillPath (p, AffineTransform::identity);
  68942. }
  68943. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  68944. {
  68945. if (bottom > top)
  68946. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  68947. }
  68948. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  68949. {
  68950. if (right > left)
  68951. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  68952. }
  68953. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  68954. {
  68955. public:
  68956. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  68957. ~CachedGlyph() {}
  68958. void draw (SavedState& state, const float x, const float y) const
  68959. {
  68960. if (edgeTable != 0)
  68961. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  68962. }
  68963. void generate (const Font& newFont, const int glyphNumber)
  68964. {
  68965. font = newFont;
  68966. glyph = glyphNumber;
  68967. edgeTable = 0;
  68968. Path glyphPath;
  68969. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  68970. if (! glyphPath.isEmpty())
  68971. {
  68972. const float fontHeight = font.getHeight();
  68973. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  68974. #if JUCE_MAC || JUCE_IOS
  68975. .translated (0.0f, -0.5f)
  68976. #endif
  68977. );
  68978. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  68979. glyphPath, transform);
  68980. }
  68981. }
  68982. int glyph, lastAccessCount;
  68983. Font font;
  68984. private:
  68985. ScopedPointer <EdgeTable> edgeTable;
  68986. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  68987. };
  68988. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  68989. {
  68990. public:
  68991. GlyphCache()
  68992. : accessCounter (0), hits (0), misses (0)
  68993. {
  68994. for (int i = 120; --i >= 0;)
  68995. glyphs.add (new CachedGlyph());
  68996. }
  68997. ~GlyphCache()
  68998. {
  68999. clearSingletonInstance();
  69000. }
  69001. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69002. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69003. {
  69004. ++accessCounter;
  69005. int oldestCounter = std::numeric_limits<int>::max();
  69006. CachedGlyph* oldest = 0;
  69007. for (int i = glyphs.size(); --i >= 0;)
  69008. {
  69009. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69010. if (glyph->glyph == glyphNumber && glyph->font == font)
  69011. {
  69012. ++hits;
  69013. glyph->lastAccessCount = accessCounter;
  69014. glyph->draw (state, x, y);
  69015. return;
  69016. }
  69017. if (glyph->lastAccessCount <= oldestCounter)
  69018. {
  69019. oldestCounter = glyph->lastAccessCount;
  69020. oldest = glyph;
  69021. }
  69022. }
  69023. if (hits + ++misses > (glyphs.size() << 4))
  69024. {
  69025. if (misses * 2 > hits)
  69026. {
  69027. for (int i = 32; --i >= 0;)
  69028. glyphs.add (new CachedGlyph());
  69029. }
  69030. hits = misses = 0;
  69031. oldest = glyphs.getLast();
  69032. }
  69033. jassert (oldest != 0);
  69034. oldest->lastAccessCount = accessCounter;
  69035. oldest->generate (font, glyphNumber);
  69036. oldest->draw (state, x, y);
  69037. }
  69038. private:
  69039. friend class OwnedArray <CachedGlyph>;
  69040. OwnedArray <CachedGlyph> glyphs;
  69041. int accessCounter, hits, misses;
  69042. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69043. };
  69044. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69045. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69046. {
  69047. currentState->font = newFont;
  69048. }
  69049. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69050. {
  69051. return currentState->font;
  69052. }
  69053. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69054. {
  69055. Font& f = currentState->font;
  69056. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69057. {
  69058. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69059. transform.getTranslationX(),
  69060. transform.getTranslationY());
  69061. }
  69062. else
  69063. {
  69064. Path p;
  69065. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69066. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69067. }
  69068. }
  69069. #if JUCE_MSVC
  69070. #pragma warning (pop)
  69071. #if JUCE_DEBUG
  69072. #pragma optimize ("", on) // resets optimisations to the project defaults
  69073. #endif
  69074. #endif
  69075. END_JUCE_NAMESPACE
  69076. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69077. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69078. BEGIN_JUCE_NAMESPACE
  69079. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69080. : flags (other.flags)
  69081. {
  69082. }
  69083. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69084. {
  69085. flags = other.flags;
  69086. return *this;
  69087. }
  69088. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69089. const double dx, const double dy, const double dw, const double dh) const throw()
  69090. {
  69091. if (w == 0 || h == 0)
  69092. return;
  69093. if ((flags & stretchToFit) != 0)
  69094. {
  69095. x = dx;
  69096. y = dy;
  69097. w = dw;
  69098. h = dh;
  69099. }
  69100. else
  69101. {
  69102. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69103. : jmin (dw / w, dh / h);
  69104. if ((flags & onlyReduceInSize) != 0)
  69105. scale = jmin (scale, 1.0);
  69106. if ((flags & onlyIncreaseInSize) != 0)
  69107. scale = jmax (scale, 1.0);
  69108. w *= scale;
  69109. h *= scale;
  69110. if ((flags & xLeft) != 0)
  69111. x = dx;
  69112. else if ((flags & xRight) != 0)
  69113. x = dx + dw - w;
  69114. else
  69115. x = dx + (dw - w) * 0.5;
  69116. if ((flags & yTop) != 0)
  69117. y = dy;
  69118. else if ((flags & yBottom) != 0)
  69119. y = dy + dh - h;
  69120. else
  69121. y = dy + (dh - h) * 0.5;
  69122. }
  69123. }
  69124. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69125. {
  69126. if (source.isEmpty())
  69127. return AffineTransform::identity;
  69128. float newX = destination.getX();
  69129. float newY = destination.getY();
  69130. float scaleX = destination.getWidth() / source.getWidth();
  69131. float scaleY = destination.getHeight() / source.getHeight();
  69132. if ((flags & stretchToFit) == 0)
  69133. {
  69134. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69135. : jmin (scaleX, scaleY);
  69136. if ((flags & onlyReduceInSize) != 0)
  69137. scaleX = jmin (scaleX, 1.0f);
  69138. if ((flags & onlyIncreaseInSize) != 0)
  69139. scaleX = jmax (scaleX, 1.0f);
  69140. scaleY = scaleX;
  69141. if ((flags & xRight) != 0)
  69142. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69143. else if ((flags & xLeft) == 0)
  69144. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69145. if ((flags & yBottom) != 0)
  69146. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69147. else if ((flags & yTop) == 0)
  69148. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69149. }
  69150. return AffineTransform::translation (-source.getX(), -source.getY())
  69151. .scaled (scaleX, scaleY)
  69152. .translated (newX, newY);
  69153. }
  69154. END_JUCE_NAMESPACE
  69155. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69156. /*** Start of inlined file: juce_Drawable.cpp ***/
  69157. BEGIN_JUCE_NAMESPACE
  69158. Drawable::Drawable()
  69159. {
  69160. setInterceptsMouseClicks (false, false);
  69161. setPaintingIsUnclipped (true);
  69162. }
  69163. Drawable::~Drawable()
  69164. {
  69165. }
  69166. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69167. {
  69168. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69169. }
  69170. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69171. {
  69172. g.saveState();
  69173. const float oldOpacity = getAlpha();
  69174. setAlpha (opacity);
  69175. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69176. (float) -originRelativeToComponent.getY())
  69177. .followedBy (getTransform())
  69178. .followedBy (transform));
  69179. if (! g.isClipEmpty())
  69180. paintEntireComponent (g, false);
  69181. setAlpha (oldOpacity);
  69182. g.restoreState();
  69183. }
  69184. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69185. {
  69186. draw (g, opacity, AffineTransform::translation (x, y));
  69187. }
  69188. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69189. {
  69190. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69191. }
  69192. DrawableComposite* Drawable::getParent() const
  69193. {
  69194. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69195. }
  69196. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69197. {
  69198. g.setOrigin (originRelativeToComponent.getX(),
  69199. originRelativeToComponent.getY());
  69200. }
  69201. void Drawable::markerHasMoved()
  69202. {
  69203. }
  69204. void Drawable::parentHierarchyChanged()
  69205. {
  69206. setBoundsToEnclose (getDrawableBounds());
  69207. }
  69208. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69209. {
  69210. Drawable* const parent = getParent();
  69211. Point<int> parentOrigin;
  69212. if (parent != 0)
  69213. parentOrigin = parent->originRelativeToComponent;
  69214. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69215. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69216. setBounds (newBounds);
  69217. }
  69218. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69219. {
  69220. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69221. }
  69222. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69223. {
  69224. if (! area.isEmpty())
  69225. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69226. }
  69227. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69228. {
  69229. Drawable* result = 0;
  69230. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69231. if (image.isValid())
  69232. {
  69233. DrawableImage* const di = new DrawableImage();
  69234. di->setImage (image);
  69235. result = di;
  69236. }
  69237. else
  69238. {
  69239. const String asString (String::createStringFromData (data, (int) numBytes));
  69240. XmlDocument doc (asString);
  69241. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69242. if (outer != 0 && outer->hasTagName ("svg"))
  69243. {
  69244. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69245. if (svg != 0)
  69246. result = Drawable::createFromSVG (*svg);
  69247. }
  69248. }
  69249. return result;
  69250. }
  69251. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69252. {
  69253. MemoryOutputStream mo;
  69254. mo.writeFromInputStream (dataSource, -1);
  69255. return createFromImageData (mo.getData(), mo.getDataSize());
  69256. }
  69257. Drawable* Drawable::createFromImageFile (const File& file)
  69258. {
  69259. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69260. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69261. }
  69262. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69263. {
  69264. return createChildFromValueTree (0, tree, imageProvider);
  69265. }
  69266. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69267. {
  69268. const Identifier type (tree.getType());
  69269. Drawable* d = 0;
  69270. if (type == DrawablePath::valueTreeType) d = new DrawablePath();
  69271. else if (type == DrawableComposite::valueTreeType) d = new DrawableComposite();
  69272. else if (type == DrawableRectangle::valueTreeType) d = new DrawableRectangle();
  69273. else if (type == DrawableImage::valueTreeType) d = new DrawableImage();
  69274. else if (type == DrawableText::valueTreeType) d = new DrawableText();
  69275. if (d != 0)
  69276. {
  69277. if (parent != 0)
  69278. parent->insertDrawable (d);
  69279. d->refreshFromValueTree (tree, imageProvider);
  69280. }
  69281. return d;
  69282. }
  69283. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69284. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69285. : state (state_)
  69286. {
  69287. }
  69288. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69289. {
  69290. }
  69291. const String Drawable::ValueTreeWrapperBase::getID() const
  69292. {
  69293. return state [idProperty];
  69294. }
  69295. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69296. {
  69297. if (newID.isEmpty())
  69298. state.removeProperty (idProperty, undoManager);
  69299. else
  69300. state.setProperty (idProperty, newID, undoManager);
  69301. }
  69302. END_JUCE_NAMESPACE
  69303. /*** End of inlined file: juce_Drawable.cpp ***/
  69304. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69305. BEGIN_JUCE_NAMESPACE
  69306. DrawableShape::DrawableShape()
  69307. : strokeType (0.0f),
  69308. mainFill (Colours::black),
  69309. strokeFill (Colours::black)
  69310. {
  69311. }
  69312. DrawableShape::DrawableShape (const DrawableShape& other)
  69313. : strokeType (other.strokeType),
  69314. mainFill (other.mainFill),
  69315. strokeFill (other.strokeFill)
  69316. {
  69317. }
  69318. DrawableShape::~DrawableShape()
  69319. {
  69320. }
  69321. void DrawableShape::setFill (const FillType& newFill)
  69322. {
  69323. mainFill = newFill;
  69324. }
  69325. void DrawableShape::setStrokeFill (const FillType& newFill)
  69326. {
  69327. strokeFill = newFill;
  69328. }
  69329. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69330. {
  69331. strokeType = newStrokeType;
  69332. strokeChanged();
  69333. }
  69334. void DrawableShape::setStrokeThickness (const float newThickness)
  69335. {
  69336. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69337. }
  69338. bool DrawableShape::isStrokeVisible() const throw()
  69339. {
  69340. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69341. }
  69342. bool DrawableShape::refreshFillTypes (const FillAndStrokeState& newState,
  69343. Expression::EvaluationContext* /*nameFinder*/,
  69344. ImageProvider* imageProvider)
  69345. {
  69346. bool hasChanged = false;
  69347. {
  69348. const FillType f (newState.getMainFill (getParent(), imageProvider));
  69349. if (mainFill != f)
  69350. {
  69351. hasChanged = true;
  69352. mainFill = f;
  69353. }
  69354. }
  69355. {
  69356. const FillType f (newState.getStrokeFill (getParent(), imageProvider));
  69357. if (strokeFill != f)
  69358. {
  69359. hasChanged = true;
  69360. strokeFill = f;
  69361. }
  69362. }
  69363. return hasChanged;
  69364. }
  69365. void DrawableShape::writeTo (FillAndStrokeState& state, ImageProvider* imageProvider, UndoManager* undoManager) const
  69366. {
  69367. state.setMainFill (mainFill, 0, 0, 0, imageProvider, undoManager);
  69368. state.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, undoManager);
  69369. state.setStrokeType (strokeType, undoManager);
  69370. }
  69371. void DrawableShape::paint (Graphics& g)
  69372. {
  69373. transformContextToCorrectOrigin (g);
  69374. g.setFillType (mainFill);
  69375. g.fillPath (path);
  69376. if (isStrokeVisible())
  69377. {
  69378. g.setFillType (strokeFill);
  69379. g.fillPath (strokePath);
  69380. }
  69381. }
  69382. void DrawableShape::pathChanged()
  69383. {
  69384. strokeChanged();
  69385. }
  69386. void DrawableShape::strokeChanged()
  69387. {
  69388. strokePath.clear();
  69389. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  69390. setBoundsToEnclose (getDrawableBounds());
  69391. repaint();
  69392. }
  69393. const Rectangle<float> DrawableShape::getDrawableBounds() const
  69394. {
  69395. if (isStrokeVisible())
  69396. return strokePath.getBounds();
  69397. else
  69398. return path.getBounds();
  69399. }
  69400. bool DrawableShape::hitTest (int x, int y) const
  69401. {
  69402. const float globalX = (float) (x - originRelativeToComponent.getX());
  69403. const float globalY = (float) (y - originRelativeToComponent.getY());
  69404. return path.contains (globalX, globalY)
  69405. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  69406. }
  69407. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69408. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69409. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69410. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69411. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69412. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69413. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69414. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69415. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69416. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69417. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69418. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69419. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69420. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69421. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69422. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69423. : Drawable::ValueTreeWrapperBase (state_)
  69424. {
  69425. }
  69426. const FillType DrawableShape::FillAndStrokeState::getMainFill (Expression::EvaluationContext* nameFinder,
  69427. ImageProvider* imageProvider) const
  69428. {
  69429. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  69430. }
  69431. ValueTree DrawableShape::FillAndStrokeState::getMainFillState()
  69432. {
  69433. ValueTree v (state.getChildWithName (fill));
  69434. if (v.isValid())
  69435. return v;
  69436. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  69437. return getMainFillState();
  69438. }
  69439. void DrawableShape::FillAndStrokeState::setMainFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69440. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69441. {
  69442. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69443. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69444. }
  69445. const FillType DrawableShape::FillAndStrokeState::getStrokeFill (Expression::EvaluationContext* nameFinder,
  69446. ImageProvider* imageProvider) const
  69447. {
  69448. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  69449. }
  69450. ValueTree DrawableShape::FillAndStrokeState::getStrokeFillState()
  69451. {
  69452. ValueTree v (state.getChildWithName (stroke));
  69453. if (v.isValid())
  69454. return v;
  69455. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  69456. return getStrokeFillState();
  69457. }
  69458. void DrawableShape::FillAndStrokeState::setStrokeFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69459. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69460. {
  69461. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69462. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69463. }
  69464. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69465. {
  69466. const String jointStyleString (state [jointStyle].toString());
  69467. const String capStyleString (state [capStyle].toString());
  69468. return PathStrokeType (state [strokeWidth],
  69469. jointStyleString == "curved" ? PathStrokeType::curved
  69470. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69471. : PathStrokeType::mitered),
  69472. capStyleString == "square" ? PathStrokeType::square
  69473. : (capStyleString == "round" ? PathStrokeType::rounded
  69474. : PathStrokeType::butt));
  69475. }
  69476. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69477. {
  69478. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69479. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69480. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69481. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69482. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69483. }
  69484. const FillType DrawableShape::FillAndStrokeState::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69485. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69486. {
  69487. const String newType (v[type].toString());
  69488. if (newType == "solid")
  69489. {
  69490. const String colourString (v [colour].toString());
  69491. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69492. : (uint32) colourString.getHexValue32()));
  69493. }
  69494. else if (newType == "gradient")
  69495. {
  69496. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69497. ColourGradient g;
  69498. if (gp1 != 0) *gp1 = p1;
  69499. if (gp2 != 0) *gp2 = p2;
  69500. if (gp3 != 0) *gp3 = p3;
  69501. g.point1 = p1.resolve (nameFinder);
  69502. g.point2 = p2.resolve (nameFinder);
  69503. g.isRadial = v[radial];
  69504. StringArray colourSteps;
  69505. colourSteps.addTokens (v[colours].toString(), false);
  69506. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69507. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69508. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69509. FillType fillType (g);
  69510. if (g.isRadial)
  69511. {
  69512. const Point<float> point3 (p3.resolve (nameFinder));
  69513. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69514. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69515. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69516. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69517. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69518. }
  69519. return fillType;
  69520. }
  69521. else if (newType == "image")
  69522. {
  69523. Image im;
  69524. if (imageProvider != 0)
  69525. im = imageProvider->getImageForIdentifier (v[imageId]);
  69526. FillType f (im, AffineTransform::identity);
  69527. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69528. return f;
  69529. }
  69530. jassert (! v.isValid());
  69531. return FillType();
  69532. }
  69533. namespace DrawableShapeHelpers
  69534. {
  69535. const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69536. {
  69537. const ColourGradient& g = *fillType.gradient;
  69538. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69539. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69540. return point3Source.transformedBy (fillType.transform);
  69541. }
  69542. }
  69543. void DrawableShape::FillAndStrokeState::writeFillType (ValueTree& v, const FillType& fillType,
  69544. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69545. ImageProvider* imageProvider, UndoManager* const undoManager)
  69546. {
  69547. if (fillType.isColour())
  69548. {
  69549. v.setProperty (type, "solid", undoManager);
  69550. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69551. }
  69552. else if (fillType.isGradient())
  69553. {
  69554. v.setProperty (type, "gradient", undoManager);
  69555. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69556. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69557. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : DrawableShapeHelpers::calcThirdGradientPoint (fillType).toString(), undoManager);
  69558. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69559. String s;
  69560. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69561. s << ' ' << fillType.gradient->getColourPosition (i)
  69562. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69563. v.setProperty (colours, s.trimStart(), undoManager);
  69564. }
  69565. else if (fillType.isTiledImage())
  69566. {
  69567. v.setProperty (type, "image", undoManager);
  69568. if (imageProvider != 0)
  69569. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69570. if (fillType.getOpacity() < 1.0f)
  69571. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69572. else
  69573. v.removeProperty (imageOpacity, undoManager);
  69574. }
  69575. else
  69576. {
  69577. jassertfalse;
  69578. }
  69579. }
  69580. END_JUCE_NAMESPACE
  69581. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69582. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69583. BEGIN_JUCE_NAMESPACE
  69584. DrawableComposite::DrawableComposite()
  69585. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  69586. updateBoundsReentrant (false)
  69587. {
  69588. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69589. RelativeCoordinate (100.0),
  69590. RelativeCoordinate (0.0),
  69591. RelativeCoordinate (100.0)));
  69592. }
  69593. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69594. : bounds (other.bounds),
  69595. updateBoundsReentrant (false)
  69596. {
  69597. for (int i = 0; i < other.getNumDrawables(); ++i)
  69598. insertDrawable (other.getDrawable(i)->createCopy());
  69599. markersX.addCopiesOf (other.markersX);
  69600. markersY.addCopiesOf (other.markersY);
  69601. }
  69602. DrawableComposite::~DrawableComposite()
  69603. {
  69604. deleteAllChildren();
  69605. }
  69606. int DrawableComposite::getNumDrawables() const throw()
  69607. {
  69608. return getNumChildComponents();
  69609. }
  69610. Drawable* DrawableComposite::getDrawable (int index) const
  69611. {
  69612. return dynamic_cast <Drawable*> (getChildComponent (index));
  69613. }
  69614. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69615. {
  69616. if (drawable != 0)
  69617. addAndMakeVisible (drawable, index);
  69618. }
  69619. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69620. {
  69621. insertDrawable (drawable.createCopy(), index);
  69622. }
  69623. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69624. {
  69625. Drawable* const d = getDrawable (index);
  69626. if (deleteDrawable)
  69627. delete d;
  69628. else
  69629. removeChildComponent (d);
  69630. }
  69631. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69632. {
  69633. for (int i = getNumChildComponents(); --i >= 0;)
  69634. if (getChildComponent(i)->getName() == name)
  69635. return getDrawable (i);
  69636. return 0;
  69637. }
  69638. void DrawableComposite::bringToFront (const int index)
  69639. {
  69640. Drawable* d = getDrawable (index);
  69641. if (d != 0)
  69642. d->toFront (false);
  69643. }
  69644. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  69645. {
  69646. Rectangle<float> r;
  69647. for (int i = getNumDrawables(); --i >= 0;)
  69648. {
  69649. Drawable* const d = getDrawable(i);
  69650. if (d != 0)
  69651. {
  69652. if (d->isTransformed())
  69653. r = r.getUnion (d->getDrawableBounds().transformed (d->getTransform()));
  69654. else
  69655. r = r.getUnion (d->getDrawableBounds());
  69656. }
  69657. }
  69658. return r;
  69659. }
  69660. void DrawableComposite::markerHasMoved()
  69661. {
  69662. for (int i = getNumDrawables(); --i >= 0;)
  69663. {
  69664. Drawable* const d = getDrawable(i);
  69665. if (d != 0)
  69666. d->markerHasMoved();
  69667. }
  69668. }
  69669. const RelativeRectangle DrawableComposite::getContentArea() const
  69670. {
  69671. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69672. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69673. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69674. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69675. }
  69676. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69677. {
  69678. setMarker (contentLeftMarkerName, true, newArea.left);
  69679. setMarker (contentRightMarkerName, true, newArea.right);
  69680. setMarker (contentTopMarkerName, false, newArea.top);
  69681. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69682. refreshTransformFromBounds();
  69683. }
  69684. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69685. {
  69686. bounds = newBoundingBox;
  69687. refreshTransformFromBounds();
  69688. }
  69689. void DrawableComposite::resetBoundingBoxToContentArea()
  69690. {
  69691. const RelativeRectangle content (getContentArea());
  69692. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69693. RelativePoint (content.right, content.top),
  69694. RelativePoint (content.left, content.bottom)));
  69695. }
  69696. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69697. {
  69698. const Rectangle<float> activeArea (getDrawableBounds());
  69699. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  69700. RelativeCoordinate (activeArea.getRight()),
  69701. RelativeCoordinate (activeArea.getY()),
  69702. RelativeCoordinate (activeArea.getBottom())));
  69703. resetBoundingBoxToContentArea();
  69704. }
  69705. void DrawableComposite::refreshTransformFromBounds()
  69706. {
  69707. Point<float> resolved[3];
  69708. bounds.resolveThreePoints (resolved, getParent());
  69709. const Rectangle<float> content (getContentArea().resolve (getParent()));
  69710. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69711. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69712. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  69713. if (t.isSingularity())
  69714. t = AffineTransform::identity;
  69715. setTransform (t);
  69716. }
  69717. void DrawableComposite::parentHierarchyChanged()
  69718. {
  69719. DrawableComposite* parent = getParent();
  69720. if (parent != 0)
  69721. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  69722. }
  69723. void DrawableComposite::childBoundsChanged (Component*)
  69724. {
  69725. updateBoundsToFitChildren();
  69726. }
  69727. void DrawableComposite::childrenChanged()
  69728. {
  69729. updateBoundsToFitChildren();
  69730. }
  69731. struct RentrancyCheckSetter
  69732. {
  69733. RentrancyCheckSetter (bool& b_) : b (b_) { b_ = true; }
  69734. ~RentrancyCheckSetter() { b = false; }
  69735. private:
  69736. bool& b;
  69737. JUCE_DECLARE_NON_COPYABLE (RentrancyCheckSetter);
  69738. };
  69739. void DrawableComposite::updateBoundsToFitChildren()
  69740. {
  69741. if (! updateBoundsReentrant)
  69742. {
  69743. const RentrancyCheckSetter checkSetter (updateBoundsReentrant);
  69744. Rectangle<int> childArea;
  69745. for (int i = getNumChildComponents(); --i >= 0;)
  69746. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  69747. const Point<int> delta (childArea.getPosition());
  69748. childArea += getPosition();
  69749. if (childArea != getBounds())
  69750. {
  69751. if (! delta.isOrigin())
  69752. {
  69753. originRelativeToComponent -= delta;
  69754. for (int i = getNumChildComponents(); --i >= 0;)
  69755. {
  69756. Component* const c = getChildComponent(i);
  69757. if (c != 0)
  69758. c->setBounds (c->getBounds() - delta);
  69759. }
  69760. }
  69761. setBounds (childArea);
  69762. }
  69763. }
  69764. }
  69765. const char* const DrawableComposite::contentLeftMarkerName = "left";
  69766. const char* const DrawableComposite::contentRightMarkerName = "right";
  69767. const char* const DrawableComposite::contentTopMarkerName = "top";
  69768. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  69769. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69770. : name (other.name), position (other.position)
  69771. {
  69772. }
  69773. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69774. : name (name_), position (position_)
  69775. {
  69776. }
  69777. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69778. {
  69779. return name != other.name || position != other.position;
  69780. }
  69781. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69782. {
  69783. return (xAxis ? markersX : markersY).size();
  69784. }
  69785. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69786. {
  69787. return (xAxis ? markersX : markersY) [index];
  69788. }
  69789. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69790. {
  69791. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69792. for (int i = 0; i < markers.size(); ++i)
  69793. {
  69794. Marker* const m = markers.getUnchecked(i);
  69795. if (m->name == name)
  69796. {
  69797. if (m->position != position)
  69798. {
  69799. m->position = position;
  69800. markerHasMoved();
  69801. }
  69802. return;
  69803. }
  69804. }
  69805. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69806. markerHasMoved();
  69807. }
  69808. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69809. {
  69810. jassert (index >= 2);
  69811. if (index >= 2)
  69812. (xAxis ? markersX : markersY).remove (index);
  69813. }
  69814. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69815. {
  69816. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69817. int i;
  69818. for (i = 0; i < markersX.size(); ++i)
  69819. {
  69820. Marker* const m = markersX.getUnchecked(i);
  69821. if (m->name == symbol)
  69822. return m->position.getExpression();
  69823. }
  69824. for (i = 0; i < markersY.size(); ++i)
  69825. {
  69826. Marker* const m = markersY.getUnchecked(i);
  69827. if (m->name == symbol)
  69828. return m->position.getExpression();
  69829. }
  69830. throw Expression::EvaluationError (symbol, member);
  69831. }
  69832. Drawable* DrawableComposite::createCopy() const
  69833. {
  69834. return new DrawableComposite (*this);
  69835. }
  69836. const Identifier DrawableComposite::valueTreeType ("Group");
  69837. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69838. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69839. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69840. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69841. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69842. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69843. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69844. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69845. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69846. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69847. : ValueTreeWrapperBase (state_)
  69848. {
  69849. jassert (state.hasType (valueTreeType));
  69850. }
  69851. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69852. {
  69853. return state.getChildWithName (childGroupTag);
  69854. }
  69855. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69856. {
  69857. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69858. }
  69859. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69860. {
  69861. return getChildList().getNumChildren();
  69862. }
  69863. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69864. {
  69865. return getChildList().getChild (index);
  69866. }
  69867. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69868. {
  69869. if (getID() == objectId)
  69870. return state;
  69871. if (! recursive)
  69872. {
  69873. return getChildList().getChildWithProperty (idProperty, objectId);
  69874. }
  69875. else
  69876. {
  69877. const ValueTree childList (getChildList());
  69878. for (int i = getNumDrawables(); --i >= 0;)
  69879. {
  69880. const ValueTree& child = childList.getChild (i);
  69881. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69882. return child;
  69883. if (child.hasType (DrawableComposite::valueTreeType))
  69884. {
  69885. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69886. if (v.isValid())
  69887. return v;
  69888. }
  69889. }
  69890. return ValueTree::invalid;
  69891. }
  69892. }
  69893. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69894. {
  69895. return getChildList().indexOf (item);
  69896. }
  69897. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69898. {
  69899. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69900. }
  69901. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69902. {
  69903. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69904. }
  69905. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69906. {
  69907. getChildList().removeChild (child, undoManager);
  69908. }
  69909. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69910. {
  69911. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69912. state.getProperty (topRight, "100, 0"),
  69913. state.getProperty (bottomLeft, "0, 100"));
  69914. }
  69915. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69916. {
  69917. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69918. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69919. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69920. }
  69921. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69922. {
  69923. const RelativeRectangle content (getContentArea());
  69924. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69925. RelativePoint (content.right, content.top),
  69926. RelativePoint (content.left, content.bottom)), undoManager);
  69927. }
  69928. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  69929. {
  69930. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  69931. getMarker (true, getMarkerState (true, 1)).position,
  69932. getMarker (false, getMarkerState (false, 0)).position,
  69933. getMarker (false, getMarkerState (false, 1)).position);
  69934. }
  69935. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  69936. {
  69937. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  69938. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  69939. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  69940. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  69941. }
  69942. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  69943. {
  69944. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  69945. }
  69946. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  69947. {
  69948. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  69949. }
  69950. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  69951. {
  69952. return getMarkerList (xAxis).getNumChildren();
  69953. }
  69954. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  69955. {
  69956. return getMarkerList (xAxis).getChild (index);
  69957. }
  69958. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  69959. {
  69960. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  69961. }
  69962. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  69963. {
  69964. return state.isAChildOf (getMarkerList (xAxis));
  69965. }
  69966. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  69967. {
  69968. (void) xAxis;
  69969. jassert (containsMarker (xAxis, state));
  69970. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  69971. }
  69972. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  69973. {
  69974. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  69975. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  69976. if (marker.isValid())
  69977. {
  69978. marker.setProperty (posProperty, m.position.toString(), undoManager);
  69979. }
  69980. else
  69981. {
  69982. marker = ValueTree (markerTag);
  69983. marker.setProperty (nameProperty, m.name, 0);
  69984. marker.setProperty (posProperty, m.position.toString(), 0);
  69985. markerList.addChild (marker, -1, undoManager);
  69986. }
  69987. }
  69988. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  69989. {
  69990. if (state [nameProperty].toString() != contentLeftMarkerName
  69991. && state [nameProperty].toString() != contentRightMarkerName
  69992. && state [nameProperty].toString() != contentTopMarkerName
  69993. && state [nameProperty].toString() != contentBottomMarkerName)
  69994. getMarkerList (xAxis).removeChild (state, undoManager);
  69995. }
  69996. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69997. {
  69998. const ValueTreeWrapper wrapper (tree);
  69999. setName (wrapper.getID());
  70000. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70001. if (bounds != newBounds)
  70002. bounds = newBounds;
  70003. const int numMarkersX = wrapper.getNumMarkers (true);
  70004. const int numMarkersY = wrapper.getNumMarkers (false);
  70005. // Remove deleted markers...
  70006. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70007. {
  70008. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70009. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70010. }
  70011. // Update markers and add new ones..
  70012. int i;
  70013. for (i = 0; i < numMarkersX; ++i)
  70014. {
  70015. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70016. Marker* m = markersX[i];
  70017. if (m == 0)
  70018. markersX.add (new Marker (newMarker));
  70019. else if (newMarker != *m)
  70020. *m = newMarker;
  70021. }
  70022. for (i = 0; i < numMarkersY; ++i)
  70023. {
  70024. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70025. Marker* m = markersY[i];
  70026. if (m == 0)
  70027. markersY.add (new Marker (newMarker));
  70028. else if (newMarker != *m)
  70029. *m = newMarker;
  70030. }
  70031. // Remove deleted drawables..
  70032. for (i = getNumDrawables(); --i >= wrapper.getNumDrawables();)
  70033. delete getDrawable(i);
  70034. // Update drawables and add new ones..
  70035. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70036. {
  70037. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70038. Drawable* d = getDrawable(i);
  70039. if (d != 0)
  70040. {
  70041. if (newDrawable.hasType (d->getValueTreeType()))
  70042. {
  70043. d->refreshFromValueTree (newDrawable, imageProvider);
  70044. }
  70045. else
  70046. {
  70047. delete d;
  70048. d = 0;
  70049. }
  70050. }
  70051. if (d == 0)
  70052. {
  70053. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70054. addAndMakeVisible (d, i);
  70055. }
  70056. }
  70057. refreshTransformFromBounds();
  70058. }
  70059. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70060. {
  70061. ValueTree tree (valueTreeType);
  70062. ValueTreeWrapper v (tree);
  70063. v.setID (getName(), 0);
  70064. v.setBoundingBox (bounds, 0);
  70065. int i;
  70066. for (i = 0; i < getNumDrawables(); ++i)
  70067. v.addDrawable (getDrawable(i)->createValueTree (imageProvider), -1, 0);
  70068. for (i = 0; i < markersX.size(); ++i)
  70069. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70070. for (i = 0; i < markersY.size(); ++i)
  70071. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70072. return tree;
  70073. }
  70074. END_JUCE_NAMESPACE
  70075. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70076. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70077. BEGIN_JUCE_NAMESPACE
  70078. DrawableImage::DrawableImage()
  70079. : image (0),
  70080. opacity (1.0f),
  70081. overlayColour (0x00000000)
  70082. {
  70083. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70084. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70085. }
  70086. DrawableImage::DrawableImage (const DrawableImage& other)
  70087. : image (other.image),
  70088. opacity (other.opacity),
  70089. overlayColour (other.overlayColour),
  70090. bounds (other.bounds)
  70091. {
  70092. }
  70093. DrawableImage::~DrawableImage()
  70094. {
  70095. }
  70096. void DrawableImage::setImage (const Image& imageToUse)
  70097. {
  70098. image = imageToUse;
  70099. setBounds (imageToUse.getBounds());
  70100. if (image.isValid())
  70101. {
  70102. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70103. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70104. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70105. }
  70106. refreshTransformFromBounds();
  70107. }
  70108. void DrawableImage::setOpacity (const float newOpacity)
  70109. {
  70110. opacity = newOpacity;
  70111. }
  70112. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70113. {
  70114. overlayColour = newOverlayColour;
  70115. }
  70116. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70117. {
  70118. bounds = newBounds;
  70119. refreshTransformFromBounds();
  70120. }
  70121. void DrawableImage::refreshTransformFromBounds()
  70122. {
  70123. if (! image.isNull())
  70124. {
  70125. Point<float> resolved[3];
  70126. bounds.resolveThreePoints (resolved, getParent());
  70127. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70128. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70129. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70130. tr.getX(), tr.getY(),
  70131. bl.getX(), bl.getY()));
  70132. if (! t.isSingularity())
  70133. setTransform (t);
  70134. }
  70135. }
  70136. void DrawableImage::paint (Graphics& g)
  70137. {
  70138. if (image.isValid())
  70139. {
  70140. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70141. {
  70142. g.setOpacity (opacity);
  70143. g.drawImageAt (image, 0, 0, false);
  70144. }
  70145. if (! overlayColour.isTransparent())
  70146. {
  70147. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70148. g.drawImageAt (image, 0, 0, true);
  70149. }
  70150. }
  70151. }
  70152. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70153. {
  70154. return image.getBounds().toFloat();
  70155. }
  70156. bool DrawableImage::hitTest (int x, int y) const
  70157. {
  70158. return (! image.isNull())
  70159. && image.getPixelAt (x, y).getAlpha() >= 127;
  70160. }
  70161. Drawable* DrawableImage::createCopy() const
  70162. {
  70163. return new DrawableImage (*this);
  70164. }
  70165. const Identifier DrawableImage::valueTreeType ("Image");
  70166. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70167. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70168. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70169. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70170. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70171. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70172. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70173. : ValueTreeWrapperBase (state_)
  70174. {
  70175. jassert (state.hasType (valueTreeType));
  70176. }
  70177. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70178. {
  70179. return state [image];
  70180. }
  70181. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70182. {
  70183. return state.getPropertyAsValue (image, undoManager);
  70184. }
  70185. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70186. {
  70187. state.setProperty (image, newIdentifier, undoManager);
  70188. }
  70189. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70190. {
  70191. return (float) state.getProperty (opacity, 1.0);
  70192. }
  70193. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70194. {
  70195. if (! state.hasProperty (opacity))
  70196. state.setProperty (opacity, 1.0, undoManager);
  70197. return state.getPropertyAsValue (opacity, undoManager);
  70198. }
  70199. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70200. {
  70201. state.setProperty (opacity, newOpacity, undoManager);
  70202. }
  70203. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70204. {
  70205. return Colour (state [overlay].toString().getHexValue32());
  70206. }
  70207. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70208. {
  70209. if (newColour.isTransparent())
  70210. state.removeProperty (overlay, undoManager);
  70211. else
  70212. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70213. }
  70214. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70215. {
  70216. return state.getPropertyAsValue (overlay, undoManager);
  70217. }
  70218. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70219. {
  70220. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70221. state.getProperty (topRight, "100, 0"),
  70222. state.getProperty (bottomLeft, "0, 100"));
  70223. }
  70224. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70225. {
  70226. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70227. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70228. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70229. }
  70230. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70231. {
  70232. const ValueTreeWrapper controller (tree);
  70233. setName (controller.getID());
  70234. const float newOpacity = controller.getOpacity();
  70235. const Colour newOverlayColour (controller.getOverlayColour());
  70236. Image newImage;
  70237. const var imageIdentifier (controller.getImageIdentifier());
  70238. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70239. if (imageProvider != 0)
  70240. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70241. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70242. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage)
  70243. {
  70244. repaint();
  70245. opacity = newOpacity;
  70246. overlayColour = newOverlayColour;
  70247. bounds = newBounds;
  70248. setImage (newImage);
  70249. }
  70250. }
  70251. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70252. {
  70253. ValueTree tree (valueTreeType);
  70254. ValueTreeWrapper v (tree);
  70255. v.setID (getName(), 0);
  70256. v.setOpacity (opacity, 0);
  70257. v.setOverlayColour (overlayColour, 0);
  70258. v.setBoundingBox (bounds, 0);
  70259. if (image.isValid())
  70260. {
  70261. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70262. if (imageProvider != 0)
  70263. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70264. }
  70265. return tree;
  70266. }
  70267. END_JUCE_NAMESPACE
  70268. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70269. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70270. BEGIN_JUCE_NAMESPACE
  70271. DrawablePath::DrawablePath()
  70272. {
  70273. }
  70274. DrawablePath::DrawablePath (const DrawablePath& other)
  70275. : DrawableShape (other)
  70276. {
  70277. if (other.relativePath != 0)
  70278. relativePath = new RelativePointPath (*other.relativePath);
  70279. else
  70280. setPath (other.path);
  70281. }
  70282. DrawablePath::~DrawablePath()
  70283. {
  70284. }
  70285. Drawable* DrawablePath::createCopy() const
  70286. {
  70287. return new DrawablePath (*this);
  70288. }
  70289. void DrawablePath::setPath (const Path& newPath)
  70290. {
  70291. path = newPath;
  70292. pathChanged();
  70293. }
  70294. const Path& DrawablePath::getPath() const
  70295. {
  70296. return path;
  70297. }
  70298. const Path& DrawablePath::getStrokePath() const
  70299. {
  70300. return strokePath;
  70301. }
  70302. bool DrawablePath::rebuildPath (Path& path) const
  70303. {
  70304. if (relativePath != 0)
  70305. {
  70306. path.clear();
  70307. relativePath->createPath (path, getParent());
  70308. return true;
  70309. }
  70310. return false;
  70311. }
  70312. const Identifier DrawablePath::valueTreeType ("Path");
  70313. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70314. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70315. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70316. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70317. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70318. : FillAndStrokeState (state_)
  70319. {
  70320. jassert (state.hasType (valueTreeType));
  70321. }
  70322. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70323. {
  70324. return state.getOrCreateChildWithName (path, 0);
  70325. }
  70326. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70327. {
  70328. return state [nonZeroWinding];
  70329. }
  70330. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70331. {
  70332. state.setProperty (nonZeroWinding, b, undoManager);
  70333. }
  70334. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70335. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70336. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70337. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70338. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70339. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70340. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70341. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70342. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70343. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70344. : state (state_)
  70345. {
  70346. }
  70347. DrawablePath::ValueTreeWrapper::Element::~Element()
  70348. {
  70349. }
  70350. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70351. {
  70352. return ValueTreeWrapper (state.getParent().getParent());
  70353. }
  70354. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70355. {
  70356. return Element (state.getSibling (-1));
  70357. }
  70358. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70359. {
  70360. const Identifier i (state.getType());
  70361. if (i == startSubPathElement || i == lineToElement) return 1;
  70362. if (i == quadraticToElement) return 2;
  70363. if (i == cubicToElement) return 3;
  70364. return 0;
  70365. }
  70366. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70367. {
  70368. jassert (index >= 0 && index < getNumControlPoints());
  70369. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70370. }
  70371. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70372. {
  70373. jassert (index >= 0 && index < getNumControlPoints());
  70374. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70375. }
  70376. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70377. {
  70378. jassert (index >= 0 && index < getNumControlPoints());
  70379. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70380. }
  70381. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70382. {
  70383. const Identifier i (state.getType());
  70384. if (i == startSubPathElement)
  70385. return getControlPoint (0);
  70386. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70387. return getPreviousElement().getEndPoint();
  70388. }
  70389. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70390. {
  70391. const Identifier i (state.getType());
  70392. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70393. if (i == quadraticToElement) return getControlPoint (1);
  70394. if (i == cubicToElement) return getControlPoint (2);
  70395. jassert (i == closeSubPathElement);
  70396. return RelativePoint();
  70397. }
  70398. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70399. {
  70400. const Identifier i (state.getType());
  70401. if (i == lineToElement || i == closeSubPathElement)
  70402. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70403. if (i == cubicToElement)
  70404. {
  70405. Path p;
  70406. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70407. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70408. return p.getLength();
  70409. }
  70410. if (i == quadraticToElement)
  70411. {
  70412. Path p;
  70413. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70414. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70415. return p.getLength();
  70416. }
  70417. jassert (i == startSubPathElement);
  70418. return 0;
  70419. }
  70420. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70421. {
  70422. return state [mode].toString();
  70423. }
  70424. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70425. {
  70426. if (state.hasType (cubicToElement))
  70427. state.setProperty (mode, newMode, undoManager);
  70428. }
  70429. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70430. {
  70431. const Identifier i (state.getType());
  70432. if (i == quadraticToElement || i == cubicToElement)
  70433. {
  70434. ValueTree newState (lineToElement);
  70435. Element e (newState);
  70436. e.setControlPoint (0, getEndPoint(), undoManager);
  70437. state = newState;
  70438. }
  70439. }
  70440. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70441. {
  70442. const Identifier i (state.getType());
  70443. if (i == lineToElement || i == quadraticToElement)
  70444. {
  70445. ValueTree newState (cubicToElement);
  70446. Element e (newState);
  70447. const RelativePoint start (getStartPoint());
  70448. const RelativePoint end (getEndPoint());
  70449. const Point<float> startResolved (start.resolve (nameFinder));
  70450. const Point<float> endResolved (end.resolve (nameFinder));
  70451. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70452. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70453. e.setControlPoint (2, end, undoManager);
  70454. state = newState;
  70455. }
  70456. }
  70457. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70458. {
  70459. const Identifier i (state.getType());
  70460. if (i != startSubPathElement)
  70461. {
  70462. ValueTree newState (startSubPathElement);
  70463. Element e (newState);
  70464. e.setControlPoint (0, getEndPoint(), undoManager);
  70465. state = newState;
  70466. }
  70467. }
  70468. namespace DrawablePathHelpers
  70469. {
  70470. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70471. {
  70472. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70473. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70474. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70475. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70476. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70477. return newCp1 + (newCp2 - newCp1) * proportion;
  70478. }
  70479. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70480. {
  70481. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70482. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70483. return mid1 + (mid2 - mid1) * proportion;
  70484. }
  70485. }
  70486. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70487. {
  70488. using namespace DrawablePathHelpers;
  70489. const Identifier i (state.getType());
  70490. float bestProp = 0;
  70491. if (i == cubicToElement)
  70492. {
  70493. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70494. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70495. float bestDistance = std::numeric_limits<float>::max();
  70496. for (int i = 110; --i >= 0;)
  70497. {
  70498. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70499. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70500. const float distance = centre.getDistanceFrom (targetPoint);
  70501. if (distance < bestDistance)
  70502. {
  70503. bestProp = prop;
  70504. bestDistance = distance;
  70505. }
  70506. }
  70507. }
  70508. else if (i == quadraticToElement)
  70509. {
  70510. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70511. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70512. float bestDistance = std::numeric_limits<float>::max();
  70513. for (int i = 110; --i >= 0;)
  70514. {
  70515. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70516. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70517. const float distance = centre.getDistanceFrom (targetPoint);
  70518. if (distance < bestDistance)
  70519. {
  70520. bestProp = prop;
  70521. bestDistance = distance;
  70522. }
  70523. }
  70524. }
  70525. else if (i == lineToElement)
  70526. {
  70527. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70528. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70529. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70530. }
  70531. return bestProp;
  70532. }
  70533. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70534. {
  70535. ValueTree newTree;
  70536. const Identifier i (state.getType());
  70537. if (i == cubicToElement)
  70538. {
  70539. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70540. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70541. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70542. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70543. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70544. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70545. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70546. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70547. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70548. setControlPoint (0, mid1, undoManager);
  70549. setControlPoint (1, newCp1, undoManager);
  70550. setControlPoint (2, newCentre, undoManager);
  70551. setModeOfEndPoint (roundedMode, undoManager);
  70552. Element newElement (newTree = ValueTree (cubicToElement));
  70553. newElement.setControlPoint (0, newCp2, 0);
  70554. newElement.setControlPoint (1, mid3, 0);
  70555. newElement.setControlPoint (2, rp4, 0);
  70556. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70557. }
  70558. else if (i == quadraticToElement)
  70559. {
  70560. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70561. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70562. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70563. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70564. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70565. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70566. setControlPoint (0, mid1, undoManager);
  70567. setControlPoint (1, newCentre, undoManager);
  70568. setModeOfEndPoint (roundedMode, undoManager);
  70569. Element newElement (newTree = ValueTree (quadraticToElement));
  70570. newElement.setControlPoint (0, mid2, 0);
  70571. newElement.setControlPoint (1, rp3, 0);
  70572. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70573. }
  70574. else if (i == lineToElement)
  70575. {
  70576. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70577. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70578. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70579. setControlPoint (0, newPoint, undoManager);
  70580. Element newElement (newTree = ValueTree (lineToElement));
  70581. newElement.setControlPoint (0, rp2, 0);
  70582. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70583. }
  70584. else if (i == closeSubPathElement)
  70585. {
  70586. }
  70587. return newTree;
  70588. }
  70589. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70590. {
  70591. state.getParent().removeChild (state, undoManager);
  70592. }
  70593. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70594. {
  70595. ValueTreeWrapper v (tree);
  70596. setName (v.getID());
  70597. if (refreshFillTypes (v, getParent(), imageProvider))
  70598. repaint();
  70599. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70600. Path newPath;
  70601. newRelativePath->createPath (newPath, getParent());
  70602. if (! newRelativePath->containsAnyDynamicPoints())
  70603. newRelativePath = 0;
  70604. const PathStrokeType newStroke (v.getStrokeType());
  70605. if (strokeType != newStroke || path != newPath)
  70606. {
  70607. path.swapWithPath (newPath);
  70608. strokeType = newStroke;
  70609. pathChanged();
  70610. }
  70611. relativePath = newRelativePath;
  70612. }
  70613. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70614. {
  70615. ValueTree tree (valueTreeType);
  70616. ValueTreeWrapper v (tree);
  70617. v.setID (getName(), 0);
  70618. writeTo (v, imageProvider, 0);
  70619. if (relativePath != 0)
  70620. {
  70621. relativePath->writeTo (tree, 0);
  70622. }
  70623. else
  70624. {
  70625. RelativePointPath rp (path);
  70626. rp.writeTo (tree, 0);
  70627. }
  70628. return tree;
  70629. }
  70630. END_JUCE_NAMESPACE
  70631. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70632. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70633. BEGIN_JUCE_NAMESPACE
  70634. DrawableRectangle::DrawableRectangle()
  70635. {
  70636. }
  70637. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70638. : DrawableShape (other)
  70639. {
  70640. }
  70641. DrawableRectangle::~DrawableRectangle()
  70642. {
  70643. }
  70644. Drawable* DrawableRectangle::createCopy() const
  70645. {
  70646. return new DrawableRectangle (*this);
  70647. }
  70648. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70649. {
  70650. bounds = newBounds;
  70651. pathChanged();
  70652. strokeChanged();
  70653. }
  70654. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70655. {
  70656. cornerSize = newSize;
  70657. pathChanged();
  70658. strokeChanged();
  70659. }
  70660. bool DrawableRectangle::rebuildPath (Path& path) const
  70661. {
  70662. Point<float> points[3];
  70663. bounds.resolveThreePoints (points, getParent());
  70664. const float w = Line<float> (points[0], points[1]).getLength();
  70665. const float h = Line<float> (points[0], points[2]).getLength();
  70666. const float cornerSizeX = (float) cornerSize.x.resolve (getParent());
  70667. const float cornerSizeY = (float) cornerSize.y.resolve (getParent());
  70668. path.clear();
  70669. if (cornerSizeX > 0 && cornerSizeY > 0)
  70670. path.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70671. else
  70672. path.addRectangle (0, 0, w, h);
  70673. path.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70674. w, 0, points[1].getX(), points[1].getY(),
  70675. 0, h, points[2].getX(), points[2].getY()));
  70676. return true;
  70677. }
  70678. const AffineTransform DrawableRectangle::calculateTransform() const
  70679. {
  70680. Point<float> resolved[3];
  70681. bounds.resolveThreePoints (resolved, getParent());
  70682. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70683. resolved[1].getX(), resolved[1].getY(),
  70684. resolved[2].getX(), resolved[2].getY());
  70685. }
  70686. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70687. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70688. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70689. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70690. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70691. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70692. : FillAndStrokeState (state_)
  70693. {
  70694. jassert (state.hasType (valueTreeType));
  70695. }
  70696. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70697. {
  70698. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70699. state.getProperty (topRight, "100, 0"),
  70700. state.getProperty (bottomLeft, "0, 100"));
  70701. }
  70702. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70703. {
  70704. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70705. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70706. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70707. }
  70708. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70709. {
  70710. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70711. }
  70712. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70713. {
  70714. return RelativePoint (state [cornerSize]);
  70715. }
  70716. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70717. {
  70718. return state.getPropertyAsValue (cornerSize, undoManager);
  70719. }
  70720. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70721. {
  70722. ValueTreeWrapper v (tree);
  70723. setName (v.getID());
  70724. if (refreshFillTypes (v, getParent(), imageProvider))
  70725. repaint();
  70726. RelativeParallelogram newBounds (v.getRectangle());
  70727. const PathStrokeType newStroke (v.getStrokeType());
  70728. const RelativePoint newCornerSize (v.getCornerSize());
  70729. if (strokeType != newStroke || newBounds != bounds || newCornerSize != cornerSize)
  70730. {
  70731. repaint();
  70732. bounds = newBounds;
  70733. strokeType = newStroke;
  70734. cornerSize = newCornerSize;
  70735. pathChanged();
  70736. }
  70737. }
  70738. const ValueTree DrawableRectangle::createValueTree (ImageProvider* imageProvider) const
  70739. {
  70740. ValueTree tree (valueTreeType);
  70741. ValueTreeWrapper v (tree);
  70742. v.setID (getName(), 0);
  70743. writeTo (v, imageProvider, 0);
  70744. v.setRectangle (bounds, 0);
  70745. v.setCornerSize (cornerSize, 0);
  70746. return tree;
  70747. }
  70748. END_JUCE_NAMESPACE
  70749. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  70750. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70751. BEGIN_JUCE_NAMESPACE
  70752. DrawableText::DrawableText()
  70753. : colour (Colours::black),
  70754. justification (Justification::centredLeft)
  70755. {
  70756. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70757. RelativePoint (50.0f, 0.0f),
  70758. RelativePoint (0.0f, 20.0f)));
  70759. setFont (Font (15.0f), true);
  70760. }
  70761. DrawableText::DrawableText (const DrawableText& other)
  70762. : bounds (other.bounds),
  70763. fontSizeControlPoint (other.fontSizeControlPoint),
  70764. font (other.font),
  70765. text (other.text),
  70766. colour (other.colour),
  70767. justification (other.justification)
  70768. {
  70769. }
  70770. DrawableText::~DrawableText()
  70771. {
  70772. }
  70773. void DrawableText::refreshBounds()
  70774. {
  70775. setBoundsToEnclose (getDrawableBounds());
  70776. repaint();
  70777. }
  70778. void DrawableText::setText (const String& newText)
  70779. {
  70780. text = newText;
  70781. refreshBounds();
  70782. }
  70783. void DrawableText::setColour (const Colour& newColour)
  70784. {
  70785. colour = newColour;
  70786. repaint();
  70787. }
  70788. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70789. {
  70790. font = newFont;
  70791. if (applySizeAndScale)
  70792. {
  70793. Point<float> corners[3];
  70794. bounds.resolveThreePoints (corners, getParent());
  70795. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70796. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70797. }
  70798. refreshBounds();
  70799. }
  70800. void DrawableText::setJustification (const Justification& newJustification)
  70801. {
  70802. justification = newJustification;
  70803. repaint();
  70804. }
  70805. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70806. {
  70807. bounds = newBounds;
  70808. refreshBounds();
  70809. }
  70810. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70811. {
  70812. fontSizeControlPoint = newPoint;
  70813. refreshBounds();
  70814. }
  70815. void DrawableText::paint (Graphics& g)
  70816. {
  70817. transformContextToCorrectOrigin (g);
  70818. Point<float> points[3];
  70819. bounds.resolveThreePoints (points, getParent());
  70820. const float w = Line<float> (points[0], points[1]).getLength();
  70821. const float h = Line<float> (points[0], points[2]).getLength();
  70822. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (getParent())));
  70823. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  70824. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  70825. Font f (font);
  70826. f.setHeight (fontHeight);
  70827. f.setHorizontalScale (fontWidth / fontHeight);
  70828. g.setColour (colour);
  70829. GlyphArrangement ga;
  70830. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70831. ga.draw (g, AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70832. w, 0, points[1].getX(), points[1].getY(),
  70833. 0, h, points[2].getX(), points[2].getY()));
  70834. }
  70835. const Rectangle<float> DrawableText::getDrawableBounds() const
  70836. {
  70837. return bounds.getBounds (getParent());
  70838. }
  70839. Drawable* DrawableText::createCopy() const
  70840. {
  70841. return new DrawableText (*this);
  70842. }
  70843. const Identifier DrawableText::valueTreeType ("Text");
  70844. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70845. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70846. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70847. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70848. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70849. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70850. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70851. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70852. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70853. : ValueTreeWrapperBase (state_)
  70854. {
  70855. jassert (state.hasType (valueTreeType));
  70856. }
  70857. const String DrawableText::ValueTreeWrapper::getText() const
  70858. {
  70859. return state [text].toString();
  70860. }
  70861. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70862. {
  70863. state.setProperty (text, newText, undoManager);
  70864. }
  70865. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70866. {
  70867. return state.getPropertyAsValue (text, undoManager);
  70868. }
  70869. const Colour DrawableText::ValueTreeWrapper::getColour() const
  70870. {
  70871. return Colour::fromString (state [colour].toString());
  70872. }
  70873. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  70874. {
  70875. state.setProperty (colour, newColour.toString(), undoManager);
  70876. }
  70877. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  70878. {
  70879. return Justification ((int) state [justification]);
  70880. }
  70881. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  70882. {
  70883. state.setProperty (justification, newJustification.getFlags(), undoManager);
  70884. }
  70885. const Font DrawableText::ValueTreeWrapper::getFont() const
  70886. {
  70887. return Font::fromString (state [font]);
  70888. }
  70889. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  70890. {
  70891. state.setProperty (font, newFont.toString(), undoManager);
  70892. }
  70893. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  70894. {
  70895. return state.getPropertyAsValue (font, undoManager);
  70896. }
  70897. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  70898. {
  70899. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  70900. }
  70901. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70902. {
  70903. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70904. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70905. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70906. }
  70907. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  70908. {
  70909. return state [fontSizeAnchor].toString();
  70910. }
  70911. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  70912. {
  70913. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  70914. }
  70915. void DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  70916. {
  70917. ValueTreeWrapper v (tree);
  70918. setName (v.getID());
  70919. const RelativeParallelogram newBounds (v.getBoundingBox());
  70920. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  70921. const Colour newColour (v.getColour());
  70922. const Justification newJustification (v.getJustification());
  70923. const String newText (v.getText());
  70924. const Font newFont (v.getFont());
  70925. if (text != newText || font != newFont || justification != newJustification
  70926. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  70927. {
  70928. repaint();
  70929. setBoundingBox (newBounds);
  70930. setFontSizeControlPoint (newFontPoint);
  70931. setColour (newColour);
  70932. setFont (newFont, false);
  70933. setJustification (newJustification);
  70934. setText (newText);
  70935. }
  70936. }
  70937. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  70938. {
  70939. ValueTree tree (valueTreeType);
  70940. ValueTreeWrapper v (tree);
  70941. v.setID (getName(), 0);
  70942. v.setText (text, 0);
  70943. v.setFont (font, 0);
  70944. v.setJustification (justification, 0);
  70945. v.setColour (colour, 0);
  70946. v.setBoundingBox (bounds, 0);
  70947. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  70948. return tree;
  70949. }
  70950. END_JUCE_NAMESPACE
  70951. /*** End of inlined file: juce_DrawableText.cpp ***/
  70952. /*** Start of inlined file: juce_SVGParser.cpp ***/
  70953. BEGIN_JUCE_NAMESPACE
  70954. class SVGState
  70955. {
  70956. public:
  70957. SVGState (const XmlElement* const topLevel)
  70958. : topLevelXml (topLevel),
  70959. elementX (0), elementY (0),
  70960. width (512), height (512),
  70961. viewBoxW (0), viewBoxH (0)
  70962. {
  70963. }
  70964. ~SVGState()
  70965. {
  70966. }
  70967. Drawable* parseSVGElement (const XmlElement& xml)
  70968. {
  70969. if (! xml.hasTagName ("svg"))
  70970. return 0;
  70971. DrawableComposite* const drawable = new DrawableComposite();
  70972. drawable->setName (xml.getStringAttribute ("id"));
  70973. SVGState newState (*this);
  70974. if (xml.hasAttribute ("transform"))
  70975. newState.addTransform (xml);
  70976. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  70977. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  70978. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  70979. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  70980. if (xml.hasAttribute ("viewBox"))
  70981. {
  70982. const String viewParams (xml.getStringAttribute ("viewBox"));
  70983. int i = 0;
  70984. float vx, vy, vw, vh;
  70985. if (parseCoords (viewParams, vx, vy, i, true)
  70986. && parseCoords (viewParams, vw, vh, i, true)
  70987. && vw > 0
  70988. && vh > 0)
  70989. {
  70990. newState.viewBoxW = vw;
  70991. newState.viewBoxH = vh;
  70992. int placementFlags = 0;
  70993. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  70994. if (aspect.containsIgnoreCase ("none"))
  70995. {
  70996. placementFlags = RectanglePlacement::stretchToFit;
  70997. }
  70998. else
  70999. {
  71000. if (aspect.containsIgnoreCase ("slice"))
  71001. placementFlags |= RectanglePlacement::fillDestination;
  71002. if (aspect.containsIgnoreCase ("xMin"))
  71003. placementFlags |= RectanglePlacement::xLeft;
  71004. else if (aspect.containsIgnoreCase ("xMax"))
  71005. placementFlags |= RectanglePlacement::xRight;
  71006. else
  71007. placementFlags |= RectanglePlacement::xMid;
  71008. if (aspect.containsIgnoreCase ("yMin"))
  71009. placementFlags |= RectanglePlacement::yTop;
  71010. else if (aspect.containsIgnoreCase ("yMax"))
  71011. placementFlags |= RectanglePlacement::yBottom;
  71012. else
  71013. placementFlags |= RectanglePlacement::yMid;
  71014. }
  71015. const RectanglePlacement placement (placementFlags);
  71016. newState.transform
  71017. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71018. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71019. .followedBy (newState.transform);
  71020. }
  71021. }
  71022. else
  71023. {
  71024. if (viewBoxW == 0)
  71025. newState.viewBoxW = newState.width;
  71026. if (viewBoxH == 0)
  71027. newState.viewBoxH = newState.height;
  71028. }
  71029. newState.parseSubElements (xml, drawable);
  71030. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71031. return drawable;
  71032. }
  71033. private:
  71034. const XmlElement* const topLevelXml;
  71035. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71036. AffineTransform transform;
  71037. String cssStyleText;
  71038. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71039. {
  71040. forEachXmlChildElement (xml, e)
  71041. {
  71042. Drawable* d = 0;
  71043. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71044. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71045. else if (e->hasTagName ("path")) d = parsePath (*e);
  71046. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71047. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71048. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71049. else if (e->hasTagName ("line")) d = parseLine (*e);
  71050. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71051. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71052. else if (e->hasTagName ("text")) d = parseText (*e);
  71053. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71054. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71055. parentDrawable->insertDrawable (d);
  71056. }
  71057. }
  71058. DrawableComposite* parseSwitch (const XmlElement& xml)
  71059. {
  71060. const XmlElement* const group = xml.getChildByName ("g");
  71061. if (group != 0)
  71062. return parseGroupElement (*group);
  71063. return 0;
  71064. }
  71065. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71066. {
  71067. DrawableComposite* const drawable = new DrawableComposite();
  71068. drawable->setName (xml.getStringAttribute ("id"));
  71069. if (xml.hasAttribute ("transform"))
  71070. {
  71071. SVGState newState (*this);
  71072. newState.addTransform (xml);
  71073. newState.parseSubElements (xml, drawable);
  71074. }
  71075. else
  71076. {
  71077. parseSubElements (xml, drawable);
  71078. }
  71079. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71080. return drawable;
  71081. }
  71082. Drawable* parsePath (const XmlElement& xml) const
  71083. {
  71084. const String d (xml.getStringAttribute ("d").trimStart());
  71085. Path path;
  71086. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71087. path.setUsingNonZeroWinding (false);
  71088. int index = 0;
  71089. float lastX = 0, lastY = 0;
  71090. float lastX2 = 0, lastY2 = 0;
  71091. juce_wchar lastCommandChar = 0;
  71092. bool isRelative = true;
  71093. bool carryOn = true;
  71094. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71095. while (d[index] != 0)
  71096. {
  71097. float x, y, x2, y2, x3, y3;
  71098. if (validCommandChars.containsChar (d[index]))
  71099. {
  71100. lastCommandChar = d [index++];
  71101. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71102. }
  71103. switch (lastCommandChar)
  71104. {
  71105. case 'M':
  71106. case 'm':
  71107. case 'L':
  71108. case 'l':
  71109. if (parseCoords (d, x, y, index, false))
  71110. {
  71111. if (isRelative)
  71112. {
  71113. x += lastX;
  71114. y += lastY;
  71115. }
  71116. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71117. {
  71118. path.startNewSubPath (x, y);
  71119. lastCommandChar = 'l';
  71120. }
  71121. else
  71122. path.lineTo (x, y);
  71123. lastX2 = lastX;
  71124. lastY2 = lastY;
  71125. lastX = x;
  71126. lastY = y;
  71127. }
  71128. else
  71129. {
  71130. ++index;
  71131. }
  71132. break;
  71133. case 'H':
  71134. case 'h':
  71135. if (parseCoord (d, x, index, false, true))
  71136. {
  71137. if (isRelative)
  71138. x += lastX;
  71139. path.lineTo (x, lastY);
  71140. lastX2 = lastX;
  71141. lastX = x;
  71142. }
  71143. else
  71144. {
  71145. ++index;
  71146. }
  71147. break;
  71148. case 'V':
  71149. case 'v':
  71150. if (parseCoord (d, y, index, false, false))
  71151. {
  71152. if (isRelative)
  71153. y += lastY;
  71154. path.lineTo (lastX, y);
  71155. lastY2 = lastY;
  71156. lastY = y;
  71157. }
  71158. else
  71159. {
  71160. ++index;
  71161. }
  71162. break;
  71163. case 'C':
  71164. case 'c':
  71165. if (parseCoords (d, x, y, index, false)
  71166. && parseCoords (d, x2, y2, index, false)
  71167. && parseCoords (d, x3, y3, index, false))
  71168. {
  71169. if (isRelative)
  71170. {
  71171. x += lastX;
  71172. y += lastY;
  71173. x2 += lastX;
  71174. y2 += lastY;
  71175. x3 += lastX;
  71176. y3 += lastY;
  71177. }
  71178. path.cubicTo (x, y, x2, y2, x3, y3);
  71179. lastX2 = x2;
  71180. lastY2 = y2;
  71181. lastX = x3;
  71182. lastY = y3;
  71183. }
  71184. else
  71185. {
  71186. ++index;
  71187. }
  71188. break;
  71189. case 'S':
  71190. case 's':
  71191. if (parseCoords (d, x, y, index, false)
  71192. && parseCoords (d, x3, y3, index, false))
  71193. {
  71194. if (isRelative)
  71195. {
  71196. x += lastX;
  71197. y += lastY;
  71198. x3 += lastX;
  71199. y3 += lastY;
  71200. }
  71201. x2 = lastX + (lastX - lastX2);
  71202. y2 = lastY + (lastY - lastY2);
  71203. path.cubicTo (x2, y2, x, y, x3, y3);
  71204. lastX2 = x;
  71205. lastY2 = y;
  71206. lastX = x3;
  71207. lastY = y3;
  71208. }
  71209. else
  71210. {
  71211. ++index;
  71212. }
  71213. break;
  71214. case 'Q':
  71215. case 'q':
  71216. if (parseCoords (d, x, y, index, false)
  71217. && parseCoords (d, x2, y2, index, false))
  71218. {
  71219. if (isRelative)
  71220. {
  71221. x += lastX;
  71222. y += lastY;
  71223. x2 += lastX;
  71224. y2 += lastY;
  71225. }
  71226. path.quadraticTo (x, y, x2, y2);
  71227. lastX2 = x;
  71228. lastY2 = y;
  71229. lastX = x2;
  71230. lastY = y2;
  71231. }
  71232. else
  71233. {
  71234. ++index;
  71235. }
  71236. break;
  71237. case 'T':
  71238. case 't':
  71239. if (parseCoords (d, x, y, index, false))
  71240. {
  71241. if (isRelative)
  71242. {
  71243. x += lastX;
  71244. y += lastY;
  71245. }
  71246. x2 = lastX + (lastX - lastX2);
  71247. y2 = lastY + (lastY - lastY2);
  71248. path.quadraticTo (x2, y2, x, y);
  71249. lastX2 = x2;
  71250. lastY2 = y2;
  71251. lastX = x;
  71252. lastY = y;
  71253. }
  71254. else
  71255. {
  71256. ++index;
  71257. }
  71258. break;
  71259. case 'A':
  71260. case 'a':
  71261. if (parseCoords (d, x, y, index, false))
  71262. {
  71263. String num;
  71264. if (parseNextNumber (d, num, index, false))
  71265. {
  71266. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71267. if (parseNextNumber (d, num, index, false))
  71268. {
  71269. const bool largeArc = num.getIntValue() != 0;
  71270. if (parseNextNumber (d, num, index, false))
  71271. {
  71272. const bool sweep = num.getIntValue() != 0;
  71273. if (parseCoords (d, x2, y2, index, false))
  71274. {
  71275. if (isRelative)
  71276. {
  71277. x2 += lastX;
  71278. y2 += lastY;
  71279. }
  71280. if (lastX != x2 || lastY != y2)
  71281. {
  71282. double centreX, centreY, startAngle, deltaAngle;
  71283. double rx = x, ry = y;
  71284. endpointToCentreParameters (lastX, lastY, x2, y2,
  71285. angle, largeArc, sweep,
  71286. rx, ry, centreX, centreY,
  71287. startAngle, deltaAngle);
  71288. path.addCentredArc ((float) centreX, (float) centreY,
  71289. (float) rx, (float) ry,
  71290. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71291. false);
  71292. path.lineTo (x2, y2);
  71293. }
  71294. lastX2 = lastX;
  71295. lastY2 = lastY;
  71296. lastX = x2;
  71297. lastY = y2;
  71298. }
  71299. }
  71300. }
  71301. }
  71302. }
  71303. else
  71304. {
  71305. ++index;
  71306. }
  71307. break;
  71308. case 'Z':
  71309. case 'z':
  71310. path.closeSubPath();
  71311. while (CharacterFunctions::isWhitespace (d [index]))
  71312. ++index;
  71313. break;
  71314. default:
  71315. carryOn = false;
  71316. break;
  71317. }
  71318. if (! carryOn)
  71319. break;
  71320. }
  71321. return parseShape (xml, path);
  71322. }
  71323. Drawable* parseRect (const XmlElement& xml) const
  71324. {
  71325. Path rect;
  71326. const bool hasRX = xml.hasAttribute ("rx");
  71327. const bool hasRY = xml.hasAttribute ("ry");
  71328. if (hasRX || hasRY)
  71329. {
  71330. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71331. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71332. if (! hasRX)
  71333. rx = ry;
  71334. else if (! hasRY)
  71335. ry = rx;
  71336. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71337. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71338. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71339. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71340. rx, ry);
  71341. }
  71342. else
  71343. {
  71344. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71345. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71346. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71347. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71348. }
  71349. return parseShape (xml, rect);
  71350. }
  71351. Drawable* parseCircle (const XmlElement& xml) const
  71352. {
  71353. Path circle;
  71354. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71355. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71356. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71357. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71358. return parseShape (xml, circle);
  71359. }
  71360. Drawable* parseEllipse (const XmlElement& xml) const
  71361. {
  71362. Path ellipse;
  71363. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71364. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71365. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71366. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71367. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71368. return parseShape (xml, ellipse);
  71369. }
  71370. Drawable* parseLine (const XmlElement& xml) const
  71371. {
  71372. Path line;
  71373. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71374. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71375. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71376. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71377. line.startNewSubPath (x1, y1);
  71378. line.lineTo (x2, y2);
  71379. return parseShape (xml, line);
  71380. }
  71381. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71382. {
  71383. const String points (xml.getStringAttribute ("points"));
  71384. Path path;
  71385. int index = 0;
  71386. float x, y;
  71387. if (parseCoords (points, x, y, index, true))
  71388. {
  71389. float firstX = x;
  71390. float firstY = y;
  71391. float lastX = 0, lastY = 0;
  71392. path.startNewSubPath (x, y);
  71393. while (parseCoords (points, x, y, index, true))
  71394. {
  71395. lastX = x;
  71396. lastY = y;
  71397. path.lineTo (x, y);
  71398. }
  71399. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71400. path.closeSubPath();
  71401. }
  71402. return parseShape (xml, path);
  71403. }
  71404. Drawable* parseShape (const XmlElement& xml, Path& path,
  71405. const bool shouldParseTransform = true) const
  71406. {
  71407. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71408. {
  71409. SVGState newState (*this);
  71410. newState.addTransform (xml);
  71411. return newState.parseShape (xml, path, false);
  71412. }
  71413. DrawablePath* dp = new DrawablePath();
  71414. dp->setName (xml.getStringAttribute ("id"));
  71415. dp->setFill (Colours::transparentBlack);
  71416. path.applyTransform (transform);
  71417. dp->setPath (path);
  71418. Path::Iterator iter (path);
  71419. bool containsClosedSubPath = false;
  71420. while (iter.next())
  71421. {
  71422. if (iter.elementType == Path::Iterator::closePath)
  71423. {
  71424. containsClosedSubPath = true;
  71425. break;
  71426. }
  71427. }
  71428. dp->setFill (getPathFillType (path,
  71429. getStyleAttribute (&xml, "fill"),
  71430. getStyleAttribute (&xml, "fill-opacity"),
  71431. getStyleAttribute (&xml, "opacity"),
  71432. containsClosedSubPath ? Colours::black
  71433. : Colours::transparentBlack));
  71434. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71435. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71436. {
  71437. dp->setStrokeFill (getPathFillType (path, strokeType,
  71438. getStyleAttribute (&xml, "stroke-opacity"),
  71439. getStyleAttribute (&xml, "opacity"),
  71440. Colours::transparentBlack));
  71441. dp->setStrokeType (getStrokeFor (&xml));
  71442. }
  71443. return dp;
  71444. }
  71445. const XmlElement* findLinkedElement (const XmlElement* e) const
  71446. {
  71447. const String id (e->getStringAttribute ("xlink:href"));
  71448. if (! id.startsWithChar ('#'))
  71449. return 0;
  71450. return findElementForId (topLevelXml, id.substring (1));
  71451. }
  71452. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71453. {
  71454. if (fillXml == 0)
  71455. return;
  71456. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71457. {
  71458. int index = 0;
  71459. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71460. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71461. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71462. double offset = e->getDoubleAttribute ("offset");
  71463. if (e->getStringAttribute ("offset").containsChar ('%'))
  71464. offset *= 0.01;
  71465. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71466. }
  71467. }
  71468. const FillType getPathFillType (const Path& path,
  71469. const String& fill,
  71470. const String& fillOpacity,
  71471. const String& overallOpacity,
  71472. const Colour& defaultColour) const
  71473. {
  71474. float opacity = 1.0f;
  71475. if (overallOpacity.isNotEmpty())
  71476. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71477. if (fillOpacity.isNotEmpty())
  71478. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71479. if (fill.startsWithIgnoreCase ("url"))
  71480. {
  71481. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71482. .upToLastOccurrenceOf (")", false, false).trim());
  71483. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71484. if (fillXml != 0
  71485. && (fillXml->hasTagName ("linearGradient")
  71486. || fillXml->hasTagName ("radialGradient")))
  71487. {
  71488. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71489. ColourGradient gradient;
  71490. addGradientStopsIn (gradient, inheritedFrom);
  71491. addGradientStopsIn (gradient, fillXml);
  71492. if (gradient.getNumColours() > 0)
  71493. {
  71494. gradient.addColour (0.0, gradient.getColour (0));
  71495. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71496. }
  71497. else
  71498. {
  71499. gradient.addColour (0.0, Colours::black);
  71500. gradient.addColour (1.0, Colours::black);
  71501. }
  71502. if (overallOpacity.isNotEmpty())
  71503. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71504. jassert (gradient.getNumColours() > 0);
  71505. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71506. float gradientWidth = viewBoxW;
  71507. float gradientHeight = viewBoxH;
  71508. float dx = 0.0f;
  71509. float dy = 0.0f;
  71510. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71511. if (! userSpace)
  71512. {
  71513. const Rectangle<float> bounds (path.getBounds());
  71514. dx = bounds.getX();
  71515. dy = bounds.getY();
  71516. gradientWidth = bounds.getWidth();
  71517. gradientHeight = bounds.getHeight();
  71518. }
  71519. if (gradient.isRadial)
  71520. {
  71521. if (userSpace)
  71522. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71523. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71524. else
  71525. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71526. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71527. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71528. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71529. //xxx (the fx, fy focal point isn't handled properly here..)
  71530. }
  71531. else
  71532. {
  71533. if (userSpace)
  71534. {
  71535. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71536. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71537. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71538. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71539. }
  71540. else
  71541. {
  71542. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71543. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71544. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71545. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71546. }
  71547. if (gradient.point1 == gradient.point2)
  71548. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71549. }
  71550. FillType type (gradient);
  71551. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71552. .followedBy (transform);
  71553. return type;
  71554. }
  71555. }
  71556. if (fill.equalsIgnoreCase ("none"))
  71557. return Colours::transparentBlack;
  71558. int i = 0;
  71559. const Colour colour (parseColour (fill, i, defaultColour));
  71560. return colour.withMultipliedAlpha (opacity);
  71561. }
  71562. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71563. {
  71564. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71565. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71566. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71567. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71568. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71569. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71570. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71571. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71572. if (join.equalsIgnoreCase ("round"))
  71573. joinStyle = PathStrokeType::curved;
  71574. else if (join.equalsIgnoreCase ("bevel"))
  71575. joinStyle = PathStrokeType::beveled;
  71576. if (cap.equalsIgnoreCase ("round"))
  71577. capStyle = PathStrokeType::rounded;
  71578. else if (cap.equalsIgnoreCase ("square"))
  71579. capStyle = PathStrokeType::square;
  71580. float ox = 0.0f, oy = 0.0f;
  71581. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71582. transform.transformPoints (ox, oy, x, y);
  71583. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71584. joinStyle, capStyle);
  71585. }
  71586. Drawable* parseText (const XmlElement& xml)
  71587. {
  71588. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71589. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71590. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71591. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71592. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71593. //xxx not done text yet!
  71594. forEachXmlChildElement (xml, e)
  71595. {
  71596. if (e->isTextElement())
  71597. {
  71598. const String text (e->getText());
  71599. Path path;
  71600. Drawable* s = parseShape (*e, path);
  71601. delete s; // xxx not finished!
  71602. }
  71603. else if (e->hasTagName ("tspan"))
  71604. {
  71605. Drawable* s = parseText (*e);
  71606. delete s; // xxx not finished!
  71607. }
  71608. }
  71609. return 0;
  71610. }
  71611. void addTransform (const XmlElement& xml)
  71612. {
  71613. transform = parseTransform (xml.getStringAttribute ("transform"))
  71614. .followedBy (transform);
  71615. }
  71616. bool parseCoord (const String& s, float& value, int& index,
  71617. const bool allowUnits, const bool isX) const
  71618. {
  71619. String number;
  71620. if (! parseNextNumber (s, number, index, allowUnits))
  71621. {
  71622. value = 0;
  71623. return false;
  71624. }
  71625. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71626. return true;
  71627. }
  71628. bool parseCoords (const String& s, float& x, float& y,
  71629. int& index, const bool allowUnits) const
  71630. {
  71631. return parseCoord (s, x, index, allowUnits, true)
  71632. && parseCoord (s, y, index, allowUnits, false);
  71633. }
  71634. float getCoordLength (const String& s, const float sizeForProportions) const
  71635. {
  71636. float n = s.getFloatValue();
  71637. const int len = s.length();
  71638. if (len > 2)
  71639. {
  71640. const float dpi = 96.0f;
  71641. const juce_wchar n1 = s [len - 2];
  71642. const juce_wchar n2 = s [len - 1];
  71643. if (n1 == 'i' && n2 == 'n')
  71644. n *= dpi;
  71645. else if (n1 == 'm' && n2 == 'm')
  71646. n *= dpi / 25.4f;
  71647. else if (n1 == 'c' && n2 == 'm')
  71648. n *= dpi / 2.54f;
  71649. else if (n1 == 'p' && n2 == 'c')
  71650. n *= 15.0f;
  71651. else if (n2 == '%')
  71652. n *= 0.01f * sizeForProportions;
  71653. }
  71654. return n;
  71655. }
  71656. void getCoordList (Array <float>& coords, const String& list,
  71657. const bool allowUnits, const bool isX) const
  71658. {
  71659. int index = 0;
  71660. float value;
  71661. while (parseCoord (list, value, index, allowUnits, isX))
  71662. coords.add (value);
  71663. }
  71664. void parseCSSStyle (const XmlElement& xml)
  71665. {
  71666. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71667. }
  71668. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71669. const String& defaultValue = String::empty) const
  71670. {
  71671. if (xml->hasAttribute (attributeName))
  71672. return xml->getStringAttribute (attributeName, defaultValue);
  71673. const String styleAtt (xml->getStringAttribute ("style"));
  71674. if (styleAtt.isNotEmpty())
  71675. {
  71676. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71677. if (value.isNotEmpty())
  71678. return value;
  71679. }
  71680. else if (xml->hasAttribute ("class"))
  71681. {
  71682. const String className ("." + xml->getStringAttribute ("class"));
  71683. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71684. if (index < 0)
  71685. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71686. if (index >= 0)
  71687. {
  71688. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71689. if (openBracket > index)
  71690. {
  71691. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71692. if (closeBracket > openBracket)
  71693. {
  71694. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71695. if (value.isNotEmpty())
  71696. return value;
  71697. }
  71698. }
  71699. }
  71700. }
  71701. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71702. if (xml != 0)
  71703. return getStyleAttribute (xml, attributeName, defaultValue);
  71704. return defaultValue;
  71705. }
  71706. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71707. {
  71708. if (xml->hasAttribute (attributeName))
  71709. return xml->getStringAttribute (attributeName);
  71710. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71711. if (xml != 0)
  71712. return getInheritedAttribute (xml, attributeName);
  71713. return String::empty;
  71714. }
  71715. static bool isIdentifierChar (const juce_wchar c)
  71716. {
  71717. return CharacterFunctions::isLetter (c) || c == '-';
  71718. }
  71719. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71720. {
  71721. int i = 0;
  71722. for (;;)
  71723. {
  71724. i = list.indexOf (i, attributeName);
  71725. if (i < 0)
  71726. break;
  71727. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71728. && ! isIdentifierChar (list [i + attributeName.length()]))
  71729. {
  71730. i = list.indexOfChar (i, ':');
  71731. if (i < 0)
  71732. break;
  71733. int end = list.indexOfChar (i, ';');
  71734. if (end < 0)
  71735. end = 0x7ffff;
  71736. return list.substring (i + 1, end).trim();
  71737. }
  71738. ++i;
  71739. }
  71740. return defaultValue;
  71741. }
  71742. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71743. {
  71744. const juce_wchar* const s = source;
  71745. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71746. ++index;
  71747. int start = index;
  71748. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71749. ++index;
  71750. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71751. ++index;
  71752. if ((s[index] == 'e' || s[index] == 'E')
  71753. && (CharacterFunctions::isDigit (s[index + 1])
  71754. || s[index + 1] == '-'
  71755. || s[index + 1] == '+'))
  71756. {
  71757. index += 2;
  71758. while (CharacterFunctions::isDigit (s[index]))
  71759. ++index;
  71760. }
  71761. if (allowUnits)
  71762. {
  71763. while (CharacterFunctions::isLetter (s[index]))
  71764. ++index;
  71765. }
  71766. if (index == start)
  71767. return false;
  71768. value = String (s + start, index - start);
  71769. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71770. ++index;
  71771. return true;
  71772. }
  71773. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71774. {
  71775. if (s [index] == '#')
  71776. {
  71777. uint32 hex [6];
  71778. zeromem (hex, sizeof (hex));
  71779. int numChars = 0;
  71780. for (int i = 6; --i >= 0;)
  71781. {
  71782. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71783. if (hexValue >= 0)
  71784. hex [numChars++] = hexValue;
  71785. else
  71786. break;
  71787. }
  71788. if (numChars <= 3)
  71789. return Colour ((uint8) (hex [0] * 0x11),
  71790. (uint8) (hex [1] * 0x11),
  71791. (uint8) (hex [2] * 0x11));
  71792. else
  71793. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71794. (uint8) ((hex [2] << 4) + hex [3]),
  71795. (uint8) ((hex [4] << 4) + hex [5]));
  71796. }
  71797. else if (s [index] == 'r'
  71798. && s [index + 1] == 'g'
  71799. && s [index + 2] == 'b')
  71800. {
  71801. const int openBracket = s.indexOfChar (index, '(');
  71802. const int closeBracket = s.indexOfChar (openBracket, ')');
  71803. if (openBracket >= 3 && closeBracket > openBracket)
  71804. {
  71805. index = closeBracket;
  71806. StringArray tokens;
  71807. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71808. tokens.trim();
  71809. tokens.removeEmptyStrings();
  71810. if (tokens[0].containsChar ('%'))
  71811. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71812. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71813. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71814. else
  71815. return Colour ((uint8) tokens[0].getIntValue(),
  71816. (uint8) tokens[1].getIntValue(),
  71817. (uint8) tokens[2].getIntValue());
  71818. }
  71819. }
  71820. return Colours::findColourForName (s, defaultColour);
  71821. }
  71822. static const AffineTransform parseTransform (String t)
  71823. {
  71824. AffineTransform result;
  71825. while (t.isNotEmpty())
  71826. {
  71827. StringArray tokens;
  71828. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71829. .upToFirstOccurrenceOf (")", false, false),
  71830. ", ", String::empty);
  71831. tokens.removeEmptyStrings (true);
  71832. float numbers [6];
  71833. for (int i = 0; i < 6; ++i)
  71834. numbers[i] = tokens[i].getFloatValue();
  71835. AffineTransform trans;
  71836. if (t.startsWithIgnoreCase ("matrix"))
  71837. {
  71838. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71839. numbers[1], numbers[3], numbers[5]);
  71840. }
  71841. else if (t.startsWithIgnoreCase ("translate"))
  71842. {
  71843. jassert (tokens.size() == 2);
  71844. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71845. }
  71846. else if (t.startsWithIgnoreCase ("scale"))
  71847. {
  71848. if (tokens.size() == 1)
  71849. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71850. else
  71851. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71852. }
  71853. else if (t.startsWithIgnoreCase ("rotate"))
  71854. {
  71855. if (tokens.size() != 3)
  71856. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71857. else
  71858. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71859. numbers[1], numbers[2]);
  71860. }
  71861. else if (t.startsWithIgnoreCase ("skewX"))
  71862. {
  71863. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71864. 0.0f, 1.0f, 0.0f);
  71865. }
  71866. else if (t.startsWithIgnoreCase ("skewY"))
  71867. {
  71868. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71869. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71870. }
  71871. result = trans.followedBy (result);
  71872. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  71873. }
  71874. return result;
  71875. }
  71876. static void endpointToCentreParameters (const double x1, const double y1,
  71877. const double x2, const double y2,
  71878. const double angle,
  71879. const bool largeArc, const bool sweep,
  71880. double& rx, double& ry,
  71881. double& centreX, double& centreY,
  71882. double& startAngle, double& deltaAngle)
  71883. {
  71884. const double midX = (x1 - x2) * 0.5;
  71885. const double midY = (y1 - y2) * 0.5;
  71886. const double cosAngle = cos (angle);
  71887. const double sinAngle = sin (angle);
  71888. const double xp = cosAngle * midX + sinAngle * midY;
  71889. const double yp = cosAngle * midY - sinAngle * midX;
  71890. const double xp2 = xp * xp;
  71891. const double yp2 = yp * yp;
  71892. double rx2 = rx * rx;
  71893. double ry2 = ry * ry;
  71894. const double s = (xp2 / rx2) + (yp2 / ry2);
  71895. double c;
  71896. if (s <= 1.0)
  71897. {
  71898. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  71899. / (( rx2 * yp2) + (ry2 * xp2))));
  71900. if (largeArc == sweep)
  71901. c = -c;
  71902. }
  71903. else
  71904. {
  71905. const double s2 = std::sqrt (s);
  71906. rx *= s2;
  71907. ry *= s2;
  71908. rx2 = rx * rx;
  71909. ry2 = ry * ry;
  71910. c = 0;
  71911. }
  71912. const double cpx = ((rx * yp) / ry) * c;
  71913. const double cpy = ((-ry * xp) / rx) * c;
  71914. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  71915. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  71916. const double ux = (xp - cpx) / rx;
  71917. const double uy = (yp - cpy) / ry;
  71918. const double vx = (-xp - cpx) / rx;
  71919. const double vy = (-yp - cpy) / ry;
  71920. const double length = juce_hypot (ux, uy);
  71921. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  71922. if (uy < 0)
  71923. startAngle = -startAngle;
  71924. startAngle += double_Pi * 0.5;
  71925. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  71926. / (length * juce_hypot (vx, vy))));
  71927. if ((ux * vy) - (uy * vx) < 0)
  71928. deltaAngle = -deltaAngle;
  71929. if (sweep)
  71930. {
  71931. if (deltaAngle < 0)
  71932. deltaAngle += double_Pi * 2.0;
  71933. }
  71934. else
  71935. {
  71936. if (deltaAngle > 0)
  71937. deltaAngle -= double_Pi * 2.0;
  71938. }
  71939. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  71940. }
  71941. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  71942. {
  71943. forEachXmlChildElement (*parent, e)
  71944. {
  71945. if (e->compareAttribute ("id", id))
  71946. return e;
  71947. const XmlElement* const found = findElementForId (e, id);
  71948. if (found != 0)
  71949. return found;
  71950. }
  71951. return 0;
  71952. }
  71953. SVGState& operator= (const SVGState&);
  71954. };
  71955. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  71956. {
  71957. SVGState state (&svgDocument);
  71958. return state.parseSVGElement (svgDocument);
  71959. }
  71960. END_JUCE_NAMESPACE
  71961. /*** End of inlined file: juce_SVGParser.cpp ***/
  71962. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  71963. BEGIN_JUCE_NAMESPACE
  71964. #if JUCE_MSVC && JUCE_DEBUG
  71965. #pragma optimize ("t", on)
  71966. #endif
  71967. DropShadowEffect::DropShadowEffect()
  71968. : offsetX (0),
  71969. offsetY (0),
  71970. radius (4),
  71971. opacity (0.6f)
  71972. {
  71973. }
  71974. DropShadowEffect::~DropShadowEffect()
  71975. {
  71976. }
  71977. void DropShadowEffect::setShadowProperties (const float newRadius,
  71978. const float newOpacity,
  71979. const int newShadowOffsetX,
  71980. const int newShadowOffsetY)
  71981. {
  71982. radius = jmax (1.1f, newRadius);
  71983. offsetX = newShadowOffsetX;
  71984. offsetY = newShadowOffsetY;
  71985. opacity = newOpacity;
  71986. }
  71987. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  71988. {
  71989. const int w = image.getWidth();
  71990. const int h = image.getHeight();
  71991. Image shadowImage (Image::SingleChannel, w, h, false);
  71992. const Image::BitmapData srcData (image, false);
  71993. const Image::BitmapData destData (shadowImage, true);
  71994. const int filter = roundToInt (63.0f / radius);
  71995. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  71996. for (int x = w; --x >= 0;)
  71997. {
  71998. int shadowAlpha = 0;
  71999. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72000. uint8* shadowPix = destData.data + x;
  72001. for (int y = h; --y >= 0;)
  72002. {
  72003. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72004. *shadowPix = (uint8) shadowAlpha;
  72005. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72006. shadowPix += destData.lineStride;
  72007. }
  72008. }
  72009. for (int y = h; --y >= 0;)
  72010. {
  72011. int shadowAlpha = 0;
  72012. uint8* shadowPix = destData.getLinePointer (y);
  72013. for (int x = w; --x >= 0;)
  72014. {
  72015. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72016. *shadowPix++ = (uint8) shadowAlpha;
  72017. }
  72018. }
  72019. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72020. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72021. g.setOpacity (alpha);
  72022. g.drawImageAt (image, 0, 0);
  72023. }
  72024. #if JUCE_MSVC && JUCE_DEBUG
  72025. #pragma optimize ("", on) // resets optimisations to the project defaults
  72026. #endif
  72027. END_JUCE_NAMESPACE
  72028. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72029. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72030. BEGIN_JUCE_NAMESPACE
  72031. GlowEffect::GlowEffect()
  72032. : radius (2.0f),
  72033. colour (Colours::white)
  72034. {
  72035. }
  72036. GlowEffect::~GlowEffect()
  72037. {
  72038. }
  72039. void GlowEffect::setGlowProperties (const float newRadius,
  72040. const Colour& newColour)
  72041. {
  72042. radius = newRadius;
  72043. colour = newColour;
  72044. }
  72045. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72046. {
  72047. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72048. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72049. blurKernel.createGaussianBlur (radius);
  72050. blurKernel.rescaleAllValues (radius);
  72051. blurKernel.applyToImage (temp, image, image.getBounds());
  72052. g.setColour (colour.withMultipliedAlpha (alpha));
  72053. g.drawImageAt (temp, 0, 0, true);
  72054. g.setOpacity (alpha);
  72055. g.drawImageAt (image, 0, 0, false);
  72056. }
  72057. END_JUCE_NAMESPACE
  72058. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72059. /*** Start of inlined file: juce_Font.cpp ***/
  72060. BEGIN_JUCE_NAMESPACE
  72061. namespace FontValues
  72062. {
  72063. float limitFontHeight (const float height) throw()
  72064. {
  72065. return jlimit (0.1f, 10000.0f, height);
  72066. }
  72067. const float defaultFontHeight = 14.0f;
  72068. String fallbackFont;
  72069. }
  72070. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72071. const float kerning_, const float ascent_, const int styleFlags_,
  72072. Typeface* const typeface_) throw()
  72073. : typefaceName (typefaceName_),
  72074. height (height_),
  72075. horizontalScale (horizontalScale_),
  72076. kerning (kerning_),
  72077. ascent (ascent_),
  72078. styleFlags (styleFlags_),
  72079. typeface (typeface_)
  72080. {
  72081. }
  72082. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72083. : typefaceName (other.typefaceName),
  72084. height (other.height),
  72085. horizontalScale (other.horizontalScale),
  72086. kerning (other.kerning),
  72087. ascent (other.ascent),
  72088. styleFlags (other.styleFlags),
  72089. typeface (other.typeface)
  72090. {
  72091. }
  72092. Font::Font()
  72093. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72094. 1.0f, 0, 0, Font::plain, 0))
  72095. {
  72096. }
  72097. Font::Font (const float fontHeight, const int styleFlags_)
  72098. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72099. 1.0f, 0, 0, styleFlags_, 0))
  72100. {
  72101. }
  72102. Font::Font (const String& typefaceName_,
  72103. const float fontHeight,
  72104. const int styleFlags_)
  72105. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72106. 1.0f, 0, 0, styleFlags_, 0))
  72107. {
  72108. }
  72109. Font::Font (const Font& other) throw()
  72110. : font (other.font)
  72111. {
  72112. }
  72113. Font& Font::operator= (const Font& other) throw()
  72114. {
  72115. font = other.font;
  72116. return *this;
  72117. }
  72118. Font::~Font() throw()
  72119. {
  72120. }
  72121. Font::Font (const Typeface::Ptr& typeface)
  72122. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72123. 1.0f, 0, 0, Font::plain, typeface))
  72124. {
  72125. }
  72126. bool Font::operator== (const Font& other) const throw()
  72127. {
  72128. return font == other.font
  72129. || (font->height == other.font->height
  72130. && font->styleFlags == other.font->styleFlags
  72131. && font->horizontalScale == other.font->horizontalScale
  72132. && font->kerning == other.font->kerning
  72133. && font->typefaceName == other.font->typefaceName);
  72134. }
  72135. bool Font::operator!= (const Font& other) const throw()
  72136. {
  72137. return ! operator== (other);
  72138. }
  72139. void Font::dupeInternalIfShared()
  72140. {
  72141. if (font->getReferenceCount() > 1)
  72142. font = new SharedFontInternal (*font);
  72143. }
  72144. const String Font::getDefaultSansSerifFontName()
  72145. {
  72146. static const String name ("<Sans-Serif>");
  72147. return name;
  72148. }
  72149. const String Font::getDefaultSerifFontName()
  72150. {
  72151. static const String name ("<Serif>");
  72152. return name;
  72153. }
  72154. const String Font::getDefaultMonospacedFontName()
  72155. {
  72156. static const String name ("<Monospaced>");
  72157. return name;
  72158. }
  72159. void Font::setTypefaceName (const String& faceName)
  72160. {
  72161. if (faceName != font->typefaceName)
  72162. {
  72163. dupeInternalIfShared();
  72164. font->typefaceName = faceName;
  72165. font->typeface = 0;
  72166. font->ascent = 0;
  72167. }
  72168. }
  72169. const String Font::getFallbackFontName()
  72170. {
  72171. return FontValues::fallbackFont;
  72172. }
  72173. void Font::setFallbackFontName (const String& name)
  72174. {
  72175. FontValues::fallbackFont = name;
  72176. }
  72177. void Font::setHeight (float newHeight)
  72178. {
  72179. newHeight = FontValues::limitFontHeight (newHeight);
  72180. if (font->height != newHeight)
  72181. {
  72182. dupeInternalIfShared();
  72183. font->height = newHeight;
  72184. }
  72185. }
  72186. void Font::setHeightWithoutChangingWidth (float newHeight)
  72187. {
  72188. newHeight = FontValues::limitFontHeight (newHeight);
  72189. if (font->height != newHeight)
  72190. {
  72191. dupeInternalIfShared();
  72192. font->horizontalScale *= (font->height / newHeight);
  72193. font->height = newHeight;
  72194. }
  72195. }
  72196. void Font::setStyleFlags (const int newFlags)
  72197. {
  72198. if (font->styleFlags != newFlags)
  72199. {
  72200. dupeInternalIfShared();
  72201. font->styleFlags = newFlags;
  72202. font->typeface = 0;
  72203. font->ascent = 0;
  72204. }
  72205. }
  72206. void Font::setSizeAndStyle (float newHeight,
  72207. const int newStyleFlags,
  72208. const float newHorizontalScale,
  72209. const float newKerningAmount)
  72210. {
  72211. newHeight = FontValues::limitFontHeight (newHeight);
  72212. if (font->height != newHeight
  72213. || font->horizontalScale != newHorizontalScale
  72214. || font->kerning != newKerningAmount)
  72215. {
  72216. dupeInternalIfShared();
  72217. font->height = newHeight;
  72218. font->horizontalScale = newHorizontalScale;
  72219. font->kerning = newKerningAmount;
  72220. }
  72221. setStyleFlags (newStyleFlags);
  72222. }
  72223. void Font::setHorizontalScale (const float scaleFactor)
  72224. {
  72225. dupeInternalIfShared();
  72226. font->horizontalScale = scaleFactor;
  72227. }
  72228. void Font::setExtraKerningFactor (const float extraKerning)
  72229. {
  72230. dupeInternalIfShared();
  72231. font->kerning = extraKerning;
  72232. }
  72233. void Font::setBold (const bool shouldBeBold)
  72234. {
  72235. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72236. : (font->styleFlags & ~bold));
  72237. }
  72238. const Font Font::boldened() const
  72239. {
  72240. Font f (*this);
  72241. f.setBold (true);
  72242. return f;
  72243. }
  72244. bool Font::isBold() const throw()
  72245. {
  72246. return (font->styleFlags & bold) != 0;
  72247. }
  72248. void Font::setItalic (const bool shouldBeItalic)
  72249. {
  72250. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72251. : (font->styleFlags & ~italic));
  72252. }
  72253. const Font Font::italicised() const
  72254. {
  72255. Font f (*this);
  72256. f.setItalic (true);
  72257. return f;
  72258. }
  72259. bool Font::isItalic() const throw()
  72260. {
  72261. return (font->styleFlags & italic) != 0;
  72262. }
  72263. void Font::setUnderline (const bool shouldBeUnderlined)
  72264. {
  72265. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72266. : (font->styleFlags & ~underlined));
  72267. }
  72268. bool Font::isUnderlined() const throw()
  72269. {
  72270. return (font->styleFlags & underlined) != 0;
  72271. }
  72272. float Font::getAscent() const
  72273. {
  72274. if (font->ascent == 0)
  72275. font->ascent = getTypeface()->getAscent();
  72276. return font->height * font->ascent;
  72277. }
  72278. float Font::getDescent() const
  72279. {
  72280. return font->height - getAscent();
  72281. }
  72282. int Font::getStringWidth (const String& text) const
  72283. {
  72284. return roundToInt (getStringWidthFloat (text));
  72285. }
  72286. float Font::getStringWidthFloat (const String& text) const
  72287. {
  72288. float w = getTypeface()->getStringWidth (text);
  72289. if (font->kerning != 0)
  72290. w += font->kerning * text.length();
  72291. return w * font->height * font->horizontalScale;
  72292. }
  72293. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72294. {
  72295. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72296. const float scale = font->height * font->horizontalScale;
  72297. const int num = xOffsets.size();
  72298. if (num > 0)
  72299. {
  72300. float* const x = &(xOffsets.getReference(0));
  72301. if (font->kerning != 0)
  72302. {
  72303. for (int i = 0; i < num; ++i)
  72304. x[i] = (x[i] + i * font->kerning) * scale;
  72305. }
  72306. else
  72307. {
  72308. for (int i = 0; i < num; ++i)
  72309. x[i] *= scale;
  72310. }
  72311. }
  72312. }
  72313. void Font::findFonts (Array<Font>& destArray)
  72314. {
  72315. const StringArray names (findAllTypefaceNames());
  72316. for (int i = 0; i < names.size(); ++i)
  72317. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72318. }
  72319. const String Font::toString() const
  72320. {
  72321. String s (getTypefaceName());
  72322. if (s == getDefaultSansSerifFontName())
  72323. s = String::empty;
  72324. else
  72325. s += "; ";
  72326. s += String (getHeight(), 1);
  72327. if (isBold())
  72328. s += " bold";
  72329. if (isItalic())
  72330. s += " italic";
  72331. return s;
  72332. }
  72333. const Font Font::fromString (const String& fontDescription)
  72334. {
  72335. String name;
  72336. const int separator = fontDescription.indexOfChar (';');
  72337. if (separator > 0)
  72338. name = fontDescription.substring (0, separator).trim();
  72339. if (name.isEmpty())
  72340. name = getDefaultSansSerifFontName();
  72341. String sizeAndStyle (fontDescription.substring (separator + 1));
  72342. float height = sizeAndStyle.getFloatValue();
  72343. if (height <= 0)
  72344. height = 10.0f;
  72345. int flags = Font::plain;
  72346. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72347. flags |= Font::bold;
  72348. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72349. flags |= Font::italic;
  72350. return Font (name, height, flags);
  72351. }
  72352. class TypefaceCache : public DeletedAtShutdown
  72353. {
  72354. public:
  72355. TypefaceCache (int numToCache = 10)
  72356. : counter (1)
  72357. {
  72358. while (--numToCache >= 0)
  72359. faces.add (new CachedFace());
  72360. }
  72361. ~TypefaceCache()
  72362. {
  72363. clearSingletonInstance();
  72364. }
  72365. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72366. const Typeface::Ptr findTypefaceFor (const Font& font)
  72367. {
  72368. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72369. const String faceName (font.getTypefaceName());
  72370. int i;
  72371. for (i = faces.size(); --i >= 0;)
  72372. {
  72373. CachedFace* const face = faces.getUnchecked(i);
  72374. if (face->flags == flags
  72375. && face->typefaceName == faceName)
  72376. {
  72377. face->lastUsageCount = ++counter;
  72378. return face->typeFace;
  72379. }
  72380. }
  72381. int replaceIndex = 0;
  72382. int bestLastUsageCount = std::numeric_limits<int>::max();
  72383. for (i = faces.size(); --i >= 0;)
  72384. {
  72385. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72386. if (bestLastUsageCount > lu)
  72387. {
  72388. bestLastUsageCount = lu;
  72389. replaceIndex = i;
  72390. }
  72391. }
  72392. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72393. face->typefaceName = faceName;
  72394. face->flags = flags;
  72395. face->lastUsageCount = ++counter;
  72396. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72397. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72398. return face->typeFace;
  72399. }
  72400. private:
  72401. struct CachedFace
  72402. {
  72403. CachedFace() throw()
  72404. : lastUsageCount (0), flags (-1)
  72405. {
  72406. }
  72407. String typefaceName;
  72408. int lastUsageCount;
  72409. int flags;
  72410. Typeface::Ptr typeFace;
  72411. };
  72412. int counter;
  72413. OwnedArray <CachedFace> faces;
  72414. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72415. };
  72416. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72417. Typeface* Font::getTypeface() const
  72418. {
  72419. if (font->typeface == 0)
  72420. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72421. return font->typeface;
  72422. }
  72423. END_JUCE_NAMESPACE
  72424. /*** End of inlined file: juce_Font.cpp ***/
  72425. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72426. BEGIN_JUCE_NAMESPACE
  72427. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72428. const juce_wchar character_, const int glyph_)
  72429. : x (x_),
  72430. y (y_),
  72431. w (w_),
  72432. font (font_),
  72433. character (character_),
  72434. glyph (glyph_)
  72435. {
  72436. }
  72437. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72438. : x (other.x),
  72439. y (other.y),
  72440. w (other.w),
  72441. font (other.font),
  72442. character (other.character),
  72443. glyph (other.glyph)
  72444. {
  72445. }
  72446. void PositionedGlyph::draw (const Graphics& g) const
  72447. {
  72448. if (! isWhitespace())
  72449. {
  72450. g.getInternalContext()->setFont (font);
  72451. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72452. }
  72453. }
  72454. void PositionedGlyph::draw (const Graphics& g,
  72455. const AffineTransform& transform) const
  72456. {
  72457. if (! isWhitespace())
  72458. {
  72459. g.getInternalContext()->setFont (font);
  72460. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72461. .followedBy (transform));
  72462. }
  72463. }
  72464. void PositionedGlyph::createPath (Path& path) const
  72465. {
  72466. if (! isWhitespace())
  72467. {
  72468. Typeface* const t = font.getTypeface();
  72469. if (t != 0)
  72470. {
  72471. Path p;
  72472. t->getOutlineForGlyph (glyph, p);
  72473. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72474. .translated (x, y));
  72475. }
  72476. }
  72477. }
  72478. bool PositionedGlyph::hitTest (float px, float py) const
  72479. {
  72480. if (getBounds().contains (px, py) && ! isWhitespace())
  72481. {
  72482. Typeface* const t = font.getTypeface();
  72483. if (t != 0)
  72484. {
  72485. Path p;
  72486. t->getOutlineForGlyph (glyph, p);
  72487. AffineTransform::translation (-x, -y)
  72488. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72489. .transformPoint (px, py);
  72490. return p.contains (px, py);
  72491. }
  72492. }
  72493. return false;
  72494. }
  72495. void PositionedGlyph::moveBy (const float deltaX,
  72496. const float deltaY)
  72497. {
  72498. x += deltaX;
  72499. y += deltaY;
  72500. }
  72501. GlyphArrangement::GlyphArrangement()
  72502. {
  72503. glyphs.ensureStorageAllocated (128);
  72504. }
  72505. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72506. {
  72507. addGlyphArrangement (other);
  72508. }
  72509. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72510. {
  72511. if (this != &other)
  72512. {
  72513. clear();
  72514. addGlyphArrangement (other);
  72515. }
  72516. return *this;
  72517. }
  72518. GlyphArrangement::~GlyphArrangement()
  72519. {
  72520. }
  72521. void GlyphArrangement::clear()
  72522. {
  72523. glyphs.clear();
  72524. }
  72525. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72526. {
  72527. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72528. return *glyphs [index];
  72529. }
  72530. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72531. {
  72532. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72533. glyphs.addCopiesOf (other.glyphs);
  72534. }
  72535. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72536. {
  72537. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72538. }
  72539. void GlyphArrangement::addLineOfText (const Font& font,
  72540. const String& text,
  72541. const float xOffset,
  72542. const float yOffset)
  72543. {
  72544. addCurtailedLineOfText (font, text,
  72545. xOffset, yOffset,
  72546. 1.0e10f, false);
  72547. }
  72548. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72549. const String& text,
  72550. float xOffset,
  72551. const float yOffset,
  72552. const float maxWidthPixels,
  72553. const bool useEllipsis)
  72554. {
  72555. if (text.isNotEmpty())
  72556. {
  72557. Array <int> newGlyphs;
  72558. Array <float> xOffsets;
  72559. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72560. const int textLen = newGlyphs.size();
  72561. const juce_wchar* const unicodeText = text;
  72562. for (int i = 0; i < textLen; ++i)
  72563. {
  72564. const float thisX = xOffsets.getUnchecked (i);
  72565. const float nextX = xOffsets.getUnchecked (i + 1);
  72566. if (nextX > maxWidthPixels + 1.0f)
  72567. {
  72568. // curtail the string if it's too wide..
  72569. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72570. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72571. break;
  72572. }
  72573. else
  72574. {
  72575. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72576. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72577. }
  72578. }
  72579. }
  72580. }
  72581. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72582. const int startIndex, int endIndex)
  72583. {
  72584. int numDeleted = 0;
  72585. if (glyphs.size() > 0)
  72586. {
  72587. Array<int> dotGlyphs;
  72588. Array<float> dotXs;
  72589. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72590. const float dx = dotXs[1];
  72591. float xOffset = 0.0f, yOffset = 0.0f;
  72592. while (endIndex > startIndex)
  72593. {
  72594. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72595. xOffset = pg->x;
  72596. yOffset = pg->y;
  72597. glyphs.remove (endIndex);
  72598. ++numDeleted;
  72599. if (xOffset + dx * 3 <= maxXPos)
  72600. break;
  72601. }
  72602. for (int i = 3; --i >= 0;)
  72603. {
  72604. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72605. font, '.', dotGlyphs.getFirst()));
  72606. --numDeleted;
  72607. xOffset += dx;
  72608. if (xOffset > maxXPos)
  72609. break;
  72610. }
  72611. }
  72612. return numDeleted;
  72613. }
  72614. void GlyphArrangement::addJustifiedText (const Font& font,
  72615. const String& text,
  72616. float x, float y,
  72617. const float maxLineWidth,
  72618. const Justification& horizontalLayout)
  72619. {
  72620. int lineStartIndex = glyphs.size();
  72621. addLineOfText (font, text, x, y);
  72622. const float originalY = y;
  72623. while (lineStartIndex < glyphs.size())
  72624. {
  72625. int i = lineStartIndex;
  72626. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72627. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72628. ++i;
  72629. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72630. int lastWordBreakIndex = -1;
  72631. while (i < glyphs.size())
  72632. {
  72633. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72634. const juce_wchar c = pg->getCharacter();
  72635. if (c == '\r' || c == '\n')
  72636. {
  72637. ++i;
  72638. if (c == '\r' && i < glyphs.size()
  72639. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72640. ++i;
  72641. break;
  72642. }
  72643. else if (pg->isWhitespace())
  72644. {
  72645. lastWordBreakIndex = i + 1;
  72646. }
  72647. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72648. {
  72649. if (lastWordBreakIndex >= 0)
  72650. i = lastWordBreakIndex;
  72651. break;
  72652. }
  72653. ++i;
  72654. }
  72655. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72656. float currentLineEndX = currentLineStartX;
  72657. for (int j = i; --j >= lineStartIndex;)
  72658. {
  72659. if (! glyphs.getUnchecked (j)->isWhitespace())
  72660. {
  72661. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72662. break;
  72663. }
  72664. }
  72665. float deltaX = 0.0f;
  72666. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72667. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72668. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72669. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72670. else if (horizontalLayout.testFlags (Justification::right))
  72671. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72672. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72673. x + deltaX - currentLineStartX, y - originalY);
  72674. lineStartIndex = i;
  72675. y += font.getHeight();
  72676. }
  72677. }
  72678. void GlyphArrangement::addFittedText (const Font& f,
  72679. const String& text,
  72680. const float x, const float y,
  72681. const float width, const float height,
  72682. const Justification& layout,
  72683. int maximumLines,
  72684. const float minimumHorizontalScale)
  72685. {
  72686. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72687. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72688. if (text.containsAnyOf ("\r\n"))
  72689. {
  72690. GlyphArrangement ga;
  72691. ga.addJustifiedText (f, text, x, y, width, layout);
  72692. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72693. float dy = y - bb.getY();
  72694. if (layout.testFlags (Justification::verticallyCentred))
  72695. dy += (height - bb.getHeight()) * 0.5f;
  72696. else if (layout.testFlags (Justification::bottom))
  72697. dy += height - bb.getHeight();
  72698. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72699. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72700. for (int i = 0; i < ga.glyphs.size(); ++i)
  72701. glyphs.add (ga.glyphs.getUnchecked (i));
  72702. ga.glyphs.clear (false);
  72703. return;
  72704. }
  72705. int startIndex = glyphs.size();
  72706. addLineOfText (f, text.trim(), x, y);
  72707. if (glyphs.size() > startIndex)
  72708. {
  72709. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72710. - glyphs.getUnchecked (startIndex)->getLeft();
  72711. if (lineWidth <= 0)
  72712. return;
  72713. if (lineWidth * minimumHorizontalScale < width)
  72714. {
  72715. if (lineWidth > width)
  72716. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72717. width / lineWidth);
  72718. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72719. x, y, width, height, layout);
  72720. }
  72721. else if (maximumLines <= 1)
  72722. {
  72723. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72724. x, y, width, height, f, layout, minimumHorizontalScale);
  72725. }
  72726. else
  72727. {
  72728. Font font (f);
  72729. String txt (text.trim());
  72730. const int length = txt.length();
  72731. const int originalStartIndex = startIndex;
  72732. int numLines = 1;
  72733. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72734. maximumLines = 1;
  72735. maximumLines = jmin (maximumLines, length);
  72736. while (numLines < maximumLines)
  72737. {
  72738. ++numLines;
  72739. const float newFontHeight = height / (float) numLines;
  72740. if (newFontHeight < font.getHeight())
  72741. {
  72742. font.setHeight (jmax (8.0f, newFontHeight));
  72743. removeRangeOfGlyphs (startIndex, -1);
  72744. addLineOfText (font, txt, x, y);
  72745. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72746. - glyphs.getUnchecked (startIndex)->getLeft();
  72747. }
  72748. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72749. break;
  72750. }
  72751. if (numLines < 1)
  72752. numLines = 1;
  72753. float lineY = y;
  72754. float widthPerLine = lineWidth / numLines;
  72755. int lastLineStartIndex = 0;
  72756. for (int line = 0; line < numLines; ++line)
  72757. {
  72758. int i = startIndex;
  72759. lastLineStartIndex = i;
  72760. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72761. if (line == numLines - 1)
  72762. {
  72763. widthPerLine = width;
  72764. i = glyphs.size();
  72765. }
  72766. else
  72767. {
  72768. while (i < glyphs.size())
  72769. {
  72770. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72771. if (lineWidth > widthPerLine)
  72772. {
  72773. // got to a point where the line's too long, so skip forward to find a
  72774. // good place to break it..
  72775. const int searchStartIndex = i;
  72776. while (i < glyphs.size())
  72777. {
  72778. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72779. {
  72780. if (glyphs.getUnchecked (i)->isWhitespace()
  72781. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72782. {
  72783. ++i;
  72784. break;
  72785. }
  72786. }
  72787. else
  72788. {
  72789. // can't find a suitable break, so try looking backwards..
  72790. i = searchStartIndex;
  72791. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72792. {
  72793. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72794. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72795. {
  72796. i -= back - 1;
  72797. break;
  72798. }
  72799. }
  72800. break;
  72801. }
  72802. ++i;
  72803. }
  72804. break;
  72805. }
  72806. ++i;
  72807. }
  72808. int wsStart = i;
  72809. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72810. --wsStart;
  72811. int wsEnd = i;
  72812. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72813. ++wsEnd;
  72814. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72815. i = jmax (wsStart, startIndex + 1);
  72816. }
  72817. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72818. x, lineY, width, font.getHeight(), font,
  72819. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72820. minimumHorizontalScale);
  72821. startIndex = i;
  72822. lineY += font.getHeight();
  72823. if (startIndex >= glyphs.size())
  72824. break;
  72825. }
  72826. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72827. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72828. }
  72829. }
  72830. }
  72831. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72832. const float dx, const float dy)
  72833. {
  72834. jassert (startIndex >= 0);
  72835. if (dx != 0.0f || dy != 0.0f)
  72836. {
  72837. if (num < 0 || startIndex + num > glyphs.size())
  72838. num = glyphs.size() - startIndex;
  72839. while (--num >= 0)
  72840. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72841. }
  72842. }
  72843. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72844. const Justification& justification, float minimumHorizontalScale)
  72845. {
  72846. int numDeleted = 0;
  72847. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72848. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72849. if (lineWidth > w)
  72850. {
  72851. if (minimumHorizontalScale < 1.0f)
  72852. {
  72853. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  72854. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  72855. }
  72856. if (lineWidth > w)
  72857. {
  72858. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  72859. numGlyphs -= numDeleted;
  72860. }
  72861. }
  72862. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  72863. return numDeleted;
  72864. }
  72865. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  72866. const float horizontalScaleFactor)
  72867. {
  72868. jassert (startIndex >= 0);
  72869. if (num < 0 || startIndex + num > glyphs.size())
  72870. num = glyphs.size() - startIndex;
  72871. if (num > 0)
  72872. {
  72873. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  72874. while (--num >= 0)
  72875. {
  72876. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72877. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  72878. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  72879. pg->w *= horizontalScaleFactor;
  72880. }
  72881. }
  72882. }
  72883. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  72884. {
  72885. jassert (startIndex >= 0);
  72886. if (num < 0 || startIndex + num > glyphs.size())
  72887. num = glyphs.size() - startIndex;
  72888. Rectangle<float> result;
  72889. while (--num >= 0)
  72890. {
  72891. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72892. if (includeWhitespace || ! pg->isWhitespace())
  72893. result = result.getUnion (pg->getBounds());
  72894. }
  72895. return result;
  72896. }
  72897. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  72898. const float x, const float y, const float width, const float height,
  72899. const Justification& justification)
  72900. {
  72901. jassert (num >= 0 && startIndex >= 0);
  72902. if (glyphs.size() > 0 && num > 0)
  72903. {
  72904. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  72905. | Justification::horizontallyCentred)));
  72906. float deltaX = 0.0f;
  72907. if (justification.testFlags (Justification::horizontallyJustified))
  72908. deltaX = x - bb.getX();
  72909. else if (justification.testFlags (Justification::horizontallyCentred))
  72910. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  72911. else if (justification.testFlags (Justification::right))
  72912. deltaX = (x + width) - bb.getRight();
  72913. else
  72914. deltaX = x - bb.getX();
  72915. float deltaY = 0.0f;
  72916. if (justification.testFlags (Justification::top))
  72917. deltaY = y - bb.getY();
  72918. else if (justification.testFlags (Justification::bottom))
  72919. deltaY = (y + height) - bb.getBottom();
  72920. else
  72921. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  72922. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  72923. if (justification.testFlags (Justification::horizontallyJustified))
  72924. {
  72925. int lineStart = 0;
  72926. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  72927. int i;
  72928. for (i = 0; i < num; ++i)
  72929. {
  72930. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  72931. if (glyphY != baseY)
  72932. {
  72933. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72934. lineStart = i;
  72935. baseY = glyphY;
  72936. }
  72937. }
  72938. if (i > lineStart)
  72939. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72940. }
  72941. }
  72942. }
  72943. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  72944. {
  72945. if (start + num < glyphs.size()
  72946. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  72947. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  72948. {
  72949. int numSpaces = 0;
  72950. int spacesAtEnd = 0;
  72951. for (int i = 0; i < num; ++i)
  72952. {
  72953. if (glyphs.getUnchecked (start + i)->isWhitespace())
  72954. {
  72955. ++spacesAtEnd;
  72956. ++numSpaces;
  72957. }
  72958. else
  72959. {
  72960. spacesAtEnd = 0;
  72961. }
  72962. }
  72963. numSpaces -= spacesAtEnd;
  72964. if (numSpaces > 0)
  72965. {
  72966. const float startX = glyphs.getUnchecked (start)->getLeft();
  72967. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  72968. const float extraPaddingBetweenWords
  72969. = (targetWidth - (endX - startX)) / (float) numSpaces;
  72970. float deltaX = 0.0f;
  72971. for (int i = 0; i < num; ++i)
  72972. {
  72973. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  72974. if (glyphs.getUnchecked (start + i)->isWhitespace())
  72975. deltaX += extraPaddingBetweenWords;
  72976. }
  72977. }
  72978. }
  72979. }
  72980. void GlyphArrangement::draw (const Graphics& g) const
  72981. {
  72982. for (int i = 0; i < glyphs.size(); ++i)
  72983. {
  72984. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  72985. if (pg->font.isUnderlined())
  72986. {
  72987. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  72988. float nextX = pg->x + pg->w;
  72989. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  72990. nextX = glyphs.getUnchecked (i + 1)->x;
  72991. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  72992. nextX - pg->x, lineThickness);
  72993. }
  72994. pg->draw (g);
  72995. }
  72996. }
  72997. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  72998. {
  72999. for (int i = 0; i < glyphs.size(); ++i)
  73000. {
  73001. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73002. if (pg->font.isUnderlined())
  73003. {
  73004. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73005. float nextX = pg->x + pg->w;
  73006. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73007. nextX = glyphs.getUnchecked (i + 1)->x;
  73008. Path p;
  73009. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73010. nextX, pg->y + lineThickness * 2.0f),
  73011. lineThickness);
  73012. g.fillPath (p, transform);
  73013. }
  73014. pg->draw (g, transform);
  73015. }
  73016. }
  73017. void GlyphArrangement::createPath (Path& path) const
  73018. {
  73019. for (int i = 0; i < glyphs.size(); ++i)
  73020. glyphs.getUnchecked (i)->createPath (path);
  73021. }
  73022. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73023. {
  73024. for (int i = 0; i < glyphs.size(); ++i)
  73025. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73026. return i;
  73027. return -1;
  73028. }
  73029. END_JUCE_NAMESPACE
  73030. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73031. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73032. BEGIN_JUCE_NAMESPACE
  73033. class TextLayout::Token
  73034. {
  73035. public:
  73036. Token (const String& t,
  73037. const Font& f,
  73038. const bool isWhitespace_)
  73039. : text (t),
  73040. font (f),
  73041. x(0),
  73042. y(0),
  73043. isWhitespace (isWhitespace_)
  73044. {
  73045. w = font.getStringWidth (t);
  73046. h = roundToInt (f.getHeight());
  73047. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73048. }
  73049. Token (const Token& other)
  73050. : text (other.text),
  73051. font (other.font),
  73052. x (other.x),
  73053. y (other.y),
  73054. w (other.w),
  73055. h (other.h),
  73056. line (other.line),
  73057. lineHeight (other.lineHeight),
  73058. isWhitespace (other.isWhitespace),
  73059. isNewLine (other.isNewLine)
  73060. {
  73061. }
  73062. void draw (Graphics& g,
  73063. const int xOffset,
  73064. const int yOffset)
  73065. {
  73066. if (! isWhitespace)
  73067. {
  73068. g.setFont (font);
  73069. g.drawSingleLineText (text.trimEnd(),
  73070. xOffset + x,
  73071. yOffset + y + (lineHeight - h)
  73072. + roundToInt (font.getAscent()));
  73073. }
  73074. }
  73075. String text;
  73076. Font font;
  73077. int x, y, w, h;
  73078. int line, lineHeight;
  73079. bool isWhitespace, isNewLine;
  73080. private:
  73081. JUCE_LEAK_DETECTOR (Token);
  73082. };
  73083. TextLayout::TextLayout()
  73084. : totalLines (0)
  73085. {
  73086. tokens.ensureStorageAllocated (64);
  73087. }
  73088. TextLayout::TextLayout (const String& text, const Font& font)
  73089. : totalLines (0)
  73090. {
  73091. tokens.ensureStorageAllocated (64);
  73092. appendText (text, font);
  73093. }
  73094. TextLayout::TextLayout (const TextLayout& other)
  73095. : totalLines (0)
  73096. {
  73097. *this = other;
  73098. }
  73099. TextLayout& TextLayout::operator= (const TextLayout& other)
  73100. {
  73101. if (this != &other)
  73102. {
  73103. clear();
  73104. totalLines = other.totalLines;
  73105. tokens.addCopiesOf (other.tokens);
  73106. }
  73107. return *this;
  73108. }
  73109. TextLayout::~TextLayout()
  73110. {
  73111. clear();
  73112. }
  73113. void TextLayout::clear()
  73114. {
  73115. tokens.clear();
  73116. totalLines = 0;
  73117. }
  73118. bool TextLayout::isEmpty() const
  73119. {
  73120. return tokens.size() == 0;
  73121. }
  73122. void TextLayout::appendText (const String& text, const Font& font)
  73123. {
  73124. const juce_wchar* t = text;
  73125. String currentString;
  73126. int lastCharType = 0;
  73127. for (;;)
  73128. {
  73129. const juce_wchar c = *t++;
  73130. if (c == 0)
  73131. break;
  73132. int charType;
  73133. if (c == '\r' || c == '\n')
  73134. {
  73135. charType = 0;
  73136. }
  73137. else if (CharacterFunctions::isWhitespace (c))
  73138. {
  73139. charType = 2;
  73140. }
  73141. else
  73142. {
  73143. charType = 1;
  73144. }
  73145. if (charType == 0 || charType != lastCharType)
  73146. {
  73147. if (currentString.isNotEmpty())
  73148. {
  73149. tokens.add (new Token (currentString, font,
  73150. lastCharType == 2 || lastCharType == 0));
  73151. }
  73152. currentString = String::charToString (c);
  73153. if (c == '\r' && *t == '\n')
  73154. currentString += *t++;
  73155. }
  73156. else
  73157. {
  73158. currentString += c;
  73159. }
  73160. lastCharType = charType;
  73161. }
  73162. if (currentString.isNotEmpty())
  73163. tokens.add (new Token (currentString, font, lastCharType == 2));
  73164. }
  73165. void TextLayout::setText (const String& text, const Font& font)
  73166. {
  73167. clear();
  73168. appendText (text, font);
  73169. }
  73170. void TextLayout::layout (int maxWidth,
  73171. const Justification& justification,
  73172. const bool attemptToBalanceLineLengths)
  73173. {
  73174. if (attemptToBalanceLineLengths)
  73175. {
  73176. const int originalW = maxWidth;
  73177. int bestWidth = maxWidth;
  73178. float bestLineProportion = 0.0f;
  73179. while (maxWidth > originalW / 2)
  73180. {
  73181. layout (maxWidth, justification, false);
  73182. if (getNumLines() <= 1)
  73183. return;
  73184. const int lastLineW = getLineWidth (getNumLines() - 1);
  73185. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73186. const float prop = lastLineW / (float) lastButOneLineW;
  73187. if (prop > 0.9f)
  73188. return;
  73189. if (prop > bestLineProportion)
  73190. {
  73191. bestLineProportion = prop;
  73192. bestWidth = maxWidth;
  73193. }
  73194. maxWidth -= 10;
  73195. }
  73196. layout (bestWidth, justification, false);
  73197. }
  73198. else
  73199. {
  73200. int x = 0;
  73201. int y = 0;
  73202. int h = 0;
  73203. totalLines = 0;
  73204. int i;
  73205. for (i = 0; i < tokens.size(); ++i)
  73206. {
  73207. Token* const t = tokens.getUnchecked(i);
  73208. t->x = x;
  73209. t->y = y;
  73210. t->line = totalLines;
  73211. x += t->w;
  73212. h = jmax (h, t->h);
  73213. const Token* nextTok = tokens [i + 1];
  73214. if (nextTok == 0)
  73215. break;
  73216. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73217. {
  73218. // finished a line, so go back and update the heights of the things on it
  73219. for (int j = i; j >= 0; --j)
  73220. {
  73221. Token* const tok = tokens.getUnchecked(j);
  73222. if (tok->line == totalLines)
  73223. tok->lineHeight = h;
  73224. else
  73225. break;
  73226. }
  73227. x = 0;
  73228. y += h;
  73229. h = 0;
  73230. ++totalLines;
  73231. }
  73232. }
  73233. // finished a line, so go back and update the heights of the things on it
  73234. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73235. {
  73236. Token* const t = tokens.getUnchecked(j);
  73237. if (t->line == totalLines)
  73238. t->lineHeight = h;
  73239. else
  73240. break;
  73241. }
  73242. ++totalLines;
  73243. if (! justification.testFlags (Justification::left))
  73244. {
  73245. int totalW = getWidth();
  73246. for (i = totalLines; --i >= 0;)
  73247. {
  73248. const int lineW = getLineWidth (i);
  73249. int dx = 0;
  73250. if (justification.testFlags (Justification::horizontallyCentred))
  73251. dx = (totalW - lineW) / 2;
  73252. else if (justification.testFlags (Justification::right))
  73253. dx = totalW - lineW;
  73254. for (int j = tokens.size(); --j >= 0;)
  73255. {
  73256. Token* const t = tokens.getUnchecked(j);
  73257. if (t->line == i)
  73258. t->x += dx;
  73259. }
  73260. }
  73261. }
  73262. }
  73263. }
  73264. int TextLayout::getLineWidth (const int lineNumber) const
  73265. {
  73266. int maxW = 0;
  73267. for (int i = tokens.size(); --i >= 0;)
  73268. {
  73269. const Token* const t = tokens.getUnchecked(i);
  73270. if (t->line == lineNumber && ! t->isWhitespace)
  73271. maxW = jmax (maxW, t->x + t->w);
  73272. }
  73273. return maxW;
  73274. }
  73275. int TextLayout::getWidth() const
  73276. {
  73277. int maxW = 0;
  73278. for (int i = tokens.size(); --i >= 0;)
  73279. {
  73280. const Token* const t = tokens.getUnchecked(i);
  73281. if (! t->isWhitespace)
  73282. maxW = jmax (maxW, t->x + t->w);
  73283. }
  73284. return maxW;
  73285. }
  73286. int TextLayout::getHeight() const
  73287. {
  73288. int maxH = 0;
  73289. for (int i = tokens.size(); --i >= 0;)
  73290. {
  73291. const Token* const t = tokens.getUnchecked(i);
  73292. if (! t->isWhitespace)
  73293. maxH = jmax (maxH, t->y + t->h);
  73294. }
  73295. return maxH;
  73296. }
  73297. void TextLayout::draw (Graphics& g,
  73298. const int xOffset,
  73299. const int yOffset) const
  73300. {
  73301. for (int i = tokens.size(); --i >= 0;)
  73302. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73303. }
  73304. void TextLayout::drawWithin (Graphics& g,
  73305. int x, int y, int w, int h,
  73306. const Justification& justification) const
  73307. {
  73308. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73309. x, y, w, h);
  73310. draw (g, x, y);
  73311. }
  73312. END_JUCE_NAMESPACE
  73313. /*** End of inlined file: juce_TextLayout.cpp ***/
  73314. /*** Start of inlined file: juce_Typeface.cpp ***/
  73315. BEGIN_JUCE_NAMESPACE
  73316. Typeface::Typeface (const String& name_) throw()
  73317. : name (name_), isFallbackFont (false)
  73318. {
  73319. }
  73320. Typeface::~Typeface()
  73321. {
  73322. }
  73323. const Typeface::Ptr Typeface::getFallbackTypeface()
  73324. {
  73325. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73326. Typeface* t = fallbackFont.getTypeface();
  73327. t->isFallbackFont = true;
  73328. return t;
  73329. }
  73330. class CustomTypeface::GlyphInfo
  73331. {
  73332. public:
  73333. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73334. : character (character_), path (path_), width (width_)
  73335. {
  73336. }
  73337. struct KerningPair
  73338. {
  73339. juce_wchar character2;
  73340. float kerningAmount;
  73341. };
  73342. void addKerningPair (const juce_wchar subsequentCharacter,
  73343. const float extraKerningAmount) throw()
  73344. {
  73345. KerningPair kp;
  73346. kp.character2 = subsequentCharacter;
  73347. kp.kerningAmount = extraKerningAmount;
  73348. kerningPairs.add (kp);
  73349. }
  73350. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73351. {
  73352. if (subsequentCharacter != 0)
  73353. {
  73354. for (int i = kerningPairs.size(); --i >= 0;)
  73355. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73356. return width + kerningPairs.getReference(i).kerningAmount;
  73357. }
  73358. return width;
  73359. }
  73360. const juce_wchar character;
  73361. const Path path;
  73362. float width;
  73363. Array <KerningPair> kerningPairs;
  73364. private:
  73365. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  73366. };
  73367. CustomTypeface::CustomTypeface()
  73368. : Typeface (String::empty)
  73369. {
  73370. clear();
  73371. }
  73372. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73373. : Typeface (String::empty)
  73374. {
  73375. clear();
  73376. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73377. BufferedInputStream in (gzin, 32768);
  73378. name = in.readString();
  73379. isBold = in.readBool();
  73380. isItalic = in.readBool();
  73381. ascent = in.readFloat();
  73382. defaultCharacter = (juce_wchar) in.readShort();
  73383. int i, numChars = in.readInt();
  73384. for (i = 0; i < numChars; ++i)
  73385. {
  73386. const juce_wchar c = (juce_wchar) in.readShort();
  73387. const float width = in.readFloat();
  73388. Path p;
  73389. p.loadPathFromStream (in);
  73390. addGlyph (c, p, width);
  73391. }
  73392. const int numKerningPairs = in.readInt();
  73393. for (i = 0; i < numKerningPairs; ++i)
  73394. {
  73395. const juce_wchar char1 = (juce_wchar) in.readShort();
  73396. const juce_wchar char2 = (juce_wchar) in.readShort();
  73397. addKerningPair (char1, char2, in.readFloat());
  73398. }
  73399. }
  73400. CustomTypeface::~CustomTypeface()
  73401. {
  73402. }
  73403. void CustomTypeface::clear()
  73404. {
  73405. defaultCharacter = 0;
  73406. ascent = 1.0f;
  73407. isBold = isItalic = false;
  73408. zeromem (lookupTable, sizeof (lookupTable));
  73409. glyphs.clear();
  73410. }
  73411. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73412. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73413. {
  73414. name = name_;
  73415. defaultCharacter = defaultCharacter_;
  73416. ascent = ascent_;
  73417. isBold = isBold_;
  73418. isItalic = isItalic_;
  73419. }
  73420. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73421. {
  73422. // Check that you're not trying to add the same character twice..
  73423. jassert (findGlyph (character, false) == 0);
  73424. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73425. lookupTable [character] = (short) glyphs.size();
  73426. glyphs.add (new GlyphInfo (character, path, width));
  73427. }
  73428. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73429. {
  73430. if (extraAmount != 0)
  73431. {
  73432. GlyphInfo* const g = findGlyph (char1, true);
  73433. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73434. if (g != 0)
  73435. g->addKerningPair (char2, extraAmount);
  73436. }
  73437. }
  73438. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73439. {
  73440. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73441. return glyphs [(int) lookupTable [(int) character]];
  73442. for (int i = 0; i < glyphs.size(); ++i)
  73443. {
  73444. GlyphInfo* const g = glyphs.getUnchecked(i);
  73445. if (g->character == character)
  73446. return g;
  73447. }
  73448. if (loadIfNeeded && loadGlyphIfPossible (character))
  73449. return findGlyph (character, false);
  73450. return 0;
  73451. }
  73452. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73453. {
  73454. GlyphInfo* glyph = findGlyph (character, true);
  73455. if (glyph == 0)
  73456. {
  73457. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73458. glyph = findGlyph (L' ', true);
  73459. if (glyph == 0)
  73460. {
  73461. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73462. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73463. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73464. {
  73465. Path path;
  73466. fallbackTypeface->getOutlineForGlyph (character, path);
  73467. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  73468. }
  73469. if (glyph == 0)
  73470. glyph = findGlyph (defaultCharacter, true);
  73471. }
  73472. }
  73473. return glyph;
  73474. }
  73475. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73476. {
  73477. return false;
  73478. }
  73479. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73480. {
  73481. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73482. for (int i = 0; i < numCharacters; ++i)
  73483. {
  73484. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73485. Array <int> glyphIndexes;
  73486. Array <float> offsets;
  73487. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73488. const int glyphIndex = glyphIndexes.getFirst();
  73489. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73490. {
  73491. const float glyphWidth = offsets[1];
  73492. Path p;
  73493. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73494. addGlyph (c, p, glyphWidth);
  73495. for (int j = glyphs.size() - 1; --j >= 0;)
  73496. {
  73497. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73498. glyphIndexes.clearQuick();
  73499. offsets.clearQuick();
  73500. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73501. if (offsets.size() > 1)
  73502. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73503. }
  73504. }
  73505. }
  73506. }
  73507. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73508. {
  73509. GZIPCompressorOutputStream out (&outputStream);
  73510. out.writeString (name);
  73511. out.writeBool (isBold);
  73512. out.writeBool (isItalic);
  73513. out.writeFloat (ascent);
  73514. out.writeShort ((short) (unsigned short) defaultCharacter);
  73515. out.writeInt (glyphs.size());
  73516. int i, numKerningPairs = 0;
  73517. for (i = 0; i < glyphs.size(); ++i)
  73518. {
  73519. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73520. out.writeShort ((short) (unsigned short) g->character);
  73521. out.writeFloat (g->width);
  73522. g->path.writePathToStream (out);
  73523. numKerningPairs += g->kerningPairs.size();
  73524. }
  73525. out.writeInt (numKerningPairs);
  73526. for (i = 0; i < glyphs.size(); ++i)
  73527. {
  73528. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73529. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73530. {
  73531. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73532. out.writeShort ((short) (unsigned short) g->character);
  73533. out.writeShort ((short) (unsigned short) p.character2);
  73534. out.writeFloat (p.kerningAmount);
  73535. }
  73536. }
  73537. return true;
  73538. }
  73539. float CustomTypeface::getAscent() const
  73540. {
  73541. return ascent;
  73542. }
  73543. float CustomTypeface::getDescent() const
  73544. {
  73545. return 1.0f - ascent;
  73546. }
  73547. float CustomTypeface::getStringWidth (const String& text)
  73548. {
  73549. float x = 0;
  73550. const juce_wchar* t = text;
  73551. while (*t != 0)
  73552. {
  73553. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73554. if (glyph == 0 && ! isFallbackFont)
  73555. {
  73556. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73557. if (fallbackTypeface != 0)
  73558. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  73559. }
  73560. if (glyph != 0)
  73561. x += glyph->getHorizontalSpacing (*t);
  73562. }
  73563. return x;
  73564. }
  73565. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73566. {
  73567. xOffsets.add (0);
  73568. float x = 0;
  73569. const juce_wchar* t = text;
  73570. while (*t != 0)
  73571. {
  73572. const juce_wchar c = *t++;
  73573. const GlyphInfo* const glyph = findGlyph (c, true);
  73574. if (glyph == 0 && ! isFallbackFont)
  73575. {
  73576. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73577. if (fallbackTypeface != 0)
  73578. {
  73579. Array <int> subGlyphs;
  73580. Array <float> subOffsets;
  73581. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  73582. if (subGlyphs.size() > 0)
  73583. {
  73584. resultGlyphs.add (subGlyphs.getFirst());
  73585. x += subOffsets[1];
  73586. xOffsets.add (x);
  73587. }
  73588. }
  73589. }
  73590. if (glyph != 0)
  73591. {
  73592. x += glyph->getHorizontalSpacing (*t);
  73593. resultGlyphs.add ((int) glyph->character);
  73594. xOffsets.add (x);
  73595. }
  73596. }
  73597. }
  73598. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73599. {
  73600. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  73601. if (glyph == 0 && ! isFallbackFont)
  73602. {
  73603. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73604. if (fallbackTypeface != 0)
  73605. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  73606. }
  73607. if (glyph != 0)
  73608. {
  73609. path = glyph->path;
  73610. return true;
  73611. }
  73612. return false;
  73613. }
  73614. END_JUCE_NAMESPACE
  73615. /*** End of inlined file: juce_Typeface.cpp ***/
  73616. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73617. BEGIN_JUCE_NAMESPACE
  73618. AffineTransform::AffineTransform() throw()
  73619. : mat00 (1.0f), mat01 (0), mat02 (0),
  73620. mat10 (0), mat11 (1.0f), mat12 (0)
  73621. {
  73622. }
  73623. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73624. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  73625. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  73626. {
  73627. }
  73628. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  73629. const float mat10_, const float mat11_, const float mat12_) throw()
  73630. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  73631. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  73632. {
  73633. }
  73634. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73635. {
  73636. mat00 = other.mat00;
  73637. mat01 = other.mat01;
  73638. mat02 = other.mat02;
  73639. mat10 = other.mat10;
  73640. mat11 = other.mat11;
  73641. mat12 = other.mat12;
  73642. return *this;
  73643. }
  73644. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73645. {
  73646. return mat00 == other.mat00
  73647. && mat01 == other.mat01
  73648. && mat02 == other.mat02
  73649. && mat10 == other.mat10
  73650. && mat11 == other.mat11
  73651. && mat12 == other.mat12;
  73652. }
  73653. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73654. {
  73655. return ! operator== (other);
  73656. }
  73657. bool AffineTransform::isIdentity() const throw()
  73658. {
  73659. return (mat01 == 0)
  73660. && (mat02 == 0)
  73661. && (mat10 == 0)
  73662. && (mat12 == 0)
  73663. && (mat00 == 1.0f)
  73664. && (mat11 == 1.0f);
  73665. }
  73666. const AffineTransform AffineTransform::identity;
  73667. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73668. {
  73669. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73670. other.mat00 * mat01 + other.mat01 * mat11,
  73671. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73672. other.mat10 * mat00 + other.mat11 * mat10,
  73673. other.mat10 * mat01 + other.mat11 * mat11,
  73674. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73675. }
  73676. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  73677. {
  73678. return AffineTransform (mat00, mat01, mat02 + dx,
  73679. mat10, mat11, mat12 + dy);
  73680. }
  73681. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  73682. {
  73683. return AffineTransform (1.0f, 0, dx,
  73684. 0, 1.0f, dy);
  73685. }
  73686. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73687. {
  73688. const float cosRad = std::cos (rad);
  73689. const float sinRad = std::sin (rad);
  73690. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  73691. cosRad * mat01 + -sinRad * mat11,
  73692. cosRad * mat02 + -sinRad * mat12,
  73693. sinRad * mat00 + cosRad * mat10,
  73694. sinRad * mat01 + cosRad * mat11,
  73695. sinRad * mat02 + cosRad * mat12);
  73696. }
  73697. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73698. {
  73699. const float cosRad = std::cos (rad);
  73700. const float sinRad = std::sin (rad);
  73701. return AffineTransform (cosRad, -sinRad, 0,
  73702. sinRad, cosRad, 0);
  73703. }
  73704. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  73705. {
  73706. const float cosRad = std::cos (rad);
  73707. const float sinRad = std::sin (rad);
  73708. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  73709. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  73710. }
  73711. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  73712. {
  73713. return followedBy (rotation (angle, pivotX, pivotY));
  73714. }
  73715. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  73716. {
  73717. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73718. factorY * mat10, factorY * mat11, factorY * mat12);
  73719. }
  73720. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  73721. {
  73722. return AffineTransform (factorX, 0, 0,
  73723. 0, factorY, 0);
  73724. }
  73725. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  73726. const float pivotX, const float pivotY) const throw()
  73727. {
  73728. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  73729. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  73730. }
  73731. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  73732. const float pivotX, const float pivotY) throw()
  73733. {
  73734. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  73735. 0, factorY, pivotY * (1.0f - factorY));
  73736. }
  73737. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  73738. {
  73739. return AffineTransform (1.0f, shearX, 0,
  73740. shearY, 1.0f, 0);
  73741. }
  73742. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  73743. {
  73744. return AffineTransform (mat00 + shearX * mat10,
  73745. mat01 + shearX * mat11,
  73746. mat02 + shearX * mat12,
  73747. shearY * mat00 + mat10,
  73748. shearY * mat01 + mat11,
  73749. shearY * mat02 + mat12);
  73750. }
  73751. const AffineTransform AffineTransform::inverted() const throw()
  73752. {
  73753. double determinant = (mat00 * mat11 - mat10 * mat01);
  73754. if (determinant != 0.0)
  73755. {
  73756. determinant = 1.0 / determinant;
  73757. const float dst00 = (float) (mat11 * determinant);
  73758. const float dst10 = (float) (-mat10 * determinant);
  73759. const float dst01 = (float) (-mat01 * determinant);
  73760. const float dst11 = (float) (mat00 * determinant);
  73761. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73762. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73763. }
  73764. else
  73765. {
  73766. // singularity..
  73767. return *this;
  73768. }
  73769. }
  73770. bool AffineTransform::isSingularity() const throw()
  73771. {
  73772. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73773. }
  73774. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73775. const float x10, const float y10,
  73776. const float x01, const float y01) throw()
  73777. {
  73778. return AffineTransform (x10 - x00, x01 - x00, x00,
  73779. y10 - y00, y01 - y00, y00);
  73780. }
  73781. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73782. const float sx2, const float sy2, const float tx2, const float ty2,
  73783. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73784. {
  73785. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73786. .inverted()
  73787. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73788. }
  73789. bool AffineTransform::isOnlyTranslation() const throw()
  73790. {
  73791. return (mat01 == 0)
  73792. && (mat10 == 0)
  73793. && (mat00 == 1.0f)
  73794. && (mat11 == 1.0f);
  73795. }
  73796. END_JUCE_NAMESPACE
  73797. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73798. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73799. BEGIN_JUCE_NAMESPACE
  73800. BorderSize::BorderSize() throw()
  73801. : top (0),
  73802. left (0),
  73803. bottom (0),
  73804. right (0)
  73805. {
  73806. }
  73807. BorderSize::BorderSize (const BorderSize& other) throw()
  73808. : top (other.top),
  73809. left (other.left),
  73810. bottom (other.bottom),
  73811. right (other.right)
  73812. {
  73813. }
  73814. BorderSize::BorderSize (const int topGap,
  73815. const int leftGap,
  73816. const int bottomGap,
  73817. const int rightGap) throw()
  73818. : top (topGap),
  73819. left (leftGap),
  73820. bottom (bottomGap),
  73821. right (rightGap)
  73822. {
  73823. }
  73824. BorderSize::BorderSize (const int allGaps) throw()
  73825. : top (allGaps),
  73826. left (allGaps),
  73827. bottom (allGaps),
  73828. right (allGaps)
  73829. {
  73830. }
  73831. BorderSize::~BorderSize() throw()
  73832. {
  73833. }
  73834. void BorderSize::setTop (const int newTopGap) throw()
  73835. {
  73836. top = newTopGap;
  73837. }
  73838. void BorderSize::setLeft (const int newLeftGap) throw()
  73839. {
  73840. left = newLeftGap;
  73841. }
  73842. void BorderSize::setBottom (const int newBottomGap) throw()
  73843. {
  73844. bottom = newBottomGap;
  73845. }
  73846. void BorderSize::setRight (const int newRightGap) throw()
  73847. {
  73848. right = newRightGap;
  73849. }
  73850. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  73851. {
  73852. return Rectangle<int> (r.getX() + left,
  73853. r.getY() + top,
  73854. r.getWidth() - (left + right),
  73855. r.getHeight() - (top + bottom));
  73856. }
  73857. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  73858. {
  73859. r.setBounds (r.getX() + left,
  73860. r.getY() + top,
  73861. r.getWidth() - (left + right),
  73862. r.getHeight() - (top + bottom));
  73863. }
  73864. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  73865. {
  73866. return Rectangle<int> (r.getX() - left,
  73867. r.getY() - top,
  73868. r.getWidth() + (left + right),
  73869. r.getHeight() + (top + bottom));
  73870. }
  73871. void BorderSize::addTo (Rectangle<int>& r) const throw()
  73872. {
  73873. r.setBounds (r.getX() - left,
  73874. r.getY() - top,
  73875. r.getWidth() + (left + right),
  73876. r.getHeight() + (top + bottom));
  73877. }
  73878. bool BorderSize::operator== (const BorderSize& other) const throw()
  73879. {
  73880. return top == other.top
  73881. && left == other.left
  73882. && bottom == other.bottom
  73883. && right == other.right;
  73884. }
  73885. bool BorderSize::operator!= (const BorderSize& other) const throw()
  73886. {
  73887. return ! operator== (other);
  73888. }
  73889. END_JUCE_NAMESPACE
  73890. /*** End of inlined file: juce_BorderSize.cpp ***/
  73891. /*** Start of inlined file: juce_Path.cpp ***/
  73892. BEGIN_JUCE_NAMESPACE
  73893. // tests that some co-ords aren't NaNs
  73894. #define CHECK_COORDS_ARE_VALID(x, y) \
  73895. jassert (x == x && y == y);
  73896. namespace PathHelpers
  73897. {
  73898. const float ellipseAngularIncrement = 0.05f;
  73899. const String nextToken (const juce_wchar*& t)
  73900. {
  73901. while (CharacterFunctions::isWhitespace (*t))
  73902. ++t;
  73903. const juce_wchar* const start = t;
  73904. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  73905. ++t;
  73906. return String (start, (int) (t - start));
  73907. }
  73908. }
  73909. const float Path::lineMarker = 100001.0f;
  73910. const float Path::moveMarker = 100002.0f;
  73911. const float Path::quadMarker = 100003.0f;
  73912. const float Path::cubicMarker = 100004.0f;
  73913. const float Path::closeSubPathMarker = 100005.0f;
  73914. Path::Path()
  73915. : numElements (0),
  73916. pathXMin (0),
  73917. pathXMax (0),
  73918. pathYMin (0),
  73919. pathYMax (0),
  73920. useNonZeroWinding (true)
  73921. {
  73922. }
  73923. Path::~Path()
  73924. {
  73925. }
  73926. Path::Path (const Path& other)
  73927. : numElements (other.numElements),
  73928. pathXMin (other.pathXMin),
  73929. pathXMax (other.pathXMax),
  73930. pathYMin (other.pathYMin),
  73931. pathYMax (other.pathYMax),
  73932. useNonZeroWinding (other.useNonZeroWinding)
  73933. {
  73934. if (numElements > 0)
  73935. {
  73936. data.setAllocatedSize ((int) numElements);
  73937. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73938. }
  73939. }
  73940. Path& Path::operator= (const Path& other)
  73941. {
  73942. if (this != &other)
  73943. {
  73944. data.ensureAllocatedSize ((int) other.numElements);
  73945. numElements = other.numElements;
  73946. pathXMin = other.pathXMin;
  73947. pathXMax = other.pathXMax;
  73948. pathYMin = other.pathYMin;
  73949. pathYMax = other.pathYMax;
  73950. useNonZeroWinding = other.useNonZeroWinding;
  73951. if (numElements > 0)
  73952. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73953. }
  73954. return *this;
  73955. }
  73956. bool Path::operator== (const Path& other) const throw()
  73957. {
  73958. return ! operator!= (other);
  73959. }
  73960. bool Path::operator!= (const Path& other) const throw()
  73961. {
  73962. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  73963. return true;
  73964. for (size_t i = 0; i < numElements; ++i)
  73965. if (data.elements[i] != other.data.elements[i])
  73966. return true;
  73967. return false;
  73968. }
  73969. void Path::clear() throw()
  73970. {
  73971. numElements = 0;
  73972. pathXMin = 0;
  73973. pathYMin = 0;
  73974. pathYMax = 0;
  73975. pathXMax = 0;
  73976. }
  73977. void Path::swapWithPath (Path& other) throw()
  73978. {
  73979. data.swapWith (other.data);
  73980. swapVariables <size_t> (numElements, other.numElements);
  73981. swapVariables <float> (pathXMin, other.pathXMin);
  73982. swapVariables <float> (pathXMax, other.pathXMax);
  73983. swapVariables <float> (pathYMin, other.pathYMin);
  73984. swapVariables <float> (pathYMax, other.pathYMax);
  73985. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  73986. }
  73987. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  73988. {
  73989. useNonZeroWinding = isNonZero;
  73990. }
  73991. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  73992. const bool preserveProportions) throw()
  73993. {
  73994. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  73995. }
  73996. bool Path::isEmpty() const throw()
  73997. {
  73998. size_t i = 0;
  73999. while (i < numElements)
  74000. {
  74001. const float type = data.elements [i++];
  74002. if (type == moveMarker)
  74003. {
  74004. i += 2;
  74005. }
  74006. else if (type == lineMarker
  74007. || type == quadMarker
  74008. || type == cubicMarker)
  74009. {
  74010. return false;
  74011. }
  74012. }
  74013. return true;
  74014. }
  74015. const Rectangle<float> Path::getBounds() const throw()
  74016. {
  74017. return Rectangle<float> (pathXMin, pathYMin,
  74018. pathXMax - pathXMin,
  74019. pathYMax - pathYMin);
  74020. }
  74021. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74022. {
  74023. return getBounds().transformed (transform);
  74024. }
  74025. void Path::startNewSubPath (const float x, const float y)
  74026. {
  74027. CHECK_COORDS_ARE_VALID (x, y);
  74028. if (numElements == 0)
  74029. {
  74030. pathXMin = pathXMax = x;
  74031. pathYMin = pathYMax = y;
  74032. }
  74033. else
  74034. {
  74035. pathXMin = jmin (pathXMin, x);
  74036. pathXMax = jmax (pathXMax, x);
  74037. pathYMin = jmin (pathYMin, y);
  74038. pathYMax = jmax (pathYMax, y);
  74039. }
  74040. data.ensureAllocatedSize ((int) numElements + 3);
  74041. data.elements [numElements++] = moveMarker;
  74042. data.elements [numElements++] = x;
  74043. data.elements [numElements++] = y;
  74044. }
  74045. void Path::startNewSubPath (const Point<float>& start)
  74046. {
  74047. startNewSubPath (start.getX(), start.getY());
  74048. }
  74049. void Path::lineTo (const float x, const float y)
  74050. {
  74051. CHECK_COORDS_ARE_VALID (x, y);
  74052. if (numElements == 0)
  74053. startNewSubPath (0, 0);
  74054. data.ensureAllocatedSize ((int) numElements + 3);
  74055. data.elements [numElements++] = lineMarker;
  74056. data.elements [numElements++] = x;
  74057. data.elements [numElements++] = y;
  74058. pathXMin = jmin (pathXMin, x);
  74059. pathXMax = jmax (pathXMax, x);
  74060. pathYMin = jmin (pathYMin, y);
  74061. pathYMax = jmax (pathYMax, y);
  74062. }
  74063. void Path::lineTo (const Point<float>& end)
  74064. {
  74065. lineTo (end.getX(), end.getY());
  74066. }
  74067. void Path::quadraticTo (const float x1, const float y1,
  74068. const float x2, const float y2)
  74069. {
  74070. CHECK_COORDS_ARE_VALID (x1, y1);
  74071. CHECK_COORDS_ARE_VALID (x2, y2);
  74072. if (numElements == 0)
  74073. startNewSubPath (0, 0);
  74074. data.ensureAllocatedSize ((int) numElements + 5);
  74075. data.elements [numElements++] = quadMarker;
  74076. data.elements [numElements++] = x1;
  74077. data.elements [numElements++] = y1;
  74078. data.elements [numElements++] = x2;
  74079. data.elements [numElements++] = y2;
  74080. pathXMin = jmin (pathXMin, x1, x2);
  74081. pathXMax = jmax (pathXMax, x1, x2);
  74082. pathYMin = jmin (pathYMin, y1, y2);
  74083. pathYMax = jmax (pathYMax, y1, y2);
  74084. }
  74085. void Path::quadraticTo (const Point<float>& controlPoint,
  74086. const Point<float>& endPoint)
  74087. {
  74088. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74089. endPoint.getX(), endPoint.getY());
  74090. }
  74091. void Path::cubicTo (const float x1, const float y1,
  74092. const float x2, const float y2,
  74093. const float x3, const float y3)
  74094. {
  74095. CHECK_COORDS_ARE_VALID (x1, y1);
  74096. CHECK_COORDS_ARE_VALID (x2, y2);
  74097. CHECK_COORDS_ARE_VALID (x3, y3);
  74098. if (numElements == 0)
  74099. startNewSubPath (0, 0);
  74100. data.ensureAllocatedSize ((int) numElements + 7);
  74101. data.elements [numElements++] = cubicMarker;
  74102. data.elements [numElements++] = x1;
  74103. data.elements [numElements++] = y1;
  74104. data.elements [numElements++] = x2;
  74105. data.elements [numElements++] = y2;
  74106. data.elements [numElements++] = x3;
  74107. data.elements [numElements++] = y3;
  74108. pathXMin = jmin (pathXMin, x1, x2, x3);
  74109. pathXMax = jmax (pathXMax, x1, x2, x3);
  74110. pathYMin = jmin (pathYMin, y1, y2, y3);
  74111. pathYMax = jmax (pathYMax, y1, y2, y3);
  74112. }
  74113. void Path::cubicTo (const Point<float>& controlPoint1,
  74114. const Point<float>& controlPoint2,
  74115. const Point<float>& endPoint)
  74116. {
  74117. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74118. controlPoint2.getX(), controlPoint2.getY(),
  74119. endPoint.getX(), endPoint.getY());
  74120. }
  74121. void Path::closeSubPath()
  74122. {
  74123. if (numElements > 0
  74124. && data.elements [numElements - 1] != closeSubPathMarker)
  74125. {
  74126. data.ensureAllocatedSize ((int) numElements + 1);
  74127. data.elements [numElements++] = closeSubPathMarker;
  74128. }
  74129. }
  74130. const Point<float> Path::getCurrentPosition() const
  74131. {
  74132. size_t i = numElements - 1;
  74133. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74134. {
  74135. while (i >= 0)
  74136. {
  74137. if (data.elements[i] == moveMarker)
  74138. {
  74139. i += 2;
  74140. break;
  74141. }
  74142. --i;
  74143. }
  74144. }
  74145. if (i > 0)
  74146. return Point<float> (data.elements [i - 1], data.elements [i]);
  74147. return Point<float>();
  74148. }
  74149. void Path::addRectangle (const float x, const float y,
  74150. const float w, const float h)
  74151. {
  74152. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74153. if (w < 0)
  74154. swapVariables (x1, x2);
  74155. if (h < 0)
  74156. swapVariables (y1, y2);
  74157. data.ensureAllocatedSize ((int) numElements + 13);
  74158. if (numElements == 0)
  74159. {
  74160. pathXMin = x1;
  74161. pathXMax = x2;
  74162. pathYMin = y1;
  74163. pathYMax = y2;
  74164. }
  74165. else
  74166. {
  74167. pathXMin = jmin (pathXMin, x1);
  74168. pathXMax = jmax (pathXMax, x2);
  74169. pathYMin = jmin (pathYMin, y1);
  74170. pathYMax = jmax (pathYMax, y2);
  74171. }
  74172. data.elements [numElements++] = moveMarker;
  74173. data.elements [numElements++] = x1;
  74174. data.elements [numElements++] = y2;
  74175. data.elements [numElements++] = lineMarker;
  74176. data.elements [numElements++] = x1;
  74177. data.elements [numElements++] = y1;
  74178. data.elements [numElements++] = lineMarker;
  74179. data.elements [numElements++] = x2;
  74180. data.elements [numElements++] = y1;
  74181. data.elements [numElements++] = lineMarker;
  74182. data.elements [numElements++] = x2;
  74183. data.elements [numElements++] = y2;
  74184. data.elements [numElements++] = closeSubPathMarker;
  74185. }
  74186. void Path::addRoundedRectangle (const float x, const float y,
  74187. const float w, const float h,
  74188. float csx,
  74189. float csy)
  74190. {
  74191. csx = jmin (csx, w * 0.5f);
  74192. csy = jmin (csy, h * 0.5f);
  74193. const float cs45x = csx * 0.45f;
  74194. const float cs45y = csy * 0.45f;
  74195. const float x2 = x + w;
  74196. const float y2 = y + h;
  74197. startNewSubPath (x + csx, y);
  74198. lineTo (x2 - csx, y);
  74199. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74200. lineTo (x2, y2 - csy);
  74201. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74202. lineTo (x + csx, y2);
  74203. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74204. lineTo (x, y + csy);
  74205. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74206. closeSubPath();
  74207. }
  74208. void Path::addRoundedRectangle (const float x, const float y,
  74209. const float w, const float h,
  74210. float cs)
  74211. {
  74212. addRoundedRectangle (x, y, w, h, cs, cs);
  74213. }
  74214. void Path::addTriangle (const float x1, const float y1,
  74215. const float x2, const float y2,
  74216. const float x3, const float y3)
  74217. {
  74218. startNewSubPath (x1, y1);
  74219. lineTo (x2, y2);
  74220. lineTo (x3, y3);
  74221. closeSubPath();
  74222. }
  74223. void Path::addQuadrilateral (const float x1, const float y1,
  74224. const float x2, const float y2,
  74225. const float x3, const float y3,
  74226. const float x4, const float y4)
  74227. {
  74228. startNewSubPath (x1, y1);
  74229. lineTo (x2, y2);
  74230. lineTo (x3, y3);
  74231. lineTo (x4, y4);
  74232. closeSubPath();
  74233. }
  74234. void Path::addEllipse (const float x, const float y,
  74235. const float w, const float h)
  74236. {
  74237. const float hw = w * 0.5f;
  74238. const float hw55 = hw * 0.55f;
  74239. const float hh = h * 0.5f;
  74240. const float hh55 = hh * 0.55f;
  74241. const float cx = x + hw;
  74242. const float cy = y + hh;
  74243. startNewSubPath (cx, cy - hh);
  74244. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74245. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74246. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74247. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74248. closeSubPath();
  74249. }
  74250. void Path::addArc (const float x, const float y,
  74251. const float w, const float h,
  74252. const float fromRadians,
  74253. const float toRadians,
  74254. const bool startAsNewSubPath)
  74255. {
  74256. const float radiusX = w / 2.0f;
  74257. const float radiusY = h / 2.0f;
  74258. addCentredArc (x + radiusX,
  74259. y + radiusY,
  74260. radiusX, radiusY,
  74261. 0.0f,
  74262. fromRadians, toRadians,
  74263. startAsNewSubPath);
  74264. }
  74265. void Path::addCentredArc (const float centreX, const float centreY,
  74266. const float radiusX, const float radiusY,
  74267. const float rotationOfEllipse,
  74268. const float fromRadians,
  74269. const float toRadians,
  74270. const bool startAsNewSubPath)
  74271. {
  74272. if (radiusX > 0.0f && radiusY > 0.0f)
  74273. {
  74274. const Point<float> centre (centreX, centreY);
  74275. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74276. float angle = fromRadians;
  74277. if (startAsNewSubPath)
  74278. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74279. if (fromRadians < toRadians)
  74280. {
  74281. if (startAsNewSubPath)
  74282. angle += PathHelpers::ellipseAngularIncrement;
  74283. while (angle < toRadians)
  74284. {
  74285. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74286. angle += PathHelpers::ellipseAngularIncrement;
  74287. }
  74288. }
  74289. else
  74290. {
  74291. if (startAsNewSubPath)
  74292. angle -= PathHelpers::ellipseAngularIncrement;
  74293. while (angle > toRadians)
  74294. {
  74295. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74296. angle -= PathHelpers::ellipseAngularIncrement;
  74297. }
  74298. }
  74299. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74300. }
  74301. }
  74302. void Path::addPieSegment (const float x, const float y,
  74303. const float width, const float height,
  74304. const float fromRadians,
  74305. const float toRadians,
  74306. const float innerCircleProportionalSize)
  74307. {
  74308. float radiusX = width * 0.5f;
  74309. float radiusY = height * 0.5f;
  74310. const Point<float> centre (x + radiusX, y + radiusY);
  74311. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74312. addArc (x, y, width, height, fromRadians, toRadians);
  74313. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74314. {
  74315. closeSubPath();
  74316. if (innerCircleProportionalSize > 0)
  74317. {
  74318. radiusX *= innerCircleProportionalSize;
  74319. radiusY *= innerCircleProportionalSize;
  74320. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74321. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74322. }
  74323. }
  74324. else
  74325. {
  74326. if (innerCircleProportionalSize > 0)
  74327. {
  74328. radiusX *= innerCircleProportionalSize;
  74329. radiusY *= innerCircleProportionalSize;
  74330. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74331. }
  74332. else
  74333. {
  74334. lineTo (centre);
  74335. }
  74336. }
  74337. closeSubPath();
  74338. }
  74339. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74340. {
  74341. const Line<float> reversed (line.reversed());
  74342. lineThickness *= 0.5f;
  74343. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74344. lineTo (line.getPointAlongLine (0, -lineThickness));
  74345. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74346. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74347. closeSubPath();
  74348. }
  74349. void Path::addArrow (const Line<float>& line, float lineThickness,
  74350. float arrowheadWidth, float arrowheadLength)
  74351. {
  74352. const Line<float> reversed (line.reversed());
  74353. lineThickness *= 0.5f;
  74354. arrowheadWidth *= 0.5f;
  74355. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74356. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74357. lineTo (line.getPointAlongLine (0, -lineThickness));
  74358. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74359. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74360. lineTo (line.getEnd());
  74361. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74362. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74363. closeSubPath();
  74364. }
  74365. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74366. const float radius, const float startAngle)
  74367. {
  74368. jassert (numberOfSides > 1); // this would be silly.
  74369. if (numberOfSides > 1)
  74370. {
  74371. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74372. for (int i = 0; i < numberOfSides; ++i)
  74373. {
  74374. const float angle = startAngle + i * angleBetweenPoints;
  74375. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74376. if (i == 0)
  74377. startNewSubPath (p);
  74378. else
  74379. lineTo (p);
  74380. }
  74381. closeSubPath();
  74382. }
  74383. }
  74384. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74385. const float innerRadius, const float outerRadius, const float startAngle)
  74386. {
  74387. jassert (numberOfPoints > 1); // this would be silly.
  74388. if (numberOfPoints > 1)
  74389. {
  74390. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74391. for (int i = 0; i < numberOfPoints; ++i)
  74392. {
  74393. const float angle = startAngle + i * angleBetweenPoints;
  74394. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74395. if (i == 0)
  74396. startNewSubPath (p);
  74397. else
  74398. lineTo (p);
  74399. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74400. }
  74401. closeSubPath();
  74402. }
  74403. }
  74404. void Path::addBubble (float x, float y,
  74405. float w, float h,
  74406. float cs,
  74407. float tipX,
  74408. float tipY,
  74409. int whichSide,
  74410. float arrowPos,
  74411. float arrowWidth)
  74412. {
  74413. if (w > 1.0f && h > 1.0f)
  74414. {
  74415. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74416. const float cs2 = 2.0f * cs;
  74417. startNewSubPath (x + cs, y);
  74418. if (whichSide == 0)
  74419. {
  74420. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74421. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74422. lineTo (arrowX1, y);
  74423. lineTo (tipX, tipY);
  74424. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74425. }
  74426. lineTo (x + w - cs, y);
  74427. if (cs > 0.0f)
  74428. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74429. if (whichSide == 3)
  74430. {
  74431. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74432. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74433. lineTo (x + w, arrowY1);
  74434. lineTo (tipX, tipY);
  74435. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74436. }
  74437. lineTo (x + w, y + h - cs);
  74438. if (cs > 0.0f)
  74439. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74440. if (whichSide == 2)
  74441. {
  74442. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74443. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74444. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74445. lineTo (tipX, tipY);
  74446. lineTo (arrowX1, y + h);
  74447. }
  74448. lineTo (x + cs, y + h);
  74449. if (cs > 0.0f)
  74450. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74451. if (whichSide == 1)
  74452. {
  74453. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74454. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74455. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74456. lineTo (tipX, tipY);
  74457. lineTo (x, arrowY1);
  74458. }
  74459. lineTo (x, y + cs);
  74460. if (cs > 0.0f)
  74461. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74462. closeSubPath();
  74463. }
  74464. }
  74465. void Path::addPath (const Path& other)
  74466. {
  74467. size_t i = 0;
  74468. while (i < other.numElements)
  74469. {
  74470. const float type = other.data.elements [i++];
  74471. if (type == moveMarker)
  74472. {
  74473. startNewSubPath (other.data.elements [i],
  74474. other.data.elements [i + 1]);
  74475. i += 2;
  74476. }
  74477. else if (type == lineMarker)
  74478. {
  74479. lineTo (other.data.elements [i],
  74480. other.data.elements [i + 1]);
  74481. i += 2;
  74482. }
  74483. else if (type == quadMarker)
  74484. {
  74485. quadraticTo (other.data.elements [i],
  74486. other.data.elements [i + 1],
  74487. other.data.elements [i + 2],
  74488. other.data.elements [i + 3]);
  74489. i += 4;
  74490. }
  74491. else if (type == cubicMarker)
  74492. {
  74493. cubicTo (other.data.elements [i],
  74494. other.data.elements [i + 1],
  74495. other.data.elements [i + 2],
  74496. other.data.elements [i + 3],
  74497. other.data.elements [i + 4],
  74498. other.data.elements [i + 5]);
  74499. i += 6;
  74500. }
  74501. else if (type == closeSubPathMarker)
  74502. {
  74503. closeSubPath();
  74504. }
  74505. else
  74506. {
  74507. // something's gone wrong with the element list!
  74508. jassertfalse;
  74509. }
  74510. }
  74511. }
  74512. void Path::addPath (const Path& other,
  74513. const AffineTransform& transformToApply)
  74514. {
  74515. size_t i = 0;
  74516. while (i < other.numElements)
  74517. {
  74518. const float type = other.data.elements [i++];
  74519. if (type == closeSubPathMarker)
  74520. {
  74521. closeSubPath();
  74522. }
  74523. else
  74524. {
  74525. float x = other.data.elements [i++];
  74526. float y = other.data.elements [i++];
  74527. transformToApply.transformPoint (x, y);
  74528. if (type == moveMarker)
  74529. {
  74530. startNewSubPath (x, y);
  74531. }
  74532. else if (type == lineMarker)
  74533. {
  74534. lineTo (x, y);
  74535. }
  74536. else if (type == quadMarker)
  74537. {
  74538. float x2 = other.data.elements [i++];
  74539. float y2 = other.data.elements [i++];
  74540. transformToApply.transformPoint (x2, y2);
  74541. quadraticTo (x, y, x2, y2);
  74542. }
  74543. else if (type == cubicMarker)
  74544. {
  74545. float x2 = other.data.elements [i++];
  74546. float y2 = other.data.elements [i++];
  74547. float x3 = other.data.elements [i++];
  74548. float y3 = other.data.elements [i++];
  74549. transformToApply.transformPoints (x2, y2, x3, y3);
  74550. cubicTo (x, y, x2, y2, x3, y3);
  74551. }
  74552. else
  74553. {
  74554. // something's gone wrong with the element list!
  74555. jassertfalse;
  74556. }
  74557. }
  74558. }
  74559. }
  74560. void Path::applyTransform (const AffineTransform& transform) throw()
  74561. {
  74562. size_t i = 0;
  74563. pathYMin = pathXMin = 0;
  74564. pathYMax = pathXMax = 0;
  74565. bool setMaxMin = false;
  74566. while (i < numElements)
  74567. {
  74568. const float type = data.elements [i++];
  74569. if (type == moveMarker)
  74570. {
  74571. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74572. if (setMaxMin)
  74573. {
  74574. pathXMin = jmin (pathXMin, data.elements [i]);
  74575. pathXMax = jmax (pathXMax, data.elements [i]);
  74576. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74577. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74578. }
  74579. else
  74580. {
  74581. pathXMin = pathXMax = data.elements [i];
  74582. pathYMin = pathYMax = data.elements [i + 1];
  74583. setMaxMin = true;
  74584. }
  74585. i += 2;
  74586. }
  74587. else if (type == lineMarker)
  74588. {
  74589. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74590. pathXMin = jmin (pathXMin, data.elements [i]);
  74591. pathXMax = jmax (pathXMax, data.elements [i]);
  74592. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74593. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74594. i += 2;
  74595. }
  74596. else if (type == quadMarker)
  74597. {
  74598. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74599. data.elements [i + 2], data.elements [i + 3]);
  74600. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74601. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74602. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74603. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74604. i += 4;
  74605. }
  74606. else if (type == cubicMarker)
  74607. {
  74608. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74609. data.elements [i + 2], data.elements [i + 3],
  74610. data.elements [i + 4], data.elements [i + 5]);
  74611. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74612. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74613. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74614. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74615. i += 6;
  74616. }
  74617. }
  74618. }
  74619. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74620. const float w, const float h,
  74621. const bool preserveProportions,
  74622. const Justification& justification) const
  74623. {
  74624. Rectangle<float> bounds (getBounds());
  74625. if (preserveProportions)
  74626. {
  74627. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74628. return AffineTransform::identity;
  74629. float newW, newH;
  74630. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74631. if (srcRatio > h / w)
  74632. {
  74633. newW = h / srcRatio;
  74634. newH = h;
  74635. }
  74636. else
  74637. {
  74638. newW = w;
  74639. newH = w * srcRatio;
  74640. }
  74641. float newXCentre = x;
  74642. float newYCentre = y;
  74643. if (justification.testFlags (Justification::left))
  74644. newXCentre += newW * 0.5f;
  74645. else if (justification.testFlags (Justification::right))
  74646. newXCentre += w - newW * 0.5f;
  74647. else
  74648. newXCentre += w * 0.5f;
  74649. if (justification.testFlags (Justification::top))
  74650. newYCentre += newH * 0.5f;
  74651. else if (justification.testFlags (Justification::bottom))
  74652. newYCentre += h - newH * 0.5f;
  74653. else
  74654. newYCentre += h * 0.5f;
  74655. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74656. bounds.getHeight() * -0.5f - bounds.getY())
  74657. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74658. .translated (newXCentre, newYCentre);
  74659. }
  74660. else
  74661. {
  74662. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74663. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74664. .translated (x, y);
  74665. }
  74666. }
  74667. bool Path::contains (const float x, const float y, const float tolerence) const
  74668. {
  74669. if (x <= pathXMin || x >= pathXMax
  74670. || y <= pathYMin || y >= pathYMax)
  74671. return false;
  74672. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74673. int positiveCrossings = 0;
  74674. int negativeCrossings = 0;
  74675. while (i.next())
  74676. {
  74677. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74678. {
  74679. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74680. if (intersectX <= x)
  74681. {
  74682. if (i.y1 < i.y2)
  74683. ++positiveCrossings;
  74684. else
  74685. ++negativeCrossings;
  74686. }
  74687. }
  74688. }
  74689. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74690. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74691. }
  74692. bool Path::contains (const Point<float>& point, const float tolerence) const
  74693. {
  74694. return contains (point.getX(), point.getY(), tolerence);
  74695. }
  74696. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74697. {
  74698. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74699. Point<float> intersection;
  74700. while (i.next())
  74701. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74702. return true;
  74703. return false;
  74704. }
  74705. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74706. {
  74707. Line<float> result (line);
  74708. const bool startInside = contains (line.getStart());
  74709. const bool endInside = contains (line.getEnd());
  74710. if (startInside == endInside)
  74711. {
  74712. if (keepSectionOutsidePath == startInside)
  74713. result = Line<float>();
  74714. }
  74715. else
  74716. {
  74717. PathFlatteningIterator i (*this, AffineTransform::identity);
  74718. Point<float> intersection;
  74719. while (i.next())
  74720. {
  74721. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74722. {
  74723. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74724. result.setStart (intersection);
  74725. else
  74726. result.setEnd (intersection);
  74727. }
  74728. }
  74729. }
  74730. return result;
  74731. }
  74732. float Path::getLength (const AffineTransform& transform) const
  74733. {
  74734. float length = 0;
  74735. PathFlatteningIterator i (*this, transform);
  74736. while (i.next())
  74737. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74738. return length;
  74739. }
  74740. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74741. {
  74742. PathFlatteningIterator i (*this, transform);
  74743. while (i.next())
  74744. {
  74745. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74746. const float lineLength = line.getLength();
  74747. if (distanceFromStart <= lineLength)
  74748. return line.getPointAlongLine (distanceFromStart);
  74749. distanceFromStart -= lineLength;
  74750. }
  74751. return Point<float> (i.x2, i.y2);
  74752. }
  74753. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74754. const AffineTransform& transform) const
  74755. {
  74756. PathFlatteningIterator i (*this, transform);
  74757. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74758. float length = 0;
  74759. Point<float> pointOnLine;
  74760. while (i.next())
  74761. {
  74762. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74763. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74764. if (distance < bestDistance)
  74765. {
  74766. bestDistance = distance;
  74767. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74768. pointOnPath = pointOnLine;
  74769. }
  74770. length += line.getLength();
  74771. }
  74772. return bestPosition;
  74773. }
  74774. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74775. {
  74776. if (cornerRadius <= 0.01f)
  74777. return *this;
  74778. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74779. size_t n = 0;
  74780. bool lastWasLine = false, firstWasLine = false;
  74781. Path p;
  74782. while (n < numElements)
  74783. {
  74784. const float type = data.elements [n++];
  74785. if (type == moveMarker)
  74786. {
  74787. indexOfPathStart = p.numElements;
  74788. indexOfPathStartThis = n - 1;
  74789. const float x = data.elements [n++];
  74790. const float y = data.elements [n++];
  74791. p.startNewSubPath (x, y);
  74792. lastWasLine = false;
  74793. firstWasLine = (data.elements [n] == lineMarker);
  74794. }
  74795. else if (type == lineMarker || type == closeSubPathMarker)
  74796. {
  74797. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74798. if (type == lineMarker)
  74799. {
  74800. endX = data.elements [n++];
  74801. endY = data.elements [n++];
  74802. if (n > 8)
  74803. {
  74804. startX = data.elements [n - 8];
  74805. startY = data.elements [n - 7];
  74806. joinX = data.elements [n - 5];
  74807. joinY = data.elements [n - 4];
  74808. }
  74809. }
  74810. else
  74811. {
  74812. endX = data.elements [indexOfPathStartThis + 1];
  74813. endY = data.elements [indexOfPathStartThis + 2];
  74814. if (n > 6)
  74815. {
  74816. startX = data.elements [n - 6];
  74817. startY = data.elements [n - 5];
  74818. joinX = data.elements [n - 3];
  74819. joinY = data.elements [n - 2];
  74820. }
  74821. }
  74822. if (lastWasLine)
  74823. {
  74824. const double len1 = juce_hypot (startX - joinX,
  74825. startY - joinY);
  74826. if (len1 > 0)
  74827. {
  74828. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74829. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74830. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74831. }
  74832. const double len2 = juce_hypot (endX - joinX,
  74833. endY - joinY);
  74834. if (len2 > 0)
  74835. {
  74836. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74837. p.quadraticTo (joinX, joinY,
  74838. (float) (joinX + (endX - joinX) * propNeeded),
  74839. (float) (joinY + (endY - joinY) * propNeeded));
  74840. }
  74841. p.lineTo (endX, endY);
  74842. }
  74843. else if (type == lineMarker)
  74844. {
  74845. p.lineTo (endX, endY);
  74846. lastWasLine = true;
  74847. }
  74848. if (type == closeSubPathMarker)
  74849. {
  74850. if (firstWasLine)
  74851. {
  74852. startX = data.elements [n - 3];
  74853. startY = data.elements [n - 2];
  74854. joinX = endX;
  74855. joinY = endY;
  74856. endX = data.elements [indexOfPathStartThis + 4];
  74857. endY = data.elements [indexOfPathStartThis + 5];
  74858. const double len1 = juce_hypot (startX - joinX,
  74859. startY - joinY);
  74860. if (len1 > 0)
  74861. {
  74862. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74863. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74864. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74865. }
  74866. const double len2 = juce_hypot (endX - joinX,
  74867. endY - joinY);
  74868. if (len2 > 0)
  74869. {
  74870. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74871. endX = (float) (joinX + (endX - joinX) * propNeeded);
  74872. endY = (float) (joinY + (endY - joinY) * propNeeded);
  74873. p.quadraticTo (joinX, joinY, endX, endY);
  74874. p.data.elements [indexOfPathStart + 1] = endX;
  74875. p.data.elements [indexOfPathStart + 2] = endY;
  74876. }
  74877. }
  74878. p.closeSubPath();
  74879. }
  74880. }
  74881. else if (type == quadMarker)
  74882. {
  74883. lastWasLine = false;
  74884. const float x1 = data.elements [n++];
  74885. const float y1 = data.elements [n++];
  74886. const float x2 = data.elements [n++];
  74887. const float y2 = data.elements [n++];
  74888. p.quadraticTo (x1, y1, x2, y2);
  74889. }
  74890. else if (type == cubicMarker)
  74891. {
  74892. lastWasLine = false;
  74893. const float x1 = data.elements [n++];
  74894. const float y1 = data.elements [n++];
  74895. const float x2 = data.elements [n++];
  74896. const float y2 = data.elements [n++];
  74897. const float x3 = data.elements [n++];
  74898. const float y3 = data.elements [n++];
  74899. p.cubicTo (x1, y1, x2, y2, x3, y3);
  74900. }
  74901. }
  74902. return p;
  74903. }
  74904. void Path::loadPathFromStream (InputStream& source)
  74905. {
  74906. while (! source.isExhausted())
  74907. {
  74908. switch (source.readByte())
  74909. {
  74910. case 'm':
  74911. {
  74912. const float x = source.readFloat();
  74913. const float y = source.readFloat();
  74914. startNewSubPath (x, y);
  74915. break;
  74916. }
  74917. case 'l':
  74918. {
  74919. const float x = source.readFloat();
  74920. const float y = source.readFloat();
  74921. lineTo (x, y);
  74922. break;
  74923. }
  74924. case 'q':
  74925. {
  74926. const float x1 = source.readFloat();
  74927. const float y1 = source.readFloat();
  74928. const float x2 = source.readFloat();
  74929. const float y2 = source.readFloat();
  74930. quadraticTo (x1, y1, x2, y2);
  74931. break;
  74932. }
  74933. case 'b':
  74934. {
  74935. const float x1 = source.readFloat();
  74936. const float y1 = source.readFloat();
  74937. const float x2 = source.readFloat();
  74938. const float y2 = source.readFloat();
  74939. const float x3 = source.readFloat();
  74940. const float y3 = source.readFloat();
  74941. cubicTo (x1, y1, x2, y2, x3, y3);
  74942. break;
  74943. }
  74944. case 'c':
  74945. closeSubPath();
  74946. break;
  74947. case 'n':
  74948. useNonZeroWinding = true;
  74949. break;
  74950. case 'z':
  74951. useNonZeroWinding = false;
  74952. break;
  74953. case 'e':
  74954. return; // end of path marker
  74955. default:
  74956. jassertfalse; // illegal char in the stream
  74957. break;
  74958. }
  74959. }
  74960. }
  74961. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  74962. {
  74963. MemoryInputStream in (pathData, numberOfBytes, false);
  74964. loadPathFromStream (in);
  74965. }
  74966. void Path::writePathToStream (OutputStream& dest) const
  74967. {
  74968. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  74969. size_t i = 0;
  74970. while (i < numElements)
  74971. {
  74972. const float type = data.elements [i++];
  74973. if (type == moveMarker)
  74974. {
  74975. dest.writeByte ('m');
  74976. dest.writeFloat (data.elements [i++]);
  74977. dest.writeFloat (data.elements [i++]);
  74978. }
  74979. else if (type == lineMarker)
  74980. {
  74981. dest.writeByte ('l');
  74982. dest.writeFloat (data.elements [i++]);
  74983. dest.writeFloat (data.elements [i++]);
  74984. }
  74985. else if (type == quadMarker)
  74986. {
  74987. dest.writeByte ('q');
  74988. dest.writeFloat (data.elements [i++]);
  74989. dest.writeFloat (data.elements [i++]);
  74990. dest.writeFloat (data.elements [i++]);
  74991. dest.writeFloat (data.elements [i++]);
  74992. }
  74993. else if (type == cubicMarker)
  74994. {
  74995. dest.writeByte ('b');
  74996. dest.writeFloat (data.elements [i++]);
  74997. dest.writeFloat (data.elements [i++]);
  74998. dest.writeFloat (data.elements [i++]);
  74999. dest.writeFloat (data.elements [i++]);
  75000. dest.writeFloat (data.elements [i++]);
  75001. dest.writeFloat (data.elements [i++]);
  75002. }
  75003. else if (type == closeSubPathMarker)
  75004. {
  75005. dest.writeByte ('c');
  75006. }
  75007. }
  75008. dest.writeByte ('e'); // marks the end-of-path
  75009. }
  75010. const String Path::toString() const
  75011. {
  75012. MemoryOutputStream s (2048);
  75013. if (! useNonZeroWinding)
  75014. s << 'a';
  75015. size_t i = 0;
  75016. float lastMarker = 0.0f;
  75017. while (i < numElements)
  75018. {
  75019. const float marker = data.elements [i++];
  75020. char markerChar = 0;
  75021. int numCoords = 0;
  75022. if (marker == moveMarker)
  75023. {
  75024. markerChar = 'm';
  75025. numCoords = 2;
  75026. }
  75027. else if (marker == lineMarker)
  75028. {
  75029. markerChar = 'l';
  75030. numCoords = 2;
  75031. }
  75032. else if (marker == quadMarker)
  75033. {
  75034. markerChar = 'q';
  75035. numCoords = 4;
  75036. }
  75037. else if (marker == cubicMarker)
  75038. {
  75039. markerChar = 'c';
  75040. numCoords = 6;
  75041. }
  75042. else
  75043. {
  75044. jassert (marker == closeSubPathMarker);
  75045. markerChar = 'z';
  75046. }
  75047. if (marker != lastMarker)
  75048. {
  75049. if (s.getDataSize() != 0)
  75050. s << ' ';
  75051. s << markerChar;
  75052. lastMarker = marker;
  75053. }
  75054. while (--numCoords >= 0 && i < numElements)
  75055. {
  75056. String coord (data.elements [i++], 3);
  75057. while (coord.endsWithChar ('0') && coord != "0")
  75058. coord = coord.dropLastCharacters (1);
  75059. if (coord.endsWithChar ('.'))
  75060. coord = coord.dropLastCharacters (1);
  75061. if (s.getDataSize() != 0)
  75062. s << ' ';
  75063. s << coord;
  75064. }
  75065. }
  75066. return s.toUTF8();
  75067. }
  75068. void Path::restoreFromString (const String& stringVersion)
  75069. {
  75070. clear();
  75071. setUsingNonZeroWinding (true);
  75072. const juce_wchar* t = stringVersion;
  75073. juce_wchar marker = 'm';
  75074. int numValues = 2;
  75075. float values [6];
  75076. for (;;)
  75077. {
  75078. const String token (PathHelpers::nextToken (t));
  75079. const juce_wchar firstChar = token[0];
  75080. int startNum = 0;
  75081. if (firstChar == 0)
  75082. break;
  75083. if (firstChar == 'm' || firstChar == 'l')
  75084. {
  75085. marker = firstChar;
  75086. numValues = 2;
  75087. }
  75088. else if (firstChar == 'q')
  75089. {
  75090. marker = firstChar;
  75091. numValues = 4;
  75092. }
  75093. else if (firstChar == 'c')
  75094. {
  75095. marker = firstChar;
  75096. numValues = 6;
  75097. }
  75098. else if (firstChar == 'z')
  75099. {
  75100. marker = firstChar;
  75101. numValues = 0;
  75102. }
  75103. else if (firstChar == 'a')
  75104. {
  75105. setUsingNonZeroWinding (false);
  75106. continue;
  75107. }
  75108. else
  75109. {
  75110. ++startNum;
  75111. values [0] = token.getFloatValue();
  75112. }
  75113. for (int i = startNum; i < numValues; ++i)
  75114. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75115. switch (marker)
  75116. {
  75117. case 'm': startNewSubPath (values[0], values[1]); break;
  75118. case 'l': lineTo (values[0], values[1]); break;
  75119. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75120. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75121. case 'z': closeSubPath(); break;
  75122. default: jassertfalse; break; // illegal string format?
  75123. }
  75124. }
  75125. }
  75126. Path::Iterator::Iterator (const Path& path_)
  75127. : path (path_),
  75128. index (0)
  75129. {
  75130. }
  75131. Path::Iterator::~Iterator()
  75132. {
  75133. }
  75134. bool Path::Iterator::next()
  75135. {
  75136. const float* const elements = path.data.elements;
  75137. if (index < path.numElements)
  75138. {
  75139. const float type = elements [index++];
  75140. if (type == moveMarker)
  75141. {
  75142. elementType = startNewSubPath;
  75143. x1 = elements [index++];
  75144. y1 = elements [index++];
  75145. }
  75146. else if (type == lineMarker)
  75147. {
  75148. elementType = lineTo;
  75149. x1 = elements [index++];
  75150. y1 = elements [index++];
  75151. }
  75152. else if (type == quadMarker)
  75153. {
  75154. elementType = quadraticTo;
  75155. x1 = elements [index++];
  75156. y1 = elements [index++];
  75157. x2 = elements [index++];
  75158. y2 = elements [index++];
  75159. }
  75160. else if (type == cubicMarker)
  75161. {
  75162. elementType = cubicTo;
  75163. x1 = elements [index++];
  75164. y1 = elements [index++];
  75165. x2 = elements [index++];
  75166. y2 = elements [index++];
  75167. x3 = elements [index++];
  75168. y3 = elements [index++];
  75169. }
  75170. else if (type == closeSubPathMarker)
  75171. {
  75172. elementType = closePath;
  75173. }
  75174. return true;
  75175. }
  75176. return false;
  75177. }
  75178. END_JUCE_NAMESPACE
  75179. /*** End of inlined file: juce_Path.cpp ***/
  75180. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75181. BEGIN_JUCE_NAMESPACE
  75182. #if JUCE_MSVC && JUCE_DEBUG
  75183. #pragma optimize ("t", on)
  75184. #endif
  75185. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75186. const AffineTransform& transform_,
  75187. float tolerence_)
  75188. : x2 (0),
  75189. y2 (0),
  75190. closesSubPath (false),
  75191. subPathIndex (-1),
  75192. path (path_),
  75193. transform (transform_),
  75194. points (path_.data.elements),
  75195. tolerence (tolerence_ * tolerence_),
  75196. subPathCloseX (0),
  75197. subPathCloseY (0),
  75198. isIdentityTransform (transform_.isIdentity()),
  75199. stackBase (32),
  75200. index (0),
  75201. stackSize (32)
  75202. {
  75203. stackPos = stackBase;
  75204. }
  75205. PathFlatteningIterator::~PathFlatteningIterator()
  75206. {
  75207. }
  75208. bool PathFlatteningIterator::next()
  75209. {
  75210. x1 = x2;
  75211. y1 = y2;
  75212. float x3 = 0;
  75213. float y3 = 0;
  75214. float x4 = 0;
  75215. float y4 = 0;
  75216. float type;
  75217. for (;;)
  75218. {
  75219. if (stackPos == stackBase)
  75220. {
  75221. if (index >= path.numElements)
  75222. {
  75223. return false;
  75224. }
  75225. else
  75226. {
  75227. type = points [index++];
  75228. if (type != Path::closeSubPathMarker)
  75229. {
  75230. x2 = points [index++];
  75231. y2 = points [index++];
  75232. if (type == Path::quadMarker)
  75233. {
  75234. x3 = points [index++];
  75235. y3 = points [index++];
  75236. if (! isIdentityTransform)
  75237. transform.transformPoints (x2, y2, x3, y3);
  75238. }
  75239. else if (type == Path::cubicMarker)
  75240. {
  75241. x3 = points [index++];
  75242. y3 = points [index++];
  75243. x4 = points [index++];
  75244. y4 = points [index++];
  75245. if (! isIdentityTransform)
  75246. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75247. }
  75248. else
  75249. {
  75250. if (! isIdentityTransform)
  75251. transform.transformPoint (x2, y2);
  75252. }
  75253. }
  75254. }
  75255. }
  75256. else
  75257. {
  75258. type = *--stackPos;
  75259. if (type != Path::closeSubPathMarker)
  75260. {
  75261. x2 = *--stackPos;
  75262. y2 = *--stackPos;
  75263. if (type == Path::quadMarker)
  75264. {
  75265. x3 = *--stackPos;
  75266. y3 = *--stackPos;
  75267. }
  75268. else if (type == Path::cubicMarker)
  75269. {
  75270. x3 = *--stackPos;
  75271. y3 = *--stackPos;
  75272. x4 = *--stackPos;
  75273. y4 = *--stackPos;
  75274. }
  75275. }
  75276. }
  75277. if (type == Path::lineMarker)
  75278. {
  75279. ++subPathIndex;
  75280. closesSubPath = (stackPos == stackBase)
  75281. && (index < path.numElements)
  75282. && (points [index] == Path::closeSubPathMarker)
  75283. && x2 == subPathCloseX
  75284. && y2 == subPathCloseY;
  75285. return true;
  75286. }
  75287. else if (type == Path::quadMarker)
  75288. {
  75289. const size_t offset = (size_t) (stackPos - stackBase);
  75290. if (offset >= stackSize - 10)
  75291. {
  75292. stackSize <<= 1;
  75293. stackBase.realloc (stackSize);
  75294. stackPos = stackBase + offset;
  75295. }
  75296. const float dx1 = x1 - x2;
  75297. const float dy1 = y1 - y2;
  75298. const float dx2 = x2 - x3;
  75299. const float dy2 = y2 - y3;
  75300. const float m1x = (x1 + x2) * 0.5f;
  75301. const float m1y = (y1 + y2) * 0.5f;
  75302. const float m2x = (x2 + x3) * 0.5f;
  75303. const float m2y = (y2 + y3) * 0.5f;
  75304. const float m3x = (m1x + m2x) * 0.5f;
  75305. const float m3y = (m1y + m2y) * 0.5f;
  75306. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75307. {
  75308. *stackPos++ = y3;
  75309. *stackPos++ = x3;
  75310. *stackPos++ = m2y;
  75311. *stackPos++ = m2x;
  75312. *stackPos++ = Path::quadMarker;
  75313. *stackPos++ = m3y;
  75314. *stackPos++ = m3x;
  75315. *stackPos++ = m1y;
  75316. *stackPos++ = m1x;
  75317. *stackPos++ = Path::quadMarker;
  75318. }
  75319. else
  75320. {
  75321. *stackPos++ = y3;
  75322. *stackPos++ = x3;
  75323. *stackPos++ = Path::lineMarker;
  75324. *stackPos++ = m3y;
  75325. *stackPos++ = m3x;
  75326. *stackPos++ = Path::lineMarker;
  75327. }
  75328. jassert (stackPos < stackBase + stackSize);
  75329. }
  75330. else if (type == Path::cubicMarker)
  75331. {
  75332. const size_t offset = (size_t) (stackPos - stackBase);
  75333. if (offset >= stackSize - 16)
  75334. {
  75335. stackSize <<= 1;
  75336. stackBase.realloc (stackSize);
  75337. stackPos = stackBase + offset;
  75338. }
  75339. const float dx1 = x1 - x2;
  75340. const float dy1 = y1 - y2;
  75341. const float dx2 = x2 - x3;
  75342. const float dy2 = y2 - y3;
  75343. const float dx3 = x3 - x4;
  75344. const float dy3 = y3 - y4;
  75345. const float m1x = (x1 + x2) * 0.5f;
  75346. const float m1y = (y1 + y2) * 0.5f;
  75347. const float m2x = (x3 + x2) * 0.5f;
  75348. const float m2y = (y3 + y2) * 0.5f;
  75349. const float m3x = (x3 + x4) * 0.5f;
  75350. const float m3y = (y3 + y4) * 0.5f;
  75351. const float m4x = (m1x + m2x) * 0.5f;
  75352. const float m4y = (m1y + m2y) * 0.5f;
  75353. const float m5x = (m3x + m2x) * 0.5f;
  75354. const float m5y = (m3y + m2y) * 0.5f;
  75355. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75356. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75357. {
  75358. *stackPos++ = y4;
  75359. *stackPos++ = x4;
  75360. *stackPos++ = m3y;
  75361. *stackPos++ = m3x;
  75362. *stackPos++ = m5y;
  75363. *stackPos++ = m5x;
  75364. *stackPos++ = Path::cubicMarker;
  75365. *stackPos++ = (m4y + m5y) * 0.5f;
  75366. *stackPos++ = (m4x + m5x) * 0.5f;
  75367. *stackPos++ = m4y;
  75368. *stackPos++ = m4x;
  75369. *stackPos++ = m1y;
  75370. *stackPos++ = m1x;
  75371. *stackPos++ = Path::cubicMarker;
  75372. }
  75373. else
  75374. {
  75375. *stackPos++ = y4;
  75376. *stackPos++ = x4;
  75377. *stackPos++ = Path::lineMarker;
  75378. *stackPos++ = m5y;
  75379. *stackPos++ = m5x;
  75380. *stackPos++ = Path::lineMarker;
  75381. *stackPos++ = m4y;
  75382. *stackPos++ = m4x;
  75383. *stackPos++ = Path::lineMarker;
  75384. }
  75385. }
  75386. else if (type == Path::closeSubPathMarker)
  75387. {
  75388. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75389. {
  75390. x1 = x2;
  75391. y1 = y2;
  75392. x2 = subPathCloseX;
  75393. y2 = subPathCloseY;
  75394. closesSubPath = true;
  75395. return true;
  75396. }
  75397. }
  75398. else
  75399. {
  75400. jassert (type == Path::moveMarker);
  75401. subPathIndex = -1;
  75402. subPathCloseX = x1 = x2;
  75403. subPathCloseY = y1 = y2;
  75404. }
  75405. }
  75406. }
  75407. #if JUCE_MSVC && JUCE_DEBUG
  75408. #pragma optimize ("", on) // resets optimisations to the project defaults
  75409. #endif
  75410. END_JUCE_NAMESPACE
  75411. /*** End of inlined file: juce_PathIterator.cpp ***/
  75412. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75413. BEGIN_JUCE_NAMESPACE
  75414. PathStrokeType::PathStrokeType (const float strokeThickness,
  75415. const JointStyle jointStyle_,
  75416. const EndCapStyle endStyle_) throw()
  75417. : thickness (strokeThickness),
  75418. jointStyle (jointStyle_),
  75419. endStyle (endStyle_)
  75420. {
  75421. }
  75422. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75423. : thickness (other.thickness),
  75424. jointStyle (other.jointStyle),
  75425. endStyle (other.endStyle)
  75426. {
  75427. }
  75428. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75429. {
  75430. thickness = other.thickness;
  75431. jointStyle = other.jointStyle;
  75432. endStyle = other.endStyle;
  75433. return *this;
  75434. }
  75435. PathStrokeType::~PathStrokeType() throw()
  75436. {
  75437. }
  75438. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75439. {
  75440. return thickness == other.thickness
  75441. && jointStyle == other.jointStyle
  75442. && endStyle == other.endStyle;
  75443. }
  75444. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75445. {
  75446. return ! operator== (other);
  75447. }
  75448. namespace PathStrokeHelpers
  75449. {
  75450. bool lineIntersection (const float x1, const float y1,
  75451. const float x2, const float y2,
  75452. const float x3, const float y3,
  75453. const float x4, const float y4,
  75454. float& intersectionX,
  75455. float& intersectionY,
  75456. float& distanceBeyondLine1EndSquared) throw()
  75457. {
  75458. if (x2 != x3 || y2 != y3)
  75459. {
  75460. const float dx1 = x2 - x1;
  75461. const float dy1 = y2 - y1;
  75462. const float dx2 = x4 - x3;
  75463. const float dy2 = y4 - y3;
  75464. const float divisor = dx1 * dy2 - dx2 * dy1;
  75465. if (divisor == 0)
  75466. {
  75467. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75468. {
  75469. if (dy1 == 0 && dy2 != 0)
  75470. {
  75471. const float along = (y1 - y3) / dy2;
  75472. intersectionX = x3 + along * dx2;
  75473. intersectionY = y1;
  75474. distanceBeyondLine1EndSquared = intersectionX - x2;
  75475. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75476. if ((x2 > x1) == (intersectionX < x2))
  75477. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75478. return along >= 0 && along <= 1.0f;
  75479. }
  75480. else if (dy2 == 0 && dy1 != 0)
  75481. {
  75482. const float along = (y3 - y1) / dy1;
  75483. intersectionX = x1 + along * dx1;
  75484. intersectionY = y3;
  75485. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75486. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75487. if (along < 1.0f)
  75488. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75489. return along >= 0 && along <= 1.0f;
  75490. }
  75491. else if (dx1 == 0 && dx2 != 0)
  75492. {
  75493. const float along = (x1 - x3) / dx2;
  75494. intersectionX = x1;
  75495. intersectionY = y3 + along * dy2;
  75496. distanceBeyondLine1EndSquared = intersectionY - y2;
  75497. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75498. if ((y2 > y1) == (intersectionY < y2))
  75499. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75500. return along >= 0 && along <= 1.0f;
  75501. }
  75502. else if (dx2 == 0 && dx1 != 0)
  75503. {
  75504. const float along = (x3 - x1) / dx1;
  75505. intersectionX = x3;
  75506. intersectionY = y1 + along * dy1;
  75507. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75508. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75509. if (along < 1.0f)
  75510. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75511. return along >= 0 && along <= 1.0f;
  75512. }
  75513. }
  75514. intersectionX = 0.5f * (x2 + x3);
  75515. intersectionY = 0.5f * (y2 + y3);
  75516. distanceBeyondLine1EndSquared = 0.0f;
  75517. return false;
  75518. }
  75519. else
  75520. {
  75521. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75522. intersectionX = x1 + along1 * dx1;
  75523. intersectionY = y1 + along1 * dy1;
  75524. if (along1 >= 0 && along1 <= 1.0f)
  75525. {
  75526. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75527. if (along2 >= 0 && along2 <= divisor)
  75528. {
  75529. distanceBeyondLine1EndSquared = 0.0f;
  75530. return true;
  75531. }
  75532. }
  75533. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75534. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75535. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75536. if (along1 < 1.0f)
  75537. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75538. return false;
  75539. }
  75540. }
  75541. intersectionX = x2;
  75542. intersectionY = y2;
  75543. distanceBeyondLine1EndSquared = 0.0f;
  75544. return true;
  75545. }
  75546. void addEdgeAndJoint (Path& destPath,
  75547. const PathStrokeType::JointStyle style,
  75548. const float maxMiterExtensionSquared, const float width,
  75549. const float x1, const float y1,
  75550. const float x2, const float y2,
  75551. const float x3, const float y3,
  75552. const float x4, const float y4,
  75553. const float midX, const float midY)
  75554. {
  75555. if (style == PathStrokeType::beveled
  75556. || (x3 == x4 && y3 == y4)
  75557. || (x1 == x2 && y1 == y2))
  75558. {
  75559. destPath.lineTo (x2, y2);
  75560. destPath.lineTo (x3, y3);
  75561. }
  75562. else
  75563. {
  75564. float jx, jy, distanceBeyondLine1EndSquared;
  75565. // if they intersect, use this point..
  75566. if (lineIntersection (x1, y1, x2, y2,
  75567. x3, y3, x4, y4,
  75568. jx, jy, distanceBeyondLine1EndSquared))
  75569. {
  75570. destPath.lineTo (jx, jy);
  75571. }
  75572. else
  75573. {
  75574. if (style == PathStrokeType::mitered)
  75575. {
  75576. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75577. && distanceBeyondLine1EndSquared > 0.0f)
  75578. {
  75579. destPath.lineTo (jx, jy);
  75580. }
  75581. else
  75582. {
  75583. // the end sticks out too far, so just use a blunt joint
  75584. destPath.lineTo (x2, y2);
  75585. destPath.lineTo (x3, y3);
  75586. }
  75587. }
  75588. else
  75589. {
  75590. // curved joints
  75591. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75592. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75593. const float angleIncrement = 0.1f;
  75594. destPath.lineTo (x2, y2);
  75595. if (std::abs (angle1 - angle2) > angleIncrement)
  75596. {
  75597. if (angle2 > angle1 + float_Pi
  75598. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75599. {
  75600. if (angle2 > angle1)
  75601. angle2 -= float_Pi * 2.0f;
  75602. jassert (angle1 <= angle2 + float_Pi);
  75603. angle1 -= angleIncrement;
  75604. while (angle1 > angle2)
  75605. {
  75606. destPath.lineTo (midX + width * std::sin (angle1),
  75607. midY + width * std::cos (angle1));
  75608. angle1 -= angleIncrement;
  75609. }
  75610. }
  75611. else
  75612. {
  75613. if (angle1 > angle2)
  75614. angle1 -= float_Pi * 2.0f;
  75615. jassert (angle1 >= angle2 - float_Pi);
  75616. angle1 += angleIncrement;
  75617. while (angle1 < angle2)
  75618. {
  75619. destPath.lineTo (midX + width * std::sin (angle1),
  75620. midY + width * std::cos (angle1));
  75621. angle1 += angleIncrement;
  75622. }
  75623. }
  75624. }
  75625. destPath.lineTo (x3, y3);
  75626. }
  75627. }
  75628. }
  75629. }
  75630. void addLineEnd (Path& destPath,
  75631. const PathStrokeType::EndCapStyle style,
  75632. const float x1, const float y1,
  75633. const float x2, const float y2,
  75634. const float width)
  75635. {
  75636. if (style == PathStrokeType::butt)
  75637. {
  75638. destPath.lineTo (x2, y2);
  75639. }
  75640. else
  75641. {
  75642. float offx1, offy1, offx2, offy2;
  75643. float dx = x2 - x1;
  75644. float dy = y2 - y1;
  75645. const float len = juce_hypotf (dx, dy);
  75646. if (len == 0)
  75647. {
  75648. offx1 = offx2 = x1;
  75649. offy1 = offy2 = y1;
  75650. }
  75651. else
  75652. {
  75653. const float offset = width / len;
  75654. dx *= offset;
  75655. dy *= offset;
  75656. offx1 = x1 + dy;
  75657. offy1 = y1 - dx;
  75658. offx2 = x2 + dy;
  75659. offy2 = y2 - dx;
  75660. }
  75661. if (style == PathStrokeType::square)
  75662. {
  75663. // sqaure ends
  75664. destPath.lineTo (offx1, offy1);
  75665. destPath.lineTo (offx2, offy2);
  75666. destPath.lineTo (x2, y2);
  75667. }
  75668. else
  75669. {
  75670. // rounded ends
  75671. const float midx = (offx1 + offx2) * 0.5f;
  75672. const float midy = (offy1 + offy2) * 0.5f;
  75673. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75674. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75675. midx, midy);
  75676. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75677. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75678. x2, y2);
  75679. }
  75680. }
  75681. }
  75682. struct Arrowhead
  75683. {
  75684. float startWidth, startLength;
  75685. float endWidth, endLength;
  75686. };
  75687. void addArrowhead (Path& destPath,
  75688. const float x1, const float y1,
  75689. const float x2, const float y2,
  75690. const float tipX, const float tipY,
  75691. const float width,
  75692. const float arrowheadWidth)
  75693. {
  75694. Line<float> line (x1, y1, x2, y2);
  75695. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75696. destPath.lineTo (tipX, tipY);
  75697. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75698. destPath.lineTo (x2, y2);
  75699. }
  75700. struct LineSection
  75701. {
  75702. float x1, y1, x2, y2; // original line
  75703. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75704. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75705. };
  75706. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75707. {
  75708. while (amountAtEnd > 0 && subPath.size() > 0)
  75709. {
  75710. LineSection& l = subPath.getReference (subPath.size() - 1);
  75711. float dx = l.rx2 - l.rx1;
  75712. float dy = l.ry2 - l.ry1;
  75713. const float len = juce_hypotf (dx, dy);
  75714. if (len <= amountAtEnd && subPath.size() > 1)
  75715. {
  75716. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75717. prev.x2 = l.x2;
  75718. prev.y2 = l.y2;
  75719. subPath.removeLast();
  75720. amountAtEnd -= len;
  75721. }
  75722. else
  75723. {
  75724. const float prop = jmin (0.9999f, amountAtEnd / len);
  75725. dx *= prop;
  75726. dy *= prop;
  75727. l.rx1 += dx;
  75728. l.ry1 += dy;
  75729. l.lx2 += dx;
  75730. l.ly2 += dy;
  75731. break;
  75732. }
  75733. }
  75734. while (amountAtStart > 0 && subPath.size() > 0)
  75735. {
  75736. LineSection& l = subPath.getReference (0);
  75737. float dx = l.rx2 - l.rx1;
  75738. float dy = l.ry2 - l.ry1;
  75739. const float len = juce_hypotf (dx, dy);
  75740. if (len <= amountAtStart && subPath.size() > 1)
  75741. {
  75742. LineSection& next = subPath.getReference (1);
  75743. next.x1 = l.x1;
  75744. next.y1 = l.y1;
  75745. subPath.remove (0);
  75746. amountAtStart -= len;
  75747. }
  75748. else
  75749. {
  75750. const float prop = jmin (0.9999f, amountAtStart / len);
  75751. dx *= prop;
  75752. dy *= prop;
  75753. l.rx2 -= dx;
  75754. l.ry2 -= dy;
  75755. l.lx1 -= dx;
  75756. l.ly1 -= dy;
  75757. break;
  75758. }
  75759. }
  75760. }
  75761. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75762. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75763. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75764. const Arrowhead* const arrowhead)
  75765. {
  75766. jassert (subPath.size() > 0);
  75767. if (arrowhead != 0)
  75768. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75769. const LineSection& firstLine = subPath.getReference (0);
  75770. float lastX1 = firstLine.lx1;
  75771. float lastY1 = firstLine.ly1;
  75772. float lastX2 = firstLine.lx2;
  75773. float lastY2 = firstLine.ly2;
  75774. if (isClosed)
  75775. {
  75776. destPath.startNewSubPath (lastX1, lastY1);
  75777. }
  75778. else
  75779. {
  75780. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75781. if (arrowhead != 0)
  75782. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75783. width, arrowhead->startWidth);
  75784. else
  75785. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75786. }
  75787. int i;
  75788. for (i = 1; i < subPath.size(); ++i)
  75789. {
  75790. const LineSection& l = subPath.getReference (i);
  75791. addEdgeAndJoint (destPath, jointStyle,
  75792. maxMiterExtensionSquared, width,
  75793. lastX1, lastY1, lastX2, lastY2,
  75794. l.lx1, l.ly1, l.lx2, l.ly2,
  75795. l.x1, l.y1);
  75796. lastX1 = l.lx1;
  75797. lastY1 = l.ly1;
  75798. lastX2 = l.lx2;
  75799. lastY2 = l.ly2;
  75800. }
  75801. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75802. if (isClosed)
  75803. {
  75804. const LineSection& l = subPath.getReference (0);
  75805. addEdgeAndJoint (destPath, jointStyle,
  75806. maxMiterExtensionSquared, width,
  75807. lastX1, lastY1, lastX2, lastY2,
  75808. l.lx1, l.ly1, l.lx2, l.ly2,
  75809. l.x1, l.y1);
  75810. destPath.closeSubPath();
  75811. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75812. }
  75813. else
  75814. {
  75815. destPath.lineTo (lastX2, lastY2);
  75816. if (arrowhead != 0)
  75817. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75818. width, arrowhead->endWidth);
  75819. else
  75820. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75821. }
  75822. lastX1 = lastLine.rx1;
  75823. lastY1 = lastLine.ry1;
  75824. lastX2 = lastLine.rx2;
  75825. lastY2 = lastLine.ry2;
  75826. for (i = subPath.size() - 1; --i >= 0;)
  75827. {
  75828. const LineSection& l = subPath.getReference (i);
  75829. addEdgeAndJoint (destPath, jointStyle,
  75830. maxMiterExtensionSquared, width,
  75831. lastX1, lastY1, lastX2, lastY2,
  75832. l.rx1, l.ry1, l.rx2, l.ry2,
  75833. l.x2, l.y2);
  75834. lastX1 = l.rx1;
  75835. lastY1 = l.ry1;
  75836. lastX2 = l.rx2;
  75837. lastY2 = l.ry2;
  75838. }
  75839. if (isClosed)
  75840. {
  75841. addEdgeAndJoint (destPath, jointStyle,
  75842. maxMiterExtensionSquared, width,
  75843. lastX1, lastY1, lastX2, lastY2,
  75844. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75845. lastLine.x2, lastLine.y2);
  75846. }
  75847. else
  75848. {
  75849. // do the last line
  75850. destPath.lineTo (lastX2, lastY2);
  75851. }
  75852. destPath.closeSubPath();
  75853. }
  75854. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75855. const PathStrokeType::EndCapStyle endStyle,
  75856. Path& destPath, const Path& source,
  75857. const AffineTransform& transform,
  75858. const float extraAccuracy, const Arrowhead* const arrowhead)
  75859. {
  75860. if (thickness <= 0)
  75861. {
  75862. destPath.clear();
  75863. return;
  75864. }
  75865. const Path* sourcePath = &source;
  75866. Path temp;
  75867. if (sourcePath == &destPath)
  75868. {
  75869. destPath.swapWithPath (temp);
  75870. sourcePath = &temp;
  75871. }
  75872. else
  75873. {
  75874. destPath.clear();
  75875. }
  75876. destPath.setUsingNonZeroWinding (true);
  75877. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  75878. const float width = 0.5f * thickness;
  75879. // Iterate the path, creating a list of the
  75880. // left/right-hand lines along either side of it...
  75881. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  75882. Array <LineSection> subPath;
  75883. subPath.ensureStorageAllocated (512);
  75884. LineSection l;
  75885. l.x1 = 0;
  75886. l.y1 = 0;
  75887. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  75888. while (it.next())
  75889. {
  75890. if (it.subPathIndex == 0)
  75891. {
  75892. if (subPath.size() > 0)
  75893. {
  75894. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75895. subPath.clearQuick();
  75896. }
  75897. l.x1 = it.x1;
  75898. l.y1 = it.y1;
  75899. }
  75900. l.x2 = it.x2;
  75901. l.y2 = it.y2;
  75902. float dx = l.x2 - l.x1;
  75903. float dy = l.y2 - l.y1;
  75904. const float hypotSquared = dx*dx + dy*dy;
  75905. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  75906. {
  75907. const float len = std::sqrt (hypotSquared);
  75908. if (len == 0)
  75909. {
  75910. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  75911. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  75912. }
  75913. else
  75914. {
  75915. const float offset = width / len;
  75916. dx *= offset;
  75917. dy *= offset;
  75918. l.rx2 = l.x1 - dy;
  75919. l.ry2 = l.y1 + dx;
  75920. l.lx1 = l.x1 + dy;
  75921. l.ly1 = l.y1 - dx;
  75922. l.lx2 = l.x2 + dy;
  75923. l.ly2 = l.y2 - dx;
  75924. l.rx1 = l.x2 - dy;
  75925. l.ry1 = l.y2 + dx;
  75926. }
  75927. subPath.add (l);
  75928. if (it.closesSubPath)
  75929. {
  75930. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75931. subPath.clearQuick();
  75932. }
  75933. else
  75934. {
  75935. l.x1 = it.x2;
  75936. l.y1 = it.y2;
  75937. }
  75938. }
  75939. }
  75940. if (subPath.size() > 0)
  75941. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75942. }
  75943. }
  75944. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  75945. const AffineTransform& transform, const float extraAccuracy) const
  75946. {
  75947. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  75948. transform, extraAccuracy, 0);
  75949. }
  75950. void PathStrokeType::createDashedStroke (Path& destPath,
  75951. const Path& sourcePath,
  75952. const float* dashLengths,
  75953. int numDashLengths,
  75954. const AffineTransform& transform,
  75955. const float extraAccuracy) const
  75956. {
  75957. if (thickness <= 0)
  75958. return;
  75959. // this should really be an even number..
  75960. jassert ((numDashLengths & 1) == 0);
  75961. Path newDestPath;
  75962. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  75963. bool first = true;
  75964. int dashNum = 0;
  75965. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  75966. float dx = 0.0f, dy = 0.0f;
  75967. for (;;)
  75968. {
  75969. const bool isSolid = ((dashNum & 1) == 0);
  75970. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  75971. jassert (dashLen > 0); // must be a positive increment!
  75972. if (dashLen <= 0)
  75973. break;
  75974. pos += dashLen;
  75975. while (pos > lineEndPos)
  75976. {
  75977. if (! it.next())
  75978. {
  75979. if (isSolid && ! first)
  75980. newDestPath.lineTo (it.x2, it.y2);
  75981. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  75982. return;
  75983. }
  75984. if (isSolid && ! first)
  75985. newDestPath.lineTo (it.x1, it.y1);
  75986. else
  75987. newDestPath.startNewSubPath (it.x1, it.y1);
  75988. dx = it.x2 - it.x1;
  75989. dy = it.y2 - it.y1;
  75990. lineLen = juce_hypotf (dx, dy);
  75991. lineEndPos += lineLen;
  75992. first = it.closesSubPath;
  75993. }
  75994. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  75995. if (isSolid)
  75996. newDestPath.lineTo (it.x1 + dx * alpha,
  75997. it.y1 + dy * alpha);
  75998. else
  75999. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76000. it.y1 + dy * alpha);
  76001. }
  76002. }
  76003. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76004. const Path& sourcePath,
  76005. const float arrowheadStartWidth, const float arrowheadStartLength,
  76006. const float arrowheadEndWidth, const float arrowheadEndLength,
  76007. const AffineTransform& transform,
  76008. const float extraAccuracy) const
  76009. {
  76010. PathStrokeHelpers::Arrowhead head;
  76011. head.startWidth = arrowheadStartWidth;
  76012. head.startLength = arrowheadStartLength;
  76013. head.endWidth = arrowheadEndWidth;
  76014. head.endLength = arrowheadEndLength;
  76015. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76016. destPath, sourcePath, transform, extraAccuracy, &head);
  76017. }
  76018. END_JUCE_NAMESPACE
  76019. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76020. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76021. BEGIN_JUCE_NAMESPACE
  76022. PositionedRectangle::PositionedRectangle() throw()
  76023. : x (0.0),
  76024. y (0.0),
  76025. w (0.0),
  76026. h (0.0),
  76027. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76028. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76029. wMode (absoluteSize),
  76030. hMode (absoluteSize)
  76031. {
  76032. }
  76033. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76034. : x (other.x),
  76035. y (other.y),
  76036. w (other.w),
  76037. h (other.h),
  76038. xMode (other.xMode),
  76039. yMode (other.yMode),
  76040. wMode (other.wMode),
  76041. hMode (other.hMode)
  76042. {
  76043. }
  76044. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76045. {
  76046. x = other.x;
  76047. y = other.y;
  76048. w = other.w;
  76049. h = other.h;
  76050. xMode = other.xMode;
  76051. yMode = other.yMode;
  76052. wMode = other.wMode;
  76053. hMode = other.hMode;
  76054. return *this;
  76055. }
  76056. PositionedRectangle::~PositionedRectangle() throw()
  76057. {
  76058. }
  76059. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76060. {
  76061. return x == other.x
  76062. && y == other.y
  76063. && w == other.w
  76064. && h == other.h
  76065. && xMode == other.xMode
  76066. && yMode == other.yMode
  76067. && wMode == other.wMode
  76068. && hMode == other.hMode;
  76069. }
  76070. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76071. {
  76072. return ! operator== (other);
  76073. }
  76074. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76075. {
  76076. StringArray tokens;
  76077. tokens.addTokens (stringVersion, false);
  76078. decodePosString (tokens [0], xMode, x);
  76079. decodePosString (tokens [1], yMode, y);
  76080. decodeSizeString (tokens [2], wMode, w);
  76081. decodeSizeString (tokens [3], hMode, h);
  76082. }
  76083. const String PositionedRectangle::toString() const throw()
  76084. {
  76085. String s;
  76086. s.preallocateStorage (12);
  76087. addPosDescription (s, xMode, x);
  76088. s << ' ';
  76089. addPosDescription (s, yMode, y);
  76090. s << ' ';
  76091. addSizeDescription (s, wMode, w);
  76092. s << ' ';
  76093. addSizeDescription (s, hMode, h);
  76094. return s;
  76095. }
  76096. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76097. {
  76098. jassert (! target.isEmpty());
  76099. double x_, y_, w_, h_;
  76100. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76101. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76102. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76103. roundToInt (w_), roundToInt (h_));
  76104. }
  76105. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76106. double& x_, double& y_,
  76107. double& w_, double& h_) const throw()
  76108. {
  76109. jassert (! target.isEmpty());
  76110. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76111. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76112. }
  76113. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76114. {
  76115. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76116. }
  76117. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76118. const Rectangle<int>& target) throw()
  76119. {
  76120. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76121. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76122. }
  76123. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76124. const double newW, const double newH,
  76125. const Rectangle<int>& target) throw()
  76126. {
  76127. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76128. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76129. }
  76130. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76131. {
  76132. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76133. updateFrom (comp.getBounds(), Rectangle<int>());
  76134. else
  76135. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76136. }
  76137. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76138. {
  76139. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76140. }
  76141. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76142. {
  76143. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76144. | absoluteFromParentBottomRight
  76145. | absoluteFromParentCentre
  76146. | proportionOfParentSize));
  76147. }
  76148. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76149. {
  76150. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76151. }
  76152. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76153. {
  76154. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76155. | absoluteFromParentBottomRight
  76156. | absoluteFromParentCentre
  76157. | proportionOfParentSize));
  76158. }
  76159. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76160. {
  76161. return (SizeMode) wMode;
  76162. }
  76163. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76164. {
  76165. return (SizeMode) hMode;
  76166. }
  76167. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76168. const PositionMode xMode_,
  76169. const AnchorPoint yAnchor,
  76170. const PositionMode yMode_,
  76171. const SizeMode widthMode,
  76172. const SizeMode heightMode,
  76173. const Rectangle<int>& target) throw()
  76174. {
  76175. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76176. {
  76177. double tx, tw;
  76178. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76179. xMode = (uint8) (xAnchor | xMode_);
  76180. wMode = (uint8) widthMode;
  76181. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76182. }
  76183. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76184. {
  76185. double ty, th;
  76186. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76187. yMode = (uint8) (yAnchor | yMode_);
  76188. hMode = (uint8) heightMode;
  76189. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76190. }
  76191. }
  76192. bool PositionedRectangle::isPositionAbsolute() const throw()
  76193. {
  76194. return xMode == absoluteFromParentTopLeft
  76195. && yMode == absoluteFromParentTopLeft
  76196. && wMode == absoluteSize
  76197. && hMode == absoluteSize;
  76198. }
  76199. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76200. {
  76201. if ((mode & proportionOfParentSize) != 0)
  76202. {
  76203. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76204. }
  76205. else
  76206. {
  76207. s << (roundToInt (value * 100.0) / 100.0);
  76208. if ((mode & absoluteFromParentBottomRight) != 0)
  76209. s << 'R';
  76210. else if ((mode & absoluteFromParentCentre) != 0)
  76211. s << 'C';
  76212. }
  76213. if ((mode & anchorAtRightOrBottom) != 0)
  76214. s << 'r';
  76215. else if ((mode & anchorAtCentre) != 0)
  76216. s << 'c';
  76217. }
  76218. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76219. {
  76220. if (mode == proportionalSize)
  76221. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76222. else if (mode == parentSizeMinusAbsolute)
  76223. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76224. else
  76225. s << (roundToInt (value * 100.0) / 100.0);
  76226. }
  76227. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76228. {
  76229. if (s.containsChar ('r'))
  76230. mode = anchorAtRightOrBottom;
  76231. else if (s.containsChar ('c'))
  76232. mode = anchorAtCentre;
  76233. else
  76234. mode = anchorAtLeftOrTop;
  76235. if (s.containsChar ('%'))
  76236. {
  76237. mode |= proportionOfParentSize;
  76238. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76239. }
  76240. else
  76241. {
  76242. if (s.containsChar ('R'))
  76243. mode |= absoluteFromParentBottomRight;
  76244. else if (s.containsChar ('C'))
  76245. mode |= absoluteFromParentCentre;
  76246. else
  76247. mode |= absoluteFromParentTopLeft;
  76248. value = s.removeCharacters ("rcRC").getDoubleValue();
  76249. }
  76250. }
  76251. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76252. {
  76253. if (s.containsChar ('%'))
  76254. {
  76255. mode = proportionalSize;
  76256. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76257. }
  76258. else if (s.containsChar ('M'))
  76259. {
  76260. mode = parentSizeMinusAbsolute;
  76261. value = s.getDoubleValue();
  76262. }
  76263. else
  76264. {
  76265. mode = absoluteSize;
  76266. value = s.getDoubleValue();
  76267. }
  76268. }
  76269. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76270. const double x_, const double w_,
  76271. const uint8 xMode_, const uint8 wMode_,
  76272. const int parentPos,
  76273. const int parentSize) const throw()
  76274. {
  76275. if (wMode_ == proportionalSize)
  76276. wOut = roundToInt (w_ * parentSize);
  76277. else if (wMode_ == parentSizeMinusAbsolute)
  76278. wOut = jmax (0, parentSize - roundToInt (w_));
  76279. else
  76280. wOut = roundToInt (w_);
  76281. if ((xMode_ & proportionOfParentSize) != 0)
  76282. xOut = parentPos + x_ * parentSize;
  76283. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76284. xOut = (parentPos + parentSize) - x_;
  76285. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76286. xOut = x_ + (parentPos + parentSize / 2);
  76287. else
  76288. xOut = x_ + parentPos;
  76289. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76290. xOut -= wOut;
  76291. else if ((xMode_ & anchorAtCentre) != 0)
  76292. xOut -= wOut / 2;
  76293. }
  76294. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76295. double x_, const double w_,
  76296. const uint8 xMode_, const uint8 wMode_,
  76297. const int parentPos,
  76298. const int parentSize) const throw()
  76299. {
  76300. if (wMode_ == proportionalSize)
  76301. {
  76302. if (parentSize > 0)
  76303. wOut = w_ / parentSize;
  76304. }
  76305. else if (wMode_ == parentSizeMinusAbsolute)
  76306. wOut = parentSize - w_;
  76307. else
  76308. wOut = w_;
  76309. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76310. x_ += w_;
  76311. else if ((xMode_ & anchorAtCentre) != 0)
  76312. x_ += w_ / 2;
  76313. if ((xMode_ & proportionOfParentSize) != 0)
  76314. {
  76315. if (parentSize > 0)
  76316. xOut = (x_ - parentPos) / parentSize;
  76317. }
  76318. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76319. xOut = (parentPos + parentSize) - x_;
  76320. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76321. xOut = x_ - (parentPos + parentSize / 2);
  76322. else
  76323. xOut = x_ - parentPos;
  76324. }
  76325. END_JUCE_NAMESPACE
  76326. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76327. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76328. BEGIN_JUCE_NAMESPACE
  76329. RectangleList::RectangleList() throw()
  76330. {
  76331. }
  76332. RectangleList::RectangleList (const Rectangle<int>& rect)
  76333. {
  76334. if (! rect.isEmpty())
  76335. rects.add (rect);
  76336. }
  76337. RectangleList::RectangleList (const RectangleList& other)
  76338. : rects (other.rects)
  76339. {
  76340. }
  76341. RectangleList& RectangleList::operator= (const RectangleList& other)
  76342. {
  76343. rects = other.rects;
  76344. return *this;
  76345. }
  76346. RectangleList::~RectangleList()
  76347. {
  76348. }
  76349. void RectangleList::clear()
  76350. {
  76351. rects.clearQuick();
  76352. }
  76353. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76354. {
  76355. if (((unsigned int) index) < (unsigned int) rects.size())
  76356. return rects.getReference (index);
  76357. return Rectangle<int>();
  76358. }
  76359. bool RectangleList::isEmpty() const throw()
  76360. {
  76361. return rects.size() == 0;
  76362. }
  76363. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76364. : current (0),
  76365. owner (list),
  76366. index (list.rects.size())
  76367. {
  76368. }
  76369. RectangleList::Iterator::~Iterator()
  76370. {
  76371. }
  76372. bool RectangleList::Iterator::next() throw()
  76373. {
  76374. if (--index >= 0)
  76375. {
  76376. current = & (owner.rects.getReference (index));
  76377. return true;
  76378. }
  76379. return false;
  76380. }
  76381. void RectangleList::add (const Rectangle<int>& rect)
  76382. {
  76383. if (! rect.isEmpty())
  76384. {
  76385. if (rects.size() == 0)
  76386. {
  76387. rects.add (rect);
  76388. }
  76389. else
  76390. {
  76391. bool anyOverlaps = false;
  76392. int i;
  76393. for (i = rects.size(); --i >= 0;)
  76394. {
  76395. Rectangle<int>& ourRect = rects.getReference (i);
  76396. if (rect.intersects (ourRect))
  76397. {
  76398. if (rect.contains (ourRect))
  76399. rects.remove (i);
  76400. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76401. anyOverlaps = true;
  76402. }
  76403. }
  76404. if (anyOverlaps && rects.size() > 0)
  76405. {
  76406. RectangleList r (rect);
  76407. for (i = rects.size(); --i >= 0;)
  76408. {
  76409. const Rectangle<int>& ourRect = rects.getReference (i);
  76410. if (rect.intersects (ourRect))
  76411. {
  76412. r.subtract (ourRect);
  76413. if (r.rects.size() == 0)
  76414. return;
  76415. }
  76416. }
  76417. for (i = r.getNumRectangles(); --i >= 0;)
  76418. rects.add (r.rects.getReference (i));
  76419. }
  76420. else
  76421. {
  76422. rects.add (rect);
  76423. }
  76424. }
  76425. }
  76426. }
  76427. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76428. {
  76429. if (! rect.isEmpty())
  76430. rects.add (rect);
  76431. }
  76432. void RectangleList::add (const int x, const int y, const int w, const int h)
  76433. {
  76434. if (rects.size() == 0)
  76435. {
  76436. if (w > 0 && h > 0)
  76437. rects.add (Rectangle<int> (x, y, w, h));
  76438. }
  76439. else
  76440. {
  76441. add (Rectangle<int> (x, y, w, h));
  76442. }
  76443. }
  76444. void RectangleList::add (const RectangleList& other)
  76445. {
  76446. for (int i = 0; i < other.rects.size(); ++i)
  76447. add (other.rects.getReference (i));
  76448. }
  76449. void RectangleList::subtract (const Rectangle<int>& rect)
  76450. {
  76451. const int originalNumRects = rects.size();
  76452. if (originalNumRects > 0)
  76453. {
  76454. const int x1 = rect.x;
  76455. const int y1 = rect.y;
  76456. const int x2 = x1 + rect.w;
  76457. const int y2 = y1 + rect.h;
  76458. for (int i = getNumRectangles(); --i >= 0;)
  76459. {
  76460. Rectangle<int>& r = rects.getReference (i);
  76461. const int rx1 = r.x;
  76462. const int ry1 = r.y;
  76463. const int rx2 = rx1 + r.w;
  76464. const int ry2 = ry1 + r.h;
  76465. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76466. {
  76467. if (x1 > rx1 && x1 < rx2)
  76468. {
  76469. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76470. {
  76471. r.w = x1 - rx1;
  76472. }
  76473. else
  76474. {
  76475. r.x = x1;
  76476. r.w = rx2 - x1;
  76477. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76478. i += 2;
  76479. }
  76480. }
  76481. else if (x2 > rx1 && x2 < rx2)
  76482. {
  76483. r.x = x2;
  76484. r.w = rx2 - x2;
  76485. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76486. {
  76487. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76488. i += 2;
  76489. }
  76490. }
  76491. else if (y1 > ry1 && y1 < ry2)
  76492. {
  76493. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76494. {
  76495. r.h = y1 - ry1;
  76496. }
  76497. else
  76498. {
  76499. r.y = y1;
  76500. r.h = ry2 - y1;
  76501. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76502. i += 2;
  76503. }
  76504. }
  76505. else if (y2 > ry1 && y2 < ry2)
  76506. {
  76507. r.y = y2;
  76508. r.h = ry2 - y2;
  76509. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76510. {
  76511. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76512. i += 2;
  76513. }
  76514. }
  76515. else
  76516. {
  76517. rects.remove (i);
  76518. }
  76519. }
  76520. }
  76521. }
  76522. }
  76523. bool RectangleList::subtract (const RectangleList& otherList)
  76524. {
  76525. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76526. subtract (otherList.rects.getReference (i));
  76527. return rects.size() > 0;
  76528. }
  76529. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76530. {
  76531. bool notEmpty = false;
  76532. if (rect.isEmpty())
  76533. {
  76534. clear();
  76535. }
  76536. else
  76537. {
  76538. for (int i = rects.size(); --i >= 0;)
  76539. {
  76540. Rectangle<int>& r = rects.getReference (i);
  76541. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76542. rects.remove (i);
  76543. else
  76544. notEmpty = true;
  76545. }
  76546. }
  76547. return notEmpty;
  76548. }
  76549. bool RectangleList::clipTo (const RectangleList& other)
  76550. {
  76551. if (rects.size() == 0)
  76552. return false;
  76553. RectangleList result;
  76554. for (int j = 0; j < rects.size(); ++j)
  76555. {
  76556. const Rectangle<int>& rect = rects.getReference (j);
  76557. for (int i = other.rects.size(); --i >= 0;)
  76558. {
  76559. Rectangle<int> r (other.rects.getReference (i));
  76560. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76561. result.rects.add (r);
  76562. }
  76563. }
  76564. swapWith (result);
  76565. return ! isEmpty();
  76566. }
  76567. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76568. {
  76569. destRegion.clear();
  76570. if (! rect.isEmpty())
  76571. {
  76572. for (int i = rects.size(); --i >= 0;)
  76573. {
  76574. Rectangle<int> r (rects.getReference (i));
  76575. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76576. destRegion.rects.add (r);
  76577. }
  76578. }
  76579. return destRegion.rects.size() > 0;
  76580. }
  76581. void RectangleList::swapWith (RectangleList& otherList) throw()
  76582. {
  76583. rects.swapWithArray (otherList.rects);
  76584. }
  76585. void RectangleList::consolidate()
  76586. {
  76587. int i;
  76588. for (i = 0; i < getNumRectangles() - 1; ++i)
  76589. {
  76590. Rectangle<int>& r = rects.getReference (i);
  76591. const int rx1 = r.x;
  76592. const int ry1 = r.y;
  76593. const int rx2 = rx1 + r.w;
  76594. const int ry2 = ry1 + r.h;
  76595. for (int j = rects.size(); --j > i;)
  76596. {
  76597. Rectangle<int>& r2 = rects.getReference (j);
  76598. const int jrx1 = r2.x;
  76599. const int jry1 = r2.y;
  76600. const int jrx2 = jrx1 + r2.w;
  76601. const int jry2 = jry1 + r2.h;
  76602. // if the vertical edges of any blocks are touching and their horizontals don't
  76603. // line up, split them horizontally..
  76604. if (jrx1 == rx2 || jrx2 == rx1)
  76605. {
  76606. if (jry1 > ry1 && jry1 < ry2)
  76607. {
  76608. r.h = jry1 - ry1;
  76609. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76610. i = -1;
  76611. break;
  76612. }
  76613. if (jry2 > ry1 && jry2 < ry2)
  76614. {
  76615. r.h = jry2 - ry1;
  76616. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76617. i = -1;
  76618. break;
  76619. }
  76620. else if (ry1 > jry1 && ry1 < jry2)
  76621. {
  76622. r2.h = ry1 - jry1;
  76623. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76624. i = -1;
  76625. break;
  76626. }
  76627. else if (ry2 > jry1 && ry2 < jry2)
  76628. {
  76629. r2.h = ry2 - jry1;
  76630. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76631. i = -1;
  76632. break;
  76633. }
  76634. }
  76635. }
  76636. }
  76637. for (i = 0; i < rects.size() - 1; ++i)
  76638. {
  76639. Rectangle<int>& r = rects.getReference (i);
  76640. for (int j = rects.size(); --j > i;)
  76641. {
  76642. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76643. {
  76644. rects.remove (j);
  76645. i = -1;
  76646. break;
  76647. }
  76648. }
  76649. }
  76650. }
  76651. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76652. {
  76653. for (int i = getNumRectangles(); --i >= 0;)
  76654. if (rects.getReference (i).contains (x, y))
  76655. return true;
  76656. return false;
  76657. }
  76658. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76659. {
  76660. if (rects.size() > 1)
  76661. {
  76662. RectangleList r (rectangleToCheck);
  76663. for (int i = rects.size(); --i >= 0;)
  76664. {
  76665. r.subtract (rects.getReference (i));
  76666. if (r.rects.size() == 0)
  76667. return true;
  76668. }
  76669. }
  76670. else if (rects.size() > 0)
  76671. {
  76672. return rects.getReference (0).contains (rectangleToCheck);
  76673. }
  76674. return false;
  76675. }
  76676. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76677. {
  76678. for (int i = rects.size(); --i >= 0;)
  76679. if (rects.getReference (i).intersects (rectangleToCheck))
  76680. return true;
  76681. return false;
  76682. }
  76683. bool RectangleList::intersects (const RectangleList& other) const throw()
  76684. {
  76685. for (int i = rects.size(); --i >= 0;)
  76686. if (other.intersectsRectangle (rects.getReference (i)))
  76687. return true;
  76688. return false;
  76689. }
  76690. const Rectangle<int> RectangleList::getBounds() const throw()
  76691. {
  76692. if (rects.size() <= 1)
  76693. {
  76694. if (rects.size() == 0)
  76695. return Rectangle<int>();
  76696. else
  76697. return rects.getReference (0);
  76698. }
  76699. else
  76700. {
  76701. const Rectangle<int>& r = rects.getReference (0);
  76702. int minX = r.x;
  76703. int minY = r.y;
  76704. int maxX = minX + r.w;
  76705. int maxY = minY + r.h;
  76706. for (int i = rects.size(); --i > 0;)
  76707. {
  76708. const Rectangle<int>& r2 = rects.getReference (i);
  76709. minX = jmin (minX, r2.x);
  76710. minY = jmin (minY, r2.y);
  76711. maxX = jmax (maxX, r2.getRight());
  76712. maxY = jmax (maxY, r2.getBottom());
  76713. }
  76714. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76715. }
  76716. }
  76717. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76718. {
  76719. for (int i = rects.size(); --i >= 0;)
  76720. {
  76721. Rectangle<int>& r = rects.getReference (i);
  76722. r.x += dx;
  76723. r.y += dy;
  76724. }
  76725. }
  76726. const Path RectangleList::toPath() const
  76727. {
  76728. Path p;
  76729. for (int i = rects.size(); --i >= 0;)
  76730. {
  76731. const Rectangle<int>& r = rects.getReference (i);
  76732. p.addRectangle ((float) r.x,
  76733. (float) r.y,
  76734. (float) r.w,
  76735. (float) r.h);
  76736. }
  76737. return p;
  76738. }
  76739. END_JUCE_NAMESPACE
  76740. /*** End of inlined file: juce_RectangleList.cpp ***/
  76741. /*** Start of inlined file: juce_Image.cpp ***/
  76742. BEGIN_JUCE_NAMESPACE
  76743. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76744. : format (format_), width (width_), height (height_)
  76745. {
  76746. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76747. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76748. }
  76749. Image::SharedImage::~SharedImage()
  76750. {
  76751. }
  76752. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76753. {
  76754. return imageData + lineStride * y + pixelStride * x;
  76755. }
  76756. class SoftwareSharedImage : public Image::SharedImage
  76757. {
  76758. public:
  76759. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76760. : Image::SharedImage (format_, width_, height_)
  76761. {
  76762. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76763. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76764. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76765. imageData = imageDataAllocated;
  76766. }
  76767. ~SoftwareSharedImage()
  76768. {
  76769. }
  76770. Image::ImageType getType() const
  76771. {
  76772. return Image::SoftwareImage;
  76773. }
  76774. LowLevelGraphicsContext* createLowLevelContext()
  76775. {
  76776. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76777. }
  76778. Image::SharedImage* clone()
  76779. {
  76780. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76781. memcpy (s->imageData, imageData, lineStride * height);
  76782. return s;
  76783. }
  76784. private:
  76785. HeapBlock<uint8> imageDataAllocated;
  76786. };
  76787. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76788. {
  76789. return new SoftwareSharedImage (format, width, height, clearImage);
  76790. }
  76791. class SubsectionSharedImage : public Image::SharedImage
  76792. {
  76793. public:
  76794. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76795. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76796. image (image_), area (area_)
  76797. {
  76798. pixelStride = image_->getPixelStride();
  76799. lineStride = image_->getLineStride();
  76800. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76801. }
  76802. Image::ImageType getType() const
  76803. {
  76804. return Image::SoftwareImage;
  76805. }
  76806. LowLevelGraphicsContext* createLowLevelContext()
  76807. {
  76808. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76809. g->clipToRectangle (area);
  76810. g->setOrigin (area.getX(), area.getY());
  76811. return g;
  76812. }
  76813. Image::SharedImage* clone()
  76814. {
  76815. return new SubsectionSharedImage (image->clone(), area);
  76816. }
  76817. private:
  76818. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76819. const Rectangle<int> area;
  76820. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  76821. };
  76822. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76823. {
  76824. if (area.contains (getBounds()))
  76825. return *this;
  76826. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76827. if (validArea.isEmpty())
  76828. return Image::null;
  76829. return Image (new SubsectionSharedImage (image, validArea));
  76830. }
  76831. Image::Image()
  76832. {
  76833. }
  76834. Image::Image (SharedImage* const instance)
  76835. : image (instance)
  76836. {
  76837. }
  76838. Image::Image (const PixelFormat format,
  76839. const int width, const int height,
  76840. const bool clearImage, const ImageType type)
  76841. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76842. : new SoftwareSharedImage (format, width, height, clearImage))
  76843. {
  76844. }
  76845. Image::Image (const Image& other)
  76846. : image (other.image)
  76847. {
  76848. }
  76849. Image& Image::operator= (const Image& other)
  76850. {
  76851. image = other.image;
  76852. return *this;
  76853. }
  76854. Image::~Image()
  76855. {
  76856. }
  76857. const Image Image::null;
  76858. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76859. {
  76860. return image == 0 ? 0 : image->createLowLevelContext();
  76861. }
  76862. void Image::duplicateIfShared()
  76863. {
  76864. if (image != 0 && image->getReferenceCount() > 1)
  76865. image = image->clone();
  76866. }
  76867. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76868. {
  76869. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76870. return *this;
  76871. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76872. Graphics g (newImage);
  76873. g.setImageResamplingQuality (quality);
  76874. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76875. return newImage;
  76876. }
  76877. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76878. {
  76879. if (image == 0 || newFormat == image->format)
  76880. return *this;
  76881. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76882. if (newFormat == SingleChannel)
  76883. {
  76884. if (! hasAlphaChannel())
  76885. {
  76886. newImage.clear (getBounds(), Colours::black);
  76887. }
  76888. else
  76889. {
  76890. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  76891. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  76892. for (int y = 0; y < image->height; ++y)
  76893. {
  76894. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76895. uint8* dst = destData.getLinePointer (y);
  76896. for (int x = image->width; --x >= 0;)
  76897. {
  76898. *dst++ = src->getAlpha();
  76899. ++src;
  76900. }
  76901. }
  76902. }
  76903. }
  76904. else
  76905. {
  76906. if (hasAlphaChannel())
  76907. newImage.clear (getBounds());
  76908. Graphics g (newImage);
  76909. g.drawImageAt (*this, 0, 0);
  76910. }
  76911. return newImage;
  76912. }
  76913. NamedValueSet* Image::getProperties() const
  76914. {
  76915. return image == 0 ? 0 : &(image->userData);
  76916. }
  76917. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76918. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76919. pixelFormat (image.getFormat()),
  76920. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76921. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76922. width (w),
  76923. height (h)
  76924. {
  76925. jassert (data != 0);
  76926. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76927. }
  76928. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76929. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76930. pixelFormat (image.getFormat()),
  76931. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76932. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76933. width (w),
  76934. height (h)
  76935. {
  76936. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76937. }
  76938. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76939. : data (image.image == 0 ? 0 : image.image->imageData),
  76940. pixelFormat (image.getFormat()),
  76941. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76942. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76943. width (image.getWidth()),
  76944. height (image.getHeight())
  76945. {
  76946. }
  76947. Image::BitmapData::~BitmapData()
  76948. {
  76949. }
  76950. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76951. {
  76952. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76953. const uint8* const pixel = getPixelPointer (x, y);
  76954. switch (pixelFormat)
  76955. {
  76956. case Image::ARGB:
  76957. {
  76958. PixelARGB p (*(const PixelARGB*) pixel);
  76959. p.unpremultiply();
  76960. return Colour (p.getARGB());
  76961. }
  76962. case Image::RGB:
  76963. return Colour (((const PixelRGB*) pixel)->getARGB());
  76964. case Image::SingleChannel:
  76965. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76966. default:
  76967. jassertfalse;
  76968. break;
  76969. }
  76970. return Colour();
  76971. }
  76972. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76973. {
  76974. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76975. uint8* const pixel = getPixelPointer (x, y);
  76976. const PixelARGB col (colour.getPixelARGB());
  76977. switch (pixelFormat)
  76978. {
  76979. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76980. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76981. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76982. default: jassertfalse; break;
  76983. }
  76984. }
  76985. void Image::setPixelData (int x, int y, int w, int h,
  76986. const uint8* const sourcePixelData, const int sourceLineStride)
  76987. {
  76988. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76989. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76990. {
  76991. const BitmapData dest (*this, x, y, w, h, true);
  76992. for (int i = 0; i < h; ++i)
  76993. {
  76994. memcpy (dest.getLinePointer(i),
  76995. sourcePixelData + sourceLineStride * i,
  76996. w * dest.pixelStride);
  76997. }
  76998. }
  76999. }
  77000. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77001. {
  77002. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77003. if (! clipped.isEmpty())
  77004. {
  77005. const PixelARGB col (colourToClearTo.getPixelARGB());
  77006. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77007. uint8* dest = destData.data;
  77008. int dh = clipped.getHeight();
  77009. while (--dh >= 0)
  77010. {
  77011. uint8* line = dest;
  77012. dest += destData.lineStride;
  77013. if (isARGB())
  77014. {
  77015. for (int x = clipped.getWidth(); --x >= 0;)
  77016. {
  77017. ((PixelARGB*) line)->set (col);
  77018. line += destData.pixelStride;
  77019. }
  77020. }
  77021. else if (isRGB())
  77022. {
  77023. for (int x = clipped.getWidth(); --x >= 0;)
  77024. {
  77025. ((PixelRGB*) line)->set (col);
  77026. line += destData.pixelStride;
  77027. }
  77028. }
  77029. else
  77030. {
  77031. for (int x = clipped.getWidth(); --x >= 0;)
  77032. {
  77033. *line = col.getAlpha();
  77034. line += destData.pixelStride;
  77035. }
  77036. }
  77037. }
  77038. }
  77039. }
  77040. const Colour Image::getPixelAt (const int x, const int y) const
  77041. {
  77042. if (((unsigned int) x) < (unsigned int) getWidth()
  77043. && ((unsigned int) y) < (unsigned int) getHeight())
  77044. {
  77045. const BitmapData srcData (*this, x, y, 1, 1);
  77046. return srcData.getPixelColour (0, 0);
  77047. }
  77048. return Colour();
  77049. }
  77050. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77051. {
  77052. if (((unsigned int) x) < (unsigned int) getWidth()
  77053. && ((unsigned int) y) < (unsigned int) getHeight())
  77054. {
  77055. const BitmapData destData (*this, x, y, 1, 1, true);
  77056. destData.setPixelColour (0, 0, colour);
  77057. }
  77058. }
  77059. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77060. {
  77061. if (((unsigned int) x) < (unsigned int) getWidth()
  77062. && ((unsigned int) y) < (unsigned int) getHeight()
  77063. && hasAlphaChannel())
  77064. {
  77065. const BitmapData destData (*this, x, y, 1, 1, true);
  77066. if (isARGB())
  77067. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77068. else
  77069. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77070. }
  77071. }
  77072. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77073. {
  77074. if (hasAlphaChannel())
  77075. {
  77076. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77077. if (isARGB())
  77078. {
  77079. for (int y = 0; y < destData.height; ++y)
  77080. {
  77081. uint8* p = destData.getLinePointer (y);
  77082. for (int x = 0; x < destData.width; ++x)
  77083. {
  77084. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77085. p += destData.pixelStride;
  77086. }
  77087. }
  77088. }
  77089. else
  77090. {
  77091. for (int y = 0; y < destData.height; ++y)
  77092. {
  77093. uint8* p = destData.getLinePointer (y);
  77094. for (int x = 0; x < destData.width; ++x)
  77095. {
  77096. *p = (uint8) (*p * amountToMultiplyBy);
  77097. p += destData.pixelStride;
  77098. }
  77099. }
  77100. }
  77101. }
  77102. else
  77103. {
  77104. jassertfalse; // can't do this without an alpha-channel!
  77105. }
  77106. }
  77107. void Image::desaturate()
  77108. {
  77109. if (isARGB() || isRGB())
  77110. {
  77111. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77112. if (isARGB())
  77113. {
  77114. for (int y = 0; y < destData.height; ++y)
  77115. {
  77116. uint8* p = destData.getLinePointer (y);
  77117. for (int x = 0; x < destData.width; ++x)
  77118. {
  77119. ((PixelARGB*) p)->desaturate();
  77120. p += destData.pixelStride;
  77121. }
  77122. }
  77123. }
  77124. else
  77125. {
  77126. for (int y = 0; y < destData.height; ++y)
  77127. {
  77128. uint8* p = destData.getLinePointer (y);
  77129. for (int x = 0; x < destData.width; ++x)
  77130. {
  77131. ((PixelRGB*) p)->desaturate();
  77132. p += destData.pixelStride;
  77133. }
  77134. }
  77135. }
  77136. }
  77137. }
  77138. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77139. {
  77140. if (hasAlphaChannel())
  77141. {
  77142. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77143. SparseSet<int> pixelsOnRow;
  77144. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77145. for (int y = 0; y < srcData.height; ++y)
  77146. {
  77147. pixelsOnRow.clear();
  77148. const uint8* lineData = srcData.getLinePointer (y);
  77149. if (isARGB())
  77150. {
  77151. for (int x = 0; x < srcData.width; ++x)
  77152. {
  77153. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77154. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77155. lineData += srcData.pixelStride;
  77156. }
  77157. }
  77158. else
  77159. {
  77160. for (int x = 0; x < srcData.width; ++x)
  77161. {
  77162. if (*lineData >= threshold)
  77163. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77164. lineData += srcData.pixelStride;
  77165. }
  77166. }
  77167. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77168. {
  77169. const Range<int> range (pixelsOnRow.getRange (i));
  77170. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77171. }
  77172. result.consolidate();
  77173. }
  77174. }
  77175. else
  77176. {
  77177. result.add (0, 0, getWidth(), getHeight());
  77178. }
  77179. }
  77180. void Image::moveImageSection (int dx, int dy,
  77181. int sx, int sy,
  77182. int w, int h)
  77183. {
  77184. if (dx < 0)
  77185. {
  77186. w += dx;
  77187. sx -= dx;
  77188. dx = 0;
  77189. }
  77190. if (dy < 0)
  77191. {
  77192. h += dy;
  77193. sy -= dy;
  77194. dy = 0;
  77195. }
  77196. if (sx < 0)
  77197. {
  77198. w += sx;
  77199. dx -= sx;
  77200. sx = 0;
  77201. }
  77202. if (sy < 0)
  77203. {
  77204. h += sy;
  77205. dy -= sy;
  77206. sy = 0;
  77207. }
  77208. const int minX = jmin (dx, sx);
  77209. const int minY = jmin (dy, sy);
  77210. w = jmin (w, getWidth() - jmax (sx, dx));
  77211. h = jmin (h, getHeight() - jmax (sy, dy));
  77212. if (w > 0 && h > 0)
  77213. {
  77214. const int maxX = jmax (dx, sx) + w;
  77215. const int maxY = jmax (dy, sy) + h;
  77216. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77217. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77218. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77219. const int lineSize = destData.pixelStride * w;
  77220. if (dy > sy)
  77221. {
  77222. while (--h >= 0)
  77223. {
  77224. const int offset = h * destData.lineStride;
  77225. memmove (dst + offset, src + offset, lineSize);
  77226. }
  77227. }
  77228. else if (dst != src)
  77229. {
  77230. while (--h >= 0)
  77231. {
  77232. memmove (dst, src, lineSize);
  77233. dst += destData.lineStride;
  77234. src += destData.lineStride;
  77235. }
  77236. }
  77237. }
  77238. }
  77239. END_JUCE_NAMESPACE
  77240. /*** End of inlined file: juce_Image.cpp ***/
  77241. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77242. BEGIN_JUCE_NAMESPACE
  77243. class ImageCache::Pimpl : public Timer,
  77244. public DeletedAtShutdown
  77245. {
  77246. public:
  77247. Pimpl()
  77248. : cacheTimeout (5000)
  77249. {
  77250. }
  77251. ~Pimpl()
  77252. {
  77253. clearSingletonInstance();
  77254. }
  77255. const Image getFromHashCode (const int64 hashCode)
  77256. {
  77257. const ScopedLock sl (lock);
  77258. for (int i = images.size(); --i >= 0;)
  77259. {
  77260. Item* const item = images.getUnchecked(i);
  77261. if (item->hashCode == hashCode)
  77262. return item->image;
  77263. }
  77264. return Image::null;
  77265. }
  77266. void addImageToCache (const Image& image, const int64 hashCode)
  77267. {
  77268. if (image.isValid())
  77269. {
  77270. if (! isTimerRunning())
  77271. startTimer (2000);
  77272. Item* const item = new Item();
  77273. item->hashCode = hashCode;
  77274. item->image = image;
  77275. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77276. const ScopedLock sl (lock);
  77277. images.add (item);
  77278. }
  77279. }
  77280. void timerCallback()
  77281. {
  77282. const uint32 now = Time::getApproximateMillisecondCounter();
  77283. const ScopedLock sl (lock);
  77284. for (int i = images.size(); --i >= 0;)
  77285. {
  77286. Item* const item = images.getUnchecked(i);
  77287. if (item->image.getReferenceCount() <= 1)
  77288. {
  77289. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77290. images.remove (i);
  77291. }
  77292. else
  77293. {
  77294. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77295. }
  77296. }
  77297. if (images.size() == 0)
  77298. stopTimer();
  77299. }
  77300. struct Item
  77301. {
  77302. Image image;
  77303. int64 hashCode;
  77304. uint32 lastUseTime;
  77305. };
  77306. int cacheTimeout;
  77307. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77308. private:
  77309. OwnedArray<Item> images;
  77310. CriticalSection lock;
  77311. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77312. };
  77313. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77314. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77315. {
  77316. if (Pimpl::getInstanceWithoutCreating() != 0)
  77317. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77318. return Image::null;
  77319. }
  77320. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77321. {
  77322. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77323. }
  77324. const Image ImageCache::getFromFile (const File& file)
  77325. {
  77326. const int64 hashCode = file.hashCode64();
  77327. Image image (getFromHashCode (hashCode));
  77328. if (image.isNull())
  77329. {
  77330. image = ImageFileFormat::loadFrom (file);
  77331. addImageToCache (image, hashCode);
  77332. }
  77333. return image;
  77334. }
  77335. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77336. {
  77337. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77338. Image image (getFromHashCode (hashCode));
  77339. if (image.isNull())
  77340. {
  77341. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77342. addImageToCache (image, hashCode);
  77343. }
  77344. return image;
  77345. }
  77346. void ImageCache::setCacheTimeout (const int millisecs)
  77347. {
  77348. Pimpl::getInstance()->cacheTimeout = millisecs;
  77349. }
  77350. END_JUCE_NAMESPACE
  77351. /*** End of inlined file: juce_ImageCache.cpp ***/
  77352. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77353. BEGIN_JUCE_NAMESPACE
  77354. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77355. : values (size_ * size_),
  77356. size (size_)
  77357. {
  77358. clear();
  77359. }
  77360. ImageConvolutionKernel::~ImageConvolutionKernel()
  77361. {
  77362. }
  77363. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77364. {
  77365. if (((unsigned int) x) < (unsigned int) size
  77366. && ((unsigned int) y) < (unsigned int) size)
  77367. {
  77368. return values [x + y * size];
  77369. }
  77370. else
  77371. {
  77372. jassertfalse;
  77373. return 0;
  77374. }
  77375. }
  77376. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77377. {
  77378. if (((unsigned int) x) < (unsigned int) size
  77379. && ((unsigned int) y) < (unsigned int) size)
  77380. {
  77381. values [x + y * size] = value;
  77382. }
  77383. else
  77384. {
  77385. jassertfalse;
  77386. }
  77387. }
  77388. void ImageConvolutionKernel::clear()
  77389. {
  77390. for (int i = size * size; --i >= 0;)
  77391. values[i] = 0;
  77392. }
  77393. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77394. {
  77395. double currentTotal = 0.0;
  77396. for (int i = size * size; --i >= 0;)
  77397. currentTotal += values[i];
  77398. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77399. }
  77400. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77401. {
  77402. for (int i = size * size; --i >= 0;)
  77403. values[i] *= multiplier;
  77404. }
  77405. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77406. {
  77407. const double radiusFactor = -1.0 / (radius * radius * 2);
  77408. const int centre = size >> 1;
  77409. for (int y = size; --y >= 0;)
  77410. {
  77411. for (int x = size; --x >= 0;)
  77412. {
  77413. const int cx = x - centre;
  77414. const int cy = y - centre;
  77415. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77416. }
  77417. }
  77418. setOverallSum (1.0f);
  77419. }
  77420. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77421. const Image& sourceImage,
  77422. const Rectangle<int>& destinationArea) const
  77423. {
  77424. if (sourceImage == destImage)
  77425. {
  77426. destImage.duplicateIfShared();
  77427. }
  77428. else
  77429. {
  77430. if (sourceImage.getWidth() != destImage.getWidth()
  77431. || sourceImage.getHeight() != destImage.getHeight()
  77432. || sourceImage.getFormat() != destImage.getFormat())
  77433. {
  77434. jassertfalse;
  77435. return;
  77436. }
  77437. }
  77438. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77439. if (area.isEmpty())
  77440. return;
  77441. const int right = area.getRight();
  77442. const int bottom = area.getBottom();
  77443. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77444. uint8* line = destData.data;
  77445. const Image::BitmapData srcData (sourceImage, false);
  77446. if (destData.pixelStride == 4)
  77447. {
  77448. for (int y = area.getY(); y < bottom; ++y)
  77449. {
  77450. uint8* dest = line;
  77451. line += destData.lineStride;
  77452. for (int x = area.getX(); x < right; ++x)
  77453. {
  77454. float c1 = 0;
  77455. float c2 = 0;
  77456. float c3 = 0;
  77457. float c4 = 0;
  77458. for (int yy = 0; yy < size; ++yy)
  77459. {
  77460. const int sy = y + yy - (size >> 1);
  77461. if (sy >= srcData.height)
  77462. break;
  77463. if (sy >= 0)
  77464. {
  77465. int sx = x - (size >> 1);
  77466. const uint8* src = srcData.getPixelPointer (sx, sy);
  77467. for (int xx = 0; xx < size; ++xx)
  77468. {
  77469. if (sx >= srcData.width)
  77470. break;
  77471. if (sx >= 0)
  77472. {
  77473. const float kernelMult = values [xx + yy * size];
  77474. c1 += kernelMult * *src++;
  77475. c2 += kernelMult * *src++;
  77476. c3 += kernelMult * *src++;
  77477. c4 += kernelMult * *src++;
  77478. }
  77479. else
  77480. {
  77481. src += 4;
  77482. }
  77483. ++sx;
  77484. }
  77485. }
  77486. }
  77487. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77488. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77489. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77490. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77491. }
  77492. }
  77493. }
  77494. else if (destData.pixelStride == 3)
  77495. {
  77496. for (int y = area.getY(); y < bottom; ++y)
  77497. {
  77498. uint8* dest = line;
  77499. line += destData.lineStride;
  77500. for (int x = area.getX(); x < right; ++x)
  77501. {
  77502. float c1 = 0;
  77503. float c2 = 0;
  77504. float c3 = 0;
  77505. for (int yy = 0; yy < size; ++yy)
  77506. {
  77507. const int sy = y + yy - (size >> 1);
  77508. if (sy >= srcData.height)
  77509. break;
  77510. if (sy >= 0)
  77511. {
  77512. int sx = x - (size >> 1);
  77513. const uint8* src = srcData.getPixelPointer (sx, sy);
  77514. for (int xx = 0; xx < size; ++xx)
  77515. {
  77516. if (sx >= srcData.width)
  77517. break;
  77518. if (sx >= 0)
  77519. {
  77520. const float kernelMult = values [xx + yy * size];
  77521. c1 += kernelMult * *src++;
  77522. c2 += kernelMult * *src++;
  77523. c3 += kernelMult * *src++;
  77524. }
  77525. else
  77526. {
  77527. src += 3;
  77528. }
  77529. ++sx;
  77530. }
  77531. }
  77532. }
  77533. *dest++ = (uint8) roundToInt (c1);
  77534. *dest++ = (uint8) roundToInt (c2);
  77535. *dest++ = (uint8) roundToInt (c3);
  77536. }
  77537. }
  77538. }
  77539. }
  77540. END_JUCE_NAMESPACE
  77541. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77542. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77543. BEGIN_JUCE_NAMESPACE
  77544. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77545. {
  77546. static PNGImageFormat png;
  77547. static JPEGImageFormat jpg;
  77548. static GIFImageFormat gif;
  77549. ImageFileFormat* formats[4];
  77550. int numFormats = 0;
  77551. formats [numFormats++] = &png;
  77552. formats [numFormats++] = &jpg;
  77553. formats [numFormats++] = &gif;
  77554. const int64 streamPos = input.getPosition();
  77555. for (int i = 0; i < numFormats; ++i)
  77556. {
  77557. const bool found = formats[i]->canUnderstand (input);
  77558. input.setPosition (streamPos);
  77559. if (found)
  77560. return formats[i];
  77561. }
  77562. return 0;
  77563. }
  77564. const Image ImageFileFormat::loadFrom (InputStream& input)
  77565. {
  77566. ImageFileFormat* const format = findImageFormatForStream (input);
  77567. if (format != 0)
  77568. return format->decodeImage (input);
  77569. return Image::null;
  77570. }
  77571. const Image ImageFileFormat::loadFrom (const File& file)
  77572. {
  77573. InputStream* const in = file.createInputStream();
  77574. if (in != 0)
  77575. {
  77576. BufferedInputStream b (in, 8192, true);
  77577. return loadFrom (b);
  77578. }
  77579. return Image::null;
  77580. }
  77581. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77582. {
  77583. if (rawData != 0 && numBytes > 4)
  77584. {
  77585. MemoryInputStream stream (rawData, numBytes, false);
  77586. return loadFrom (stream);
  77587. }
  77588. return Image::null;
  77589. }
  77590. END_JUCE_NAMESPACE
  77591. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77592. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77593. BEGIN_JUCE_NAMESPACE
  77594. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77595. const Image juce_loadWithCoreImage (InputStream& input);
  77596. #else
  77597. class GIFLoader
  77598. {
  77599. public:
  77600. GIFLoader (InputStream& in)
  77601. : input (in),
  77602. dataBlockIsZero (false),
  77603. fresh (false),
  77604. finished (false)
  77605. {
  77606. currentBit = lastBit = lastByteIndex = 0;
  77607. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77608. firstcode = oldcode = 0;
  77609. clearCode = end_code = 0;
  77610. int imageWidth, imageHeight;
  77611. int transparent = -1;
  77612. if (! getSizeFromHeader (imageWidth, imageHeight))
  77613. return;
  77614. if ((imageWidth <= 0) || (imageHeight <= 0))
  77615. return;
  77616. unsigned char buf [16];
  77617. if (in.read (buf, 3) != 3)
  77618. return;
  77619. int numColours = 2 << (buf[0] & 7);
  77620. if ((buf[0] & 0x80) != 0)
  77621. readPalette (numColours);
  77622. for (;;)
  77623. {
  77624. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77625. break;
  77626. if (buf[0] == '!')
  77627. {
  77628. if (input.read (buf, 1) != 1)
  77629. break;
  77630. if (processExtension (buf[0], transparent) < 0)
  77631. break;
  77632. continue;
  77633. }
  77634. if (buf[0] != ',')
  77635. continue;
  77636. if (input.read (buf, 9) != 9)
  77637. break;
  77638. imageWidth = makeWord (buf[4], buf[5]);
  77639. imageHeight = makeWord (buf[6], buf[7]);
  77640. numColours = 2 << (buf[8] & 7);
  77641. if ((buf[8] & 0x80) != 0)
  77642. if (! readPalette (numColours))
  77643. break;
  77644. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77645. imageWidth, imageHeight, (transparent >= 0));
  77646. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77647. readImage ((buf[8] & 0x40) != 0, transparent);
  77648. break;
  77649. }
  77650. }
  77651. ~GIFLoader() {}
  77652. Image image;
  77653. private:
  77654. InputStream& input;
  77655. uint8 buffer [300];
  77656. uint8 palette [256][4];
  77657. bool dataBlockIsZero, fresh, finished;
  77658. int currentBit, lastBit, lastByteIndex;
  77659. int codeSize, setCodeSize;
  77660. int maxCode, maxCodeSize;
  77661. int firstcode, oldcode;
  77662. int clearCode, end_code;
  77663. enum { maxGifCode = 1 << 12 };
  77664. int table [2] [maxGifCode];
  77665. int stack [2 * maxGifCode];
  77666. int *sp;
  77667. bool getSizeFromHeader (int& w, int& h)
  77668. {
  77669. char b[8];
  77670. if (input.read (b, 6) == 6)
  77671. {
  77672. if ((strncmp ("GIF87a", b, 6) == 0)
  77673. || (strncmp ("GIF89a", b, 6) == 0))
  77674. {
  77675. if (input.read (b, 4) == 4)
  77676. {
  77677. w = makeWord (b[0], b[1]);
  77678. h = makeWord (b[2], b[3]);
  77679. return true;
  77680. }
  77681. }
  77682. }
  77683. return false;
  77684. }
  77685. bool readPalette (const int numCols)
  77686. {
  77687. unsigned char rgb[4];
  77688. for (int i = 0; i < numCols; ++i)
  77689. {
  77690. input.read (rgb, 3);
  77691. palette [i][0] = rgb[0];
  77692. palette [i][1] = rgb[1];
  77693. palette [i][2] = rgb[2];
  77694. palette [i][3] = 0xff;
  77695. }
  77696. return true;
  77697. }
  77698. int readDataBlock (unsigned char* dest)
  77699. {
  77700. unsigned char n;
  77701. if (input.read (&n, 1) == 1)
  77702. {
  77703. dataBlockIsZero = (n == 0);
  77704. if (dataBlockIsZero || (input.read (dest, n) == n))
  77705. return n;
  77706. }
  77707. return -1;
  77708. }
  77709. int processExtension (const int type, int& transparent)
  77710. {
  77711. unsigned char b [300];
  77712. int n = 0;
  77713. if (type == 0xf9)
  77714. {
  77715. n = readDataBlock (b);
  77716. if (n < 0)
  77717. return 1;
  77718. if ((b[0] & 0x1) != 0)
  77719. transparent = b[3];
  77720. }
  77721. do
  77722. {
  77723. n = readDataBlock (b);
  77724. }
  77725. while (n > 0);
  77726. return n;
  77727. }
  77728. int readLZWByte (const bool initialise, const int inputCodeSize)
  77729. {
  77730. int code, incode, i;
  77731. if (initialise)
  77732. {
  77733. setCodeSize = inputCodeSize;
  77734. codeSize = setCodeSize + 1;
  77735. clearCode = 1 << setCodeSize;
  77736. end_code = clearCode + 1;
  77737. maxCodeSize = 2 * clearCode;
  77738. maxCode = clearCode + 2;
  77739. getCode (0, true);
  77740. fresh = true;
  77741. for (i = 0; i < clearCode; ++i)
  77742. {
  77743. table[0][i] = 0;
  77744. table[1][i] = i;
  77745. }
  77746. for (; i < maxGifCode; ++i)
  77747. {
  77748. table[0][i] = 0;
  77749. table[1][i] = 0;
  77750. }
  77751. sp = stack;
  77752. return 0;
  77753. }
  77754. else if (fresh)
  77755. {
  77756. fresh = false;
  77757. do
  77758. {
  77759. firstcode = oldcode
  77760. = getCode (codeSize, false);
  77761. }
  77762. while (firstcode == clearCode);
  77763. return firstcode;
  77764. }
  77765. if (sp > stack)
  77766. return *--sp;
  77767. while ((code = getCode (codeSize, false)) >= 0)
  77768. {
  77769. if (code == clearCode)
  77770. {
  77771. for (i = 0; i < clearCode; ++i)
  77772. {
  77773. table[0][i] = 0;
  77774. table[1][i] = i;
  77775. }
  77776. for (; i < maxGifCode; ++i)
  77777. {
  77778. table[0][i] = 0;
  77779. table[1][i] = 0;
  77780. }
  77781. codeSize = setCodeSize + 1;
  77782. maxCodeSize = 2 * clearCode;
  77783. maxCode = clearCode + 2;
  77784. sp = stack;
  77785. firstcode = oldcode = getCode (codeSize, false);
  77786. return firstcode;
  77787. }
  77788. else if (code == end_code)
  77789. {
  77790. if (dataBlockIsZero)
  77791. return -2;
  77792. unsigned char buf [260];
  77793. int n;
  77794. while ((n = readDataBlock (buf)) > 0)
  77795. {}
  77796. if (n != 0)
  77797. return -2;
  77798. }
  77799. incode = code;
  77800. if (code >= maxCode)
  77801. {
  77802. *sp++ = firstcode;
  77803. code = oldcode;
  77804. }
  77805. while (code >= clearCode)
  77806. {
  77807. *sp++ = table[1][code];
  77808. if (code == table[0][code])
  77809. return -2;
  77810. code = table[0][code];
  77811. }
  77812. *sp++ = firstcode = table[1][code];
  77813. if ((code = maxCode) < maxGifCode)
  77814. {
  77815. table[0][code] = oldcode;
  77816. table[1][code] = firstcode;
  77817. ++maxCode;
  77818. if ((maxCode >= maxCodeSize)
  77819. && (maxCodeSize < maxGifCode))
  77820. {
  77821. maxCodeSize <<= 1;
  77822. ++codeSize;
  77823. }
  77824. }
  77825. oldcode = incode;
  77826. if (sp > stack)
  77827. return *--sp;
  77828. }
  77829. return code;
  77830. }
  77831. int getCode (const int codeSize_, const bool initialise)
  77832. {
  77833. if (initialise)
  77834. {
  77835. currentBit = 0;
  77836. lastBit = 0;
  77837. finished = false;
  77838. return 0;
  77839. }
  77840. if ((currentBit + codeSize_) >= lastBit)
  77841. {
  77842. if (finished)
  77843. return -1;
  77844. buffer[0] = buffer [lastByteIndex - 2];
  77845. buffer[1] = buffer [lastByteIndex - 1];
  77846. const int n = readDataBlock (&buffer[2]);
  77847. if (n == 0)
  77848. finished = true;
  77849. lastByteIndex = 2 + n;
  77850. currentBit = (currentBit - lastBit) + 16;
  77851. lastBit = (2 + n) * 8 ;
  77852. }
  77853. int result = 0;
  77854. int i = currentBit;
  77855. for (int j = 0; j < codeSize_; ++j)
  77856. {
  77857. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77858. ++i;
  77859. }
  77860. currentBit += codeSize_;
  77861. return result;
  77862. }
  77863. bool readImage (const int interlace, const int transparent)
  77864. {
  77865. unsigned char c;
  77866. if (input.read (&c, 1) != 1
  77867. || readLZWByte (true, c) < 0)
  77868. return false;
  77869. if (transparent >= 0)
  77870. {
  77871. palette [transparent][0] = 0;
  77872. palette [transparent][1] = 0;
  77873. palette [transparent][2] = 0;
  77874. palette [transparent][3] = 0;
  77875. }
  77876. int index;
  77877. int xpos = 0, ypos = 0, pass = 0;
  77878. const Image::BitmapData destData (image, true);
  77879. uint8* p = destData.data;
  77880. const bool hasAlpha = image.hasAlphaChannel();
  77881. while ((index = readLZWByte (false, c)) >= 0)
  77882. {
  77883. const uint8* const paletteEntry = palette [index];
  77884. if (hasAlpha)
  77885. {
  77886. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77887. paletteEntry[0],
  77888. paletteEntry[1],
  77889. paletteEntry[2]);
  77890. ((PixelARGB*) p)->premultiply();
  77891. }
  77892. else
  77893. {
  77894. ((PixelRGB*) p)->setARGB (0,
  77895. paletteEntry[0],
  77896. paletteEntry[1],
  77897. paletteEntry[2]);
  77898. }
  77899. p += destData.pixelStride;
  77900. ++xpos;
  77901. if (xpos == destData.width)
  77902. {
  77903. xpos = 0;
  77904. if (interlace)
  77905. {
  77906. switch (pass)
  77907. {
  77908. case 0:
  77909. case 1: ypos += 8; break;
  77910. case 2: ypos += 4; break;
  77911. case 3: ypos += 2; break;
  77912. }
  77913. while (ypos >= destData.height)
  77914. {
  77915. ++pass;
  77916. switch (pass)
  77917. {
  77918. case 1: ypos = 4; break;
  77919. case 2: ypos = 2; break;
  77920. case 3: ypos = 1; break;
  77921. default: return true;
  77922. }
  77923. }
  77924. }
  77925. else
  77926. {
  77927. ++ypos;
  77928. }
  77929. p = destData.getPixelPointer (xpos, ypos);
  77930. }
  77931. if (ypos >= destData.height)
  77932. break;
  77933. }
  77934. return true;
  77935. }
  77936. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77937. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  77938. };
  77939. #endif
  77940. GIFImageFormat::GIFImageFormat() {}
  77941. GIFImageFormat::~GIFImageFormat() {}
  77942. const String GIFImageFormat::getFormatName() { return "GIF"; }
  77943. bool GIFImageFormat::canUnderstand (InputStream& in)
  77944. {
  77945. char header [4];
  77946. return (in.read (header, sizeof (header)) == sizeof (header))
  77947. && header[0] == 'G'
  77948. && header[1] == 'I'
  77949. && header[2] == 'F';
  77950. }
  77951. const Image GIFImageFormat::decodeImage (InputStream& in)
  77952. {
  77953. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77954. return juce_loadWithCoreImage (in);
  77955. #else
  77956. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  77957. return loader->image;
  77958. #endif
  77959. }
  77960. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  77961. {
  77962. jassertfalse; // writing isn't implemented for GIFs!
  77963. return false;
  77964. }
  77965. END_JUCE_NAMESPACE
  77966. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77967. #endif
  77968. //==============================================================================
  77969. // some files include lots of library code, so leave them to the end to avoid cluttering
  77970. // up the build for the clean files.
  77971. #if JUCE_BUILD_CORE
  77972. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77973. namespace zlibNamespace
  77974. {
  77975. #if JUCE_INCLUDE_ZLIB_CODE
  77976. #undef OS_CODE
  77977. #undef fdopen
  77978. /*** Start of inlined file: zlib.h ***/
  77979. #ifndef ZLIB_H
  77980. #define ZLIB_H
  77981. /*** Start of inlined file: zconf.h ***/
  77982. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77983. #ifndef ZCONF_H
  77984. #define ZCONF_H
  77985. // *** Just a few hacks here to make it compile nicely with Juce..
  77986. #define Z_PREFIX 1
  77987. #undef __MACTYPES__
  77988. #ifdef _MSC_VER
  77989. #pragma warning (disable : 4131 4127 4244 4267)
  77990. #endif
  77991. /*
  77992. * If you *really* need a unique prefix for all types and library functions,
  77993. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77994. */
  77995. #ifdef Z_PREFIX
  77996. # define deflateInit_ z_deflateInit_
  77997. # define deflate z_deflate
  77998. # define deflateEnd z_deflateEnd
  77999. # define inflateInit_ z_inflateInit_
  78000. # define inflate z_inflate
  78001. # define inflateEnd z_inflateEnd
  78002. # define inflatePrime z_inflatePrime
  78003. # define inflateGetHeader z_inflateGetHeader
  78004. # define adler32_combine z_adler32_combine
  78005. # define crc32_combine z_crc32_combine
  78006. # define deflateInit2_ z_deflateInit2_
  78007. # define deflateSetDictionary z_deflateSetDictionary
  78008. # define deflateCopy z_deflateCopy
  78009. # define deflateReset z_deflateReset
  78010. # define deflateParams z_deflateParams
  78011. # define deflateBound z_deflateBound
  78012. # define deflatePrime z_deflatePrime
  78013. # define inflateInit2_ z_inflateInit2_
  78014. # define inflateSetDictionary z_inflateSetDictionary
  78015. # define inflateSync z_inflateSync
  78016. # define inflateSyncPoint z_inflateSyncPoint
  78017. # define inflateCopy z_inflateCopy
  78018. # define inflateReset z_inflateReset
  78019. # define inflateBack z_inflateBack
  78020. # define inflateBackEnd z_inflateBackEnd
  78021. # define compress z_compress
  78022. # define compress2 z_compress2
  78023. # define compressBound z_compressBound
  78024. # define uncompress z_uncompress
  78025. # define adler32 z_adler32
  78026. # define crc32 z_crc32
  78027. # define get_crc_table z_get_crc_table
  78028. # define zError z_zError
  78029. # define alloc_func z_alloc_func
  78030. # define free_func z_free_func
  78031. # define in_func z_in_func
  78032. # define out_func z_out_func
  78033. # define Byte z_Byte
  78034. # define uInt z_uInt
  78035. # define uLong z_uLong
  78036. # define Bytef z_Bytef
  78037. # define charf z_charf
  78038. # define intf z_intf
  78039. # define uIntf z_uIntf
  78040. # define uLongf z_uLongf
  78041. # define voidpf z_voidpf
  78042. # define voidp z_voidp
  78043. #endif
  78044. #if defined(__MSDOS__) && !defined(MSDOS)
  78045. # define MSDOS
  78046. #endif
  78047. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78048. # define OS2
  78049. #endif
  78050. #if defined(_WINDOWS) && !defined(WINDOWS)
  78051. # define WINDOWS
  78052. #endif
  78053. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78054. # ifndef WIN32
  78055. # define WIN32
  78056. # endif
  78057. #endif
  78058. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78059. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78060. # ifndef SYS16BIT
  78061. # define SYS16BIT
  78062. # endif
  78063. # endif
  78064. #endif
  78065. /*
  78066. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78067. * than 64k bytes at a time (needed on systems with 16-bit int).
  78068. */
  78069. #ifdef SYS16BIT
  78070. # define MAXSEG_64K
  78071. #endif
  78072. #ifdef MSDOS
  78073. # define UNALIGNED_OK
  78074. #endif
  78075. #ifdef __STDC_VERSION__
  78076. # ifndef STDC
  78077. # define STDC
  78078. # endif
  78079. # if __STDC_VERSION__ >= 199901L
  78080. # ifndef STDC99
  78081. # define STDC99
  78082. # endif
  78083. # endif
  78084. #endif
  78085. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78086. # define STDC
  78087. #endif
  78088. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78089. # define STDC
  78090. #endif
  78091. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78092. # define STDC
  78093. #endif
  78094. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78095. # define STDC
  78096. #endif
  78097. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78098. # define STDC
  78099. #endif
  78100. #ifndef STDC
  78101. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78102. # define const /* note: need a more gentle solution here */
  78103. # endif
  78104. #endif
  78105. /* Some Mac compilers merge all .h files incorrectly: */
  78106. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78107. # define NO_DUMMY_DECL
  78108. #endif
  78109. /* Maximum value for memLevel in deflateInit2 */
  78110. #ifndef MAX_MEM_LEVEL
  78111. # ifdef MAXSEG_64K
  78112. # define MAX_MEM_LEVEL 8
  78113. # else
  78114. # define MAX_MEM_LEVEL 9
  78115. # endif
  78116. #endif
  78117. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78118. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78119. * created by gzip. (Files created by minigzip can still be extracted by
  78120. * gzip.)
  78121. */
  78122. #ifndef MAX_WBITS
  78123. # define MAX_WBITS 15 /* 32K LZ77 window */
  78124. #endif
  78125. /* The memory requirements for deflate are (in bytes):
  78126. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78127. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78128. plus a few kilobytes for small objects. For example, if you want to reduce
  78129. the default memory requirements from 256K to 128K, compile with
  78130. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78131. Of course this will generally degrade compression (there's no free lunch).
  78132. The memory requirements for inflate are (in bytes) 1 << windowBits
  78133. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78134. for small objects.
  78135. */
  78136. /* Type declarations */
  78137. #ifndef OF /* function prototypes */
  78138. # ifdef STDC
  78139. # define OF(args) args
  78140. # else
  78141. # define OF(args) ()
  78142. # endif
  78143. #endif
  78144. /* The following definitions for FAR are needed only for MSDOS mixed
  78145. * model programming (small or medium model with some far allocations).
  78146. * This was tested only with MSC; for other MSDOS compilers you may have
  78147. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78148. * just define FAR to be empty.
  78149. */
  78150. #ifdef SYS16BIT
  78151. # if defined(M_I86SM) || defined(M_I86MM)
  78152. /* MSC small or medium model */
  78153. # define SMALL_MEDIUM
  78154. # ifdef _MSC_VER
  78155. # define FAR _far
  78156. # else
  78157. # define FAR far
  78158. # endif
  78159. # endif
  78160. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78161. /* Turbo C small or medium model */
  78162. # define SMALL_MEDIUM
  78163. # ifdef __BORLANDC__
  78164. # define FAR _far
  78165. # else
  78166. # define FAR far
  78167. # endif
  78168. # endif
  78169. #endif
  78170. #if defined(WINDOWS) || defined(WIN32)
  78171. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78172. * This is not mandatory, but it offers a little performance increase.
  78173. */
  78174. # ifdef ZLIB_DLL
  78175. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78176. # ifdef ZLIB_INTERNAL
  78177. # define ZEXTERN extern __declspec(dllexport)
  78178. # else
  78179. # define ZEXTERN extern __declspec(dllimport)
  78180. # endif
  78181. # endif
  78182. # endif /* ZLIB_DLL */
  78183. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78184. * define ZLIB_WINAPI.
  78185. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78186. */
  78187. # ifdef ZLIB_WINAPI
  78188. # ifdef FAR
  78189. # undef FAR
  78190. # endif
  78191. # include <windows.h>
  78192. /* No need for _export, use ZLIB.DEF instead. */
  78193. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78194. # define ZEXPORT WINAPI
  78195. # ifdef WIN32
  78196. # define ZEXPORTVA WINAPIV
  78197. # else
  78198. # define ZEXPORTVA FAR CDECL
  78199. # endif
  78200. # endif
  78201. #endif
  78202. #if defined (__BEOS__)
  78203. # ifdef ZLIB_DLL
  78204. # ifdef ZLIB_INTERNAL
  78205. # define ZEXPORT __declspec(dllexport)
  78206. # define ZEXPORTVA __declspec(dllexport)
  78207. # else
  78208. # define ZEXPORT __declspec(dllimport)
  78209. # define ZEXPORTVA __declspec(dllimport)
  78210. # endif
  78211. # endif
  78212. #endif
  78213. #ifndef ZEXTERN
  78214. # define ZEXTERN extern
  78215. #endif
  78216. #ifndef ZEXPORT
  78217. # define ZEXPORT
  78218. #endif
  78219. #ifndef ZEXPORTVA
  78220. # define ZEXPORTVA
  78221. #endif
  78222. #ifndef FAR
  78223. # define FAR
  78224. #endif
  78225. #if !defined(__MACTYPES__)
  78226. typedef unsigned char Byte; /* 8 bits */
  78227. #endif
  78228. typedef unsigned int uInt; /* 16 bits or more */
  78229. typedef unsigned long uLong; /* 32 bits or more */
  78230. #ifdef SMALL_MEDIUM
  78231. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78232. # define Bytef Byte FAR
  78233. #else
  78234. typedef Byte FAR Bytef;
  78235. #endif
  78236. typedef char FAR charf;
  78237. typedef int FAR intf;
  78238. typedef uInt FAR uIntf;
  78239. typedef uLong FAR uLongf;
  78240. #ifdef STDC
  78241. typedef void const *voidpc;
  78242. typedef void FAR *voidpf;
  78243. typedef void *voidp;
  78244. #else
  78245. typedef Byte const *voidpc;
  78246. typedef Byte FAR *voidpf;
  78247. typedef Byte *voidp;
  78248. #endif
  78249. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78250. # include <sys/types.h> /* for off_t */
  78251. # include <unistd.h> /* for SEEK_* and off_t */
  78252. # ifdef VMS
  78253. # include <unixio.h> /* for off_t */
  78254. # endif
  78255. # define z_off_t off_t
  78256. #endif
  78257. #ifndef SEEK_SET
  78258. # define SEEK_SET 0 /* Seek from beginning of file. */
  78259. # define SEEK_CUR 1 /* Seek from current position. */
  78260. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78261. #endif
  78262. #ifndef z_off_t
  78263. # define z_off_t long
  78264. #endif
  78265. #if defined(__OS400__)
  78266. # define NO_vsnprintf
  78267. #endif
  78268. #if defined(__MVS__)
  78269. # define NO_vsnprintf
  78270. # ifdef FAR
  78271. # undef FAR
  78272. # endif
  78273. #endif
  78274. /* MVS linker does not support external names larger than 8 bytes */
  78275. #if defined(__MVS__)
  78276. # pragma map(deflateInit_,"DEIN")
  78277. # pragma map(deflateInit2_,"DEIN2")
  78278. # pragma map(deflateEnd,"DEEND")
  78279. # pragma map(deflateBound,"DEBND")
  78280. # pragma map(inflateInit_,"ININ")
  78281. # pragma map(inflateInit2_,"ININ2")
  78282. # pragma map(inflateEnd,"INEND")
  78283. # pragma map(inflateSync,"INSY")
  78284. # pragma map(inflateSetDictionary,"INSEDI")
  78285. # pragma map(compressBound,"CMBND")
  78286. # pragma map(inflate_table,"INTABL")
  78287. # pragma map(inflate_fast,"INFA")
  78288. # pragma map(inflate_copyright,"INCOPY")
  78289. #endif
  78290. #endif /* ZCONF_H */
  78291. /*** End of inlined file: zconf.h ***/
  78292. #ifdef __cplusplus
  78293. //extern "C" {
  78294. #endif
  78295. #define ZLIB_VERSION "1.2.3"
  78296. #define ZLIB_VERNUM 0x1230
  78297. /*
  78298. The 'zlib' compression library provides in-memory compression and
  78299. decompression functions, including integrity checks of the uncompressed
  78300. data. This version of the library supports only one compression method
  78301. (deflation) but other algorithms will be added later and will have the same
  78302. stream interface.
  78303. Compression can be done in a single step if the buffers are large
  78304. enough (for example if an input file is mmap'ed), or can be done by
  78305. repeated calls of the compression function. In the latter case, the
  78306. application must provide more input and/or consume the output
  78307. (providing more output space) before each call.
  78308. The compressed data format used by default by the in-memory functions is
  78309. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78310. around a deflate stream, which is itself documented in RFC 1951.
  78311. The library also supports reading and writing files in gzip (.gz) format
  78312. with an interface similar to that of stdio using the functions that start
  78313. with "gz". The gzip format is different from the zlib format. gzip is a
  78314. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78315. This library can optionally read and write gzip streams in memory as well.
  78316. The zlib format was designed to be compact and fast for use in memory
  78317. and on communications channels. The gzip format was designed for single-
  78318. file compression on file systems, has a larger header than zlib to maintain
  78319. directory information, and uses a different, slower check method than zlib.
  78320. The library does not install any signal handler. The decoder checks
  78321. the consistency of the compressed data, so the library should never
  78322. crash even in case of corrupted input.
  78323. */
  78324. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78325. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78326. struct internal_state;
  78327. typedef struct z_stream_s {
  78328. Bytef *next_in; /* next input byte */
  78329. uInt avail_in; /* number of bytes available at next_in */
  78330. uLong total_in; /* total nb of input bytes read so far */
  78331. Bytef *next_out; /* next output byte should be put there */
  78332. uInt avail_out; /* remaining free space at next_out */
  78333. uLong total_out; /* total nb of bytes output so far */
  78334. char *msg; /* last error message, NULL if no error */
  78335. struct internal_state FAR *state; /* not visible by applications */
  78336. alloc_func zalloc; /* used to allocate the internal state */
  78337. free_func zfree; /* used to free the internal state */
  78338. voidpf opaque; /* private data object passed to zalloc and zfree */
  78339. int data_type; /* best guess about the data type: binary or text */
  78340. uLong adler; /* adler32 value of the uncompressed data */
  78341. uLong reserved; /* reserved for future use */
  78342. } z_stream;
  78343. typedef z_stream FAR *z_streamp;
  78344. /*
  78345. gzip header information passed to and from zlib routines. See RFC 1952
  78346. for more details on the meanings of these fields.
  78347. */
  78348. typedef struct gz_header_s {
  78349. int text; /* true if compressed data believed to be text */
  78350. uLong time; /* modification time */
  78351. int xflags; /* extra flags (not used when writing a gzip file) */
  78352. int os; /* operating system */
  78353. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78354. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78355. uInt extra_max; /* space at extra (only when reading header) */
  78356. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78357. uInt name_max; /* space at name (only when reading header) */
  78358. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78359. uInt comm_max; /* space at comment (only when reading header) */
  78360. int hcrc; /* true if there was or will be a header crc */
  78361. int done; /* true when done reading gzip header (not used
  78362. when writing a gzip file) */
  78363. } gz_header;
  78364. typedef gz_header FAR *gz_headerp;
  78365. /*
  78366. The application must update next_in and avail_in when avail_in has
  78367. dropped to zero. It must update next_out and avail_out when avail_out
  78368. has dropped to zero. The application must initialize zalloc, zfree and
  78369. opaque before calling the init function. All other fields are set by the
  78370. compression library and must not be updated by the application.
  78371. The opaque value provided by the application will be passed as the first
  78372. parameter for calls of zalloc and zfree. This can be useful for custom
  78373. memory management. The compression library attaches no meaning to the
  78374. opaque value.
  78375. zalloc must return Z_NULL if there is not enough memory for the object.
  78376. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78377. thread safe.
  78378. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78379. exactly 65536 bytes, but will not be required to allocate more than this
  78380. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78381. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78382. have their offset normalized to zero. The default allocation function
  78383. provided by this library ensures this (see zutil.c). To reduce memory
  78384. requirements and avoid any allocation of 64K objects, at the expense of
  78385. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78386. The fields total_in and total_out can be used for statistics or
  78387. progress reports. After compression, total_in holds the total size of
  78388. the uncompressed data and may be saved for use in the decompressor
  78389. (particularly if the decompressor wants to decompress everything in
  78390. a single step).
  78391. */
  78392. /* constants */
  78393. #define Z_NO_FLUSH 0
  78394. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78395. #define Z_SYNC_FLUSH 2
  78396. #define Z_FULL_FLUSH 3
  78397. #define Z_FINISH 4
  78398. #define Z_BLOCK 5
  78399. /* Allowed flush values; see deflate() and inflate() below for details */
  78400. #define Z_OK 0
  78401. #define Z_STREAM_END 1
  78402. #define Z_NEED_DICT 2
  78403. #define Z_ERRNO (-1)
  78404. #define Z_STREAM_ERROR (-2)
  78405. #define Z_DATA_ERROR (-3)
  78406. #define Z_MEM_ERROR (-4)
  78407. #define Z_BUF_ERROR (-5)
  78408. #define Z_VERSION_ERROR (-6)
  78409. /* Return codes for the compression/decompression functions. Negative
  78410. * values are errors, positive values are used for special but normal events.
  78411. */
  78412. #define Z_NO_COMPRESSION 0
  78413. #define Z_BEST_SPEED 1
  78414. #define Z_BEST_COMPRESSION 9
  78415. #define Z_DEFAULT_COMPRESSION (-1)
  78416. /* compression levels */
  78417. #define Z_FILTERED 1
  78418. #define Z_HUFFMAN_ONLY 2
  78419. #define Z_RLE 3
  78420. #define Z_FIXED 4
  78421. #define Z_DEFAULT_STRATEGY 0
  78422. /* compression strategy; see deflateInit2() below for details */
  78423. #define Z_BINARY 0
  78424. #define Z_TEXT 1
  78425. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78426. #define Z_UNKNOWN 2
  78427. /* Possible values of the data_type field (though see inflate()) */
  78428. #define Z_DEFLATED 8
  78429. /* The deflate compression method (the only one supported in this version) */
  78430. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78431. #define zlib_version zlibVersion()
  78432. /* for compatibility with versions < 1.0.2 */
  78433. /* basic functions */
  78434. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78435. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78436. If the first character differs, the library code actually used is
  78437. not compatible with the zlib.h header file used by the application.
  78438. This check is automatically made by deflateInit and inflateInit.
  78439. */
  78440. /*
  78441. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78442. Initializes the internal stream state for compression. The fields
  78443. zalloc, zfree and opaque must be initialized before by the caller.
  78444. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78445. use default allocation functions.
  78446. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78447. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78448. all (the input data is simply copied a block at a time).
  78449. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78450. compression (currently equivalent to level 6).
  78451. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78452. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78453. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78454. with the version assumed by the caller (ZLIB_VERSION).
  78455. msg is set to null if there is no error message. deflateInit does not
  78456. perform any compression: this will be done by deflate().
  78457. */
  78458. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78459. /*
  78460. deflate compresses as much data as possible, and stops when the input
  78461. buffer becomes empty or the output buffer becomes full. It may introduce some
  78462. output latency (reading input without producing any output) except when
  78463. forced to flush.
  78464. The detailed semantics are as follows. deflate performs one or both of the
  78465. following actions:
  78466. - Compress more input starting at next_in and update next_in and avail_in
  78467. accordingly. If not all input can be processed (because there is not
  78468. enough room in the output buffer), next_in and avail_in are updated and
  78469. processing will resume at this point for the next call of deflate().
  78470. - Provide more output starting at next_out and update next_out and avail_out
  78471. accordingly. This action is forced if the parameter flush is non zero.
  78472. Forcing flush frequently degrades the compression ratio, so this parameter
  78473. should be set only when necessary (in interactive applications).
  78474. Some output may be provided even if flush is not set.
  78475. Before the call of deflate(), the application should ensure that at least
  78476. one of the actions is possible, by providing more input and/or consuming
  78477. more output, and updating avail_in or avail_out accordingly; avail_out
  78478. should never be zero before the call. The application can consume the
  78479. compressed output when it wants, for example when the output buffer is full
  78480. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78481. and with zero avail_out, it must be called again after making room in the
  78482. output buffer because there might be more output pending.
  78483. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78484. decide how much data to accumualte before producing output, in order to
  78485. maximize compression.
  78486. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78487. flushed to the output buffer and the output is aligned on a byte boundary, so
  78488. that the decompressor can get all input data available so far. (In particular
  78489. avail_in is zero after the call if enough output space has been provided
  78490. before the call.) Flushing may degrade compression for some compression
  78491. algorithms and so it should be used only when necessary.
  78492. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78493. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78494. restart from this point if previous compressed data has been damaged or if
  78495. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78496. compression.
  78497. If deflate returns with avail_out == 0, this function must be called again
  78498. with the same value of the flush parameter and more output space (updated
  78499. avail_out), until the flush is complete (deflate returns with non-zero
  78500. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78501. avail_out is greater than six to avoid repeated flush markers due to
  78502. avail_out == 0 on return.
  78503. If the parameter flush is set to Z_FINISH, pending input is processed,
  78504. pending output is flushed and deflate returns with Z_STREAM_END if there
  78505. was enough output space; if deflate returns with Z_OK, this function must be
  78506. called again with Z_FINISH and more output space (updated avail_out) but no
  78507. more input data, until it returns with Z_STREAM_END or an error. After
  78508. deflate has returned Z_STREAM_END, the only possible operations on the
  78509. stream are deflateReset or deflateEnd.
  78510. Z_FINISH can be used immediately after deflateInit if all the compression
  78511. is to be done in a single step. In this case, avail_out must be at least
  78512. the value returned by deflateBound (see below). If deflate does not return
  78513. Z_STREAM_END, then it must be called again as described above.
  78514. deflate() sets strm->adler to the adler32 checksum of all input read
  78515. so far (that is, total_in bytes).
  78516. deflate() may update strm->data_type if it can make a good guess about
  78517. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78518. binary. This field is only for information purposes and does not affect
  78519. the compression algorithm in any manner.
  78520. deflate() returns Z_OK if some progress has been made (more input
  78521. processed or more output produced), Z_STREAM_END if all input has been
  78522. consumed and all output has been produced (only when flush is set to
  78523. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78524. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78525. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78526. fatal, and deflate() can be called again with more input and more output
  78527. space to continue compressing.
  78528. */
  78529. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78530. /*
  78531. All dynamically allocated data structures for this stream are freed.
  78532. This function discards any unprocessed input and does not flush any
  78533. pending output.
  78534. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78535. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78536. prematurely (some input or output was discarded). In the error case,
  78537. msg may be set but then points to a static string (which must not be
  78538. deallocated).
  78539. */
  78540. /*
  78541. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78542. Initializes the internal stream state for decompression. The fields
  78543. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78544. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78545. value depends on the compression method), inflateInit determines the
  78546. compression method from the zlib header and allocates all data structures
  78547. accordingly; otherwise the allocation will be deferred to the first call of
  78548. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78549. use default allocation functions.
  78550. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78551. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78552. version assumed by the caller. msg is set to null if there is no error
  78553. message. inflateInit does not perform any decompression apart from reading
  78554. the zlib header if present: this will be done by inflate(). (So next_in and
  78555. avail_in may be modified, but next_out and avail_out are unchanged.)
  78556. */
  78557. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78558. /*
  78559. inflate decompresses as much data as possible, and stops when the input
  78560. buffer becomes empty or the output buffer becomes full. It may introduce
  78561. some output latency (reading input without producing any output) except when
  78562. forced to flush.
  78563. The detailed semantics are as follows. inflate performs one or both of the
  78564. following actions:
  78565. - Decompress more input starting at next_in and update next_in and avail_in
  78566. accordingly. If not all input can be processed (because there is not
  78567. enough room in the output buffer), next_in is updated and processing
  78568. will resume at this point for the next call of inflate().
  78569. - Provide more output starting at next_out and update next_out and avail_out
  78570. accordingly. inflate() provides as much output as possible, until there
  78571. is no more input data or no more space in the output buffer (see below
  78572. about the flush parameter).
  78573. Before the call of inflate(), the application should ensure that at least
  78574. one of the actions is possible, by providing more input and/or consuming
  78575. more output, and updating the next_* and avail_* values accordingly.
  78576. The application can consume the uncompressed output when it wants, for
  78577. example when the output buffer is full (avail_out == 0), or after each
  78578. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78579. must be called again after making room in the output buffer because there
  78580. might be more output pending.
  78581. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78582. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78583. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78584. if and when it gets to the next deflate block boundary. When decoding the
  78585. zlib or gzip format, this will cause inflate() to return immediately after
  78586. the header and before the first block. When doing a raw inflate, inflate()
  78587. will go ahead and process the first block, and will return when it gets to
  78588. the end of that block, or when it runs out of data.
  78589. The Z_BLOCK option assists in appending to or combining deflate streams.
  78590. Also to assist in this, on return inflate() will set strm->data_type to the
  78591. number of unused bits in the last byte taken from strm->next_in, plus 64
  78592. if inflate() is currently decoding the last block in the deflate stream,
  78593. plus 128 if inflate() returned immediately after decoding an end-of-block
  78594. code or decoding the complete header up to just before the first byte of the
  78595. deflate stream. The end-of-block will not be indicated until all of the
  78596. uncompressed data from that block has been written to strm->next_out. The
  78597. number of unused bits may in general be greater than seven, except when
  78598. bit 7 of data_type is set, in which case the number of unused bits will be
  78599. less than eight.
  78600. inflate() should normally be called until it returns Z_STREAM_END or an
  78601. error. However if all decompression is to be performed in a single step
  78602. (a single call of inflate), the parameter flush should be set to
  78603. Z_FINISH. In this case all pending input is processed and all pending
  78604. output is flushed; avail_out must be large enough to hold all the
  78605. uncompressed data. (The size of the uncompressed data may have been saved
  78606. by the compressor for this purpose.) The next operation on this stream must
  78607. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78608. is never required, but can be used to inform inflate that a faster approach
  78609. may be used for the single inflate() call.
  78610. In this implementation, inflate() always flushes as much output as
  78611. possible to the output buffer, and always uses the faster approach on the
  78612. first call. So the only effect of the flush parameter in this implementation
  78613. is on the return value of inflate(), as noted below, or when it returns early
  78614. because Z_BLOCK is used.
  78615. If a preset dictionary is needed after this call (see inflateSetDictionary
  78616. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78617. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78618. strm->adler to the adler32 checksum of all output produced so far (that is,
  78619. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78620. below. At the end of the stream, inflate() checks that its computed adler32
  78621. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78622. only if the checksum is correct.
  78623. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78624. deflate data. The header type is detected automatically. Any information
  78625. contained in the gzip header is not retained, so applications that need that
  78626. information should instead use raw inflate, see inflateInit2() below, or
  78627. inflateBack() and perform their own processing of the gzip header and
  78628. trailer.
  78629. inflate() returns Z_OK if some progress has been made (more input processed
  78630. or more output produced), Z_STREAM_END if the end of the compressed data has
  78631. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78632. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78633. corrupted (input stream not conforming to the zlib format or incorrect check
  78634. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78635. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78636. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78637. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78638. inflate() can be called again with more input and more output space to
  78639. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78640. call inflateSync() to look for a good compression block if a partial recovery
  78641. of the data is desired.
  78642. */
  78643. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78644. /*
  78645. All dynamically allocated data structures for this stream are freed.
  78646. This function discards any unprocessed input and does not flush any
  78647. pending output.
  78648. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78649. was inconsistent. In the error case, msg may be set but then points to a
  78650. static string (which must not be deallocated).
  78651. */
  78652. /* Advanced functions */
  78653. /*
  78654. The following functions are needed only in some special applications.
  78655. */
  78656. /*
  78657. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78658. int level,
  78659. int method,
  78660. int windowBits,
  78661. int memLevel,
  78662. int strategy));
  78663. This is another version of deflateInit with more compression options. The
  78664. fields next_in, zalloc, zfree and opaque must be initialized before by
  78665. the caller.
  78666. The method parameter is the compression method. It must be Z_DEFLATED in
  78667. this version of the library.
  78668. The windowBits parameter is the base two logarithm of the window size
  78669. (the size of the history buffer). It should be in the range 8..15 for this
  78670. version of the library. Larger values of this parameter result in better
  78671. compression at the expense of memory usage. The default value is 15 if
  78672. deflateInit is used instead.
  78673. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78674. determines the window size. deflate() will then generate raw deflate data
  78675. with no zlib header or trailer, and will not compute an adler32 check value.
  78676. windowBits can also be greater than 15 for optional gzip encoding. Add
  78677. 16 to windowBits to write a simple gzip header and trailer around the
  78678. compressed data instead of a zlib wrapper. The gzip header will have no
  78679. file name, no extra data, no comment, no modification time (set to zero),
  78680. no header crc, and the operating system will be set to 255 (unknown). If a
  78681. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78682. The memLevel parameter specifies how much memory should be allocated
  78683. for the internal compression state. memLevel=1 uses minimum memory but
  78684. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78685. for optimal speed. The default value is 8. See zconf.h for total memory
  78686. usage as a function of windowBits and memLevel.
  78687. The strategy parameter is used to tune the compression algorithm. Use the
  78688. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78689. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78690. string match), or Z_RLE to limit match distances to one (run-length
  78691. encoding). Filtered data consists mostly of small values with a somewhat
  78692. random distribution. In this case, the compression algorithm is tuned to
  78693. compress them better. The effect of Z_FILTERED is to force more Huffman
  78694. coding and less string matching; it is somewhat intermediate between
  78695. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78696. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78697. parameter only affects the compression ratio but not the correctness of the
  78698. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78699. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78700. applications.
  78701. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78702. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78703. method). msg is set to null if there is no error message. deflateInit2 does
  78704. not perform any compression: this will be done by deflate().
  78705. */
  78706. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78707. const Bytef *dictionary,
  78708. uInt dictLength));
  78709. /*
  78710. Initializes the compression dictionary from the given byte sequence
  78711. without producing any compressed output. This function must be called
  78712. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78713. call of deflate. The compressor and decompressor must use exactly the same
  78714. dictionary (see inflateSetDictionary).
  78715. The dictionary should consist of strings (byte sequences) that are likely
  78716. to be encountered later in the data to be compressed, with the most commonly
  78717. used strings preferably put towards the end of the dictionary. Using a
  78718. dictionary is most useful when the data to be compressed is short and can be
  78719. predicted with good accuracy; the data can then be compressed better than
  78720. with the default empty dictionary.
  78721. Depending on the size of the compression data structures selected by
  78722. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78723. discarded, for example if the dictionary is larger than the window size in
  78724. deflate or deflate2. Thus the strings most likely to be useful should be
  78725. put at the end of the dictionary, not at the front. In addition, the
  78726. current implementation of deflate will use at most the window size minus
  78727. 262 bytes of the provided dictionary.
  78728. Upon return of this function, strm->adler is set to the adler32 value
  78729. of the dictionary; the decompressor may later use this value to determine
  78730. which dictionary has been used by the compressor. (The adler32 value
  78731. applies to the whole dictionary even if only a subset of the dictionary is
  78732. actually used by the compressor.) If a raw deflate was requested, then the
  78733. adler32 value is not computed and strm->adler is not set.
  78734. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78735. parameter is invalid (such as NULL dictionary) or the stream state is
  78736. inconsistent (for example if deflate has already been called for this stream
  78737. or if the compression method is bsort). deflateSetDictionary does not
  78738. perform any compression: this will be done by deflate().
  78739. */
  78740. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78741. z_streamp source));
  78742. /*
  78743. Sets the destination stream as a complete copy of the source stream.
  78744. This function can be useful when several compression strategies will be
  78745. tried, for example when there are several ways of pre-processing the input
  78746. data with a filter. The streams that will be discarded should then be freed
  78747. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78748. compression state which can be quite large, so this strategy is slow and
  78749. can consume lots of memory.
  78750. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78751. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78752. (such as zalloc being NULL). msg is left unchanged in both source and
  78753. destination.
  78754. */
  78755. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78756. /*
  78757. This function is equivalent to deflateEnd followed by deflateInit,
  78758. but does not free and reallocate all the internal compression state.
  78759. The stream will keep the same compression level and any other attributes
  78760. that may have been set by deflateInit2.
  78761. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78762. stream state was inconsistent (such as zalloc or state being NULL).
  78763. */
  78764. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78765. int level,
  78766. int strategy));
  78767. /*
  78768. Dynamically update the compression level and compression strategy. The
  78769. interpretation of level and strategy is as in deflateInit2. This can be
  78770. used to switch between compression and straight copy of the input data, or
  78771. to switch to a different kind of input data requiring a different
  78772. strategy. If the compression level is changed, the input available so far
  78773. is compressed with the old level (and may be flushed); the new level will
  78774. take effect only at the next call of deflate().
  78775. Before the call of deflateParams, the stream state must be set as for
  78776. a call of deflate(), since the currently available input may have to
  78777. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78778. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78779. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78780. if strm->avail_out was zero.
  78781. */
  78782. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78783. int good_length,
  78784. int max_lazy,
  78785. int nice_length,
  78786. int max_chain));
  78787. /*
  78788. Fine tune deflate's internal compression parameters. This should only be
  78789. used by someone who understands the algorithm used by zlib's deflate for
  78790. searching for the best matching string, and even then only by the most
  78791. fanatic optimizer trying to squeeze out the last compressed bit for their
  78792. specific input data. Read the deflate.c source code for the meaning of the
  78793. max_lazy, good_length, nice_length, and max_chain parameters.
  78794. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78795. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78796. */
  78797. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78798. uLong sourceLen));
  78799. /*
  78800. deflateBound() returns an upper bound on the compressed size after
  78801. deflation of sourceLen bytes. It must be called after deflateInit()
  78802. or deflateInit2(). This would be used to allocate an output buffer
  78803. for deflation in a single pass, and so would be called before deflate().
  78804. */
  78805. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78806. int bits,
  78807. int value));
  78808. /*
  78809. deflatePrime() inserts bits in the deflate output stream. The intent
  78810. is that this function is used to start off the deflate output with the
  78811. bits leftover from a previous deflate stream when appending to it. As such,
  78812. this function can only be used for raw deflate, and must be used before the
  78813. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78814. less than or equal to 16, and that many of the least significant bits of
  78815. value will be inserted in the output.
  78816. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78817. stream state was inconsistent.
  78818. */
  78819. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78820. gz_headerp head));
  78821. /*
  78822. deflateSetHeader() provides gzip header information for when a gzip
  78823. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78824. after deflateInit2() or deflateReset() and before the first call of
  78825. deflate(). The text, time, os, extra field, name, and comment information
  78826. in the provided gz_header structure are written to the gzip header (xflag is
  78827. ignored -- the extra flags are set according to the compression level). The
  78828. caller must assure that, if not Z_NULL, name and comment are terminated with
  78829. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78830. available there. If hcrc is true, a gzip header crc is included. Note that
  78831. the current versions of the command-line version of gzip (up through version
  78832. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78833. gzip file" and give up.
  78834. If deflateSetHeader is not used, the default gzip header has text false,
  78835. the time set to zero, and os set to 255, with no extra, name, or comment
  78836. fields. The gzip header is returned to the default state by deflateReset().
  78837. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78838. stream state was inconsistent.
  78839. */
  78840. /*
  78841. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78842. int windowBits));
  78843. This is another version of inflateInit with an extra parameter. The
  78844. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78845. before by the caller.
  78846. The windowBits parameter is the base two logarithm of the maximum window
  78847. size (the size of the history buffer). It should be in the range 8..15 for
  78848. this version of the library. The default value is 15 if inflateInit is used
  78849. instead. windowBits must be greater than or equal to the windowBits value
  78850. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78851. deflateInit2() was not used. If a compressed stream with a larger window
  78852. size is given as input, inflate() will return with the error code
  78853. Z_DATA_ERROR instead of trying to allocate a larger window.
  78854. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78855. determines the window size. inflate() will then process raw deflate data,
  78856. not looking for a zlib or gzip header, not generating a check value, and not
  78857. looking for any check values for comparison at the end of the stream. This
  78858. is for use with other formats that use the deflate compressed data format
  78859. such as zip. Those formats provide their own check values. If a custom
  78860. format is developed using the raw deflate format for compressed data, it is
  78861. recommended that a check value such as an adler32 or a crc32 be applied to
  78862. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78863. most applications, the zlib format should be used as is. Note that comments
  78864. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78865. windowBits can also be greater than 15 for optional gzip decoding. Add
  78866. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78867. detection, or add 16 to decode only the gzip format (the zlib format will
  78868. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78869. a crc32 instead of an adler32.
  78870. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78871. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78872. is set to null if there is no error message. inflateInit2 does not perform
  78873. any decompression apart from reading the zlib header if present: this will
  78874. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78875. and avail_out are unchanged.)
  78876. */
  78877. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78878. const Bytef *dictionary,
  78879. uInt dictLength));
  78880. /*
  78881. Initializes the decompression dictionary from the given uncompressed byte
  78882. sequence. This function must be called immediately after a call of inflate,
  78883. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78884. can be determined from the adler32 value returned by that call of inflate.
  78885. The compressor and decompressor must use exactly the same dictionary (see
  78886. deflateSetDictionary). For raw inflate, this function can be called
  78887. immediately after inflateInit2() or inflateReset() and before any call of
  78888. inflate() to set the dictionary. The application must insure that the
  78889. dictionary that was used for compression is provided.
  78890. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78891. parameter is invalid (such as NULL dictionary) or the stream state is
  78892. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78893. expected one (incorrect adler32 value). inflateSetDictionary does not
  78894. perform any decompression: this will be done by subsequent calls of
  78895. inflate().
  78896. */
  78897. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78898. /*
  78899. Skips invalid compressed data until a full flush point (see above the
  78900. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78901. available input is skipped. No output is provided.
  78902. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78903. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78904. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78905. case, the application may save the current current value of total_in which
  78906. indicates where valid compressed data was found. In the error case, the
  78907. application may repeatedly call inflateSync, providing more input each time,
  78908. until success or end of the input data.
  78909. */
  78910. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78911. z_streamp source));
  78912. /*
  78913. Sets the destination stream as a complete copy of the source stream.
  78914. This function can be useful when randomly accessing a large stream. The
  78915. first pass through the stream can periodically record the inflate state,
  78916. allowing restarting inflate at those points when randomly accessing the
  78917. stream.
  78918. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78919. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78920. (such as zalloc being NULL). msg is left unchanged in both source and
  78921. destination.
  78922. */
  78923. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78924. /*
  78925. This function is equivalent to inflateEnd followed by inflateInit,
  78926. but does not free and reallocate all the internal decompression state.
  78927. The stream will keep attributes that may have been set by inflateInit2.
  78928. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78929. stream state was inconsistent (such as zalloc or state being NULL).
  78930. */
  78931. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78932. int bits,
  78933. int value));
  78934. /*
  78935. This function inserts bits in the inflate input stream. The intent is
  78936. that this function is used to start inflating at a bit position in the
  78937. middle of a byte. The provided bits will be used before any bytes are used
  78938. from next_in. This function should only be used with raw inflate, and
  78939. should be used before the first inflate() call after inflateInit2() or
  78940. inflateReset(). bits must be less than or equal to 16, and that many of the
  78941. least significant bits of value will be inserted in the input.
  78942. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78943. stream state was inconsistent.
  78944. */
  78945. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78946. gz_headerp head));
  78947. /*
  78948. inflateGetHeader() requests that gzip header information be stored in the
  78949. provided gz_header structure. inflateGetHeader() may be called after
  78950. inflateInit2() or inflateReset(), and before the first call of inflate().
  78951. As inflate() processes the gzip stream, head->done is zero until the header
  78952. is completed, at which time head->done is set to one. If a zlib stream is
  78953. being decoded, then head->done is set to -1 to indicate that there will be
  78954. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78955. force inflate() to return immediately after header processing is complete
  78956. and before any actual data is decompressed.
  78957. The text, time, xflags, and os fields are filled in with the gzip header
  78958. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78959. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78960. contains the maximum number of bytes to write to extra. Once done is true,
  78961. extra_len contains the actual extra field length, and extra contains the
  78962. extra field, or that field truncated if extra_max is less than extra_len.
  78963. If name is not Z_NULL, then up to name_max characters are written there,
  78964. terminated with a zero unless the length is greater than name_max. If
  78965. comment is not Z_NULL, then up to comm_max characters are written there,
  78966. terminated with a zero unless the length is greater than comm_max. When
  78967. any of extra, name, or comment are not Z_NULL and the respective field is
  78968. not present in the header, then that field is set to Z_NULL to signal its
  78969. absence. This allows the use of deflateSetHeader() with the returned
  78970. structure to duplicate the header. However if those fields are set to
  78971. allocated memory, then the application will need to save those pointers
  78972. elsewhere so that they can be eventually freed.
  78973. If inflateGetHeader is not used, then the header information is simply
  78974. discarded. The header is always checked for validity, including the header
  78975. CRC if present. inflateReset() will reset the process to discard the header
  78976. information. The application would need to call inflateGetHeader() again to
  78977. retrieve the header from the next gzip stream.
  78978. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78979. stream state was inconsistent.
  78980. */
  78981. /*
  78982. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78983. unsigned char FAR *window));
  78984. Initialize the internal stream state for decompression using inflateBack()
  78985. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78986. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78987. derived memory allocation routines are used. windowBits is the base two
  78988. logarithm of the window size, in the range 8..15. window is a caller
  78989. supplied buffer of that size. Except for special applications where it is
  78990. assured that deflate was used with small window sizes, windowBits must be 15
  78991. and a 32K byte window must be supplied to be able to decompress general
  78992. deflate streams.
  78993. See inflateBack() for the usage of these routines.
  78994. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78995. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78996. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78997. match the version of the header file.
  78998. */
  78999. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79000. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79001. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79002. in_func in, void FAR *in_desc,
  79003. out_func out, void FAR *out_desc));
  79004. /*
  79005. inflateBack() does a raw inflate with a single call using a call-back
  79006. interface for input and output. This is more efficient than inflate() for
  79007. file i/o applications in that it avoids copying between the output and the
  79008. sliding window by simply making the window itself the output buffer. This
  79009. function trusts the application to not change the output buffer passed by
  79010. the output function, at least until inflateBack() returns.
  79011. inflateBackInit() must be called first to allocate the internal state
  79012. and to initialize the state with the user-provided window buffer.
  79013. inflateBack() may then be used multiple times to inflate a complete, raw
  79014. deflate stream with each call. inflateBackEnd() is then called to free
  79015. the allocated state.
  79016. A raw deflate stream is one with no zlib or gzip header or trailer.
  79017. This routine would normally be used in a utility that reads zip or gzip
  79018. files and writes out uncompressed files. The utility would decode the
  79019. header and process the trailer on its own, hence this routine expects
  79020. only the raw deflate stream to decompress. This is different from the
  79021. normal behavior of inflate(), which expects either a zlib or gzip header and
  79022. trailer around the deflate stream.
  79023. inflateBack() uses two subroutines supplied by the caller that are then
  79024. called by inflateBack() for input and output. inflateBack() calls those
  79025. routines until it reads a complete deflate stream and writes out all of the
  79026. uncompressed data, or until it encounters an error. The function's
  79027. parameters and return types are defined above in the in_func and out_func
  79028. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79029. number of bytes of provided input, and a pointer to that input in buf. If
  79030. there is no input available, in() must return zero--buf is ignored in that
  79031. case--and inflateBack() will return a buffer error. inflateBack() will call
  79032. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79033. should return zero on success, or non-zero on failure. If out() returns
  79034. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79035. are permitted to change the contents of the window provided to
  79036. inflateBackInit(), which is also the buffer that out() uses to write from.
  79037. The length written by out() will be at most the window size. Any non-zero
  79038. amount of input may be provided by in().
  79039. For convenience, inflateBack() can be provided input on the first call by
  79040. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79041. in() will be called. Therefore strm->next_in must be initialized before
  79042. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79043. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79044. must also be initialized, and then if strm->avail_in is not zero, input will
  79045. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79046. The in_desc and out_desc parameters of inflateBack() is passed as the
  79047. first parameter of in() and out() respectively when they are called. These
  79048. descriptors can be optionally used to pass any information that the caller-
  79049. supplied in() and out() functions need to do their job.
  79050. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79051. pass back any unused input that was provided by the last in() call. The
  79052. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79053. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79054. error in the deflate stream (in which case strm->msg is set to indicate the
  79055. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79056. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79057. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79058. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79059. out() returning non-zero. (in() will always be called before out(), so
  79060. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79061. that inflateBack() cannot return Z_OK.
  79062. */
  79063. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79064. /*
  79065. All memory allocated by inflateBackInit() is freed.
  79066. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79067. state was inconsistent.
  79068. */
  79069. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79070. /* Return flags indicating compile-time options.
  79071. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79072. 1.0: size of uInt
  79073. 3.2: size of uLong
  79074. 5.4: size of voidpf (pointer)
  79075. 7.6: size of z_off_t
  79076. Compiler, assembler, and debug options:
  79077. 8: DEBUG
  79078. 9: ASMV or ASMINF -- use ASM code
  79079. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79080. 11: 0 (reserved)
  79081. One-time table building (smaller code, but not thread-safe if true):
  79082. 12: BUILDFIXED -- build static block decoding tables when needed
  79083. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79084. 14,15: 0 (reserved)
  79085. Library content (indicates missing functionality):
  79086. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79087. deflate code when not needed)
  79088. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79089. and decode gzip streams (to avoid linking crc code)
  79090. 18-19: 0 (reserved)
  79091. Operation variations (changes in library functionality):
  79092. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79093. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79094. 22,23: 0 (reserved)
  79095. The sprintf variant used by gzprintf (zero is best):
  79096. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79097. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79098. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79099. Remainder:
  79100. 27-31: 0 (reserved)
  79101. */
  79102. /* utility functions */
  79103. /*
  79104. The following utility functions are implemented on top of the
  79105. basic stream-oriented functions. To simplify the interface, some
  79106. default options are assumed (compression level and memory usage,
  79107. standard memory allocation functions). The source code of these
  79108. utility functions can easily be modified if you need special options.
  79109. */
  79110. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79111. const Bytef *source, uLong sourceLen));
  79112. /*
  79113. Compresses the source buffer into the destination buffer. sourceLen is
  79114. the byte length of the source buffer. Upon entry, destLen is the total
  79115. size of the destination buffer, which must be at least the value returned
  79116. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79117. compressed buffer.
  79118. This function can be used to compress a whole file at once if the
  79119. input file is mmap'ed.
  79120. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79121. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79122. buffer.
  79123. */
  79124. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79125. const Bytef *source, uLong sourceLen,
  79126. int level));
  79127. /*
  79128. Compresses the source buffer into the destination buffer. The level
  79129. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79130. length of the source buffer. Upon entry, destLen is the total size of the
  79131. destination buffer, which must be at least the value returned by
  79132. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79133. compressed buffer.
  79134. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79135. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79136. Z_STREAM_ERROR if the level parameter is invalid.
  79137. */
  79138. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79139. /*
  79140. compressBound() returns an upper bound on the compressed size after
  79141. compress() or compress2() on sourceLen bytes. It would be used before
  79142. a compress() or compress2() call to allocate the destination buffer.
  79143. */
  79144. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79145. const Bytef *source, uLong sourceLen));
  79146. /*
  79147. Decompresses the source buffer into the destination buffer. sourceLen is
  79148. the byte length of the source buffer. Upon entry, destLen is the total
  79149. size of the destination buffer, which must be large enough to hold the
  79150. entire uncompressed data. (The size of the uncompressed data must have
  79151. been saved previously by the compressor and transmitted to the decompressor
  79152. by some mechanism outside the scope of this compression library.)
  79153. Upon exit, destLen is the actual size of the compressed buffer.
  79154. This function can be used to decompress a whole file at once if the
  79155. input file is mmap'ed.
  79156. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79157. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79158. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79159. */
  79160. typedef voidp gzFile;
  79161. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79162. /*
  79163. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79164. is as in fopen ("rb" or "wb") but can also include a compression level
  79165. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79166. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79167. as in "wb1R". (See the description of deflateInit2 for more information
  79168. about the strategy parameter.)
  79169. gzopen can be used to read a file which is not in gzip format; in this
  79170. case gzread will directly read from the file without decompression.
  79171. gzopen returns NULL if the file could not be opened or if there was
  79172. insufficient memory to allocate the (de)compression state; errno
  79173. can be checked to distinguish the two cases (if errno is zero, the
  79174. zlib error is Z_MEM_ERROR). */
  79175. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79176. /*
  79177. gzdopen() associates a gzFile with the file descriptor fd. File
  79178. descriptors are obtained from calls like open, dup, creat, pipe or
  79179. fileno (in the file has been previously opened with fopen).
  79180. The mode parameter is as in gzopen.
  79181. The next call of gzclose on the returned gzFile will also close the
  79182. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79183. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79184. gzdopen returns NULL if there was insufficient memory to allocate
  79185. the (de)compression state.
  79186. */
  79187. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79188. /*
  79189. Dynamically update the compression level or strategy. See the description
  79190. of deflateInit2 for the meaning of these parameters.
  79191. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79192. opened for writing.
  79193. */
  79194. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79195. /*
  79196. Reads the given number of uncompressed bytes from the compressed file.
  79197. If the input file was not in gzip format, gzread copies the given number
  79198. of bytes into the buffer.
  79199. gzread returns the number of uncompressed bytes actually read (0 for
  79200. end of file, -1 for error). */
  79201. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79202. voidpc buf, unsigned len));
  79203. /*
  79204. Writes the given number of uncompressed bytes into the compressed file.
  79205. gzwrite returns the number of uncompressed bytes actually written
  79206. (0 in case of error).
  79207. */
  79208. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79209. /*
  79210. Converts, formats, and writes the args to the compressed file under
  79211. control of the format string, as in fprintf. gzprintf returns the number of
  79212. uncompressed bytes actually written (0 in case of error). The number of
  79213. uncompressed bytes written is limited to 4095. The caller should assure that
  79214. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79215. return an error (0) with nothing written. In this case, there may also be a
  79216. buffer overflow with unpredictable consequences, which is possible only if
  79217. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79218. because the secure snprintf() or vsnprintf() functions were not available.
  79219. */
  79220. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79221. /*
  79222. Writes the given null-terminated string to the compressed file, excluding
  79223. the terminating null character.
  79224. gzputs returns the number of characters written, or -1 in case of error.
  79225. */
  79226. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79227. /*
  79228. Reads bytes from the compressed file until len-1 characters are read, or
  79229. a newline character is read and transferred to buf, or an end-of-file
  79230. condition is encountered. The string is then terminated with a null
  79231. character.
  79232. gzgets returns buf, or Z_NULL in case of error.
  79233. */
  79234. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79235. /*
  79236. Writes c, converted to an unsigned char, into the compressed file.
  79237. gzputc returns the value that was written, or -1 in case of error.
  79238. */
  79239. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79240. /*
  79241. Reads one byte from the compressed file. gzgetc returns this byte
  79242. or -1 in case of end of file or error.
  79243. */
  79244. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79245. /*
  79246. Push one character back onto the stream to be read again later.
  79247. Only one character of push-back is allowed. gzungetc() returns the
  79248. character pushed, or -1 on failure. gzungetc() will fail if a
  79249. character has been pushed but not read yet, or if c is -1. The pushed
  79250. character will be discarded if the stream is repositioned with gzseek()
  79251. or gzrewind().
  79252. */
  79253. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79254. /*
  79255. Flushes all pending output into the compressed file. The parameter
  79256. flush is as in the deflate() function. The return value is the zlib
  79257. error number (see function gzerror below). gzflush returns Z_OK if
  79258. the flush parameter is Z_FINISH and all output could be flushed.
  79259. gzflush should be called only when strictly necessary because it can
  79260. degrade compression.
  79261. */
  79262. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79263. z_off_t offset, int whence));
  79264. /*
  79265. Sets the starting position for the next gzread or gzwrite on the
  79266. given compressed file. The offset represents a number of bytes in the
  79267. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79268. the value SEEK_END is not supported.
  79269. If the file is opened for reading, this function is emulated but can be
  79270. extremely slow. If the file is opened for writing, only forward seeks are
  79271. supported; gzseek then compresses a sequence of zeroes up to the new
  79272. starting position.
  79273. gzseek returns the resulting offset location as measured in bytes from
  79274. the beginning of the uncompressed stream, or -1 in case of error, in
  79275. particular if the file is opened for writing and the new starting position
  79276. would be before the current position.
  79277. */
  79278. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79279. /*
  79280. Rewinds the given file. This function is supported only for reading.
  79281. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79282. */
  79283. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79284. /*
  79285. Returns the starting position for the next gzread or gzwrite on the
  79286. given compressed file. This position represents a number of bytes in the
  79287. uncompressed data stream.
  79288. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79289. */
  79290. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79291. /*
  79292. Returns 1 when EOF has previously been detected reading the given
  79293. input stream, otherwise zero.
  79294. */
  79295. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79296. /*
  79297. Returns 1 if file is being read directly without decompression, otherwise
  79298. zero.
  79299. */
  79300. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79301. /*
  79302. Flushes all pending output if necessary, closes the compressed file
  79303. and deallocates all the (de)compression state. The return value is the zlib
  79304. error number (see function gzerror below).
  79305. */
  79306. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79307. /*
  79308. Returns the error message for the last error which occurred on the
  79309. given compressed file. errnum is set to zlib error number. If an
  79310. error occurred in the file system and not in the compression library,
  79311. errnum is set to Z_ERRNO and the application may consult errno
  79312. to get the exact error code.
  79313. */
  79314. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79315. /*
  79316. Clears the error and end-of-file flags for file. This is analogous to the
  79317. clearerr() function in stdio. This is useful for continuing to read a gzip
  79318. file that is being written concurrently.
  79319. */
  79320. /* checksum functions */
  79321. /*
  79322. These functions are not related to compression but are exported
  79323. anyway because they might be useful in applications using the
  79324. compression library.
  79325. */
  79326. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79327. /*
  79328. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79329. return the updated checksum. If buf is NULL, this function returns
  79330. the required initial value for the checksum.
  79331. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79332. much faster. Usage example:
  79333. uLong adler = adler32(0L, Z_NULL, 0);
  79334. while (read_buffer(buffer, length) != EOF) {
  79335. adler = adler32(adler, buffer, length);
  79336. }
  79337. if (adler != original_adler) error();
  79338. */
  79339. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79340. z_off_t len2));
  79341. /*
  79342. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79343. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79344. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79345. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79346. */
  79347. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79348. /*
  79349. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79350. updated CRC-32. If buf is NULL, this function returns the required initial
  79351. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79352. performed within this function so it shouldn't be done by the application.
  79353. Usage example:
  79354. uLong crc = crc32(0L, Z_NULL, 0);
  79355. while (read_buffer(buffer, length) != EOF) {
  79356. crc = crc32(crc, buffer, length);
  79357. }
  79358. if (crc != original_crc) error();
  79359. */
  79360. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79361. /*
  79362. Combine two CRC-32 check values into one. For two sequences of bytes,
  79363. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79364. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79365. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79366. len2.
  79367. */
  79368. /* various hacks, don't look :) */
  79369. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79370. * and the compiler's view of z_stream:
  79371. */
  79372. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79373. const char *version, int stream_size));
  79374. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79375. const char *version, int stream_size));
  79376. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79377. int windowBits, int memLevel,
  79378. int strategy, const char *version,
  79379. int stream_size));
  79380. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79381. const char *version, int stream_size));
  79382. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79383. unsigned char FAR *window,
  79384. const char *version,
  79385. int stream_size));
  79386. #define deflateInit(strm, level) \
  79387. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79388. #define inflateInit(strm) \
  79389. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79390. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79391. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79392. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79393. #define inflateInit2(strm, windowBits) \
  79394. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79395. #define inflateBackInit(strm, windowBits, window) \
  79396. inflateBackInit_((strm), (windowBits), (window), \
  79397. ZLIB_VERSION, sizeof(z_stream))
  79398. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79399. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79400. #endif
  79401. ZEXTERN const char * ZEXPORT zError OF((int));
  79402. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79403. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79404. #ifdef __cplusplus
  79405. //}
  79406. #endif
  79407. #endif /* ZLIB_H */
  79408. /*** End of inlined file: zlib.h ***/
  79409. #undef OS_CODE
  79410. #else
  79411. #include <zlib.h>
  79412. #endif
  79413. }
  79414. BEGIN_JUCE_NAMESPACE
  79415. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79416. {
  79417. public:
  79418. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79419. : data (0),
  79420. dataSize (0),
  79421. compLevel (compressionLevel),
  79422. strategy (0),
  79423. setParams (true),
  79424. streamIsValid (false),
  79425. finished (false),
  79426. shouldFinish (false)
  79427. {
  79428. using namespace zlibNamespace;
  79429. zerostruct (stream);
  79430. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79431. windowBits != 0 ? windowBits : MAX_WBITS,
  79432. 8, strategy) == Z_OK);
  79433. }
  79434. ~GZIPCompressorHelper()
  79435. {
  79436. using namespace zlibNamespace;
  79437. if (streamIsValid)
  79438. deflateEnd (&stream);
  79439. }
  79440. bool needsInput() const throw()
  79441. {
  79442. return dataSize <= 0;
  79443. }
  79444. void setInput (const uint8* const newData, const int size) throw()
  79445. {
  79446. data = newData;
  79447. dataSize = size;
  79448. }
  79449. int doNextBlock (uint8* const dest, const int destSize) throw()
  79450. {
  79451. using namespace zlibNamespace;
  79452. if (streamIsValid)
  79453. {
  79454. stream.next_in = const_cast <uint8*> (data);
  79455. stream.next_out = dest;
  79456. stream.avail_in = dataSize;
  79457. stream.avail_out = destSize;
  79458. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79459. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79460. setParams = false;
  79461. switch (result)
  79462. {
  79463. case Z_STREAM_END:
  79464. finished = true;
  79465. // Deliberate fall-through..
  79466. case Z_OK:
  79467. data += dataSize - stream.avail_in;
  79468. dataSize = stream.avail_in;
  79469. return destSize - stream.avail_out;
  79470. default:
  79471. break;
  79472. }
  79473. }
  79474. return 0;
  79475. }
  79476. enum { gzipCompBufferSize = 32768 };
  79477. private:
  79478. zlibNamespace::z_stream stream;
  79479. const uint8* data;
  79480. int dataSize, compLevel, strategy;
  79481. bool setParams, streamIsValid;
  79482. public:
  79483. bool finished, shouldFinish;
  79484. };
  79485. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79486. int compressionLevel,
  79487. const bool deleteDestStream,
  79488. const int windowBits)
  79489. : destStream (destStream_),
  79490. streamToDelete (deleteDestStream ? destStream_ : 0),
  79491. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79492. {
  79493. if (compressionLevel < 1 || compressionLevel > 9)
  79494. compressionLevel = -1;
  79495. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79496. }
  79497. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79498. {
  79499. flush();
  79500. }
  79501. void GZIPCompressorOutputStream::flush()
  79502. {
  79503. if (! helper->finished)
  79504. {
  79505. helper->shouldFinish = true;
  79506. while (! helper->finished)
  79507. doNextBlock();
  79508. }
  79509. destStream->flush();
  79510. }
  79511. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79512. {
  79513. if (! helper->finished)
  79514. {
  79515. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79516. while (! helper->needsInput())
  79517. {
  79518. if (! doNextBlock())
  79519. return false;
  79520. }
  79521. }
  79522. return true;
  79523. }
  79524. bool GZIPCompressorOutputStream::doNextBlock()
  79525. {
  79526. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79527. return len <= 0 || destStream->write (buffer, len);
  79528. }
  79529. int64 GZIPCompressorOutputStream::getPosition()
  79530. {
  79531. return destStream->getPosition();
  79532. }
  79533. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79534. {
  79535. jassertfalse; // can't do it!
  79536. return false;
  79537. }
  79538. END_JUCE_NAMESPACE
  79539. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79540. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79541. #if JUCE_MSVC
  79542. #pragma warning (push)
  79543. #pragma warning (disable: 4309 4305)
  79544. #endif
  79545. namespace zlibNamespace
  79546. {
  79547. #if JUCE_INCLUDE_ZLIB_CODE
  79548. #undef OS_CODE
  79549. #undef fdopen
  79550. #define ZLIB_INTERNAL
  79551. #define NO_DUMMY_DECL
  79552. /*** Start of inlined file: adler32.c ***/
  79553. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79554. #define ZLIB_INTERNAL
  79555. #define BASE 65521UL /* largest prime smaller than 65536 */
  79556. #define NMAX 5552
  79557. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79558. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79559. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79560. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79561. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79562. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79563. /* use NO_DIVIDE if your processor does not do division in hardware */
  79564. #ifdef NO_DIVIDE
  79565. # define MOD(a) \
  79566. do { \
  79567. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79568. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79569. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79570. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79571. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79572. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79573. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79574. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79575. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79576. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79577. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79578. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79579. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79580. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79581. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79582. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79583. if (a >= BASE) a -= BASE; \
  79584. } while (0)
  79585. # define MOD4(a) \
  79586. do { \
  79587. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79588. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79589. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79590. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79591. if (a >= BASE) a -= BASE; \
  79592. } while (0)
  79593. #else
  79594. # define MOD(a) a %= BASE
  79595. # define MOD4(a) a %= BASE
  79596. #endif
  79597. /* ========================================================================= */
  79598. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79599. {
  79600. unsigned long sum2;
  79601. unsigned n;
  79602. /* split Adler-32 into component sums */
  79603. sum2 = (adler >> 16) & 0xffff;
  79604. adler &= 0xffff;
  79605. /* in case user likes doing a byte at a time, keep it fast */
  79606. if (len == 1) {
  79607. adler += buf[0];
  79608. if (adler >= BASE)
  79609. adler -= BASE;
  79610. sum2 += adler;
  79611. if (sum2 >= BASE)
  79612. sum2 -= BASE;
  79613. return adler | (sum2 << 16);
  79614. }
  79615. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79616. if (buf == Z_NULL)
  79617. return 1L;
  79618. /* in case short lengths are provided, keep it somewhat fast */
  79619. if (len < 16) {
  79620. while (len--) {
  79621. adler += *buf++;
  79622. sum2 += adler;
  79623. }
  79624. if (adler >= BASE)
  79625. adler -= BASE;
  79626. MOD4(sum2); /* only added so many BASE's */
  79627. return adler | (sum2 << 16);
  79628. }
  79629. /* do length NMAX blocks -- requires just one modulo operation */
  79630. while (len >= NMAX) {
  79631. len -= NMAX;
  79632. n = NMAX / 16; /* NMAX is divisible by 16 */
  79633. do {
  79634. DO16(buf); /* 16 sums unrolled */
  79635. buf += 16;
  79636. } while (--n);
  79637. MOD(adler);
  79638. MOD(sum2);
  79639. }
  79640. /* do remaining bytes (less than NMAX, still just one modulo) */
  79641. if (len) { /* avoid modulos if none remaining */
  79642. while (len >= 16) {
  79643. len -= 16;
  79644. DO16(buf);
  79645. buf += 16;
  79646. }
  79647. while (len--) {
  79648. adler += *buf++;
  79649. sum2 += adler;
  79650. }
  79651. MOD(adler);
  79652. MOD(sum2);
  79653. }
  79654. /* return recombined sums */
  79655. return adler | (sum2 << 16);
  79656. }
  79657. /* ========================================================================= */
  79658. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79659. {
  79660. unsigned long sum1;
  79661. unsigned long sum2;
  79662. unsigned rem;
  79663. /* the derivation of this formula is left as an exercise for the reader */
  79664. rem = (unsigned)(len2 % BASE);
  79665. sum1 = adler1 & 0xffff;
  79666. sum2 = rem * sum1;
  79667. MOD(sum2);
  79668. sum1 += (adler2 & 0xffff) + BASE - 1;
  79669. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79670. if (sum1 > BASE) sum1 -= BASE;
  79671. if (sum1 > BASE) sum1 -= BASE;
  79672. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79673. if (sum2 > BASE) sum2 -= BASE;
  79674. return sum1 | (sum2 << 16);
  79675. }
  79676. /*** End of inlined file: adler32.c ***/
  79677. /*** Start of inlined file: compress.c ***/
  79678. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79679. #define ZLIB_INTERNAL
  79680. /* ===========================================================================
  79681. Compresses the source buffer into the destination buffer. The level
  79682. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79683. length of the source buffer. Upon entry, destLen is the total size of the
  79684. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79685. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79686. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79687. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79688. Z_STREAM_ERROR if the level parameter is invalid.
  79689. */
  79690. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79691. uLong sourceLen, int level)
  79692. {
  79693. z_stream stream;
  79694. int err;
  79695. stream.next_in = (Bytef*)source;
  79696. stream.avail_in = (uInt)sourceLen;
  79697. #ifdef MAXSEG_64K
  79698. /* Check for source > 64K on 16-bit machine: */
  79699. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79700. #endif
  79701. stream.next_out = dest;
  79702. stream.avail_out = (uInt)*destLen;
  79703. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79704. stream.zalloc = (alloc_func)0;
  79705. stream.zfree = (free_func)0;
  79706. stream.opaque = (voidpf)0;
  79707. err = deflateInit(&stream, level);
  79708. if (err != Z_OK) return err;
  79709. err = deflate(&stream, Z_FINISH);
  79710. if (err != Z_STREAM_END) {
  79711. deflateEnd(&stream);
  79712. return err == Z_OK ? Z_BUF_ERROR : err;
  79713. }
  79714. *destLen = stream.total_out;
  79715. err = deflateEnd(&stream);
  79716. return err;
  79717. }
  79718. /* ===========================================================================
  79719. */
  79720. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79721. {
  79722. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79723. }
  79724. /* ===========================================================================
  79725. If the default memLevel or windowBits for deflateInit() is changed, then
  79726. this function needs to be updated.
  79727. */
  79728. uLong ZEXPORT compressBound (uLong sourceLen)
  79729. {
  79730. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79731. }
  79732. /*** End of inlined file: compress.c ***/
  79733. #undef DO1
  79734. #undef DO8
  79735. /*** Start of inlined file: crc32.c ***/
  79736. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79737. /*
  79738. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79739. protection on the static variables used to control the first-use generation
  79740. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79741. first call get_crc_table() to initialize the tables before allowing more than
  79742. one thread to use crc32().
  79743. */
  79744. #ifdef MAKECRCH
  79745. # include <stdio.h>
  79746. # ifndef DYNAMIC_CRC_TABLE
  79747. # define DYNAMIC_CRC_TABLE
  79748. # endif /* !DYNAMIC_CRC_TABLE */
  79749. #endif /* MAKECRCH */
  79750. /*** Start of inlined file: zutil.h ***/
  79751. /* WARNING: this file should *not* be used by applications. It is
  79752. part of the implementation of the compression library and is
  79753. subject to change. Applications should only use zlib.h.
  79754. */
  79755. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79756. #ifndef ZUTIL_H
  79757. #define ZUTIL_H
  79758. #define ZLIB_INTERNAL
  79759. #ifdef STDC
  79760. # ifndef _WIN32_WCE
  79761. # include <stddef.h>
  79762. # endif
  79763. # include <string.h>
  79764. # include <stdlib.h>
  79765. #endif
  79766. #ifdef NO_ERRNO_H
  79767. # ifdef _WIN32_WCE
  79768. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79769. * errno. We define it as a global variable to simplify porting.
  79770. * Its value is always 0 and should not be used. We rename it to
  79771. * avoid conflict with other libraries that use the same workaround.
  79772. */
  79773. # define errno z_errno
  79774. # endif
  79775. extern int errno;
  79776. #else
  79777. # ifndef _WIN32_WCE
  79778. # include <errno.h>
  79779. # endif
  79780. #endif
  79781. #ifndef local
  79782. # define local static
  79783. #endif
  79784. /* compile with -Dlocal if your debugger can't find static symbols */
  79785. typedef unsigned char uch;
  79786. typedef uch FAR uchf;
  79787. typedef unsigned short ush;
  79788. typedef ush FAR ushf;
  79789. typedef unsigned long ulg;
  79790. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79791. /* (size given to avoid silly warnings with Visual C++) */
  79792. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79793. #define ERR_RETURN(strm,err) \
  79794. return (strm->msg = (char*)ERR_MSG(err), (err))
  79795. /* To be used only when the state is known to be valid */
  79796. /* common constants */
  79797. #ifndef DEF_WBITS
  79798. # define DEF_WBITS MAX_WBITS
  79799. #endif
  79800. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79801. #if MAX_MEM_LEVEL >= 8
  79802. # define DEF_MEM_LEVEL 8
  79803. #else
  79804. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79805. #endif
  79806. /* default memLevel */
  79807. #define STORED_BLOCK 0
  79808. #define STATIC_TREES 1
  79809. #define DYN_TREES 2
  79810. /* The three kinds of block type */
  79811. #define MIN_MATCH 3
  79812. #define MAX_MATCH 258
  79813. /* The minimum and maximum match lengths */
  79814. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79815. /* target dependencies */
  79816. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79817. # define OS_CODE 0x00
  79818. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79819. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79820. /* Allow compilation with ANSI keywords only enabled */
  79821. void _Cdecl farfree( void *block );
  79822. void *_Cdecl farmalloc( unsigned long nbytes );
  79823. # else
  79824. # include <alloc.h>
  79825. # endif
  79826. # else /* MSC or DJGPP */
  79827. # include <malloc.h>
  79828. # endif
  79829. #endif
  79830. #ifdef AMIGA
  79831. # define OS_CODE 0x01
  79832. #endif
  79833. #if defined(VAXC) || defined(VMS)
  79834. # define OS_CODE 0x02
  79835. # define F_OPEN(name, mode) \
  79836. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79837. #endif
  79838. #if defined(ATARI) || defined(atarist)
  79839. # define OS_CODE 0x05
  79840. #endif
  79841. #ifdef OS2
  79842. # define OS_CODE 0x06
  79843. # ifdef M_I86
  79844. #include <malloc.h>
  79845. # endif
  79846. #endif
  79847. #if defined(MACOS) || TARGET_OS_MAC
  79848. # define OS_CODE 0x07
  79849. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79850. # include <unix.h> /* for fdopen */
  79851. # else
  79852. # ifndef fdopen
  79853. # define fdopen(fd,mode) NULL /* No fdopen() */
  79854. # endif
  79855. # endif
  79856. #endif
  79857. #ifdef TOPS20
  79858. # define OS_CODE 0x0a
  79859. #endif
  79860. #ifdef WIN32
  79861. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79862. # define OS_CODE 0x0b
  79863. # endif
  79864. #endif
  79865. #ifdef __50SERIES /* Prime/PRIMOS */
  79866. # define OS_CODE 0x0f
  79867. #endif
  79868. #if defined(_BEOS_) || defined(RISCOS)
  79869. # define fdopen(fd,mode) NULL /* No fdopen() */
  79870. #endif
  79871. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79872. # if defined(_WIN32_WCE)
  79873. # define fdopen(fd,mode) NULL /* No fdopen() */
  79874. # ifndef _PTRDIFF_T_DEFINED
  79875. typedef int ptrdiff_t;
  79876. # define _PTRDIFF_T_DEFINED
  79877. # endif
  79878. # else
  79879. # define fdopen(fd,type) _fdopen(fd,type)
  79880. # endif
  79881. #endif
  79882. /* common defaults */
  79883. #ifndef OS_CODE
  79884. # define OS_CODE 0x03 /* assume Unix */
  79885. #endif
  79886. #ifndef F_OPEN
  79887. # define F_OPEN(name, mode) fopen((name), (mode))
  79888. #endif
  79889. /* functions */
  79890. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79891. # ifndef HAVE_VSNPRINTF
  79892. # define HAVE_VSNPRINTF
  79893. # endif
  79894. #endif
  79895. #if defined(__CYGWIN__)
  79896. # ifndef HAVE_VSNPRINTF
  79897. # define HAVE_VSNPRINTF
  79898. # endif
  79899. #endif
  79900. #ifndef HAVE_VSNPRINTF
  79901. # ifdef MSDOS
  79902. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79903. but for now we just assume it doesn't. */
  79904. # define NO_vsnprintf
  79905. # endif
  79906. # ifdef __TURBOC__
  79907. # define NO_vsnprintf
  79908. # endif
  79909. # ifdef WIN32
  79910. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79911. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79912. # define vsnprintf _vsnprintf
  79913. # endif
  79914. # endif
  79915. # ifdef __SASC
  79916. # define NO_vsnprintf
  79917. # endif
  79918. #endif
  79919. #ifdef VMS
  79920. # define NO_vsnprintf
  79921. #endif
  79922. #if defined(pyr)
  79923. # define NO_MEMCPY
  79924. #endif
  79925. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79926. /* Use our own functions for small and medium model with MSC <= 5.0.
  79927. * You may have to use the same strategy for Borland C (untested).
  79928. * The __SC__ check is for Symantec.
  79929. */
  79930. # define NO_MEMCPY
  79931. #endif
  79932. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79933. # define HAVE_MEMCPY
  79934. #endif
  79935. #ifdef HAVE_MEMCPY
  79936. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79937. # define zmemcpy _fmemcpy
  79938. # define zmemcmp _fmemcmp
  79939. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79940. # else
  79941. # define zmemcpy memcpy
  79942. # define zmemcmp memcmp
  79943. # define zmemzero(dest, len) memset(dest, 0, len)
  79944. # endif
  79945. #else
  79946. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79947. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79948. extern void zmemzero OF((Bytef* dest, uInt len));
  79949. #endif
  79950. /* Diagnostic functions */
  79951. #ifdef DEBUG
  79952. # include <stdio.h>
  79953. extern int z_verbose;
  79954. extern void z_error OF((const char *m));
  79955. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79956. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79957. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79958. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79959. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79960. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79961. #else
  79962. # define Assert(cond,msg)
  79963. # define Trace(x)
  79964. # define Tracev(x)
  79965. # define Tracevv(x)
  79966. # define Tracec(c,x)
  79967. # define Tracecv(c,x)
  79968. #endif
  79969. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79970. void zcfree OF((voidpf opaque, voidpf ptr));
  79971. #define ZALLOC(strm, items, size) \
  79972. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79973. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79974. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79975. #endif /* ZUTIL_H */
  79976. /*** End of inlined file: zutil.h ***/
  79977. /* for STDC and FAR definitions */
  79978. #define local static
  79979. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79980. #ifndef NOBYFOUR
  79981. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79982. # include <limits.h>
  79983. # define BYFOUR
  79984. # if (UINT_MAX == 0xffffffffUL)
  79985. typedef unsigned int u4;
  79986. # else
  79987. # if (ULONG_MAX == 0xffffffffUL)
  79988. typedef unsigned long u4;
  79989. # else
  79990. # if (USHRT_MAX == 0xffffffffUL)
  79991. typedef unsigned short u4;
  79992. # else
  79993. # undef BYFOUR /* can't find a four-byte integer type! */
  79994. # endif
  79995. # endif
  79996. # endif
  79997. # endif /* STDC */
  79998. #endif /* !NOBYFOUR */
  79999. /* Definitions for doing the crc four data bytes at a time. */
  80000. #ifdef BYFOUR
  80001. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80002. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80003. local unsigned long crc32_little OF((unsigned long,
  80004. const unsigned char FAR *, unsigned));
  80005. local unsigned long crc32_big OF((unsigned long,
  80006. const unsigned char FAR *, unsigned));
  80007. # define TBLS 8
  80008. #else
  80009. # define TBLS 1
  80010. #endif /* BYFOUR */
  80011. /* Local functions for crc concatenation */
  80012. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80013. unsigned long vec));
  80014. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80015. #ifdef DYNAMIC_CRC_TABLE
  80016. local volatile int crc_table_empty = 1;
  80017. local unsigned long FAR crc_table[TBLS][256];
  80018. local void make_crc_table OF((void));
  80019. #ifdef MAKECRCH
  80020. local void write_table OF((FILE *, const unsigned long FAR *));
  80021. #endif /* MAKECRCH */
  80022. /*
  80023. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80024. 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.
  80025. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80026. with the lowest powers in the most significant bit. Then adding polynomials
  80027. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80028. one. If we call the above polynomial p, and represent a byte as the
  80029. polynomial q, also with the lowest power in the most significant bit (so the
  80030. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80031. where a mod b means the remainder after dividing a by b.
  80032. This calculation is done using the shift-register method of multiplying and
  80033. taking the remainder. The register is initialized to zero, and for each
  80034. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80035. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80036. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80037. out is a one). We start with the highest power (least significant bit) of
  80038. q and repeat for all eight bits of q.
  80039. The first table is simply the CRC of all possible eight bit values. This is
  80040. all the information needed to generate CRCs on data a byte at a time for all
  80041. combinations of CRC register values and incoming bytes. The remaining tables
  80042. allow for word-at-a-time CRC calculation for both big-endian and little-
  80043. endian machines, where a word is four bytes.
  80044. */
  80045. local void make_crc_table()
  80046. {
  80047. unsigned long c;
  80048. int n, k;
  80049. unsigned long poly; /* polynomial exclusive-or pattern */
  80050. /* terms of polynomial defining this crc (except x^32): */
  80051. static volatile int first = 1; /* flag to limit concurrent making */
  80052. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80053. /* See if another task is already doing this (not thread-safe, but better
  80054. than nothing -- significantly reduces duration of vulnerability in
  80055. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80056. if (first) {
  80057. first = 0;
  80058. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80059. poly = 0UL;
  80060. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80061. poly |= 1UL << (31 - p[n]);
  80062. /* generate a crc for every 8-bit value */
  80063. for (n = 0; n < 256; n++) {
  80064. c = (unsigned long)n;
  80065. for (k = 0; k < 8; k++)
  80066. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80067. crc_table[0][n] = c;
  80068. }
  80069. #ifdef BYFOUR
  80070. /* generate crc for each value followed by one, two, and three zeros,
  80071. and then the byte reversal of those as well as the first table */
  80072. for (n = 0; n < 256; n++) {
  80073. c = crc_table[0][n];
  80074. crc_table[4][n] = REV(c);
  80075. for (k = 1; k < 4; k++) {
  80076. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80077. crc_table[k][n] = c;
  80078. crc_table[k + 4][n] = REV(c);
  80079. }
  80080. }
  80081. #endif /* BYFOUR */
  80082. crc_table_empty = 0;
  80083. }
  80084. else { /* not first */
  80085. /* wait for the other guy to finish (not efficient, but rare) */
  80086. while (crc_table_empty)
  80087. ;
  80088. }
  80089. #ifdef MAKECRCH
  80090. /* write out CRC tables to crc32.h */
  80091. {
  80092. FILE *out;
  80093. out = fopen("crc32.h", "w");
  80094. if (out == NULL) return;
  80095. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80096. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80097. fprintf(out, "local const unsigned long FAR ");
  80098. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80099. write_table(out, crc_table[0]);
  80100. # ifdef BYFOUR
  80101. fprintf(out, "#ifdef BYFOUR\n");
  80102. for (k = 1; k < 8; k++) {
  80103. fprintf(out, " },\n {\n");
  80104. write_table(out, crc_table[k]);
  80105. }
  80106. fprintf(out, "#endif\n");
  80107. # endif /* BYFOUR */
  80108. fprintf(out, " }\n};\n");
  80109. fclose(out);
  80110. }
  80111. #endif /* MAKECRCH */
  80112. }
  80113. #ifdef MAKECRCH
  80114. local void write_table(out, table)
  80115. FILE *out;
  80116. const unsigned long FAR *table;
  80117. {
  80118. int n;
  80119. for (n = 0; n < 256; n++)
  80120. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80121. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80122. }
  80123. #endif /* MAKECRCH */
  80124. #else /* !DYNAMIC_CRC_TABLE */
  80125. /* ========================================================================
  80126. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80127. */
  80128. /*** Start of inlined file: crc32.h ***/
  80129. local const unsigned long FAR crc_table[TBLS][256] =
  80130. {
  80131. {
  80132. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80133. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80134. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80135. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80136. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80137. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80138. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80139. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80140. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80141. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80142. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80143. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80144. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80145. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80146. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80147. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80148. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80149. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80150. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80151. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80152. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80153. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80154. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80155. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80156. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80157. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80158. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80159. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80160. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80161. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80162. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80163. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80164. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80165. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80166. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80167. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80168. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80169. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80170. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80171. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80172. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80173. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80174. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80175. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80176. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80177. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80178. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80179. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80180. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80181. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80182. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80183. 0x2d02ef8dUL
  80184. #ifdef BYFOUR
  80185. },
  80186. {
  80187. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80188. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80189. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80190. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80191. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80192. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80193. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80194. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80195. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80196. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80197. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80198. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80199. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80200. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80201. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80202. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80203. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80204. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80205. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80206. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80207. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80208. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80209. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80210. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80211. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80212. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80213. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80214. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80215. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80216. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80217. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80218. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80219. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80220. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80221. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80222. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80223. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80224. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80225. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80226. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80227. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80228. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80229. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80230. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80231. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80232. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80233. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80234. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80235. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80236. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80237. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80238. 0x9324fd72UL
  80239. },
  80240. {
  80241. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80242. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80243. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80244. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80245. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80246. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80247. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80248. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80249. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80250. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80251. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80252. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80253. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80254. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80255. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80256. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80257. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80258. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80259. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80260. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80261. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80262. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80263. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80264. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80265. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80266. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80267. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80268. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80269. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80270. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80271. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80272. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80273. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80274. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80275. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80276. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80277. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80278. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80279. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80280. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80281. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80282. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80283. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80284. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80285. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80286. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80287. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80288. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80289. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80290. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80291. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80292. 0xbe9834edUL
  80293. },
  80294. {
  80295. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80296. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80297. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80298. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80299. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80300. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80301. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80302. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80303. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80304. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80305. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80306. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80307. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80308. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80309. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80310. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80311. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80312. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80313. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80314. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80315. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80316. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80317. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80318. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80319. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80320. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80321. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80322. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80323. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80324. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80325. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80326. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80327. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80328. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80329. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80330. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80331. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80332. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80333. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80334. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80335. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80336. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80337. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80338. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80339. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80340. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80341. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80342. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80343. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80344. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80345. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80346. 0xde0506f1UL
  80347. },
  80348. {
  80349. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80350. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80351. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80352. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80353. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80354. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80355. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80356. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80357. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80358. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80359. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80360. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80361. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80362. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80363. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80364. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80365. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80366. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80367. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80368. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80369. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80370. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80371. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80372. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80373. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80374. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80375. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80376. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80377. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80378. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80379. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80380. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80381. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80382. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80383. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80384. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80385. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80386. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80387. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80388. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80389. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80390. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80391. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80392. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80393. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80394. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80395. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80396. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80397. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80398. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80399. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80400. 0x8def022dUL
  80401. },
  80402. {
  80403. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80404. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80405. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80406. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80407. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80408. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80409. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80410. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80411. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80412. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80413. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80414. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80415. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80416. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80417. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80418. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80419. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80420. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80421. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80422. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80423. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80424. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80425. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80426. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80427. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80428. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80429. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80430. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80431. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80432. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80433. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80434. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80435. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80436. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80437. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80438. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80439. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80440. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80441. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80442. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80443. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80444. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80445. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80446. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80447. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80448. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80449. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80450. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80451. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80452. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80453. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80454. 0x72fd2493UL
  80455. },
  80456. {
  80457. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80458. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80459. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80460. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80461. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80462. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80463. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80464. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80465. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80466. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80467. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80468. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80469. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80470. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80471. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80472. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80473. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80474. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80475. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80476. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80477. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80478. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80479. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80480. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80481. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80482. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80483. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80484. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80485. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80486. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80487. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80488. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80489. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80490. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80491. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80492. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80493. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80494. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80495. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80496. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80497. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80498. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80499. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80500. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80501. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80502. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80503. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80504. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80505. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80506. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80507. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80508. 0xed3498beUL
  80509. },
  80510. {
  80511. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80512. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80513. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80514. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80515. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80516. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80517. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80518. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80519. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80520. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80521. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80522. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80523. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80524. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80525. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80526. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80527. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80528. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80529. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80530. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80531. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80532. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80533. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80534. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80535. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80536. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80537. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80538. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80539. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80540. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80541. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80542. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80543. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80544. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80545. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80546. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80547. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80548. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80549. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80550. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80551. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80552. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80553. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80554. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80555. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80556. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80557. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80558. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80559. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80560. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80561. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80562. 0xf10605deUL
  80563. #endif
  80564. }
  80565. };
  80566. /*** End of inlined file: crc32.h ***/
  80567. #endif /* DYNAMIC_CRC_TABLE */
  80568. /* =========================================================================
  80569. * This function can be used by asm versions of crc32()
  80570. */
  80571. const unsigned long FAR * ZEXPORT get_crc_table()
  80572. {
  80573. #ifdef DYNAMIC_CRC_TABLE
  80574. if (crc_table_empty)
  80575. make_crc_table();
  80576. #endif /* DYNAMIC_CRC_TABLE */
  80577. return (const unsigned long FAR *)crc_table;
  80578. }
  80579. /* ========================================================================= */
  80580. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80581. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80582. /* ========================================================================= */
  80583. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80584. {
  80585. if (buf == Z_NULL) return 0UL;
  80586. #ifdef DYNAMIC_CRC_TABLE
  80587. if (crc_table_empty)
  80588. make_crc_table();
  80589. #endif /* DYNAMIC_CRC_TABLE */
  80590. #ifdef BYFOUR
  80591. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80592. u4 endian;
  80593. endian = 1;
  80594. if (*((unsigned char *)(&endian)))
  80595. return crc32_little(crc, buf, len);
  80596. else
  80597. return crc32_big(crc, buf, len);
  80598. }
  80599. #endif /* BYFOUR */
  80600. crc = crc ^ 0xffffffffUL;
  80601. while (len >= 8) {
  80602. DO8;
  80603. len -= 8;
  80604. }
  80605. if (len) do {
  80606. DO1;
  80607. } while (--len);
  80608. return crc ^ 0xffffffffUL;
  80609. }
  80610. #ifdef BYFOUR
  80611. /* ========================================================================= */
  80612. #define DOLIT4 c ^= *buf4++; \
  80613. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80614. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80615. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80616. /* ========================================================================= */
  80617. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80618. {
  80619. register u4 c;
  80620. register const u4 FAR *buf4;
  80621. c = (u4)crc;
  80622. c = ~c;
  80623. while (len && ((ptrdiff_t)buf & 3)) {
  80624. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80625. len--;
  80626. }
  80627. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80628. while (len >= 32) {
  80629. DOLIT32;
  80630. len -= 32;
  80631. }
  80632. while (len >= 4) {
  80633. DOLIT4;
  80634. len -= 4;
  80635. }
  80636. buf = (const unsigned char FAR *)buf4;
  80637. if (len) do {
  80638. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80639. } while (--len);
  80640. c = ~c;
  80641. return (unsigned long)c;
  80642. }
  80643. /* ========================================================================= */
  80644. #define DOBIG4 c ^= *++buf4; \
  80645. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80646. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80647. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80648. /* ========================================================================= */
  80649. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80650. {
  80651. register u4 c;
  80652. register const u4 FAR *buf4;
  80653. c = REV((u4)crc);
  80654. c = ~c;
  80655. while (len && ((ptrdiff_t)buf & 3)) {
  80656. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80657. len--;
  80658. }
  80659. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80660. buf4--;
  80661. while (len >= 32) {
  80662. DOBIG32;
  80663. len -= 32;
  80664. }
  80665. while (len >= 4) {
  80666. DOBIG4;
  80667. len -= 4;
  80668. }
  80669. buf4++;
  80670. buf = (const unsigned char FAR *)buf4;
  80671. if (len) do {
  80672. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80673. } while (--len);
  80674. c = ~c;
  80675. return (unsigned long)(REV(c));
  80676. }
  80677. #endif /* BYFOUR */
  80678. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80679. /* ========================================================================= */
  80680. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80681. {
  80682. unsigned long sum;
  80683. sum = 0;
  80684. while (vec) {
  80685. if (vec & 1)
  80686. sum ^= *mat;
  80687. vec >>= 1;
  80688. mat++;
  80689. }
  80690. return sum;
  80691. }
  80692. /* ========================================================================= */
  80693. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80694. {
  80695. int n;
  80696. for (n = 0; n < GF2_DIM; n++)
  80697. square[n] = gf2_matrix_times(mat, mat[n]);
  80698. }
  80699. /* ========================================================================= */
  80700. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80701. {
  80702. int n;
  80703. unsigned long row;
  80704. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80705. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80706. /* degenerate case */
  80707. if (len2 == 0)
  80708. return crc1;
  80709. /* put operator for one zero bit in odd */
  80710. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80711. row = 1;
  80712. for (n = 1; n < GF2_DIM; n++) {
  80713. odd[n] = row;
  80714. row <<= 1;
  80715. }
  80716. /* put operator for two zero bits in even */
  80717. gf2_matrix_square(even, odd);
  80718. /* put operator for four zero bits in odd */
  80719. gf2_matrix_square(odd, even);
  80720. /* apply len2 zeros to crc1 (first square will put the operator for one
  80721. zero byte, eight zero bits, in even) */
  80722. do {
  80723. /* apply zeros operator for this bit of len2 */
  80724. gf2_matrix_square(even, odd);
  80725. if (len2 & 1)
  80726. crc1 = gf2_matrix_times(even, crc1);
  80727. len2 >>= 1;
  80728. /* if no more bits set, then done */
  80729. if (len2 == 0)
  80730. break;
  80731. /* another iteration of the loop with odd and even swapped */
  80732. gf2_matrix_square(odd, even);
  80733. if (len2 & 1)
  80734. crc1 = gf2_matrix_times(odd, crc1);
  80735. len2 >>= 1;
  80736. /* if no more bits set, then done */
  80737. } while (len2 != 0);
  80738. /* return combined crc */
  80739. crc1 ^= crc2;
  80740. return crc1;
  80741. }
  80742. /*** End of inlined file: crc32.c ***/
  80743. /*** Start of inlined file: deflate.c ***/
  80744. /*
  80745. * ALGORITHM
  80746. *
  80747. * The "deflation" process depends on being able to identify portions
  80748. * of the input text which are identical to earlier input (within a
  80749. * sliding window trailing behind the input currently being processed).
  80750. *
  80751. * The most straightforward technique turns out to be the fastest for
  80752. * most input files: try all possible matches and select the longest.
  80753. * The key feature of this algorithm is that insertions into the string
  80754. * dictionary are very simple and thus fast, and deletions are avoided
  80755. * completely. Insertions are performed at each input character, whereas
  80756. * string matches are performed only when the previous match ends. So it
  80757. * is preferable to spend more time in matches to allow very fast string
  80758. * insertions and avoid deletions. The matching algorithm for small
  80759. * strings is inspired from that of Rabin & Karp. A brute force approach
  80760. * is used to find longer strings when a small match has been found.
  80761. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80762. * (by Leonid Broukhis).
  80763. * A previous version of this file used a more sophisticated algorithm
  80764. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80765. * time, but has a larger average cost, uses more memory and is patented.
  80766. * However the F&G algorithm may be faster for some highly redundant
  80767. * files if the parameter max_chain_length (described below) is too large.
  80768. *
  80769. * ACKNOWLEDGEMENTS
  80770. *
  80771. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80772. * I found it in 'freeze' written by Leonid Broukhis.
  80773. * Thanks to many people for bug reports and testing.
  80774. *
  80775. * REFERENCES
  80776. *
  80777. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80778. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80779. *
  80780. * A description of the Rabin and Karp algorithm is given in the book
  80781. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80782. *
  80783. * Fiala,E.R., and Greene,D.H.
  80784. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80785. *
  80786. */
  80787. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80788. /*** Start of inlined file: deflate.h ***/
  80789. /* WARNING: this file should *not* be used by applications. It is
  80790. part of the implementation of the compression library and is
  80791. subject to change. Applications should only use zlib.h.
  80792. */
  80793. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80794. #ifndef DEFLATE_H
  80795. #define DEFLATE_H
  80796. /* define NO_GZIP when compiling if you want to disable gzip header and
  80797. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80798. the crc code when it is not needed. For shared libraries, gzip encoding
  80799. should be left enabled. */
  80800. #ifndef NO_GZIP
  80801. # define GZIP
  80802. #endif
  80803. #define NO_DUMMY_DECL
  80804. /* ===========================================================================
  80805. * Internal compression state.
  80806. */
  80807. #define LENGTH_CODES 29
  80808. /* number of length codes, not counting the special END_BLOCK code */
  80809. #define LITERALS 256
  80810. /* number of literal bytes 0..255 */
  80811. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80812. /* number of Literal or Length codes, including the END_BLOCK code */
  80813. #define D_CODES 30
  80814. /* number of distance codes */
  80815. #define BL_CODES 19
  80816. /* number of codes used to transfer the bit lengths */
  80817. #define HEAP_SIZE (2*L_CODES+1)
  80818. /* maximum heap size */
  80819. #define MAX_BITS 15
  80820. /* All codes must not exceed MAX_BITS bits */
  80821. #define INIT_STATE 42
  80822. #define EXTRA_STATE 69
  80823. #define NAME_STATE 73
  80824. #define COMMENT_STATE 91
  80825. #define HCRC_STATE 103
  80826. #define BUSY_STATE 113
  80827. #define FINISH_STATE 666
  80828. /* Stream status */
  80829. /* Data structure describing a single value and its code string. */
  80830. typedef struct ct_data_s {
  80831. union {
  80832. ush freq; /* frequency count */
  80833. ush code; /* bit string */
  80834. } fc;
  80835. union {
  80836. ush dad; /* father node in Huffman tree */
  80837. ush len; /* length of bit string */
  80838. } dl;
  80839. } FAR ct_data;
  80840. #define Freq fc.freq
  80841. #define Code fc.code
  80842. #define Dad dl.dad
  80843. #define Len dl.len
  80844. typedef struct static_tree_desc_s static_tree_desc;
  80845. typedef struct tree_desc_s {
  80846. ct_data *dyn_tree; /* the dynamic tree */
  80847. int max_code; /* largest code with non zero frequency */
  80848. static_tree_desc *stat_desc; /* the corresponding static tree */
  80849. } FAR tree_desc;
  80850. typedef ush Pos;
  80851. typedef Pos FAR Posf;
  80852. typedef unsigned IPos;
  80853. /* A Pos is an index in the character window. We use short instead of int to
  80854. * save space in the various tables. IPos is used only for parameter passing.
  80855. */
  80856. typedef struct internal_state {
  80857. z_streamp strm; /* pointer back to this zlib stream */
  80858. int status; /* as the name implies */
  80859. Bytef *pending_buf; /* output still pending */
  80860. ulg pending_buf_size; /* size of pending_buf */
  80861. Bytef *pending_out; /* next pending byte to output to the stream */
  80862. uInt pending; /* nb of bytes in the pending buffer */
  80863. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80864. gz_headerp gzhead; /* gzip header information to write */
  80865. uInt gzindex; /* where in extra, name, or comment */
  80866. Byte method; /* STORED (for zip only) or DEFLATED */
  80867. int last_flush; /* value of flush param for previous deflate call */
  80868. /* used by deflate.c: */
  80869. uInt w_size; /* LZ77 window size (32K by default) */
  80870. uInt w_bits; /* log2(w_size) (8..16) */
  80871. uInt w_mask; /* w_size - 1 */
  80872. Bytef *window;
  80873. /* Sliding window. Input bytes are read into the second half of the window,
  80874. * and move to the first half later to keep a dictionary of at least wSize
  80875. * bytes. With this organization, matches are limited to a distance of
  80876. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80877. * performed with a length multiple of the block size. Also, it limits
  80878. * the window size to 64K, which is quite useful on MSDOS.
  80879. * To do: use the user input buffer as sliding window.
  80880. */
  80881. ulg window_size;
  80882. /* Actual size of window: 2*wSize, except when the user input buffer
  80883. * is directly used as sliding window.
  80884. */
  80885. Posf *prev;
  80886. /* Link to older string with same hash index. To limit the size of this
  80887. * array to 64K, this link is maintained only for the last 32K strings.
  80888. * An index in this array is thus a window index modulo 32K.
  80889. */
  80890. Posf *head; /* Heads of the hash chains or NIL. */
  80891. uInt ins_h; /* hash index of string to be inserted */
  80892. uInt hash_size; /* number of elements in hash table */
  80893. uInt hash_bits; /* log2(hash_size) */
  80894. uInt hash_mask; /* hash_size-1 */
  80895. uInt hash_shift;
  80896. /* Number of bits by which ins_h must be shifted at each input
  80897. * step. It must be such that after MIN_MATCH steps, the oldest
  80898. * byte no longer takes part in the hash key, that is:
  80899. * hash_shift * MIN_MATCH >= hash_bits
  80900. */
  80901. long block_start;
  80902. /* Window position at the beginning of the current output block. Gets
  80903. * negative when the window is moved backwards.
  80904. */
  80905. uInt match_length; /* length of best match */
  80906. IPos prev_match; /* previous match */
  80907. int match_available; /* set if previous match exists */
  80908. uInt strstart; /* start of string to insert */
  80909. uInt match_start; /* start of matching string */
  80910. uInt lookahead; /* number of valid bytes ahead in window */
  80911. uInt prev_length;
  80912. /* Length of the best match at previous step. Matches not greater than this
  80913. * are discarded. This is used in the lazy match evaluation.
  80914. */
  80915. uInt max_chain_length;
  80916. /* To speed up deflation, hash chains are never searched beyond this
  80917. * length. A higher limit improves compression ratio but degrades the
  80918. * speed.
  80919. */
  80920. uInt max_lazy_match;
  80921. /* Attempt to find a better match only when the current match is strictly
  80922. * smaller than this value. This mechanism is used only for compression
  80923. * levels >= 4.
  80924. */
  80925. # define max_insert_length max_lazy_match
  80926. /* Insert new strings in the hash table only if the match length is not
  80927. * greater than this length. This saves time but degrades compression.
  80928. * max_insert_length is used only for compression levels <= 3.
  80929. */
  80930. int level; /* compression level (1..9) */
  80931. int strategy; /* favor or force Huffman coding*/
  80932. uInt good_match;
  80933. /* Use a faster search when the previous match is longer than this */
  80934. int nice_match; /* Stop searching when current match exceeds this */
  80935. /* used by trees.c: */
  80936. /* Didn't use ct_data typedef below to supress compiler warning */
  80937. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80938. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80939. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80940. struct tree_desc_s l_desc; /* desc. for literal tree */
  80941. struct tree_desc_s d_desc; /* desc. for distance tree */
  80942. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80943. ush bl_count[MAX_BITS+1];
  80944. /* number of codes at each bit length for an optimal tree */
  80945. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80946. int heap_len; /* number of elements in the heap */
  80947. int heap_max; /* element of largest frequency */
  80948. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80949. * The same heap array is used to build all trees.
  80950. */
  80951. uch depth[2*L_CODES+1];
  80952. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80953. */
  80954. uchf *l_buf; /* buffer for literals or lengths */
  80955. uInt lit_bufsize;
  80956. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80957. * limiting lit_bufsize to 64K:
  80958. * - frequencies can be kept in 16 bit counters
  80959. * - if compression is not successful for the first block, all input
  80960. * data is still in the window so we can still emit a stored block even
  80961. * when input comes from standard input. (This can also be done for
  80962. * all blocks if lit_bufsize is not greater than 32K.)
  80963. * - if compression is not successful for a file smaller than 64K, we can
  80964. * even emit a stored file instead of a stored block (saving 5 bytes).
  80965. * This is applicable only for zip (not gzip or zlib).
  80966. * - creating new Huffman trees less frequently may not provide fast
  80967. * adaptation to changes in the input data statistics. (Take for
  80968. * example a binary file with poorly compressible code followed by
  80969. * a highly compressible string table.) Smaller buffer sizes give
  80970. * fast adaptation but have of course the overhead of transmitting
  80971. * trees more frequently.
  80972. * - I can't count above 4
  80973. */
  80974. uInt last_lit; /* running index in l_buf */
  80975. ushf *d_buf;
  80976. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80977. * the same number of elements. To use different lengths, an extra flag
  80978. * array would be necessary.
  80979. */
  80980. ulg opt_len; /* bit length of current block with optimal trees */
  80981. ulg static_len; /* bit length of current block with static trees */
  80982. uInt matches; /* number of string matches in current block */
  80983. int last_eob_len; /* bit length of EOB code for last block */
  80984. #ifdef DEBUG
  80985. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80986. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80987. #endif
  80988. ush bi_buf;
  80989. /* Output buffer. bits are inserted starting at the bottom (least
  80990. * significant bits).
  80991. */
  80992. int bi_valid;
  80993. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80994. * are always zero.
  80995. */
  80996. } FAR deflate_state;
  80997. /* Output a byte on the stream.
  80998. * IN assertion: there is enough room in pending_buf.
  80999. */
  81000. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81001. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81002. /* Minimum amount of lookahead, except at the end of the input file.
  81003. * See deflate.c for comments about the MIN_MATCH+1.
  81004. */
  81005. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81006. /* In order to simplify the code, particularly on 16 bit machines, match
  81007. * distances are limited to MAX_DIST instead of WSIZE.
  81008. */
  81009. /* in trees.c */
  81010. void _tr_init OF((deflate_state *s));
  81011. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81012. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81013. int eof));
  81014. void _tr_align OF((deflate_state *s));
  81015. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81016. int eof));
  81017. #define d_code(dist) \
  81018. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81019. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81020. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81021. * used.
  81022. */
  81023. #ifndef DEBUG
  81024. /* Inline versions of _tr_tally for speed: */
  81025. #if defined(GEN_TREES_H) || !defined(STDC)
  81026. extern uch _length_code[];
  81027. extern uch _dist_code[];
  81028. #else
  81029. extern const uch _length_code[];
  81030. extern const uch _dist_code[];
  81031. #endif
  81032. # define _tr_tally_lit(s, c, flush) \
  81033. { uch cc = (c); \
  81034. s->d_buf[s->last_lit] = 0; \
  81035. s->l_buf[s->last_lit++] = cc; \
  81036. s->dyn_ltree[cc].Freq++; \
  81037. flush = (s->last_lit == s->lit_bufsize-1); \
  81038. }
  81039. # define _tr_tally_dist(s, distance, length, flush) \
  81040. { uch len = (length); \
  81041. ush dist = (distance); \
  81042. s->d_buf[s->last_lit] = dist; \
  81043. s->l_buf[s->last_lit++] = len; \
  81044. dist--; \
  81045. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81046. s->dyn_dtree[d_code(dist)].Freq++; \
  81047. flush = (s->last_lit == s->lit_bufsize-1); \
  81048. }
  81049. #else
  81050. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81051. # define _tr_tally_dist(s, distance, length, flush) \
  81052. flush = _tr_tally(s, distance, length)
  81053. #endif
  81054. #endif /* DEFLATE_H */
  81055. /*** End of inlined file: deflate.h ***/
  81056. const char deflate_copyright[] =
  81057. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81058. /*
  81059. If you use the zlib library in a product, an acknowledgment is welcome
  81060. in the documentation of your product. If for some reason you cannot
  81061. include such an acknowledgment, I would appreciate that you keep this
  81062. copyright string in the executable of your product.
  81063. */
  81064. /* ===========================================================================
  81065. * Function prototypes.
  81066. */
  81067. typedef enum {
  81068. need_more, /* block not completed, need more input or more output */
  81069. block_done, /* block flush performed */
  81070. finish_started, /* finish started, need only more output at next deflate */
  81071. finish_done /* finish done, accept no more input or output */
  81072. } block_state;
  81073. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81074. /* Compression function. Returns the block state after the call. */
  81075. local void fill_window OF((deflate_state *s));
  81076. local block_state deflate_stored OF((deflate_state *s, int flush));
  81077. local block_state deflate_fast OF((deflate_state *s, int flush));
  81078. #ifndef FASTEST
  81079. local block_state deflate_slow OF((deflate_state *s, int flush));
  81080. #endif
  81081. local void lm_init OF((deflate_state *s));
  81082. local void putShortMSB OF((deflate_state *s, uInt b));
  81083. local void flush_pending OF((z_streamp strm));
  81084. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81085. #ifndef FASTEST
  81086. #ifdef ASMV
  81087. void match_init OF((void)); /* asm code initialization */
  81088. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81089. #else
  81090. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81091. #endif
  81092. #endif
  81093. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81094. #ifdef DEBUG
  81095. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81096. int length));
  81097. #endif
  81098. /* ===========================================================================
  81099. * Local data
  81100. */
  81101. #define NIL 0
  81102. /* Tail of hash chains */
  81103. #ifndef TOO_FAR
  81104. # define TOO_FAR 4096
  81105. #endif
  81106. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81107. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81108. /* Minimum amount of lookahead, except at the end of the input file.
  81109. * See deflate.c for comments about the MIN_MATCH+1.
  81110. */
  81111. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81112. * the desired pack level (0..9). The values given below have been tuned to
  81113. * exclude worst case performance for pathological files. Better values may be
  81114. * found for specific files.
  81115. */
  81116. typedef struct config_s {
  81117. ush good_length; /* reduce lazy search above this match length */
  81118. ush max_lazy; /* do not perform lazy search above this match length */
  81119. ush nice_length; /* quit search above this match length */
  81120. ush max_chain;
  81121. compress_func func;
  81122. } config;
  81123. #ifdef FASTEST
  81124. local const config configuration_table[2] = {
  81125. /* good lazy nice chain */
  81126. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81127. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81128. #else
  81129. local const config configuration_table[10] = {
  81130. /* good lazy nice chain */
  81131. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81132. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81133. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81134. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81135. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81136. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81137. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81138. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81139. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81140. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81141. #endif
  81142. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81143. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81144. * meaning.
  81145. */
  81146. #define EQUAL 0
  81147. /* result of memcmp for equal strings */
  81148. #ifndef NO_DUMMY_DECL
  81149. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81150. #endif
  81151. /* ===========================================================================
  81152. * Update a hash value with the given input byte
  81153. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81154. * input characters, so that a running hash key can be computed from the
  81155. * previous key instead of complete recalculation each time.
  81156. */
  81157. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81158. /* ===========================================================================
  81159. * Insert string str in the dictionary and set match_head to the previous head
  81160. * of the hash chain (the most recent string with same hash key). Return
  81161. * the previous length of the hash chain.
  81162. * If this file is compiled with -DFASTEST, the compression level is forced
  81163. * to 1, and no hash chains are maintained.
  81164. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81165. * input characters and the first MIN_MATCH bytes of str are valid
  81166. * (except for the last MIN_MATCH-1 bytes of the input file).
  81167. */
  81168. #ifdef FASTEST
  81169. #define INSERT_STRING(s, str, match_head) \
  81170. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81171. match_head = s->head[s->ins_h], \
  81172. s->head[s->ins_h] = (Pos)(str))
  81173. #else
  81174. #define INSERT_STRING(s, str, match_head) \
  81175. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81176. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81177. s->head[s->ins_h] = (Pos)(str))
  81178. #endif
  81179. /* ===========================================================================
  81180. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81181. * prev[] will be initialized on the fly.
  81182. */
  81183. #define CLEAR_HASH(s) \
  81184. s->head[s->hash_size-1] = NIL; \
  81185. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81186. /* ========================================================================= */
  81187. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81188. {
  81189. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81190. Z_DEFAULT_STRATEGY, version, stream_size);
  81191. /* To do: ignore strm->next_in if we use it as window */
  81192. }
  81193. /* ========================================================================= */
  81194. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81195. {
  81196. deflate_state *s;
  81197. int wrap = 1;
  81198. static const char my_version[] = ZLIB_VERSION;
  81199. ushf *overlay;
  81200. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81201. * output size for (length,distance) codes is <= 24 bits.
  81202. */
  81203. if (version == Z_NULL || version[0] != my_version[0] ||
  81204. stream_size != sizeof(z_stream)) {
  81205. return Z_VERSION_ERROR;
  81206. }
  81207. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81208. strm->msg = Z_NULL;
  81209. if (strm->zalloc == (alloc_func)0) {
  81210. strm->zalloc = zcalloc;
  81211. strm->opaque = (voidpf)0;
  81212. }
  81213. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81214. #ifdef FASTEST
  81215. if (level != 0) level = 1;
  81216. #else
  81217. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81218. #endif
  81219. if (windowBits < 0) { /* suppress zlib wrapper */
  81220. wrap = 0;
  81221. windowBits = -windowBits;
  81222. }
  81223. #ifdef GZIP
  81224. else if (windowBits > 15) {
  81225. wrap = 2; /* write gzip wrapper instead */
  81226. windowBits -= 16;
  81227. }
  81228. #endif
  81229. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81230. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81231. strategy < 0 || strategy > Z_FIXED) {
  81232. return Z_STREAM_ERROR;
  81233. }
  81234. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81235. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81236. if (s == Z_NULL) return Z_MEM_ERROR;
  81237. strm->state = (struct internal_state FAR *)s;
  81238. s->strm = strm;
  81239. s->wrap = wrap;
  81240. s->gzhead = Z_NULL;
  81241. s->w_bits = windowBits;
  81242. s->w_size = 1 << s->w_bits;
  81243. s->w_mask = s->w_size - 1;
  81244. s->hash_bits = memLevel + 7;
  81245. s->hash_size = 1 << s->hash_bits;
  81246. s->hash_mask = s->hash_size - 1;
  81247. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81248. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81249. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81250. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81251. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81252. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81253. s->pending_buf = (uchf *) overlay;
  81254. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81255. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81256. s->pending_buf == Z_NULL) {
  81257. s->status = FINISH_STATE;
  81258. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81259. deflateEnd (strm);
  81260. return Z_MEM_ERROR;
  81261. }
  81262. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81263. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81264. s->level = level;
  81265. s->strategy = strategy;
  81266. s->method = (Byte)method;
  81267. return deflateReset(strm);
  81268. }
  81269. /* ========================================================================= */
  81270. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81271. {
  81272. deflate_state *s;
  81273. uInt length = dictLength;
  81274. uInt n;
  81275. IPos hash_head = 0;
  81276. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81277. strm->state->wrap == 2 ||
  81278. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81279. return Z_STREAM_ERROR;
  81280. s = strm->state;
  81281. if (s->wrap)
  81282. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81283. if (length < MIN_MATCH) return Z_OK;
  81284. if (length > MAX_DIST(s)) {
  81285. length = MAX_DIST(s);
  81286. dictionary += dictLength - length; /* use the tail of the dictionary */
  81287. }
  81288. zmemcpy(s->window, dictionary, length);
  81289. s->strstart = length;
  81290. s->block_start = (long)length;
  81291. /* Insert all strings in the hash table (except for the last two bytes).
  81292. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81293. * call of fill_window.
  81294. */
  81295. s->ins_h = s->window[0];
  81296. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81297. for (n = 0; n <= length - MIN_MATCH; n++) {
  81298. INSERT_STRING(s, n, hash_head);
  81299. }
  81300. if (hash_head) hash_head = 0; /* to make compiler happy */
  81301. return Z_OK;
  81302. }
  81303. /* ========================================================================= */
  81304. int ZEXPORT deflateReset (z_streamp strm)
  81305. {
  81306. deflate_state *s;
  81307. if (strm == Z_NULL || strm->state == Z_NULL ||
  81308. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81309. return Z_STREAM_ERROR;
  81310. }
  81311. strm->total_in = strm->total_out = 0;
  81312. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81313. strm->data_type = Z_UNKNOWN;
  81314. s = (deflate_state *)strm->state;
  81315. s->pending = 0;
  81316. s->pending_out = s->pending_buf;
  81317. if (s->wrap < 0) {
  81318. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81319. }
  81320. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81321. strm->adler =
  81322. #ifdef GZIP
  81323. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81324. #endif
  81325. adler32(0L, Z_NULL, 0);
  81326. s->last_flush = Z_NO_FLUSH;
  81327. _tr_init(s);
  81328. lm_init(s);
  81329. return Z_OK;
  81330. }
  81331. /* ========================================================================= */
  81332. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81333. {
  81334. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81335. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81336. strm->state->gzhead = head;
  81337. return Z_OK;
  81338. }
  81339. /* ========================================================================= */
  81340. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81341. {
  81342. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81343. strm->state->bi_valid = bits;
  81344. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81345. return Z_OK;
  81346. }
  81347. /* ========================================================================= */
  81348. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81349. {
  81350. deflate_state *s;
  81351. compress_func func;
  81352. int err = Z_OK;
  81353. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81354. s = strm->state;
  81355. #ifdef FASTEST
  81356. if (level != 0) level = 1;
  81357. #else
  81358. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81359. #endif
  81360. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81361. return Z_STREAM_ERROR;
  81362. }
  81363. func = configuration_table[s->level].func;
  81364. if (func != configuration_table[level].func && strm->total_in != 0) {
  81365. /* Flush the last buffer: */
  81366. err = deflate(strm, Z_PARTIAL_FLUSH);
  81367. }
  81368. if (s->level != level) {
  81369. s->level = level;
  81370. s->max_lazy_match = configuration_table[level].max_lazy;
  81371. s->good_match = configuration_table[level].good_length;
  81372. s->nice_match = configuration_table[level].nice_length;
  81373. s->max_chain_length = configuration_table[level].max_chain;
  81374. }
  81375. s->strategy = strategy;
  81376. return err;
  81377. }
  81378. /* ========================================================================= */
  81379. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81380. {
  81381. deflate_state *s;
  81382. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81383. s = strm->state;
  81384. s->good_match = good_length;
  81385. s->max_lazy_match = max_lazy;
  81386. s->nice_match = nice_length;
  81387. s->max_chain_length = max_chain;
  81388. return Z_OK;
  81389. }
  81390. /* =========================================================================
  81391. * For the default windowBits of 15 and memLevel of 8, this function returns
  81392. * a close to exact, as well as small, upper bound on the compressed size.
  81393. * They are coded as constants here for a reason--if the #define's are
  81394. * changed, then this function needs to be changed as well. The return
  81395. * value for 15 and 8 only works for those exact settings.
  81396. *
  81397. * For any setting other than those defaults for windowBits and memLevel,
  81398. * the value returned is a conservative worst case for the maximum expansion
  81399. * resulting from using fixed blocks instead of stored blocks, which deflate
  81400. * can emit on compressed data for some combinations of the parameters.
  81401. *
  81402. * This function could be more sophisticated to provide closer upper bounds
  81403. * for every combination of windowBits and memLevel, as well as wrap.
  81404. * But even the conservative upper bound of about 14% expansion does not
  81405. * seem onerous for output buffer allocation.
  81406. */
  81407. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81408. {
  81409. deflate_state *s;
  81410. uLong destLen;
  81411. /* conservative upper bound */
  81412. destLen = sourceLen +
  81413. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81414. /* if can't get parameters, return conservative bound */
  81415. if (strm == Z_NULL || strm->state == Z_NULL)
  81416. return destLen;
  81417. /* if not default parameters, return conservative bound */
  81418. s = strm->state;
  81419. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81420. return destLen;
  81421. /* default settings: return tight bound for that case */
  81422. return compressBound(sourceLen);
  81423. }
  81424. /* =========================================================================
  81425. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81426. * IN assertion: the stream state is correct and there is enough room in
  81427. * pending_buf.
  81428. */
  81429. local void putShortMSB (deflate_state *s, uInt b)
  81430. {
  81431. put_byte(s, (Byte)(b >> 8));
  81432. put_byte(s, (Byte)(b & 0xff));
  81433. }
  81434. /* =========================================================================
  81435. * Flush as much pending output as possible. All deflate() output goes
  81436. * through this function so some applications may wish to modify it
  81437. * to avoid allocating a large strm->next_out buffer and copying into it.
  81438. * (See also read_buf()).
  81439. */
  81440. local void flush_pending (z_streamp strm)
  81441. {
  81442. unsigned len = strm->state->pending;
  81443. if (len > strm->avail_out) len = strm->avail_out;
  81444. if (len == 0) return;
  81445. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81446. strm->next_out += len;
  81447. strm->state->pending_out += len;
  81448. strm->total_out += len;
  81449. strm->avail_out -= len;
  81450. strm->state->pending -= len;
  81451. if (strm->state->pending == 0) {
  81452. strm->state->pending_out = strm->state->pending_buf;
  81453. }
  81454. }
  81455. /* ========================================================================= */
  81456. int ZEXPORT deflate (z_streamp strm, int flush)
  81457. {
  81458. int old_flush; /* value of flush param for previous deflate call */
  81459. deflate_state *s;
  81460. if (strm == Z_NULL || strm->state == Z_NULL ||
  81461. flush > Z_FINISH || flush < 0) {
  81462. return Z_STREAM_ERROR;
  81463. }
  81464. s = strm->state;
  81465. if (strm->next_out == Z_NULL ||
  81466. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81467. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81468. ERR_RETURN(strm, Z_STREAM_ERROR);
  81469. }
  81470. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81471. s->strm = strm; /* just in case */
  81472. old_flush = s->last_flush;
  81473. s->last_flush = flush;
  81474. /* Write the header */
  81475. if (s->status == INIT_STATE) {
  81476. #ifdef GZIP
  81477. if (s->wrap == 2) {
  81478. strm->adler = crc32(0L, Z_NULL, 0);
  81479. put_byte(s, 31);
  81480. put_byte(s, 139);
  81481. put_byte(s, 8);
  81482. if (s->gzhead == NULL) {
  81483. put_byte(s, 0);
  81484. put_byte(s, 0);
  81485. put_byte(s, 0);
  81486. put_byte(s, 0);
  81487. put_byte(s, 0);
  81488. put_byte(s, s->level == 9 ? 2 :
  81489. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81490. 4 : 0));
  81491. put_byte(s, OS_CODE);
  81492. s->status = BUSY_STATE;
  81493. }
  81494. else {
  81495. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81496. (s->gzhead->hcrc ? 2 : 0) +
  81497. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81498. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81499. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81500. );
  81501. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81502. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81503. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81504. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81505. put_byte(s, s->level == 9 ? 2 :
  81506. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81507. 4 : 0));
  81508. put_byte(s, s->gzhead->os & 0xff);
  81509. if (s->gzhead->extra != NULL) {
  81510. put_byte(s, s->gzhead->extra_len & 0xff);
  81511. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81512. }
  81513. if (s->gzhead->hcrc)
  81514. strm->adler = crc32(strm->adler, s->pending_buf,
  81515. s->pending);
  81516. s->gzindex = 0;
  81517. s->status = EXTRA_STATE;
  81518. }
  81519. }
  81520. else
  81521. #endif
  81522. {
  81523. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81524. uInt level_flags;
  81525. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81526. level_flags = 0;
  81527. else if (s->level < 6)
  81528. level_flags = 1;
  81529. else if (s->level == 6)
  81530. level_flags = 2;
  81531. else
  81532. level_flags = 3;
  81533. header |= (level_flags << 6);
  81534. if (s->strstart != 0) header |= PRESET_DICT;
  81535. header += 31 - (header % 31);
  81536. s->status = BUSY_STATE;
  81537. putShortMSB(s, header);
  81538. /* Save the adler32 of the preset dictionary: */
  81539. if (s->strstart != 0) {
  81540. putShortMSB(s, (uInt)(strm->adler >> 16));
  81541. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81542. }
  81543. strm->adler = adler32(0L, Z_NULL, 0);
  81544. }
  81545. }
  81546. #ifdef GZIP
  81547. if (s->status == EXTRA_STATE) {
  81548. if (s->gzhead->extra != NULL) {
  81549. uInt beg = s->pending; /* start of bytes to update crc */
  81550. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81551. if (s->pending == s->pending_buf_size) {
  81552. if (s->gzhead->hcrc && s->pending > beg)
  81553. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81554. s->pending - beg);
  81555. flush_pending(strm);
  81556. beg = s->pending;
  81557. if (s->pending == s->pending_buf_size)
  81558. break;
  81559. }
  81560. put_byte(s, s->gzhead->extra[s->gzindex]);
  81561. s->gzindex++;
  81562. }
  81563. if (s->gzhead->hcrc && s->pending > beg)
  81564. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81565. s->pending - beg);
  81566. if (s->gzindex == s->gzhead->extra_len) {
  81567. s->gzindex = 0;
  81568. s->status = NAME_STATE;
  81569. }
  81570. }
  81571. else
  81572. s->status = NAME_STATE;
  81573. }
  81574. if (s->status == NAME_STATE) {
  81575. if (s->gzhead->name != NULL) {
  81576. uInt beg = s->pending; /* start of bytes to update crc */
  81577. int val;
  81578. do {
  81579. if (s->pending == s->pending_buf_size) {
  81580. if (s->gzhead->hcrc && s->pending > beg)
  81581. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81582. s->pending - beg);
  81583. flush_pending(strm);
  81584. beg = s->pending;
  81585. if (s->pending == s->pending_buf_size) {
  81586. val = 1;
  81587. break;
  81588. }
  81589. }
  81590. val = s->gzhead->name[s->gzindex++];
  81591. put_byte(s, val);
  81592. } while (val != 0);
  81593. if (s->gzhead->hcrc && s->pending > beg)
  81594. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81595. s->pending - beg);
  81596. if (val == 0) {
  81597. s->gzindex = 0;
  81598. s->status = COMMENT_STATE;
  81599. }
  81600. }
  81601. else
  81602. s->status = COMMENT_STATE;
  81603. }
  81604. if (s->status == COMMENT_STATE) {
  81605. if (s->gzhead->comment != NULL) {
  81606. uInt beg = s->pending; /* start of bytes to update crc */
  81607. int val;
  81608. do {
  81609. if (s->pending == s->pending_buf_size) {
  81610. if (s->gzhead->hcrc && s->pending > beg)
  81611. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81612. s->pending - beg);
  81613. flush_pending(strm);
  81614. beg = s->pending;
  81615. if (s->pending == s->pending_buf_size) {
  81616. val = 1;
  81617. break;
  81618. }
  81619. }
  81620. val = s->gzhead->comment[s->gzindex++];
  81621. put_byte(s, val);
  81622. } while (val != 0);
  81623. if (s->gzhead->hcrc && s->pending > beg)
  81624. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81625. s->pending - beg);
  81626. if (val == 0)
  81627. s->status = HCRC_STATE;
  81628. }
  81629. else
  81630. s->status = HCRC_STATE;
  81631. }
  81632. if (s->status == HCRC_STATE) {
  81633. if (s->gzhead->hcrc) {
  81634. if (s->pending + 2 > s->pending_buf_size)
  81635. flush_pending(strm);
  81636. if (s->pending + 2 <= s->pending_buf_size) {
  81637. put_byte(s, (Byte)(strm->adler & 0xff));
  81638. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81639. strm->adler = crc32(0L, Z_NULL, 0);
  81640. s->status = BUSY_STATE;
  81641. }
  81642. }
  81643. else
  81644. s->status = BUSY_STATE;
  81645. }
  81646. #endif
  81647. /* Flush as much pending output as possible */
  81648. if (s->pending != 0) {
  81649. flush_pending(strm);
  81650. if (strm->avail_out == 0) {
  81651. /* Since avail_out is 0, deflate will be called again with
  81652. * more output space, but possibly with both pending and
  81653. * avail_in equal to zero. There won't be anything to do,
  81654. * but this is not an error situation so make sure we
  81655. * return OK instead of BUF_ERROR at next call of deflate:
  81656. */
  81657. s->last_flush = -1;
  81658. return Z_OK;
  81659. }
  81660. /* Make sure there is something to do and avoid duplicate consecutive
  81661. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81662. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81663. */
  81664. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81665. flush != Z_FINISH) {
  81666. ERR_RETURN(strm, Z_BUF_ERROR);
  81667. }
  81668. /* User must not provide more input after the first FINISH: */
  81669. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81670. ERR_RETURN(strm, Z_BUF_ERROR);
  81671. }
  81672. /* Start a new block or continue the current one.
  81673. */
  81674. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81675. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81676. block_state bstate;
  81677. bstate = (*(configuration_table[s->level].func))(s, flush);
  81678. if (bstate == finish_started || bstate == finish_done) {
  81679. s->status = FINISH_STATE;
  81680. }
  81681. if (bstate == need_more || bstate == finish_started) {
  81682. if (strm->avail_out == 0) {
  81683. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81684. }
  81685. return Z_OK;
  81686. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81687. * of deflate should use the same flush parameter to make sure
  81688. * that the flush is complete. So we don't have to output an
  81689. * empty block here, this will be done at next call. This also
  81690. * ensures that for a very small output buffer, we emit at most
  81691. * one empty block.
  81692. */
  81693. }
  81694. if (bstate == block_done) {
  81695. if (flush == Z_PARTIAL_FLUSH) {
  81696. _tr_align(s);
  81697. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81698. _tr_stored_block(s, (char*)0, 0L, 0);
  81699. /* For a full flush, this empty block will be recognized
  81700. * as a special marker by inflate_sync().
  81701. */
  81702. if (flush == Z_FULL_FLUSH) {
  81703. CLEAR_HASH(s); /* forget history */
  81704. }
  81705. }
  81706. flush_pending(strm);
  81707. if (strm->avail_out == 0) {
  81708. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81709. return Z_OK;
  81710. }
  81711. }
  81712. }
  81713. Assert(strm->avail_out > 0, "bug2");
  81714. if (flush != Z_FINISH) return Z_OK;
  81715. if (s->wrap <= 0) return Z_STREAM_END;
  81716. /* Write the trailer */
  81717. #ifdef GZIP
  81718. if (s->wrap == 2) {
  81719. put_byte(s, (Byte)(strm->adler & 0xff));
  81720. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81721. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81722. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81723. put_byte(s, (Byte)(strm->total_in & 0xff));
  81724. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81725. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81726. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81727. }
  81728. else
  81729. #endif
  81730. {
  81731. putShortMSB(s, (uInt)(strm->adler >> 16));
  81732. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81733. }
  81734. flush_pending(strm);
  81735. /* If avail_out is zero, the application will call deflate again
  81736. * to flush the rest.
  81737. */
  81738. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81739. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81740. }
  81741. /* ========================================================================= */
  81742. int ZEXPORT deflateEnd (z_streamp strm)
  81743. {
  81744. int status;
  81745. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81746. status = strm->state->status;
  81747. if (status != INIT_STATE &&
  81748. status != EXTRA_STATE &&
  81749. status != NAME_STATE &&
  81750. status != COMMENT_STATE &&
  81751. status != HCRC_STATE &&
  81752. status != BUSY_STATE &&
  81753. status != FINISH_STATE) {
  81754. return Z_STREAM_ERROR;
  81755. }
  81756. /* Deallocate in reverse order of allocations: */
  81757. TRY_FREE(strm, strm->state->pending_buf);
  81758. TRY_FREE(strm, strm->state->head);
  81759. TRY_FREE(strm, strm->state->prev);
  81760. TRY_FREE(strm, strm->state->window);
  81761. ZFREE(strm, strm->state);
  81762. strm->state = Z_NULL;
  81763. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81764. }
  81765. /* =========================================================================
  81766. * Copy the source state to the destination state.
  81767. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81768. * doesn't have enough memory anyway to duplicate compression states).
  81769. */
  81770. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81771. {
  81772. #ifdef MAXSEG_64K
  81773. return Z_STREAM_ERROR;
  81774. #else
  81775. deflate_state *ds;
  81776. deflate_state *ss;
  81777. ushf *overlay;
  81778. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81779. return Z_STREAM_ERROR;
  81780. }
  81781. ss = source->state;
  81782. zmemcpy(dest, source, sizeof(z_stream));
  81783. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81784. if (ds == Z_NULL) return Z_MEM_ERROR;
  81785. dest->state = (struct internal_state FAR *) ds;
  81786. zmemcpy(ds, ss, sizeof(deflate_state));
  81787. ds->strm = dest;
  81788. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81789. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81790. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81791. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81792. ds->pending_buf = (uchf *) overlay;
  81793. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81794. ds->pending_buf == Z_NULL) {
  81795. deflateEnd (dest);
  81796. return Z_MEM_ERROR;
  81797. }
  81798. /* following zmemcpy do not work for 16-bit MSDOS */
  81799. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81800. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81801. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81802. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81803. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81804. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81805. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81806. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81807. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81808. ds->bl_desc.dyn_tree = ds->bl_tree;
  81809. return Z_OK;
  81810. #endif /* MAXSEG_64K */
  81811. }
  81812. /* ===========================================================================
  81813. * Read a new buffer from the current input stream, update the adler32
  81814. * and total number of bytes read. All deflate() input goes through
  81815. * this function so some applications may wish to modify it to avoid
  81816. * allocating a large strm->next_in buffer and copying from it.
  81817. * (See also flush_pending()).
  81818. */
  81819. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81820. {
  81821. unsigned len = strm->avail_in;
  81822. if (len > size) len = size;
  81823. if (len == 0) return 0;
  81824. strm->avail_in -= len;
  81825. if (strm->state->wrap == 1) {
  81826. strm->adler = adler32(strm->adler, strm->next_in, len);
  81827. }
  81828. #ifdef GZIP
  81829. else if (strm->state->wrap == 2) {
  81830. strm->adler = crc32(strm->adler, strm->next_in, len);
  81831. }
  81832. #endif
  81833. zmemcpy(buf, strm->next_in, len);
  81834. strm->next_in += len;
  81835. strm->total_in += len;
  81836. return (int)len;
  81837. }
  81838. /* ===========================================================================
  81839. * Initialize the "longest match" routines for a new zlib stream
  81840. */
  81841. local void lm_init (deflate_state *s)
  81842. {
  81843. s->window_size = (ulg)2L*s->w_size;
  81844. CLEAR_HASH(s);
  81845. /* Set the default configuration parameters:
  81846. */
  81847. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81848. s->good_match = configuration_table[s->level].good_length;
  81849. s->nice_match = configuration_table[s->level].nice_length;
  81850. s->max_chain_length = configuration_table[s->level].max_chain;
  81851. s->strstart = 0;
  81852. s->block_start = 0L;
  81853. s->lookahead = 0;
  81854. s->match_length = s->prev_length = MIN_MATCH-1;
  81855. s->match_available = 0;
  81856. s->ins_h = 0;
  81857. #ifndef FASTEST
  81858. #ifdef ASMV
  81859. match_init(); /* initialize the asm code */
  81860. #endif
  81861. #endif
  81862. }
  81863. #ifndef FASTEST
  81864. /* ===========================================================================
  81865. * Set match_start to the longest match starting at the given string and
  81866. * return its length. Matches shorter or equal to prev_length are discarded,
  81867. * in which case the result is equal to prev_length and match_start is
  81868. * garbage.
  81869. * IN assertions: cur_match is the head of the hash chain for the current
  81870. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81871. * OUT assertion: the match length is not greater than s->lookahead.
  81872. */
  81873. #ifndef ASMV
  81874. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81875. * match.S. The code will be functionally equivalent.
  81876. */
  81877. local uInt longest_match(deflate_state *s, IPos cur_match)
  81878. {
  81879. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81880. register Bytef *scan = s->window + s->strstart; /* current string */
  81881. register Bytef *match; /* matched string */
  81882. register int len; /* length of current match */
  81883. int best_len = s->prev_length; /* best match length so far */
  81884. int nice_match = s->nice_match; /* stop if match long enough */
  81885. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81886. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81887. /* Stop when cur_match becomes <= limit. To simplify the code,
  81888. * we prevent matches with the string of window index 0.
  81889. */
  81890. Posf *prev = s->prev;
  81891. uInt wmask = s->w_mask;
  81892. #ifdef UNALIGNED_OK
  81893. /* Compare two bytes at a time. Note: this is not always beneficial.
  81894. * Try with and without -DUNALIGNED_OK to check.
  81895. */
  81896. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81897. register ush scan_start = *(ushf*)scan;
  81898. register ush scan_end = *(ushf*)(scan+best_len-1);
  81899. #else
  81900. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81901. register Byte scan_end1 = scan[best_len-1];
  81902. register Byte scan_end = scan[best_len];
  81903. #endif
  81904. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81905. * It is easy to get rid of this optimization if necessary.
  81906. */
  81907. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81908. /* Do not waste too much time if we already have a good match: */
  81909. if (s->prev_length >= s->good_match) {
  81910. chain_length >>= 2;
  81911. }
  81912. /* Do not look for matches beyond the end of the input. This is necessary
  81913. * to make deflate deterministic.
  81914. */
  81915. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81916. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81917. do {
  81918. Assert(cur_match < s->strstart, "no future");
  81919. match = s->window + cur_match;
  81920. /* Skip to next match if the match length cannot increase
  81921. * or if the match length is less than 2. Note that the checks below
  81922. * for insufficient lookahead only occur occasionally for performance
  81923. * reasons. Therefore uninitialized memory will be accessed, and
  81924. * conditional jumps will be made that depend on those values.
  81925. * However the length of the match is limited to the lookahead, so
  81926. * the output of deflate is not affected by the uninitialized values.
  81927. */
  81928. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81929. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81930. * UNALIGNED_OK if your compiler uses a different size.
  81931. */
  81932. if (*(ushf*)(match+best_len-1) != scan_end ||
  81933. *(ushf*)match != scan_start) continue;
  81934. /* It is not necessary to compare scan[2] and match[2] since they are
  81935. * always equal when the other bytes match, given that the hash keys
  81936. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81937. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81938. * lookahead only every 4th comparison; the 128th check will be made
  81939. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81940. * necessary to put more guard bytes at the end of the window, or
  81941. * to check more often for insufficient lookahead.
  81942. */
  81943. Assert(scan[2] == match[2], "scan[2]?");
  81944. scan++, match++;
  81945. do {
  81946. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81947. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81948. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81949. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81950. scan < strend);
  81951. /* The funny "do {}" generates better code on most compilers */
  81952. /* Here, scan <= window+strstart+257 */
  81953. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81954. if (*scan == *match) scan++;
  81955. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81956. scan = strend - (MAX_MATCH-1);
  81957. #else /* UNALIGNED_OK */
  81958. if (match[best_len] != scan_end ||
  81959. match[best_len-1] != scan_end1 ||
  81960. *match != *scan ||
  81961. *++match != scan[1]) continue;
  81962. /* The check at best_len-1 can be removed because it will be made
  81963. * again later. (This heuristic is not always a win.)
  81964. * It is not necessary to compare scan[2] and match[2] since they
  81965. * are always equal when the other bytes match, given that
  81966. * the hash keys are equal and that HASH_BITS >= 8.
  81967. */
  81968. scan += 2, match++;
  81969. Assert(*scan == *match, "match[2]?");
  81970. /* We check for insufficient lookahead only every 8th comparison;
  81971. * the 256th check will be made at strstart+258.
  81972. */
  81973. do {
  81974. } while (*++scan == *++match && *++scan == *++match &&
  81975. *++scan == *++match && *++scan == *++match &&
  81976. *++scan == *++match && *++scan == *++match &&
  81977. *++scan == *++match && *++scan == *++match &&
  81978. scan < strend);
  81979. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81980. len = MAX_MATCH - (int)(strend - scan);
  81981. scan = strend - MAX_MATCH;
  81982. #endif /* UNALIGNED_OK */
  81983. if (len > best_len) {
  81984. s->match_start = cur_match;
  81985. best_len = len;
  81986. if (len >= nice_match) break;
  81987. #ifdef UNALIGNED_OK
  81988. scan_end = *(ushf*)(scan+best_len-1);
  81989. #else
  81990. scan_end1 = scan[best_len-1];
  81991. scan_end = scan[best_len];
  81992. #endif
  81993. }
  81994. } while ((cur_match = prev[cur_match & wmask]) > limit
  81995. && --chain_length != 0);
  81996. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81997. return s->lookahead;
  81998. }
  81999. #endif /* ASMV */
  82000. #endif /* FASTEST */
  82001. /* ---------------------------------------------------------------------------
  82002. * Optimized version for level == 1 or strategy == Z_RLE only
  82003. */
  82004. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82005. {
  82006. register Bytef *scan = s->window + s->strstart; /* current string */
  82007. register Bytef *match; /* matched string */
  82008. register int len; /* length of current match */
  82009. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82010. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82011. * It is easy to get rid of this optimization if necessary.
  82012. */
  82013. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82014. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82015. Assert(cur_match < s->strstart, "no future");
  82016. match = s->window + cur_match;
  82017. /* Return failure if the match length is less than 2:
  82018. */
  82019. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82020. /* The check at best_len-1 can be removed because it will be made
  82021. * again later. (This heuristic is not always a win.)
  82022. * It is not necessary to compare scan[2] and match[2] since they
  82023. * are always equal when the other bytes match, given that
  82024. * the hash keys are equal and that HASH_BITS >= 8.
  82025. */
  82026. scan += 2, match += 2;
  82027. Assert(*scan == *match, "match[2]?");
  82028. /* We check for insufficient lookahead only every 8th comparison;
  82029. * the 256th check will be made at strstart+258.
  82030. */
  82031. do {
  82032. } while (*++scan == *++match && *++scan == *++match &&
  82033. *++scan == *++match && *++scan == *++match &&
  82034. *++scan == *++match && *++scan == *++match &&
  82035. *++scan == *++match && *++scan == *++match &&
  82036. scan < strend);
  82037. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82038. len = MAX_MATCH - (int)(strend - scan);
  82039. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82040. s->match_start = cur_match;
  82041. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82042. }
  82043. #ifdef DEBUG
  82044. /* ===========================================================================
  82045. * Check that the match at match_start is indeed a match.
  82046. */
  82047. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82048. {
  82049. /* check that the match is indeed a match */
  82050. if (zmemcmp(s->window + match,
  82051. s->window + start, length) != EQUAL) {
  82052. fprintf(stderr, " start %u, match %u, length %d\n",
  82053. start, match, length);
  82054. do {
  82055. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82056. } while (--length != 0);
  82057. z_error("invalid match");
  82058. }
  82059. if (z_verbose > 1) {
  82060. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82061. do { putc(s->window[start++], stderr); } while (--length != 0);
  82062. }
  82063. }
  82064. #else
  82065. # define check_match(s, start, match, length)
  82066. #endif /* DEBUG */
  82067. /* ===========================================================================
  82068. * Fill the window when the lookahead becomes insufficient.
  82069. * Updates strstart and lookahead.
  82070. *
  82071. * IN assertion: lookahead < MIN_LOOKAHEAD
  82072. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82073. * At least one byte has been read, or avail_in == 0; reads are
  82074. * performed for at least two bytes (required for the zip translate_eol
  82075. * option -- not supported here).
  82076. */
  82077. local void fill_window (deflate_state *s)
  82078. {
  82079. register unsigned n, m;
  82080. register Posf *p;
  82081. unsigned more; /* Amount of free space at the end of the window. */
  82082. uInt wsize = s->w_size;
  82083. do {
  82084. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82085. /* Deal with !@#$% 64K limit: */
  82086. if (sizeof(int) <= 2) {
  82087. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82088. more = wsize;
  82089. } else if (more == (unsigned)(-1)) {
  82090. /* Very unlikely, but possible on 16 bit machine if
  82091. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82092. */
  82093. more--;
  82094. }
  82095. }
  82096. /* If the window is almost full and there is insufficient lookahead,
  82097. * move the upper half to the lower one to make room in the upper half.
  82098. */
  82099. if (s->strstart >= wsize+MAX_DIST(s)) {
  82100. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82101. s->match_start -= wsize;
  82102. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82103. s->block_start -= (long) wsize;
  82104. /* Slide the hash table (could be avoided with 32 bit values
  82105. at the expense of memory usage). We slide even when level == 0
  82106. to keep the hash table consistent if we switch back to level > 0
  82107. later. (Using level 0 permanently is not an optimal usage of
  82108. zlib, so we don't care about this pathological case.)
  82109. */
  82110. /* %%% avoid this when Z_RLE */
  82111. n = s->hash_size;
  82112. p = &s->head[n];
  82113. do {
  82114. m = *--p;
  82115. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82116. } while (--n);
  82117. n = wsize;
  82118. #ifndef FASTEST
  82119. p = &s->prev[n];
  82120. do {
  82121. m = *--p;
  82122. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82123. /* If n is not on any hash chain, prev[n] is garbage but
  82124. * its value will never be used.
  82125. */
  82126. } while (--n);
  82127. #endif
  82128. more += wsize;
  82129. }
  82130. if (s->strm->avail_in == 0) return;
  82131. /* If there was no sliding:
  82132. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82133. * more == window_size - lookahead - strstart
  82134. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82135. * => more >= window_size - 2*WSIZE + 2
  82136. * In the BIG_MEM or MMAP case (not yet supported),
  82137. * window_size == input_size + MIN_LOOKAHEAD &&
  82138. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82139. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82140. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82141. */
  82142. Assert(more >= 2, "more < 2");
  82143. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82144. s->lookahead += n;
  82145. /* Initialize the hash value now that we have some input: */
  82146. if (s->lookahead >= MIN_MATCH) {
  82147. s->ins_h = s->window[s->strstart];
  82148. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82149. #if MIN_MATCH != 3
  82150. Call UPDATE_HASH() MIN_MATCH-3 more times
  82151. #endif
  82152. }
  82153. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82154. * but this is not important since only literal bytes will be emitted.
  82155. */
  82156. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82157. }
  82158. /* ===========================================================================
  82159. * Flush the current block, with given end-of-file flag.
  82160. * IN assertion: strstart is set to the end of the current match.
  82161. */
  82162. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82163. _tr_flush_block(s, (s->block_start >= 0L ? \
  82164. (charf *)&s->window[(unsigned)s->block_start] : \
  82165. (charf *)Z_NULL), \
  82166. (ulg)((long)s->strstart - s->block_start), \
  82167. (eof)); \
  82168. s->block_start = s->strstart; \
  82169. flush_pending(s->strm); \
  82170. Tracev((stderr,"[FLUSH]")); \
  82171. }
  82172. /* Same but force premature exit if necessary. */
  82173. #define FLUSH_BLOCK(s, eof) { \
  82174. FLUSH_BLOCK_ONLY(s, eof); \
  82175. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82176. }
  82177. /* ===========================================================================
  82178. * Copy without compression as much as possible from the input stream, return
  82179. * the current block state.
  82180. * This function does not insert new strings in the dictionary since
  82181. * uncompressible data is probably not useful. This function is used
  82182. * only for the level=0 compression option.
  82183. * NOTE: this function should be optimized to avoid extra copying from
  82184. * window to pending_buf.
  82185. */
  82186. local block_state deflate_stored(deflate_state *s, int flush)
  82187. {
  82188. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82189. * to pending_buf_size, and each stored block has a 5 byte header:
  82190. */
  82191. ulg max_block_size = 0xffff;
  82192. ulg max_start;
  82193. if (max_block_size > s->pending_buf_size - 5) {
  82194. max_block_size = s->pending_buf_size - 5;
  82195. }
  82196. /* Copy as much as possible from input to output: */
  82197. for (;;) {
  82198. /* Fill the window as much as possible: */
  82199. if (s->lookahead <= 1) {
  82200. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82201. s->block_start >= (long)s->w_size, "slide too late");
  82202. fill_window(s);
  82203. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82204. if (s->lookahead == 0) break; /* flush the current block */
  82205. }
  82206. Assert(s->block_start >= 0L, "block gone");
  82207. s->strstart += s->lookahead;
  82208. s->lookahead = 0;
  82209. /* Emit a stored block if pending_buf will be full: */
  82210. max_start = s->block_start + max_block_size;
  82211. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82212. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82213. s->lookahead = (uInt)(s->strstart - max_start);
  82214. s->strstart = (uInt)max_start;
  82215. FLUSH_BLOCK(s, 0);
  82216. }
  82217. /* Flush if we may have to slide, otherwise block_start may become
  82218. * negative and the data will be gone:
  82219. */
  82220. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82221. FLUSH_BLOCK(s, 0);
  82222. }
  82223. }
  82224. FLUSH_BLOCK(s, flush == Z_FINISH);
  82225. return flush == Z_FINISH ? finish_done : block_done;
  82226. }
  82227. /* ===========================================================================
  82228. * Compress as much as possible from the input stream, return the current
  82229. * block state.
  82230. * This function does not perform lazy evaluation of matches and inserts
  82231. * new strings in the dictionary only for unmatched strings or for short
  82232. * matches. It is used only for the fast compression options.
  82233. */
  82234. local block_state deflate_fast(deflate_state *s, int flush)
  82235. {
  82236. IPos hash_head = NIL; /* head of the hash chain */
  82237. int bflush; /* set if current block must be flushed */
  82238. for (;;) {
  82239. /* Make sure that we always have enough lookahead, except
  82240. * at the end of the input file. We need MAX_MATCH bytes
  82241. * for the next match, plus MIN_MATCH bytes to insert the
  82242. * string following the next match.
  82243. */
  82244. if (s->lookahead < MIN_LOOKAHEAD) {
  82245. fill_window(s);
  82246. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82247. return need_more;
  82248. }
  82249. if (s->lookahead == 0) break; /* flush the current block */
  82250. }
  82251. /* Insert the string window[strstart .. strstart+2] in the
  82252. * dictionary, and set hash_head to the head of the hash chain:
  82253. */
  82254. if (s->lookahead >= MIN_MATCH) {
  82255. INSERT_STRING(s, s->strstart, hash_head);
  82256. }
  82257. /* Find the longest match, discarding those <= prev_length.
  82258. * At this point we have always match_length < MIN_MATCH
  82259. */
  82260. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82261. /* To simplify the code, we prevent matches with the string
  82262. * of window index 0 (in particular we have to avoid a match
  82263. * of the string with itself at the start of the input file).
  82264. */
  82265. #ifdef FASTEST
  82266. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82267. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82268. s->match_length = longest_match_fast (s, hash_head);
  82269. }
  82270. #else
  82271. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82272. s->match_length = longest_match (s, hash_head);
  82273. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82274. s->match_length = longest_match_fast (s, hash_head);
  82275. }
  82276. #endif
  82277. /* longest_match() or longest_match_fast() sets match_start */
  82278. }
  82279. if (s->match_length >= MIN_MATCH) {
  82280. check_match(s, s->strstart, s->match_start, s->match_length);
  82281. _tr_tally_dist(s, s->strstart - s->match_start,
  82282. s->match_length - MIN_MATCH, bflush);
  82283. s->lookahead -= s->match_length;
  82284. /* Insert new strings in the hash table only if the match length
  82285. * is not too large. This saves time but degrades compression.
  82286. */
  82287. #ifndef FASTEST
  82288. if (s->match_length <= s->max_insert_length &&
  82289. s->lookahead >= MIN_MATCH) {
  82290. s->match_length--; /* string at strstart already in table */
  82291. do {
  82292. s->strstart++;
  82293. INSERT_STRING(s, s->strstart, hash_head);
  82294. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82295. * always MIN_MATCH bytes ahead.
  82296. */
  82297. } while (--s->match_length != 0);
  82298. s->strstart++;
  82299. } else
  82300. #endif
  82301. {
  82302. s->strstart += s->match_length;
  82303. s->match_length = 0;
  82304. s->ins_h = s->window[s->strstart];
  82305. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82306. #if MIN_MATCH != 3
  82307. Call UPDATE_HASH() MIN_MATCH-3 more times
  82308. #endif
  82309. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82310. * matter since it will be recomputed at next deflate call.
  82311. */
  82312. }
  82313. } else {
  82314. /* No match, output a literal byte */
  82315. Tracevv((stderr,"%c", s->window[s->strstart]));
  82316. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82317. s->lookahead--;
  82318. s->strstart++;
  82319. }
  82320. if (bflush) FLUSH_BLOCK(s, 0);
  82321. }
  82322. FLUSH_BLOCK(s, flush == Z_FINISH);
  82323. return flush == Z_FINISH ? finish_done : block_done;
  82324. }
  82325. #ifndef FASTEST
  82326. /* ===========================================================================
  82327. * Same as above, but achieves better compression. We use a lazy
  82328. * evaluation for matches: a match is finally adopted only if there is
  82329. * no better match at the next window position.
  82330. */
  82331. local block_state deflate_slow(deflate_state *s, int flush)
  82332. {
  82333. IPos hash_head = NIL; /* head of hash chain */
  82334. int bflush; /* set if current block must be flushed */
  82335. /* Process the input block. */
  82336. for (;;) {
  82337. /* Make sure that we always have enough lookahead, except
  82338. * at the end of the input file. We need MAX_MATCH bytes
  82339. * for the next match, plus MIN_MATCH bytes to insert the
  82340. * string following the next match.
  82341. */
  82342. if (s->lookahead < MIN_LOOKAHEAD) {
  82343. fill_window(s);
  82344. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82345. return need_more;
  82346. }
  82347. if (s->lookahead == 0) break; /* flush the current block */
  82348. }
  82349. /* Insert the string window[strstart .. strstart+2] in the
  82350. * dictionary, and set hash_head to the head of the hash chain:
  82351. */
  82352. if (s->lookahead >= MIN_MATCH) {
  82353. INSERT_STRING(s, s->strstart, hash_head);
  82354. }
  82355. /* Find the longest match, discarding those <= prev_length.
  82356. */
  82357. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82358. s->match_length = MIN_MATCH-1;
  82359. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82360. s->strstart - hash_head <= MAX_DIST(s)) {
  82361. /* To simplify the code, we prevent matches with the string
  82362. * of window index 0 (in particular we have to avoid a match
  82363. * of the string with itself at the start of the input file).
  82364. */
  82365. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82366. s->match_length = longest_match (s, hash_head);
  82367. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82368. s->match_length = longest_match_fast (s, hash_head);
  82369. }
  82370. /* longest_match() or longest_match_fast() sets match_start */
  82371. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82372. #if TOO_FAR <= 32767
  82373. || (s->match_length == MIN_MATCH &&
  82374. s->strstart - s->match_start > TOO_FAR)
  82375. #endif
  82376. )) {
  82377. /* If prev_match is also MIN_MATCH, match_start is garbage
  82378. * but we will ignore the current match anyway.
  82379. */
  82380. s->match_length = MIN_MATCH-1;
  82381. }
  82382. }
  82383. /* If there was a match at the previous step and the current
  82384. * match is not better, output the previous match:
  82385. */
  82386. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82387. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82388. /* Do not insert strings in hash table beyond this. */
  82389. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82390. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82391. s->prev_length - MIN_MATCH, bflush);
  82392. /* Insert in hash table all strings up to the end of the match.
  82393. * strstart-1 and strstart are already inserted. If there is not
  82394. * enough lookahead, the last two strings are not inserted in
  82395. * the hash table.
  82396. */
  82397. s->lookahead -= s->prev_length-1;
  82398. s->prev_length -= 2;
  82399. do {
  82400. if (++s->strstart <= max_insert) {
  82401. INSERT_STRING(s, s->strstart, hash_head);
  82402. }
  82403. } while (--s->prev_length != 0);
  82404. s->match_available = 0;
  82405. s->match_length = MIN_MATCH-1;
  82406. s->strstart++;
  82407. if (bflush) FLUSH_BLOCK(s, 0);
  82408. } else if (s->match_available) {
  82409. /* If there was no match at the previous position, output a
  82410. * single literal. If there was a match but the current match
  82411. * is longer, truncate the previous match to a single literal.
  82412. */
  82413. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82414. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82415. if (bflush) {
  82416. FLUSH_BLOCK_ONLY(s, 0);
  82417. }
  82418. s->strstart++;
  82419. s->lookahead--;
  82420. if (s->strm->avail_out == 0) return need_more;
  82421. } else {
  82422. /* There is no previous match to compare with, wait for
  82423. * the next step to decide.
  82424. */
  82425. s->match_available = 1;
  82426. s->strstart++;
  82427. s->lookahead--;
  82428. }
  82429. }
  82430. Assert (flush != Z_NO_FLUSH, "no flush?");
  82431. if (s->match_available) {
  82432. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82433. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82434. s->match_available = 0;
  82435. }
  82436. FLUSH_BLOCK(s, flush == Z_FINISH);
  82437. return flush == Z_FINISH ? finish_done : block_done;
  82438. }
  82439. #endif /* FASTEST */
  82440. #if 0
  82441. /* ===========================================================================
  82442. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82443. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82444. * deflate switches away from Z_RLE.)
  82445. */
  82446. local block_state deflate_rle(s, flush)
  82447. deflate_state *s;
  82448. int flush;
  82449. {
  82450. int bflush; /* set if current block must be flushed */
  82451. uInt run; /* length of run */
  82452. uInt max; /* maximum length of run */
  82453. uInt prev; /* byte at distance one to match */
  82454. Bytef *scan; /* scan for end of run */
  82455. for (;;) {
  82456. /* Make sure that we always have enough lookahead, except
  82457. * at the end of the input file. We need MAX_MATCH bytes
  82458. * for the longest encodable run.
  82459. */
  82460. if (s->lookahead < MAX_MATCH) {
  82461. fill_window(s);
  82462. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82463. return need_more;
  82464. }
  82465. if (s->lookahead == 0) break; /* flush the current block */
  82466. }
  82467. /* See how many times the previous byte repeats */
  82468. run = 0;
  82469. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82470. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82471. scan = s->window + s->strstart - 1;
  82472. prev = *scan++;
  82473. do {
  82474. if (*scan++ != prev)
  82475. break;
  82476. } while (++run < max);
  82477. }
  82478. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82479. if (run >= MIN_MATCH) {
  82480. check_match(s, s->strstart, s->strstart - 1, run);
  82481. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82482. s->lookahead -= run;
  82483. s->strstart += run;
  82484. } else {
  82485. /* No match, output a literal byte */
  82486. Tracevv((stderr,"%c", s->window[s->strstart]));
  82487. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82488. s->lookahead--;
  82489. s->strstart++;
  82490. }
  82491. if (bflush) FLUSH_BLOCK(s, 0);
  82492. }
  82493. FLUSH_BLOCK(s, flush == Z_FINISH);
  82494. return flush == Z_FINISH ? finish_done : block_done;
  82495. }
  82496. #endif
  82497. /*** End of inlined file: deflate.c ***/
  82498. /*** Start of inlined file: inffast.c ***/
  82499. /*** Start of inlined file: inftrees.h ***/
  82500. /* WARNING: this file should *not* be used by applications. It is
  82501. part of the implementation of the compression library and is
  82502. subject to change. Applications should only use zlib.h.
  82503. */
  82504. #ifndef _INFTREES_H_
  82505. #define _INFTREES_H_
  82506. /* Structure for decoding tables. Each entry provides either the
  82507. information needed to do the operation requested by the code that
  82508. indexed that table entry, or it provides a pointer to another
  82509. table that indexes more bits of the code. op indicates whether
  82510. the entry is a pointer to another table, a literal, a length or
  82511. distance, an end-of-block, or an invalid code. For a table
  82512. pointer, the low four bits of op is the number of index bits of
  82513. that table. For a length or distance, the low four bits of op
  82514. is the number of extra bits to get after the code. bits is
  82515. the number of bits in this code or part of the code to drop off
  82516. of the bit buffer. val is the actual byte to output in the case
  82517. of a literal, the base length or distance, or the offset from
  82518. the current table to the next table. Each entry is four bytes. */
  82519. typedef struct {
  82520. unsigned char op; /* operation, extra bits, table bits */
  82521. unsigned char bits; /* bits in this part of the code */
  82522. unsigned short val; /* offset in table or code value */
  82523. } code;
  82524. /* op values as set by inflate_table():
  82525. 00000000 - literal
  82526. 0000tttt - table link, tttt != 0 is the number of table index bits
  82527. 0001eeee - length or distance, eeee is the number of extra bits
  82528. 01100000 - end of block
  82529. 01000000 - invalid code
  82530. */
  82531. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82532. exhaustive search was 1444 code structures (852 for length/literals
  82533. and 592 for distances, the latter actually the result of an
  82534. exhaustive search). The true maximum is not known, but the value
  82535. below is more than safe. */
  82536. #define ENOUGH 2048
  82537. #define MAXD 592
  82538. /* Type of code to build for inftable() */
  82539. typedef enum {
  82540. CODES,
  82541. LENS,
  82542. DISTS
  82543. } codetype;
  82544. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82545. unsigned codes, code FAR * FAR *table,
  82546. unsigned FAR *bits, unsigned short FAR *work));
  82547. #endif
  82548. /*** End of inlined file: inftrees.h ***/
  82549. /*** Start of inlined file: inflate.h ***/
  82550. /* WARNING: this file should *not* be used by applications. It is
  82551. part of the implementation of the compression library and is
  82552. subject to change. Applications should only use zlib.h.
  82553. */
  82554. #ifndef _INFLATE_H_
  82555. #define _INFLATE_H_
  82556. /* define NO_GZIP when compiling if you want to disable gzip header and
  82557. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82558. the crc code when it is not needed. For shared libraries, gzip decoding
  82559. should be left enabled. */
  82560. #ifndef NO_GZIP
  82561. # define GUNZIP
  82562. #endif
  82563. /* Possible inflate modes between inflate() calls */
  82564. typedef enum {
  82565. HEAD, /* i: waiting for magic header */
  82566. FLAGS, /* i: waiting for method and flags (gzip) */
  82567. TIME, /* i: waiting for modification time (gzip) */
  82568. OS, /* i: waiting for extra flags and operating system (gzip) */
  82569. EXLEN, /* i: waiting for extra length (gzip) */
  82570. EXTRA, /* i: waiting for extra bytes (gzip) */
  82571. NAME, /* i: waiting for end of file name (gzip) */
  82572. COMMENT, /* i: waiting for end of comment (gzip) */
  82573. HCRC, /* i: waiting for header crc (gzip) */
  82574. DICTID, /* i: waiting for dictionary check value */
  82575. DICT, /* waiting for inflateSetDictionary() call */
  82576. TYPE, /* i: waiting for type bits, including last-flag bit */
  82577. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82578. STORED, /* i: waiting for stored size (length and complement) */
  82579. COPY, /* i/o: waiting for input or output to copy stored block */
  82580. TABLE, /* i: waiting for dynamic block table lengths */
  82581. LENLENS, /* i: waiting for code length code lengths */
  82582. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82583. LEN, /* i: waiting for length/lit code */
  82584. LENEXT, /* i: waiting for length extra bits */
  82585. DIST, /* i: waiting for distance code */
  82586. DISTEXT, /* i: waiting for distance extra bits */
  82587. MATCH, /* o: waiting for output space to copy string */
  82588. LIT, /* o: waiting for output space to write literal */
  82589. CHECK, /* i: waiting for 32-bit check value */
  82590. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82591. DONE, /* finished check, done -- remain here until reset */
  82592. BAD, /* got a data error -- remain here until reset */
  82593. MEM, /* got an inflate() memory error -- remain here until reset */
  82594. SYNC /* looking for synchronization bytes to restart inflate() */
  82595. } inflate_mode;
  82596. /*
  82597. State transitions between above modes -
  82598. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82599. Process header:
  82600. HEAD -> (gzip) or (zlib)
  82601. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82602. NAME -> COMMENT -> HCRC -> TYPE
  82603. (zlib) -> DICTID or TYPE
  82604. DICTID -> DICT -> TYPE
  82605. Read deflate blocks:
  82606. TYPE -> STORED or TABLE or LEN or CHECK
  82607. STORED -> COPY -> TYPE
  82608. TABLE -> LENLENS -> CODELENS -> LEN
  82609. Read deflate codes:
  82610. LEN -> LENEXT or LIT or TYPE
  82611. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82612. LIT -> LEN
  82613. Process trailer:
  82614. CHECK -> LENGTH -> DONE
  82615. */
  82616. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82617. struct inflate_state {
  82618. inflate_mode mode; /* current inflate mode */
  82619. int last; /* true if processing last block */
  82620. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82621. int havedict; /* true if dictionary provided */
  82622. int flags; /* gzip header method and flags (0 if zlib) */
  82623. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82624. unsigned long check; /* protected copy of check value */
  82625. unsigned long total; /* protected copy of output count */
  82626. gz_headerp head; /* where to save gzip header information */
  82627. /* sliding window */
  82628. unsigned wbits; /* log base 2 of requested window size */
  82629. unsigned wsize; /* window size or zero if not using window */
  82630. unsigned whave; /* valid bytes in the window */
  82631. unsigned write; /* window write index */
  82632. unsigned char FAR *window; /* allocated sliding window, if needed */
  82633. /* bit accumulator */
  82634. unsigned long hold; /* input bit accumulator */
  82635. unsigned bits; /* number of bits in "in" */
  82636. /* for string and stored block copying */
  82637. unsigned length; /* literal or length of data to copy */
  82638. unsigned offset; /* distance back to copy string from */
  82639. /* for table and code decoding */
  82640. unsigned extra; /* extra bits needed */
  82641. /* fixed and dynamic code tables */
  82642. code const FAR *lencode; /* starting table for length/literal codes */
  82643. code const FAR *distcode; /* starting table for distance codes */
  82644. unsigned lenbits; /* index bits for lencode */
  82645. unsigned distbits; /* index bits for distcode */
  82646. /* dynamic table building */
  82647. unsigned ncode; /* number of code length code lengths */
  82648. unsigned nlen; /* number of length code lengths */
  82649. unsigned ndist; /* number of distance code lengths */
  82650. unsigned have; /* number of code lengths in lens[] */
  82651. code FAR *next; /* next available space in codes[] */
  82652. unsigned short lens[320]; /* temporary storage for code lengths */
  82653. unsigned short work[288]; /* work area for code table building */
  82654. code codes[ENOUGH]; /* space for code tables */
  82655. };
  82656. #endif
  82657. /*** End of inlined file: inflate.h ***/
  82658. /*** Start of inlined file: inffast.h ***/
  82659. /* WARNING: this file should *not* be used by applications. It is
  82660. part of the implementation of the compression library and is
  82661. subject to change. Applications should only use zlib.h.
  82662. */
  82663. void inflate_fast OF((z_streamp strm, unsigned start));
  82664. /*** End of inlined file: inffast.h ***/
  82665. #ifndef ASMINF
  82666. /* Allow machine dependent optimization for post-increment or pre-increment.
  82667. Based on testing to date,
  82668. Pre-increment preferred for:
  82669. - PowerPC G3 (Adler)
  82670. - MIPS R5000 (Randers-Pehrson)
  82671. Post-increment preferred for:
  82672. - none
  82673. No measurable difference:
  82674. - Pentium III (Anderson)
  82675. - M68060 (Nikl)
  82676. */
  82677. #ifdef POSTINC
  82678. # define OFF 0
  82679. # define PUP(a) *(a)++
  82680. #else
  82681. # define OFF 1
  82682. # define PUP(a) *++(a)
  82683. #endif
  82684. /*
  82685. Decode literal, length, and distance codes and write out the resulting
  82686. literal and match bytes until either not enough input or output is
  82687. available, an end-of-block is encountered, or a data error is encountered.
  82688. When large enough input and output buffers are supplied to inflate(), for
  82689. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82690. inflate execution time is spent in this routine.
  82691. Entry assumptions:
  82692. state->mode == LEN
  82693. strm->avail_in >= 6
  82694. strm->avail_out >= 258
  82695. start >= strm->avail_out
  82696. state->bits < 8
  82697. On return, state->mode is one of:
  82698. LEN -- ran out of enough output space or enough available input
  82699. TYPE -- reached end of block code, inflate() to interpret next block
  82700. BAD -- error in block data
  82701. Notes:
  82702. - The maximum input bits used by a length/distance pair is 15 bits for the
  82703. length code, 5 bits for the length extra, 15 bits for the distance code,
  82704. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82705. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82706. checking for available input while decoding.
  82707. - The maximum bytes that a single length/distance pair can output is 258
  82708. bytes, which is the maximum length that can be coded. inflate_fast()
  82709. requires strm->avail_out >= 258 for each loop to avoid checking for
  82710. output space.
  82711. */
  82712. void inflate_fast (z_streamp strm, unsigned start)
  82713. {
  82714. struct inflate_state FAR *state;
  82715. unsigned char FAR *in; /* local strm->next_in */
  82716. unsigned char FAR *last; /* while in < last, enough input available */
  82717. unsigned char FAR *out; /* local strm->next_out */
  82718. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82719. unsigned char FAR *end; /* while out < end, enough space available */
  82720. #ifdef INFLATE_STRICT
  82721. unsigned dmax; /* maximum distance from zlib header */
  82722. #endif
  82723. unsigned wsize; /* window size or zero if not using window */
  82724. unsigned whave; /* valid bytes in the window */
  82725. unsigned write; /* window write index */
  82726. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82727. unsigned long hold; /* local strm->hold */
  82728. unsigned bits; /* local strm->bits */
  82729. code const FAR *lcode; /* local strm->lencode */
  82730. code const FAR *dcode; /* local strm->distcode */
  82731. unsigned lmask; /* mask for first level of length codes */
  82732. unsigned dmask; /* mask for first level of distance codes */
  82733. code thisx; /* retrieved table entry */
  82734. unsigned op; /* code bits, operation, extra bits, or */
  82735. /* window position, window bytes to copy */
  82736. unsigned len; /* match length, unused bytes */
  82737. unsigned dist; /* match distance */
  82738. unsigned char FAR *from; /* where to copy match from */
  82739. /* copy state to local variables */
  82740. state = (struct inflate_state FAR *)strm->state;
  82741. in = strm->next_in - OFF;
  82742. last = in + (strm->avail_in - 5);
  82743. out = strm->next_out - OFF;
  82744. beg = out - (start - strm->avail_out);
  82745. end = out + (strm->avail_out - 257);
  82746. #ifdef INFLATE_STRICT
  82747. dmax = state->dmax;
  82748. #endif
  82749. wsize = state->wsize;
  82750. whave = state->whave;
  82751. write = state->write;
  82752. window = state->window;
  82753. hold = state->hold;
  82754. bits = state->bits;
  82755. lcode = state->lencode;
  82756. dcode = state->distcode;
  82757. lmask = (1U << state->lenbits) - 1;
  82758. dmask = (1U << state->distbits) - 1;
  82759. /* decode literals and length/distances until end-of-block or not enough
  82760. input data or output space */
  82761. do {
  82762. if (bits < 15) {
  82763. hold += (unsigned long)(PUP(in)) << bits;
  82764. bits += 8;
  82765. hold += (unsigned long)(PUP(in)) << bits;
  82766. bits += 8;
  82767. }
  82768. thisx = lcode[hold & lmask];
  82769. dolen:
  82770. op = (unsigned)(thisx.bits);
  82771. hold >>= op;
  82772. bits -= op;
  82773. op = (unsigned)(thisx.op);
  82774. if (op == 0) { /* literal */
  82775. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82776. "inflate: literal '%c'\n" :
  82777. "inflate: literal 0x%02x\n", thisx.val));
  82778. PUP(out) = (unsigned char)(thisx.val);
  82779. }
  82780. else if (op & 16) { /* length base */
  82781. len = (unsigned)(thisx.val);
  82782. op &= 15; /* number of extra bits */
  82783. if (op) {
  82784. if (bits < op) {
  82785. hold += (unsigned long)(PUP(in)) << bits;
  82786. bits += 8;
  82787. }
  82788. len += (unsigned)hold & ((1U << op) - 1);
  82789. hold >>= op;
  82790. bits -= op;
  82791. }
  82792. Tracevv((stderr, "inflate: length %u\n", len));
  82793. if (bits < 15) {
  82794. hold += (unsigned long)(PUP(in)) << bits;
  82795. bits += 8;
  82796. hold += (unsigned long)(PUP(in)) << bits;
  82797. bits += 8;
  82798. }
  82799. thisx = dcode[hold & dmask];
  82800. dodist:
  82801. op = (unsigned)(thisx.bits);
  82802. hold >>= op;
  82803. bits -= op;
  82804. op = (unsigned)(thisx.op);
  82805. if (op & 16) { /* distance base */
  82806. dist = (unsigned)(thisx.val);
  82807. op &= 15; /* number of extra bits */
  82808. if (bits < op) {
  82809. hold += (unsigned long)(PUP(in)) << bits;
  82810. bits += 8;
  82811. if (bits < op) {
  82812. hold += (unsigned long)(PUP(in)) << bits;
  82813. bits += 8;
  82814. }
  82815. }
  82816. dist += (unsigned)hold & ((1U << op) - 1);
  82817. #ifdef INFLATE_STRICT
  82818. if (dist > dmax) {
  82819. strm->msg = (char *)"invalid distance too far back";
  82820. state->mode = BAD;
  82821. break;
  82822. }
  82823. #endif
  82824. hold >>= op;
  82825. bits -= op;
  82826. Tracevv((stderr, "inflate: distance %u\n", dist));
  82827. op = (unsigned)(out - beg); /* max distance in output */
  82828. if (dist > op) { /* see if copy from window */
  82829. op = dist - op; /* distance back in window */
  82830. if (op > whave) {
  82831. strm->msg = (char *)"invalid distance too far back";
  82832. state->mode = BAD;
  82833. break;
  82834. }
  82835. from = window - OFF;
  82836. if (write == 0) { /* very common case */
  82837. from += wsize - op;
  82838. if (op < len) { /* some from window */
  82839. len -= op;
  82840. do {
  82841. PUP(out) = PUP(from);
  82842. } while (--op);
  82843. from = out - dist; /* rest from output */
  82844. }
  82845. }
  82846. else if (write < op) { /* wrap around window */
  82847. from += wsize + write - op;
  82848. op -= write;
  82849. if (op < len) { /* some from end of window */
  82850. len -= op;
  82851. do {
  82852. PUP(out) = PUP(from);
  82853. } while (--op);
  82854. from = window - OFF;
  82855. if (write < len) { /* some from start of window */
  82856. op = write;
  82857. len -= op;
  82858. do {
  82859. PUP(out) = PUP(from);
  82860. } while (--op);
  82861. from = out - dist; /* rest from output */
  82862. }
  82863. }
  82864. }
  82865. else { /* contiguous in window */
  82866. from += write - op;
  82867. if (op < len) { /* some from window */
  82868. len -= op;
  82869. do {
  82870. PUP(out) = PUP(from);
  82871. } while (--op);
  82872. from = out - dist; /* rest from output */
  82873. }
  82874. }
  82875. while (len > 2) {
  82876. PUP(out) = PUP(from);
  82877. PUP(out) = PUP(from);
  82878. PUP(out) = PUP(from);
  82879. len -= 3;
  82880. }
  82881. if (len) {
  82882. PUP(out) = PUP(from);
  82883. if (len > 1)
  82884. PUP(out) = PUP(from);
  82885. }
  82886. }
  82887. else {
  82888. from = out - dist; /* copy direct from output */
  82889. do { /* minimum length is three */
  82890. PUP(out) = PUP(from);
  82891. PUP(out) = PUP(from);
  82892. PUP(out) = PUP(from);
  82893. len -= 3;
  82894. } while (len > 2);
  82895. if (len) {
  82896. PUP(out) = PUP(from);
  82897. if (len > 1)
  82898. PUP(out) = PUP(from);
  82899. }
  82900. }
  82901. }
  82902. else if ((op & 64) == 0) { /* 2nd level distance code */
  82903. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82904. goto dodist;
  82905. }
  82906. else {
  82907. strm->msg = (char *)"invalid distance code";
  82908. state->mode = BAD;
  82909. break;
  82910. }
  82911. }
  82912. else if ((op & 64) == 0) { /* 2nd level length code */
  82913. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82914. goto dolen;
  82915. }
  82916. else if (op & 32) { /* end-of-block */
  82917. Tracevv((stderr, "inflate: end of block\n"));
  82918. state->mode = TYPE;
  82919. break;
  82920. }
  82921. else {
  82922. strm->msg = (char *)"invalid literal/length code";
  82923. state->mode = BAD;
  82924. break;
  82925. }
  82926. } while (in < last && out < end);
  82927. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82928. len = bits >> 3;
  82929. in -= len;
  82930. bits -= len << 3;
  82931. hold &= (1U << bits) - 1;
  82932. /* update state and return */
  82933. strm->next_in = in + OFF;
  82934. strm->next_out = out + OFF;
  82935. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82936. strm->avail_out = (unsigned)(out < end ?
  82937. 257 + (end - out) : 257 - (out - end));
  82938. state->hold = hold;
  82939. state->bits = bits;
  82940. return;
  82941. }
  82942. /*
  82943. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82944. - Using bit fields for code structure
  82945. - Different op definition to avoid & for extra bits (do & for table bits)
  82946. - Three separate decoding do-loops for direct, window, and write == 0
  82947. - Special case for distance > 1 copies to do overlapped load and store copy
  82948. - Explicit branch predictions (based on measured branch probabilities)
  82949. - Deferring match copy and interspersed it with decoding subsequent codes
  82950. - Swapping literal/length else
  82951. - Swapping window/direct else
  82952. - Larger unrolled copy loops (three is about right)
  82953. - Moving len -= 3 statement into middle of loop
  82954. */
  82955. #endif /* !ASMINF */
  82956. /*** End of inlined file: inffast.c ***/
  82957. #undef PULLBYTE
  82958. #undef LOAD
  82959. #undef RESTORE
  82960. #undef INITBITS
  82961. #undef NEEDBITS
  82962. #undef DROPBITS
  82963. #undef BYTEBITS
  82964. /*** Start of inlined file: inflate.c ***/
  82965. /*
  82966. * Change history:
  82967. *
  82968. * 1.2.beta0 24 Nov 2002
  82969. * - First version -- complete rewrite of inflate to simplify code, avoid
  82970. * creation of window when not needed, minimize use of window when it is
  82971. * needed, make inffast.c even faster, implement gzip decoding, and to
  82972. * improve code readability and style over the previous zlib inflate code
  82973. *
  82974. * 1.2.beta1 25 Nov 2002
  82975. * - Use pointers for available input and output checking in inffast.c
  82976. * - Remove input and output counters in inffast.c
  82977. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82978. * - Remove unnecessary second byte pull from length extra in inffast.c
  82979. * - Unroll direct copy to three copies per loop in inffast.c
  82980. *
  82981. * 1.2.beta2 4 Dec 2002
  82982. * - Change external routine names to reduce potential conflicts
  82983. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82984. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82985. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82986. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82987. *
  82988. * 1.2.beta3 22 Dec 2002
  82989. * - Add comments on state->bits assertion in inffast.c
  82990. * - Add comments on op field in inftrees.h
  82991. * - Fix bug in reuse of allocated window after inflateReset()
  82992. * - Remove bit fields--back to byte structure for speed
  82993. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82994. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82995. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82996. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82997. * - Use local copies of stream next and avail values, as well as local bit
  82998. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82999. *
  83000. * 1.2.beta4 1 Jan 2003
  83001. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83002. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83003. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83004. * - Rearrange window copies in inflate_fast() for speed and simplification
  83005. * - Unroll last copy for window match in inflate_fast()
  83006. * - Use local copies of window variables in inflate_fast() for speed
  83007. * - Pull out common write == 0 case for speed in inflate_fast()
  83008. * - Make op and len in inflate_fast() unsigned for consistency
  83009. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83010. * - Simplified bad distance check in inflate_fast()
  83011. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83012. * source file infback.c to provide a call-back interface to inflate for
  83013. * programs like gzip and unzip -- uses window as output buffer to avoid
  83014. * window copying
  83015. *
  83016. * 1.2.beta5 1 Jan 2003
  83017. * - Improved inflateBack() interface to allow the caller to provide initial
  83018. * input in strm.
  83019. * - Fixed stored blocks bug in inflateBack()
  83020. *
  83021. * 1.2.beta6 4 Jan 2003
  83022. * - Added comments in inffast.c on effectiveness of POSTINC
  83023. * - Typecasting all around to reduce compiler warnings
  83024. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83025. * make compilers happy
  83026. * - Changed type of window in inflateBackInit() to unsigned char *
  83027. *
  83028. * 1.2.beta7 27 Jan 2003
  83029. * - Changed many types to unsigned or unsigned short to avoid warnings
  83030. * - Added inflateCopy() function
  83031. *
  83032. * 1.2.0 9 Mar 2003
  83033. * - Changed inflateBack() interface to provide separate opaque descriptors
  83034. * for the in() and out() functions
  83035. * - Changed inflateBack() argument and in_func typedef to swap the length
  83036. * and buffer address return values for the input function
  83037. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83038. *
  83039. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83040. */
  83041. /*** Start of inlined file: inffast.h ***/
  83042. /* WARNING: this file should *not* be used by applications. It is
  83043. part of the implementation of the compression library and is
  83044. subject to change. Applications should only use zlib.h.
  83045. */
  83046. void inflate_fast OF((z_streamp strm, unsigned start));
  83047. /*** End of inlined file: inffast.h ***/
  83048. #ifdef MAKEFIXED
  83049. # ifndef BUILDFIXED
  83050. # define BUILDFIXED
  83051. # endif
  83052. #endif
  83053. /* function prototypes */
  83054. local void fixedtables OF((struct inflate_state FAR *state));
  83055. local int updatewindow OF((z_streamp strm, unsigned out));
  83056. #ifdef BUILDFIXED
  83057. void makefixed OF((void));
  83058. #endif
  83059. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83060. unsigned len));
  83061. int ZEXPORT inflateReset (z_streamp strm)
  83062. {
  83063. struct inflate_state FAR *state;
  83064. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83065. state = (struct inflate_state FAR *)strm->state;
  83066. strm->total_in = strm->total_out = state->total = 0;
  83067. strm->msg = Z_NULL;
  83068. strm->adler = 1; /* to support ill-conceived Java test suite */
  83069. state->mode = HEAD;
  83070. state->last = 0;
  83071. state->havedict = 0;
  83072. state->dmax = 32768U;
  83073. state->head = Z_NULL;
  83074. state->wsize = 0;
  83075. state->whave = 0;
  83076. state->write = 0;
  83077. state->hold = 0;
  83078. state->bits = 0;
  83079. state->lencode = state->distcode = state->next = state->codes;
  83080. Tracev((stderr, "inflate: reset\n"));
  83081. return Z_OK;
  83082. }
  83083. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83084. {
  83085. struct inflate_state FAR *state;
  83086. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83087. state = (struct inflate_state FAR *)strm->state;
  83088. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83089. value &= (1L << bits) - 1;
  83090. state->hold += value << state->bits;
  83091. state->bits += bits;
  83092. return Z_OK;
  83093. }
  83094. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83095. {
  83096. struct inflate_state FAR *state;
  83097. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83098. stream_size != (int)(sizeof(z_stream)))
  83099. return Z_VERSION_ERROR;
  83100. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83101. strm->msg = Z_NULL; /* in case we return an error */
  83102. if (strm->zalloc == (alloc_func)0) {
  83103. strm->zalloc = zcalloc;
  83104. strm->opaque = (voidpf)0;
  83105. }
  83106. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83107. state = (struct inflate_state FAR *)
  83108. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83109. if (state == Z_NULL) return Z_MEM_ERROR;
  83110. Tracev((stderr, "inflate: allocated\n"));
  83111. strm->state = (struct internal_state FAR *)state;
  83112. if (windowBits < 0) {
  83113. state->wrap = 0;
  83114. windowBits = -windowBits;
  83115. }
  83116. else {
  83117. state->wrap = (windowBits >> 4) + 1;
  83118. #ifdef GUNZIP
  83119. if (windowBits < 48) windowBits &= 15;
  83120. #endif
  83121. }
  83122. if (windowBits < 8 || windowBits > 15) {
  83123. ZFREE(strm, state);
  83124. strm->state = Z_NULL;
  83125. return Z_STREAM_ERROR;
  83126. }
  83127. state->wbits = (unsigned)windowBits;
  83128. state->window = Z_NULL;
  83129. return inflateReset(strm);
  83130. }
  83131. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83132. {
  83133. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83134. }
  83135. /*
  83136. Return state with length and distance decoding tables and index sizes set to
  83137. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83138. If BUILDFIXED is defined, then instead this routine builds the tables the
  83139. first time it's called, and returns those tables the first time and
  83140. thereafter. This reduces the size of the code by about 2K bytes, in
  83141. exchange for a little execution time. However, BUILDFIXED should not be
  83142. used for threaded applications, since the rewriting of the tables and virgin
  83143. may not be thread-safe.
  83144. */
  83145. local void fixedtables (struct inflate_state FAR *state)
  83146. {
  83147. #ifdef BUILDFIXED
  83148. static int virgin = 1;
  83149. static code *lenfix, *distfix;
  83150. static code fixed[544];
  83151. /* build fixed huffman tables if first call (may not be thread safe) */
  83152. if (virgin) {
  83153. unsigned sym, bits;
  83154. static code *next;
  83155. /* literal/length table */
  83156. sym = 0;
  83157. while (sym < 144) state->lens[sym++] = 8;
  83158. while (sym < 256) state->lens[sym++] = 9;
  83159. while (sym < 280) state->lens[sym++] = 7;
  83160. while (sym < 288) state->lens[sym++] = 8;
  83161. next = fixed;
  83162. lenfix = next;
  83163. bits = 9;
  83164. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83165. /* distance table */
  83166. sym = 0;
  83167. while (sym < 32) state->lens[sym++] = 5;
  83168. distfix = next;
  83169. bits = 5;
  83170. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83171. /* do this just once */
  83172. virgin = 0;
  83173. }
  83174. #else /* !BUILDFIXED */
  83175. /*** Start of inlined file: inffixed.h ***/
  83176. /* WARNING: this file should *not* be used by applications. It
  83177. is part of the implementation of the compression library and
  83178. is subject to change. Applications should only use zlib.h.
  83179. */
  83180. static const code lenfix[512] = {
  83181. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83182. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83183. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83184. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83185. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83186. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83187. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83188. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83189. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83190. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83191. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83192. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83193. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83194. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83195. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83196. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83197. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83198. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83199. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83200. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83201. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83202. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83203. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83204. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83205. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83206. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83207. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83208. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83209. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83210. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83211. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83212. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83213. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83214. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83215. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83216. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83217. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83218. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83219. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83220. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83221. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83222. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83223. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83224. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83225. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83226. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83227. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83228. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83229. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83230. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83231. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83232. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83233. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83234. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83235. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83236. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83237. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83238. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83239. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83240. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83241. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83242. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83243. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83244. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83245. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83246. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83247. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83248. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83249. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83250. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83251. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83252. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83253. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83254. {0,9,255}
  83255. };
  83256. static const code distfix[32] = {
  83257. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83258. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83259. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83260. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83261. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83262. {22,5,193},{64,5,0}
  83263. };
  83264. /*** End of inlined file: inffixed.h ***/
  83265. #endif /* BUILDFIXED */
  83266. state->lencode = lenfix;
  83267. state->lenbits = 9;
  83268. state->distcode = distfix;
  83269. state->distbits = 5;
  83270. }
  83271. #ifdef MAKEFIXED
  83272. #include <stdio.h>
  83273. /*
  83274. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83275. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83276. those tables to stdout, which would be piped to inffixed.h. A small program
  83277. can simply call makefixed to do this:
  83278. void makefixed(void);
  83279. int main(void)
  83280. {
  83281. makefixed();
  83282. return 0;
  83283. }
  83284. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83285. a.out > inffixed.h
  83286. */
  83287. void makefixed()
  83288. {
  83289. unsigned low, size;
  83290. struct inflate_state state;
  83291. fixedtables(&state);
  83292. puts(" /* inffixed.h -- table for decoding fixed codes");
  83293. puts(" * Generated automatically by makefixed().");
  83294. puts(" */");
  83295. puts("");
  83296. puts(" /* WARNING: this file should *not* be used by applications.");
  83297. puts(" It is part of the implementation of this library and is");
  83298. puts(" subject to change. Applications should only use zlib.h.");
  83299. puts(" */");
  83300. puts("");
  83301. size = 1U << 9;
  83302. printf(" static const code lenfix[%u] = {", size);
  83303. low = 0;
  83304. for (;;) {
  83305. if ((low % 7) == 0) printf("\n ");
  83306. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83307. state.lencode[low].val);
  83308. if (++low == size) break;
  83309. putchar(',');
  83310. }
  83311. puts("\n };");
  83312. size = 1U << 5;
  83313. printf("\n static const code distfix[%u] = {", size);
  83314. low = 0;
  83315. for (;;) {
  83316. if ((low % 6) == 0) printf("\n ");
  83317. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83318. state.distcode[low].val);
  83319. if (++low == size) break;
  83320. putchar(',');
  83321. }
  83322. puts("\n };");
  83323. }
  83324. #endif /* MAKEFIXED */
  83325. /*
  83326. Update the window with the last wsize (normally 32K) bytes written before
  83327. returning. If window does not exist yet, create it. This is only called
  83328. when a window is already in use, or when output has been written during this
  83329. inflate call, but the end of the deflate stream has not been reached yet.
  83330. It is also called to create a window for dictionary data when a dictionary
  83331. is loaded.
  83332. Providing output buffers larger than 32K to inflate() should provide a speed
  83333. advantage, since only the last 32K of output is copied to the sliding window
  83334. upon return from inflate(), and since all distances after the first 32K of
  83335. output will fall in the output data, making match copies simpler and faster.
  83336. The advantage may be dependent on the size of the processor's data caches.
  83337. */
  83338. local int updatewindow (z_streamp strm, unsigned out)
  83339. {
  83340. struct inflate_state FAR *state;
  83341. unsigned copy, dist;
  83342. state = (struct inflate_state FAR *)strm->state;
  83343. /* if it hasn't been done already, allocate space for the window */
  83344. if (state->window == Z_NULL) {
  83345. state->window = (unsigned char FAR *)
  83346. ZALLOC(strm, 1U << state->wbits,
  83347. sizeof(unsigned char));
  83348. if (state->window == Z_NULL) return 1;
  83349. }
  83350. /* if window not in use yet, initialize */
  83351. if (state->wsize == 0) {
  83352. state->wsize = 1U << state->wbits;
  83353. state->write = 0;
  83354. state->whave = 0;
  83355. }
  83356. /* copy state->wsize or less output bytes into the circular window */
  83357. copy = out - strm->avail_out;
  83358. if (copy >= state->wsize) {
  83359. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83360. state->write = 0;
  83361. state->whave = state->wsize;
  83362. }
  83363. else {
  83364. dist = state->wsize - state->write;
  83365. if (dist > copy) dist = copy;
  83366. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83367. copy -= dist;
  83368. if (copy) {
  83369. zmemcpy(state->window, strm->next_out - copy, copy);
  83370. state->write = copy;
  83371. state->whave = state->wsize;
  83372. }
  83373. else {
  83374. state->write += dist;
  83375. if (state->write == state->wsize) state->write = 0;
  83376. if (state->whave < state->wsize) state->whave += dist;
  83377. }
  83378. }
  83379. return 0;
  83380. }
  83381. /* Macros for inflate(): */
  83382. /* check function to use adler32() for zlib or crc32() for gzip */
  83383. #ifdef GUNZIP
  83384. # define UPDATE(check, buf, len) \
  83385. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83386. #else
  83387. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83388. #endif
  83389. /* check macros for header crc */
  83390. #ifdef GUNZIP
  83391. # define CRC2(check, word) \
  83392. do { \
  83393. hbuf[0] = (unsigned char)(word); \
  83394. hbuf[1] = (unsigned char)((word) >> 8); \
  83395. check = crc32(check, hbuf, 2); \
  83396. } while (0)
  83397. # define CRC4(check, word) \
  83398. do { \
  83399. hbuf[0] = (unsigned char)(word); \
  83400. hbuf[1] = (unsigned char)((word) >> 8); \
  83401. hbuf[2] = (unsigned char)((word) >> 16); \
  83402. hbuf[3] = (unsigned char)((word) >> 24); \
  83403. check = crc32(check, hbuf, 4); \
  83404. } while (0)
  83405. #endif
  83406. /* Load registers with state in inflate() for speed */
  83407. #define LOAD() \
  83408. do { \
  83409. put = strm->next_out; \
  83410. left = strm->avail_out; \
  83411. next = strm->next_in; \
  83412. have = strm->avail_in; \
  83413. hold = state->hold; \
  83414. bits = state->bits; \
  83415. } while (0)
  83416. /* Restore state from registers in inflate() */
  83417. #define RESTORE() \
  83418. do { \
  83419. strm->next_out = put; \
  83420. strm->avail_out = left; \
  83421. strm->next_in = next; \
  83422. strm->avail_in = have; \
  83423. state->hold = hold; \
  83424. state->bits = bits; \
  83425. } while (0)
  83426. /* Clear the input bit accumulator */
  83427. #define INITBITS() \
  83428. do { \
  83429. hold = 0; \
  83430. bits = 0; \
  83431. } while (0)
  83432. /* Get a byte of input into the bit accumulator, or return from inflate()
  83433. if there is no input available. */
  83434. #define PULLBYTE() \
  83435. do { \
  83436. if (have == 0) goto inf_leave; \
  83437. have--; \
  83438. hold += (unsigned long)(*next++) << bits; \
  83439. bits += 8; \
  83440. } while (0)
  83441. /* Assure that there are at least n bits in the bit accumulator. If there is
  83442. not enough available input to do that, then return from inflate(). */
  83443. #define NEEDBITS(n) \
  83444. do { \
  83445. while (bits < (unsigned)(n)) \
  83446. PULLBYTE(); \
  83447. } while (0)
  83448. /* Return the low n bits of the bit accumulator (n < 16) */
  83449. #define BITS(n) \
  83450. ((unsigned)hold & ((1U << (n)) - 1))
  83451. /* Remove n bits from the bit accumulator */
  83452. #define DROPBITS(n) \
  83453. do { \
  83454. hold >>= (n); \
  83455. bits -= (unsigned)(n); \
  83456. } while (0)
  83457. /* Remove zero to seven bits as needed to go to a byte boundary */
  83458. #define BYTEBITS() \
  83459. do { \
  83460. hold >>= bits & 7; \
  83461. bits -= bits & 7; \
  83462. } while (0)
  83463. /* Reverse the bytes in a 32-bit value */
  83464. #define REVERSE(q) \
  83465. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83466. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83467. /*
  83468. inflate() uses a state machine to process as much input data and generate as
  83469. much output data as possible before returning. The state machine is
  83470. structured roughly as follows:
  83471. for (;;) switch (state) {
  83472. ...
  83473. case STATEn:
  83474. if (not enough input data or output space to make progress)
  83475. return;
  83476. ... make progress ...
  83477. state = STATEm;
  83478. break;
  83479. ...
  83480. }
  83481. so when inflate() is called again, the same case is attempted again, and
  83482. if the appropriate resources are provided, the machine proceeds to the
  83483. next state. The NEEDBITS() macro is usually the way the state evaluates
  83484. whether it can proceed or should return. NEEDBITS() does the return if
  83485. the requested bits are not available. The typical use of the BITS macros
  83486. is:
  83487. NEEDBITS(n);
  83488. ... do something with BITS(n) ...
  83489. DROPBITS(n);
  83490. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83491. input left to load n bits into the accumulator, or it continues. BITS(n)
  83492. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83493. the low n bits off the accumulator. INITBITS() clears the accumulator
  83494. and sets the number of available bits to zero. BYTEBITS() discards just
  83495. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83496. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83497. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83498. if there is no input available. The decoding of variable length codes uses
  83499. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83500. code, and no more.
  83501. Some states loop until they get enough input, making sure that enough
  83502. state information is maintained to continue the loop where it left off
  83503. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83504. would all have to actually be part of the saved state in case NEEDBITS()
  83505. returns:
  83506. case STATEw:
  83507. while (want < need) {
  83508. NEEDBITS(n);
  83509. keep[want++] = BITS(n);
  83510. DROPBITS(n);
  83511. }
  83512. state = STATEx;
  83513. case STATEx:
  83514. As shown above, if the next state is also the next case, then the break
  83515. is omitted.
  83516. A state may also return if there is not enough output space available to
  83517. complete that state. Those states are copying stored data, writing a
  83518. literal byte, and copying a matching string.
  83519. When returning, a "goto inf_leave" is used to update the total counters,
  83520. update the check value, and determine whether any progress has been made
  83521. during that inflate() call in order to return the proper return code.
  83522. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83523. When there is a window, goto inf_leave will update the window with the last
  83524. output written. If a goto inf_leave occurs in the middle of decompression
  83525. and there is no window currently, goto inf_leave will create one and copy
  83526. output to the window for the next call of inflate().
  83527. In this implementation, the flush parameter of inflate() only affects the
  83528. return code (per zlib.h). inflate() always writes as much as possible to
  83529. strm->next_out, given the space available and the provided input--the effect
  83530. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83531. the allocation of and copying into a sliding window until necessary, which
  83532. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83533. stream available. So the only thing the flush parameter actually does is:
  83534. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83535. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83536. */
  83537. int ZEXPORT inflate (z_streamp strm, int flush)
  83538. {
  83539. struct inflate_state FAR *state;
  83540. unsigned char FAR *next; /* next input */
  83541. unsigned char FAR *put; /* next output */
  83542. unsigned have, left; /* available input and output */
  83543. unsigned long hold; /* bit buffer */
  83544. unsigned bits; /* bits in bit buffer */
  83545. unsigned in, out; /* save starting available input and output */
  83546. unsigned copy; /* number of stored or match bytes to copy */
  83547. unsigned char FAR *from; /* where to copy match bytes from */
  83548. code thisx; /* current decoding table entry */
  83549. code last; /* parent table entry */
  83550. unsigned len; /* length to copy for repeats, bits to drop */
  83551. int ret; /* return code */
  83552. #ifdef GUNZIP
  83553. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83554. #endif
  83555. static const unsigned short order[19] = /* permutation of code lengths */
  83556. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83557. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83558. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83559. return Z_STREAM_ERROR;
  83560. state = (struct inflate_state FAR *)strm->state;
  83561. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83562. LOAD();
  83563. in = have;
  83564. out = left;
  83565. ret = Z_OK;
  83566. for (;;)
  83567. switch (state->mode) {
  83568. case HEAD:
  83569. if (state->wrap == 0) {
  83570. state->mode = TYPEDO;
  83571. break;
  83572. }
  83573. NEEDBITS(16);
  83574. #ifdef GUNZIP
  83575. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83576. state->check = crc32(0L, Z_NULL, 0);
  83577. CRC2(state->check, hold);
  83578. INITBITS();
  83579. state->mode = FLAGS;
  83580. break;
  83581. }
  83582. state->flags = 0; /* expect zlib header */
  83583. if (state->head != Z_NULL)
  83584. state->head->done = -1;
  83585. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83586. #else
  83587. if (
  83588. #endif
  83589. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83590. strm->msg = (char *)"incorrect header check";
  83591. state->mode = BAD;
  83592. break;
  83593. }
  83594. if (BITS(4) != Z_DEFLATED) {
  83595. strm->msg = (char *)"unknown compression method";
  83596. state->mode = BAD;
  83597. break;
  83598. }
  83599. DROPBITS(4);
  83600. len = BITS(4) + 8;
  83601. if (len > state->wbits) {
  83602. strm->msg = (char *)"invalid window size";
  83603. state->mode = BAD;
  83604. break;
  83605. }
  83606. state->dmax = 1U << len;
  83607. Tracev((stderr, "inflate: zlib header ok\n"));
  83608. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83609. state->mode = hold & 0x200 ? DICTID : TYPE;
  83610. INITBITS();
  83611. break;
  83612. #ifdef GUNZIP
  83613. case FLAGS:
  83614. NEEDBITS(16);
  83615. state->flags = (int)(hold);
  83616. if ((state->flags & 0xff) != Z_DEFLATED) {
  83617. strm->msg = (char *)"unknown compression method";
  83618. state->mode = BAD;
  83619. break;
  83620. }
  83621. if (state->flags & 0xe000) {
  83622. strm->msg = (char *)"unknown header flags set";
  83623. state->mode = BAD;
  83624. break;
  83625. }
  83626. if (state->head != Z_NULL)
  83627. state->head->text = (int)((hold >> 8) & 1);
  83628. if (state->flags & 0x0200) CRC2(state->check, hold);
  83629. INITBITS();
  83630. state->mode = TIME;
  83631. case TIME:
  83632. NEEDBITS(32);
  83633. if (state->head != Z_NULL)
  83634. state->head->time = hold;
  83635. if (state->flags & 0x0200) CRC4(state->check, hold);
  83636. INITBITS();
  83637. state->mode = OS;
  83638. case OS:
  83639. NEEDBITS(16);
  83640. if (state->head != Z_NULL) {
  83641. state->head->xflags = (int)(hold & 0xff);
  83642. state->head->os = (int)(hold >> 8);
  83643. }
  83644. if (state->flags & 0x0200) CRC2(state->check, hold);
  83645. INITBITS();
  83646. state->mode = EXLEN;
  83647. case EXLEN:
  83648. if (state->flags & 0x0400) {
  83649. NEEDBITS(16);
  83650. state->length = (unsigned)(hold);
  83651. if (state->head != Z_NULL)
  83652. state->head->extra_len = (unsigned)hold;
  83653. if (state->flags & 0x0200) CRC2(state->check, hold);
  83654. INITBITS();
  83655. }
  83656. else if (state->head != Z_NULL)
  83657. state->head->extra = Z_NULL;
  83658. state->mode = EXTRA;
  83659. case EXTRA:
  83660. if (state->flags & 0x0400) {
  83661. copy = state->length;
  83662. if (copy > have) copy = have;
  83663. if (copy) {
  83664. if (state->head != Z_NULL &&
  83665. state->head->extra != Z_NULL) {
  83666. len = state->head->extra_len - state->length;
  83667. zmemcpy(state->head->extra + len, next,
  83668. len + copy > state->head->extra_max ?
  83669. state->head->extra_max - len : copy);
  83670. }
  83671. if (state->flags & 0x0200)
  83672. state->check = crc32(state->check, next, copy);
  83673. have -= copy;
  83674. next += copy;
  83675. state->length -= copy;
  83676. }
  83677. if (state->length) goto inf_leave;
  83678. }
  83679. state->length = 0;
  83680. state->mode = NAME;
  83681. case NAME:
  83682. if (state->flags & 0x0800) {
  83683. if (have == 0) goto inf_leave;
  83684. copy = 0;
  83685. do {
  83686. len = (unsigned)(next[copy++]);
  83687. if (state->head != Z_NULL &&
  83688. state->head->name != Z_NULL &&
  83689. state->length < state->head->name_max)
  83690. state->head->name[state->length++] = len;
  83691. } while (len && copy < have);
  83692. if (state->flags & 0x0200)
  83693. state->check = crc32(state->check, next, copy);
  83694. have -= copy;
  83695. next += copy;
  83696. if (len) goto inf_leave;
  83697. }
  83698. else if (state->head != Z_NULL)
  83699. state->head->name = Z_NULL;
  83700. state->length = 0;
  83701. state->mode = COMMENT;
  83702. case COMMENT:
  83703. if (state->flags & 0x1000) {
  83704. if (have == 0) goto inf_leave;
  83705. copy = 0;
  83706. do {
  83707. len = (unsigned)(next[copy++]);
  83708. if (state->head != Z_NULL &&
  83709. state->head->comment != Z_NULL &&
  83710. state->length < state->head->comm_max)
  83711. state->head->comment[state->length++] = len;
  83712. } while (len && copy < have);
  83713. if (state->flags & 0x0200)
  83714. state->check = crc32(state->check, next, copy);
  83715. have -= copy;
  83716. next += copy;
  83717. if (len) goto inf_leave;
  83718. }
  83719. else if (state->head != Z_NULL)
  83720. state->head->comment = Z_NULL;
  83721. state->mode = HCRC;
  83722. case HCRC:
  83723. if (state->flags & 0x0200) {
  83724. NEEDBITS(16);
  83725. if (hold != (state->check & 0xffff)) {
  83726. strm->msg = (char *)"header crc mismatch";
  83727. state->mode = BAD;
  83728. break;
  83729. }
  83730. INITBITS();
  83731. }
  83732. if (state->head != Z_NULL) {
  83733. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83734. state->head->done = 1;
  83735. }
  83736. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83737. state->mode = TYPE;
  83738. break;
  83739. #endif
  83740. case DICTID:
  83741. NEEDBITS(32);
  83742. strm->adler = state->check = REVERSE(hold);
  83743. INITBITS();
  83744. state->mode = DICT;
  83745. case DICT:
  83746. if (state->havedict == 0) {
  83747. RESTORE();
  83748. return Z_NEED_DICT;
  83749. }
  83750. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83751. state->mode = TYPE;
  83752. case TYPE:
  83753. if (flush == Z_BLOCK) goto inf_leave;
  83754. case TYPEDO:
  83755. if (state->last) {
  83756. BYTEBITS();
  83757. state->mode = CHECK;
  83758. break;
  83759. }
  83760. NEEDBITS(3);
  83761. state->last = BITS(1);
  83762. DROPBITS(1);
  83763. switch (BITS(2)) {
  83764. case 0: /* stored block */
  83765. Tracev((stderr, "inflate: stored block%s\n",
  83766. state->last ? " (last)" : ""));
  83767. state->mode = STORED;
  83768. break;
  83769. case 1: /* fixed block */
  83770. fixedtables(state);
  83771. Tracev((stderr, "inflate: fixed codes block%s\n",
  83772. state->last ? " (last)" : ""));
  83773. state->mode = LEN; /* decode codes */
  83774. break;
  83775. case 2: /* dynamic block */
  83776. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83777. state->last ? " (last)" : ""));
  83778. state->mode = TABLE;
  83779. break;
  83780. case 3:
  83781. strm->msg = (char *)"invalid block type";
  83782. state->mode = BAD;
  83783. }
  83784. DROPBITS(2);
  83785. break;
  83786. case STORED:
  83787. BYTEBITS(); /* go to byte boundary */
  83788. NEEDBITS(32);
  83789. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83790. strm->msg = (char *)"invalid stored block lengths";
  83791. state->mode = BAD;
  83792. break;
  83793. }
  83794. state->length = (unsigned)hold & 0xffff;
  83795. Tracev((stderr, "inflate: stored length %u\n",
  83796. state->length));
  83797. INITBITS();
  83798. state->mode = COPY;
  83799. case COPY:
  83800. copy = state->length;
  83801. if (copy) {
  83802. if (copy > have) copy = have;
  83803. if (copy > left) copy = left;
  83804. if (copy == 0) goto inf_leave;
  83805. zmemcpy(put, next, copy);
  83806. have -= copy;
  83807. next += copy;
  83808. left -= copy;
  83809. put += copy;
  83810. state->length -= copy;
  83811. break;
  83812. }
  83813. Tracev((stderr, "inflate: stored end\n"));
  83814. state->mode = TYPE;
  83815. break;
  83816. case TABLE:
  83817. NEEDBITS(14);
  83818. state->nlen = BITS(5) + 257;
  83819. DROPBITS(5);
  83820. state->ndist = BITS(5) + 1;
  83821. DROPBITS(5);
  83822. state->ncode = BITS(4) + 4;
  83823. DROPBITS(4);
  83824. #ifndef PKZIP_BUG_WORKAROUND
  83825. if (state->nlen > 286 || state->ndist > 30) {
  83826. strm->msg = (char *)"too many length or distance symbols";
  83827. state->mode = BAD;
  83828. break;
  83829. }
  83830. #endif
  83831. Tracev((stderr, "inflate: table sizes ok\n"));
  83832. state->have = 0;
  83833. state->mode = LENLENS;
  83834. case LENLENS:
  83835. while (state->have < state->ncode) {
  83836. NEEDBITS(3);
  83837. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83838. DROPBITS(3);
  83839. }
  83840. while (state->have < 19)
  83841. state->lens[order[state->have++]] = 0;
  83842. state->next = state->codes;
  83843. state->lencode = (code const FAR *)(state->next);
  83844. state->lenbits = 7;
  83845. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83846. &(state->lenbits), state->work);
  83847. if (ret) {
  83848. strm->msg = (char *)"invalid code lengths set";
  83849. state->mode = BAD;
  83850. break;
  83851. }
  83852. Tracev((stderr, "inflate: code lengths ok\n"));
  83853. state->have = 0;
  83854. state->mode = CODELENS;
  83855. case CODELENS:
  83856. while (state->have < state->nlen + state->ndist) {
  83857. for (;;) {
  83858. thisx = state->lencode[BITS(state->lenbits)];
  83859. if ((unsigned)(thisx.bits) <= bits) break;
  83860. PULLBYTE();
  83861. }
  83862. if (thisx.val < 16) {
  83863. NEEDBITS(thisx.bits);
  83864. DROPBITS(thisx.bits);
  83865. state->lens[state->have++] = thisx.val;
  83866. }
  83867. else {
  83868. if (thisx.val == 16) {
  83869. NEEDBITS(thisx.bits + 2);
  83870. DROPBITS(thisx.bits);
  83871. if (state->have == 0) {
  83872. strm->msg = (char *)"invalid bit length repeat";
  83873. state->mode = BAD;
  83874. break;
  83875. }
  83876. len = state->lens[state->have - 1];
  83877. copy = 3 + BITS(2);
  83878. DROPBITS(2);
  83879. }
  83880. else if (thisx.val == 17) {
  83881. NEEDBITS(thisx.bits + 3);
  83882. DROPBITS(thisx.bits);
  83883. len = 0;
  83884. copy = 3 + BITS(3);
  83885. DROPBITS(3);
  83886. }
  83887. else {
  83888. NEEDBITS(thisx.bits + 7);
  83889. DROPBITS(thisx.bits);
  83890. len = 0;
  83891. copy = 11 + BITS(7);
  83892. DROPBITS(7);
  83893. }
  83894. if (state->have + copy > state->nlen + state->ndist) {
  83895. strm->msg = (char *)"invalid bit length repeat";
  83896. state->mode = BAD;
  83897. break;
  83898. }
  83899. while (copy--)
  83900. state->lens[state->have++] = (unsigned short)len;
  83901. }
  83902. }
  83903. /* handle error breaks in while */
  83904. if (state->mode == BAD) break;
  83905. /* build code tables */
  83906. state->next = state->codes;
  83907. state->lencode = (code const FAR *)(state->next);
  83908. state->lenbits = 9;
  83909. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83910. &(state->lenbits), state->work);
  83911. if (ret) {
  83912. strm->msg = (char *)"invalid literal/lengths set";
  83913. state->mode = BAD;
  83914. break;
  83915. }
  83916. state->distcode = (code const FAR *)(state->next);
  83917. state->distbits = 6;
  83918. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83919. &(state->next), &(state->distbits), state->work);
  83920. if (ret) {
  83921. strm->msg = (char *)"invalid distances set";
  83922. state->mode = BAD;
  83923. break;
  83924. }
  83925. Tracev((stderr, "inflate: codes ok\n"));
  83926. state->mode = LEN;
  83927. case LEN:
  83928. if (have >= 6 && left >= 258) {
  83929. RESTORE();
  83930. inflate_fast(strm, out);
  83931. LOAD();
  83932. break;
  83933. }
  83934. for (;;) {
  83935. thisx = state->lencode[BITS(state->lenbits)];
  83936. if ((unsigned)(thisx.bits) <= bits) break;
  83937. PULLBYTE();
  83938. }
  83939. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83940. last = thisx;
  83941. for (;;) {
  83942. thisx = state->lencode[last.val +
  83943. (BITS(last.bits + last.op) >> last.bits)];
  83944. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83945. PULLBYTE();
  83946. }
  83947. DROPBITS(last.bits);
  83948. }
  83949. DROPBITS(thisx.bits);
  83950. state->length = (unsigned)thisx.val;
  83951. if ((int)(thisx.op) == 0) {
  83952. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83953. "inflate: literal '%c'\n" :
  83954. "inflate: literal 0x%02x\n", thisx.val));
  83955. state->mode = LIT;
  83956. break;
  83957. }
  83958. if (thisx.op & 32) {
  83959. Tracevv((stderr, "inflate: end of block\n"));
  83960. state->mode = TYPE;
  83961. break;
  83962. }
  83963. if (thisx.op & 64) {
  83964. strm->msg = (char *)"invalid literal/length code";
  83965. state->mode = BAD;
  83966. break;
  83967. }
  83968. state->extra = (unsigned)(thisx.op) & 15;
  83969. state->mode = LENEXT;
  83970. case LENEXT:
  83971. if (state->extra) {
  83972. NEEDBITS(state->extra);
  83973. state->length += BITS(state->extra);
  83974. DROPBITS(state->extra);
  83975. }
  83976. Tracevv((stderr, "inflate: length %u\n", state->length));
  83977. state->mode = DIST;
  83978. case DIST:
  83979. for (;;) {
  83980. thisx = state->distcode[BITS(state->distbits)];
  83981. if ((unsigned)(thisx.bits) <= bits) break;
  83982. PULLBYTE();
  83983. }
  83984. if ((thisx.op & 0xf0) == 0) {
  83985. last = thisx;
  83986. for (;;) {
  83987. thisx = state->distcode[last.val +
  83988. (BITS(last.bits + last.op) >> last.bits)];
  83989. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83990. PULLBYTE();
  83991. }
  83992. DROPBITS(last.bits);
  83993. }
  83994. DROPBITS(thisx.bits);
  83995. if (thisx.op & 64) {
  83996. strm->msg = (char *)"invalid distance code";
  83997. state->mode = BAD;
  83998. break;
  83999. }
  84000. state->offset = (unsigned)thisx.val;
  84001. state->extra = (unsigned)(thisx.op) & 15;
  84002. state->mode = DISTEXT;
  84003. case DISTEXT:
  84004. if (state->extra) {
  84005. NEEDBITS(state->extra);
  84006. state->offset += BITS(state->extra);
  84007. DROPBITS(state->extra);
  84008. }
  84009. #ifdef INFLATE_STRICT
  84010. if (state->offset > state->dmax) {
  84011. strm->msg = (char *)"invalid distance too far back";
  84012. state->mode = BAD;
  84013. break;
  84014. }
  84015. #endif
  84016. if (state->offset > state->whave + out - left) {
  84017. strm->msg = (char *)"invalid distance too far back";
  84018. state->mode = BAD;
  84019. break;
  84020. }
  84021. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84022. state->mode = MATCH;
  84023. case MATCH:
  84024. if (left == 0) goto inf_leave;
  84025. copy = out - left;
  84026. if (state->offset > copy) { /* copy from window */
  84027. copy = state->offset - copy;
  84028. if (copy > state->write) {
  84029. copy -= state->write;
  84030. from = state->window + (state->wsize - copy);
  84031. }
  84032. else
  84033. from = state->window + (state->write - copy);
  84034. if (copy > state->length) copy = state->length;
  84035. }
  84036. else { /* copy from output */
  84037. from = put - state->offset;
  84038. copy = state->length;
  84039. }
  84040. if (copy > left) copy = left;
  84041. left -= copy;
  84042. state->length -= copy;
  84043. do {
  84044. *put++ = *from++;
  84045. } while (--copy);
  84046. if (state->length == 0) state->mode = LEN;
  84047. break;
  84048. case LIT:
  84049. if (left == 0) goto inf_leave;
  84050. *put++ = (unsigned char)(state->length);
  84051. left--;
  84052. state->mode = LEN;
  84053. break;
  84054. case CHECK:
  84055. if (state->wrap) {
  84056. NEEDBITS(32);
  84057. out -= left;
  84058. strm->total_out += out;
  84059. state->total += out;
  84060. if (out)
  84061. strm->adler = state->check =
  84062. UPDATE(state->check, put - out, out);
  84063. out = left;
  84064. if ((
  84065. #ifdef GUNZIP
  84066. state->flags ? hold :
  84067. #endif
  84068. REVERSE(hold)) != state->check) {
  84069. strm->msg = (char *)"incorrect data check";
  84070. state->mode = BAD;
  84071. break;
  84072. }
  84073. INITBITS();
  84074. Tracev((stderr, "inflate: check matches trailer\n"));
  84075. }
  84076. #ifdef GUNZIP
  84077. state->mode = LENGTH;
  84078. case LENGTH:
  84079. if (state->wrap && state->flags) {
  84080. NEEDBITS(32);
  84081. if (hold != (state->total & 0xffffffffUL)) {
  84082. strm->msg = (char *)"incorrect length check";
  84083. state->mode = BAD;
  84084. break;
  84085. }
  84086. INITBITS();
  84087. Tracev((stderr, "inflate: length matches trailer\n"));
  84088. }
  84089. #endif
  84090. state->mode = DONE;
  84091. case DONE:
  84092. ret = Z_STREAM_END;
  84093. goto inf_leave;
  84094. case BAD:
  84095. ret = Z_DATA_ERROR;
  84096. goto inf_leave;
  84097. case MEM:
  84098. return Z_MEM_ERROR;
  84099. case SYNC:
  84100. default:
  84101. return Z_STREAM_ERROR;
  84102. }
  84103. /*
  84104. Return from inflate(), updating the total counts and the check value.
  84105. If there was no progress during the inflate() call, return a buffer
  84106. error. Call updatewindow() to create and/or update the window state.
  84107. Note: a memory error from inflate() is non-recoverable.
  84108. */
  84109. inf_leave:
  84110. RESTORE();
  84111. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84112. if (updatewindow(strm, out)) {
  84113. state->mode = MEM;
  84114. return Z_MEM_ERROR;
  84115. }
  84116. in -= strm->avail_in;
  84117. out -= strm->avail_out;
  84118. strm->total_in += in;
  84119. strm->total_out += out;
  84120. state->total += out;
  84121. if (state->wrap && out)
  84122. strm->adler = state->check =
  84123. UPDATE(state->check, strm->next_out - out, out);
  84124. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84125. (state->mode == TYPE ? 128 : 0);
  84126. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84127. ret = Z_BUF_ERROR;
  84128. return ret;
  84129. }
  84130. int ZEXPORT inflateEnd (z_streamp strm)
  84131. {
  84132. struct inflate_state FAR *state;
  84133. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84134. return Z_STREAM_ERROR;
  84135. state = (struct inflate_state FAR *)strm->state;
  84136. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84137. ZFREE(strm, strm->state);
  84138. strm->state = Z_NULL;
  84139. Tracev((stderr, "inflate: end\n"));
  84140. return Z_OK;
  84141. }
  84142. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84143. {
  84144. struct inflate_state FAR *state;
  84145. unsigned long id_;
  84146. /* check state */
  84147. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84148. state = (struct inflate_state FAR *)strm->state;
  84149. if (state->wrap != 0 && state->mode != DICT)
  84150. return Z_STREAM_ERROR;
  84151. /* check for correct dictionary id */
  84152. if (state->mode == DICT) {
  84153. id_ = adler32(0L, Z_NULL, 0);
  84154. id_ = adler32(id_, dictionary, dictLength);
  84155. if (id_ != state->check)
  84156. return Z_DATA_ERROR;
  84157. }
  84158. /* copy dictionary to window */
  84159. if (updatewindow(strm, strm->avail_out)) {
  84160. state->mode = MEM;
  84161. return Z_MEM_ERROR;
  84162. }
  84163. if (dictLength > state->wsize) {
  84164. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84165. state->wsize);
  84166. state->whave = state->wsize;
  84167. }
  84168. else {
  84169. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84170. dictLength);
  84171. state->whave = dictLength;
  84172. }
  84173. state->havedict = 1;
  84174. Tracev((stderr, "inflate: dictionary set\n"));
  84175. return Z_OK;
  84176. }
  84177. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84178. {
  84179. struct inflate_state FAR *state;
  84180. /* check state */
  84181. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84182. state = (struct inflate_state FAR *)strm->state;
  84183. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84184. /* save header structure */
  84185. state->head = head;
  84186. head->done = 0;
  84187. return Z_OK;
  84188. }
  84189. /*
  84190. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84191. or when out of input. When called, *have is the number of pattern bytes
  84192. found in order so far, in 0..3. On return *have is updated to the new
  84193. state. If on return *have equals four, then the pattern was found and the
  84194. return value is how many bytes were read including the last byte of the
  84195. pattern. If *have is less than four, then the pattern has not been found
  84196. yet and the return value is len. In the latter case, syncsearch() can be
  84197. called again with more data and the *have state. *have is initialized to
  84198. zero for the first call.
  84199. */
  84200. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84201. {
  84202. unsigned got;
  84203. unsigned next;
  84204. got = *have;
  84205. next = 0;
  84206. while (next < len && got < 4) {
  84207. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84208. got++;
  84209. else if (buf[next])
  84210. got = 0;
  84211. else
  84212. got = 4 - got;
  84213. next++;
  84214. }
  84215. *have = got;
  84216. return next;
  84217. }
  84218. int ZEXPORT inflateSync (z_streamp strm)
  84219. {
  84220. unsigned len; /* number of bytes to look at or looked at */
  84221. unsigned long in, out; /* temporary to save total_in and total_out */
  84222. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84223. struct inflate_state FAR *state;
  84224. /* check parameters */
  84225. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84226. state = (struct inflate_state FAR *)strm->state;
  84227. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84228. /* if first time, start search in bit buffer */
  84229. if (state->mode != SYNC) {
  84230. state->mode = SYNC;
  84231. state->hold <<= state->bits & 7;
  84232. state->bits -= state->bits & 7;
  84233. len = 0;
  84234. while (state->bits >= 8) {
  84235. buf[len++] = (unsigned char)(state->hold);
  84236. state->hold >>= 8;
  84237. state->bits -= 8;
  84238. }
  84239. state->have = 0;
  84240. syncsearch(&(state->have), buf, len);
  84241. }
  84242. /* search available input */
  84243. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84244. strm->avail_in -= len;
  84245. strm->next_in += len;
  84246. strm->total_in += len;
  84247. /* return no joy or set up to restart inflate() on a new block */
  84248. if (state->have != 4) return Z_DATA_ERROR;
  84249. in = strm->total_in; out = strm->total_out;
  84250. inflateReset(strm);
  84251. strm->total_in = in; strm->total_out = out;
  84252. state->mode = TYPE;
  84253. return Z_OK;
  84254. }
  84255. /*
  84256. Returns true if inflate is currently at the end of a block generated by
  84257. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84258. implementation to provide an additional safety check. PPP uses
  84259. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84260. block. When decompressing, PPP checks that at the end of input packet,
  84261. inflate is waiting for these length bytes.
  84262. */
  84263. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84264. {
  84265. struct inflate_state FAR *state;
  84266. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84267. state = (struct inflate_state FAR *)strm->state;
  84268. return state->mode == STORED && state->bits == 0;
  84269. }
  84270. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84271. {
  84272. struct inflate_state FAR *state;
  84273. struct inflate_state FAR *copy;
  84274. unsigned char FAR *window;
  84275. unsigned wsize;
  84276. /* check input */
  84277. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84278. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84279. return Z_STREAM_ERROR;
  84280. state = (struct inflate_state FAR *)source->state;
  84281. /* allocate space */
  84282. copy = (struct inflate_state FAR *)
  84283. ZALLOC(source, 1, sizeof(struct inflate_state));
  84284. if (copy == Z_NULL) return Z_MEM_ERROR;
  84285. window = Z_NULL;
  84286. if (state->window != Z_NULL) {
  84287. window = (unsigned char FAR *)
  84288. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84289. if (window == Z_NULL) {
  84290. ZFREE(source, copy);
  84291. return Z_MEM_ERROR;
  84292. }
  84293. }
  84294. /* copy state */
  84295. zmemcpy(dest, source, sizeof(z_stream));
  84296. zmemcpy(copy, state, sizeof(struct inflate_state));
  84297. if (state->lencode >= state->codes &&
  84298. state->lencode <= state->codes + ENOUGH - 1) {
  84299. copy->lencode = copy->codes + (state->lencode - state->codes);
  84300. copy->distcode = copy->codes + (state->distcode - state->codes);
  84301. }
  84302. copy->next = copy->codes + (state->next - state->codes);
  84303. if (window != Z_NULL) {
  84304. wsize = 1U << state->wbits;
  84305. zmemcpy(window, state->window, wsize);
  84306. }
  84307. copy->window = window;
  84308. dest->state = (struct internal_state FAR *)copy;
  84309. return Z_OK;
  84310. }
  84311. /*** End of inlined file: inflate.c ***/
  84312. /*** Start of inlined file: inftrees.c ***/
  84313. #define MAXBITS 15
  84314. const char inflate_copyright[] =
  84315. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84316. /*
  84317. If you use the zlib library in a product, an acknowledgment is welcome
  84318. in the documentation of your product. If for some reason you cannot
  84319. include such an acknowledgment, I would appreciate that you keep this
  84320. copyright string in the executable of your product.
  84321. */
  84322. /*
  84323. Build a set of tables to decode the provided canonical Huffman code.
  84324. The code lengths are lens[0..codes-1]. The result starts at *table,
  84325. whose indices are 0..2^bits-1. work is a writable array of at least
  84326. lens shorts, which is used as a work area. type is the type of code
  84327. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84328. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84329. on return points to the next available entry's address. bits is the
  84330. requested root table index bits, and on return it is the actual root
  84331. table index bits. It will differ if the request is greater than the
  84332. longest code or if it is less than the shortest code.
  84333. */
  84334. int inflate_table (codetype type,
  84335. unsigned short FAR *lens,
  84336. unsigned codes,
  84337. code FAR * FAR *table,
  84338. unsigned FAR *bits,
  84339. unsigned short FAR *work)
  84340. {
  84341. unsigned len; /* a code's length in bits */
  84342. unsigned sym; /* index of code symbols */
  84343. unsigned min, max; /* minimum and maximum code lengths */
  84344. unsigned root; /* number of index bits for root table */
  84345. unsigned curr; /* number of index bits for current table */
  84346. unsigned drop; /* code bits to drop for sub-table */
  84347. int left; /* number of prefix codes available */
  84348. unsigned used; /* code entries in table used */
  84349. unsigned huff; /* Huffman code */
  84350. unsigned incr; /* for incrementing code, index */
  84351. unsigned fill; /* index for replicating entries */
  84352. unsigned low; /* low bits for current root entry */
  84353. unsigned mask; /* mask for low root bits */
  84354. code thisx; /* table entry for duplication */
  84355. code FAR *next; /* next available space in table */
  84356. const unsigned short FAR *base; /* base value table to use */
  84357. const unsigned short FAR *extra; /* extra bits table to use */
  84358. int end; /* use base and extra for symbol > end */
  84359. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84360. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84361. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84362. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84363. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84364. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84365. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84366. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84367. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84368. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84369. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84370. 8193, 12289, 16385, 24577, 0, 0};
  84371. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84372. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84373. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84374. 28, 28, 29, 29, 64, 64};
  84375. /*
  84376. Process a set of code lengths to create a canonical Huffman code. The
  84377. code lengths are lens[0..codes-1]. Each length corresponds to the
  84378. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84379. symbols by length from short to long, and retaining the symbol order
  84380. for codes with equal lengths. Then the code starts with all zero bits
  84381. for the first code of the shortest length, and the codes are integer
  84382. increments for the same length, and zeros are appended as the length
  84383. increases. For the deflate format, these bits are stored backwards
  84384. from their more natural integer increment ordering, and so when the
  84385. decoding tables are built in the large loop below, the integer codes
  84386. are incremented backwards.
  84387. This routine assumes, but does not check, that all of the entries in
  84388. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84389. 1..MAXBITS is interpreted as that code length. zero means that that
  84390. symbol does not occur in this code.
  84391. The codes are sorted by computing a count of codes for each length,
  84392. creating from that a table of starting indices for each length in the
  84393. sorted table, and then entering the symbols in order in the sorted
  84394. table. The sorted table is work[], with that space being provided by
  84395. the caller.
  84396. The length counts are used for other purposes as well, i.e. finding
  84397. the minimum and maximum length codes, determining if there are any
  84398. codes at all, checking for a valid set of lengths, and looking ahead
  84399. at length counts to determine sub-table sizes when building the
  84400. decoding tables.
  84401. */
  84402. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84403. for (len = 0; len <= MAXBITS; len++)
  84404. count[len] = 0;
  84405. for (sym = 0; sym < codes; sym++)
  84406. count[lens[sym]]++;
  84407. /* bound code lengths, force root to be within code lengths */
  84408. root = *bits;
  84409. for (max = MAXBITS; max >= 1; max--)
  84410. if (count[max] != 0) break;
  84411. if (root > max) root = max;
  84412. if (max == 0) { /* no symbols to code at all */
  84413. thisx.op = (unsigned char)64; /* invalid code marker */
  84414. thisx.bits = (unsigned char)1;
  84415. thisx.val = (unsigned short)0;
  84416. *(*table)++ = thisx; /* make a table to force an error */
  84417. *(*table)++ = thisx;
  84418. *bits = 1;
  84419. return 0; /* no symbols, but wait for decoding to report error */
  84420. }
  84421. for (min = 1; min <= MAXBITS; min++)
  84422. if (count[min] != 0) break;
  84423. if (root < min) root = min;
  84424. /* check for an over-subscribed or incomplete set of lengths */
  84425. left = 1;
  84426. for (len = 1; len <= MAXBITS; len++) {
  84427. left <<= 1;
  84428. left -= count[len];
  84429. if (left < 0) return -1; /* over-subscribed */
  84430. }
  84431. if (left > 0 && (type == CODES || max != 1))
  84432. return -1; /* incomplete set */
  84433. /* generate offsets into symbol table for each length for sorting */
  84434. offs[1] = 0;
  84435. for (len = 1; len < MAXBITS; len++)
  84436. offs[len + 1] = offs[len] + count[len];
  84437. /* sort symbols by length, by symbol order within each length */
  84438. for (sym = 0; sym < codes; sym++)
  84439. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84440. /*
  84441. Create and fill in decoding tables. In this loop, the table being
  84442. filled is at next and has curr index bits. The code being used is huff
  84443. with length len. That code is converted to an index by dropping drop
  84444. bits off of the bottom. For codes where len is less than drop + curr,
  84445. those top drop + curr - len bits are incremented through all values to
  84446. fill the table with replicated entries.
  84447. root is the number of index bits for the root table. When len exceeds
  84448. root, sub-tables are created pointed to by the root entry with an index
  84449. of the low root bits of huff. This is saved in low to check for when a
  84450. new sub-table should be started. drop is zero when the root table is
  84451. being filled, and drop is root when sub-tables are being filled.
  84452. When a new sub-table is needed, it is necessary to look ahead in the
  84453. code lengths to determine what size sub-table is needed. The length
  84454. counts are used for this, and so count[] is decremented as codes are
  84455. entered in the tables.
  84456. used keeps track of how many table entries have been allocated from the
  84457. provided *table space. It is checked when a LENS table is being made
  84458. against the space in *table, ENOUGH, minus the maximum space needed by
  84459. the worst case distance code, MAXD. This should never happen, but the
  84460. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84461. This assumes that when type == LENS, bits == 9.
  84462. sym increments through all symbols, and the loop terminates when
  84463. all codes of length max, i.e. all codes, have been processed. This
  84464. routine permits incomplete codes, so another loop after this one fills
  84465. in the rest of the decoding tables with invalid code markers.
  84466. */
  84467. /* set up for code type */
  84468. switch (type) {
  84469. case CODES:
  84470. base = extra = work; /* dummy value--not used */
  84471. end = 19;
  84472. break;
  84473. case LENS:
  84474. base = lbase;
  84475. base -= 257;
  84476. extra = lext;
  84477. extra -= 257;
  84478. end = 256;
  84479. break;
  84480. default: /* DISTS */
  84481. base = dbase;
  84482. extra = dext;
  84483. end = -1;
  84484. }
  84485. /* initialize state for loop */
  84486. huff = 0; /* starting code */
  84487. sym = 0; /* starting code symbol */
  84488. len = min; /* starting code length */
  84489. next = *table; /* current table to fill in */
  84490. curr = root; /* current table index bits */
  84491. drop = 0; /* current bits to drop from code for index */
  84492. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84493. used = 1U << root; /* use root table entries */
  84494. mask = used - 1; /* mask for comparing low */
  84495. /* check available table space */
  84496. if (type == LENS && used >= ENOUGH - MAXD)
  84497. return 1;
  84498. /* process all codes and make table entries */
  84499. for (;;) {
  84500. /* create table entry */
  84501. thisx.bits = (unsigned char)(len - drop);
  84502. if ((int)(work[sym]) < end) {
  84503. thisx.op = (unsigned char)0;
  84504. thisx.val = work[sym];
  84505. }
  84506. else if ((int)(work[sym]) > end) {
  84507. thisx.op = (unsigned char)(extra[work[sym]]);
  84508. thisx.val = base[work[sym]];
  84509. }
  84510. else {
  84511. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84512. thisx.val = 0;
  84513. }
  84514. /* replicate for those indices with low len bits equal to huff */
  84515. incr = 1U << (len - drop);
  84516. fill = 1U << curr;
  84517. min = fill; /* save offset to next table */
  84518. do {
  84519. fill -= incr;
  84520. next[(huff >> drop) + fill] = thisx;
  84521. } while (fill != 0);
  84522. /* backwards increment the len-bit code huff */
  84523. incr = 1U << (len - 1);
  84524. while (huff & incr)
  84525. incr >>= 1;
  84526. if (incr != 0) {
  84527. huff &= incr - 1;
  84528. huff += incr;
  84529. }
  84530. else
  84531. huff = 0;
  84532. /* go to next symbol, update count, len */
  84533. sym++;
  84534. if (--(count[len]) == 0) {
  84535. if (len == max) break;
  84536. len = lens[work[sym]];
  84537. }
  84538. /* create new sub-table if needed */
  84539. if (len > root && (huff & mask) != low) {
  84540. /* if first time, transition to sub-tables */
  84541. if (drop == 0)
  84542. drop = root;
  84543. /* increment past last table */
  84544. next += min; /* here min is 1 << curr */
  84545. /* determine length of next table */
  84546. curr = len - drop;
  84547. left = (int)(1 << curr);
  84548. while (curr + drop < max) {
  84549. left -= count[curr + drop];
  84550. if (left <= 0) break;
  84551. curr++;
  84552. left <<= 1;
  84553. }
  84554. /* check for enough space */
  84555. used += 1U << curr;
  84556. if (type == LENS && used >= ENOUGH - MAXD)
  84557. return 1;
  84558. /* point entry in root table to sub-table */
  84559. low = huff & mask;
  84560. (*table)[low].op = (unsigned char)curr;
  84561. (*table)[low].bits = (unsigned char)root;
  84562. (*table)[low].val = (unsigned short)(next - *table);
  84563. }
  84564. }
  84565. /*
  84566. Fill in rest of table for incomplete codes. This loop is similar to the
  84567. loop above in incrementing huff for table indices. It is assumed that
  84568. len is equal to curr + drop, so there is no loop needed to increment
  84569. through high index bits. When the current sub-table is filled, the loop
  84570. drops back to the root table to fill in any remaining entries there.
  84571. */
  84572. thisx.op = (unsigned char)64; /* invalid code marker */
  84573. thisx.bits = (unsigned char)(len - drop);
  84574. thisx.val = (unsigned short)0;
  84575. while (huff != 0) {
  84576. /* when done with sub-table, drop back to root table */
  84577. if (drop != 0 && (huff & mask) != low) {
  84578. drop = 0;
  84579. len = root;
  84580. next = *table;
  84581. thisx.bits = (unsigned char)len;
  84582. }
  84583. /* put invalid code marker in table */
  84584. next[huff >> drop] = thisx;
  84585. /* backwards increment the len-bit code huff */
  84586. incr = 1U << (len - 1);
  84587. while (huff & incr)
  84588. incr >>= 1;
  84589. if (incr != 0) {
  84590. huff &= incr - 1;
  84591. huff += incr;
  84592. }
  84593. else
  84594. huff = 0;
  84595. }
  84596. /* set return parameters */
  84597. *table += used;
  84598. *bits = root;
  84599. return 0;
  84600. }
  84601. /*** End of inlined file: inftrees.c ***/
  84602. /*** Start of inlined file: trees.c ***/
  84603. /*
  84604. * ALGORITHM
  84605. *
  84606. * The "deflation" process uses several Huffman trees. The more
  84607. * common source values are represented by shorter bit sequences.
  84608. *
  84609. * Each code tree is stored in a compressed form which is itself
  84610. * a Huffman encoding of the lengths of all the code strings (in
  84611. * ascending order by source values). The actual code strings are
  84612. * reconstructed from the lengths in the inflate process, as described
  84613. * in the deflate specification.
  84614. *
  84615. * REFERENCES
  84616. *
  84617. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84618. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84619. *
  84620. * Storer, James A.
  84621. * Data Compression: Methods and Theory, pp. 49-50.
  84622. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84623. *
  84624. * Sedgewick, R.
  84625. * Algorithms, p290.
  84626. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84627. */
  84628. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84629. /* #define GEN_TREES_H */
  84630. #ifdef DEBUG
  84631. # include <ctype.h>
  84632. #endif
  84633. /* ===========================================================================
  84634. * Constants
  84635. */
  84636. #define MAX_BL_BITS 7
  84637. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84638. #define END_BLOCK 256
  84639. /* end of block literal code */
  84640. #define REP_3_6 16
  84641. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84642. #define REPZ_3_10 17
  84643. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84644. #define REPZ_11_138 18
  84645. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84646. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84647. = {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};
  84648. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84649. = {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};
  84650. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84651. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84652. local const uch bl_order[BL_CODES]
  84653. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84654. /* The lengths of the bit length codes are sent in order of decreasing
  84655. * probability, to avoid transmitting the lengths for unused bit length codes.
  84656. */
  84657. #define Buf_size (8 * 2*sizeof(char))
  84658. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84659. * more than 16 bits on some systems.)
  84660. */
  84661. /* ===========================================================================
  84662. * Local data. These are initialized only once.
  84663. */
  84664. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84665. #if defined(GEN_TREES_H) || !defined(STDC)
  84666. /* non ANSI compilers may not accept trees.h */
  84667. local ct_data static_ltree[L_CODES+2];
  84668. /* The static literal tree. Since the bit lengths are imposed, there is no
  84669. * need for the L_CODES extra codes used during heap construction. However
  84670. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84671. * below).
  84672. */
  84673. local ct_data static_dtree[D_CODES];
  84674. /* The static distance tree. (Actually a trivial tree since all codes use
  84675. * 5 bits.)
  84676. */
  84677. uch _dist_code[DIST_CODE_LEN];
  84678. /* Distance codes. The first 256 values correspond to the distances
  84679. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84680. * the 15 bit distances.
  84681. */
  84682. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84683. /* length code for each normalized match length (0 == MIN_MATCH) */
  84684. local int base_length[LENGTH_CODES];
  84685. /* First normalized length for each code (0 = MIN_MATCH) */
  84686. local int base_dist[D_CODES];
  84687. /* First normalized distance for each code (0 = distance of 1) */
  84688. #else
  84689. /*** Start of inlined file: trees.h ***/
  84690. local const ct_data static_ltree[L_CODES+2] = {
  84691. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84692. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84693. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84694. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84695. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84696. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84697. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84698. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84699. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84700. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84701. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84702. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84703. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84704. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84705. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84706. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84707. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84708. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84709. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84710. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84711. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84712. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84713. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84714. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84715. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84716. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84717. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84718. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84719. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84720. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84721. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84722. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84723. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84724. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84725. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84726. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84727. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84728. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84729. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84730. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84731. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84732. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84733. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84734. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84735. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84736. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84737. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84738. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84739. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84740. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84741. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84742. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84743. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84744. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84745. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84746. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84747. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84748. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84749. };
  84750. local const ct_data static_dtree[D_CODES] = {
  84751. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84752. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84753. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84754. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84755. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84756. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84757. };
  84758. const uch _dist_code[DIST_CODE_LEN] = {
  84759. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84760. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84761. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84762. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84763. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84764. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84765. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84766. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84767. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84768. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84769. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84770. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84771. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84772. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84773. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84774. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84775. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84776. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84777. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84778. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84779. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84780. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84781. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84782. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84783. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84784. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84785. };
  84786. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84787. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84788. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84789. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84790. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84791. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84792. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84793. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84794. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84795. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84796. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84797. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84798. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84799. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84800. };
  84801. local const int base_length[LENGTH_CODES] = {
  84802. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84803. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84804. };
  84805. local const int base_dist[D_CODES] = {
  84806. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84807. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84808. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84809. };
  84810. /*** End of inlined file: trees.h ***/
  84811. #endif /* GEN_TREES_H */
  84812. struct static_tree_desc_s {
  84813. const ct_data *static_tree; /* static tree or NULL */
  84814. const intf *extra_bits; /* extra bits for each code or NULL */
  84815. int extra_base; /* base index for extra_bits */
  84816. int elems; /* max number of elements in the tree */
  84817. int max_length; /* max bit length for the codes */
  84818. };
  84819. local static_tree_desc static_l_desc =
  84820. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84821. local static_tree_desc static_d_desc =
  84822. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84823. local static_tree_desc static_bl_desc =
  84824. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84825. /* ===========================================================================
  84826. * Local (static) routines in this file.
  84827. */
  84828. local void tr_static_init OF((void));
  84829. local void init_block OF((deflate_state *s));
  84830. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84831. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84832. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84833. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84834. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84835. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84836. local int build_bl_tree OF((deflate_state *s));
  84837. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84838. int blcodes));
  84839. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84840. ct_data *dtree));
  84841. local void set_data_type OF((deflate_state *s));
  84842. local unsigned bi_reverse OF((unsigned value, int length));
  84843. local void bi_windup OF((deflate_state *s));
  84844. local void bi_flush OF((deflate_state *s));
  84845. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84846. int header));
  84847. #ifdef GEN_TREES_H
  84848. local void gen_trees_header OF((void));
  84849. #endif
  84850. #ifndef DEBUG
  84851. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84852. /* Send a code of the given tree. c and tree must not have side effects */
  84853. #else /* DEBUG */
  84854. # define send_code(s, c, tree) \
  84855. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84856. send_bits(s, tree[c].Code, tree[c].Len); }
  84857. #endif
  84858. /* ===========================================================================
  84859. * Output a short LSB first on the stream.
  84860. * IN assertion: there is enough room in pendingBuf.
  84861. */
  84862. #define put_short(s, w) { \
  84863. put_byte(s, (uch)((w) & 0xff)); \
  84864. put_byte(s, (uch)((ush)(w) >> 8)); \
  84865. }
  84866. /* ===========================================================================
  84867. * Send a value on a given number of bits.
  84868. * IN assertion: length <= 16 and value fits in length bits.
  84869. */
  84870. #ifdef DEBUG
  84871. local void send_bits OF((deflate_state *s, int value, int length));
  84872. local void send_bits (deflate_state *s, int value, int length)
  84873. {
  84874. Tracevv((stderr," l %2d v %4x ", length, value));
  84875. Assert(length > 0 && length <= 15, "invalid length");
  84876. s->bits_sent += (ulg)length;
  84877. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84878. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84879. * unused bits in value.
  84880. */
  84881. if (s->bi_valid > (int)Buf_size - length) {
  84882. s->bi_buf |= (value << s->bi_valid);
  84883. put_short(s, s->bi_buf);
  84884. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84885. s->bi_valid += length - Buf_size;
  84886. } else {
  84887. s->bi_buf |= value << s->bi_valid;
  84888. s->bi_valid += length;
  84889. }
  84890. }
  84891. #else /* !DEBUG */
  84892. #define send_bits(s, value, length) \
  84893. { int len = length;\
  84894. if (s->bi_valid > (int)Buf_size - len) {\
  84895. int val = value;\
  84896. s->bi_buf |= (val << s->bi_valid);\
  84897. put_short(s, s->bi_buf);\
  84898. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84899. s->bi_valid += len - Buf_size;\
  84900. } else {\
  84901. s->bi_buf |= (value) << s->bi_valid;\
  84902. s->bi_valid += len;\
  84903. }\
  84904. }
  84905. #endif /* DEBUG */
  84906. /* the arguments must not have side effects */
  84907. /* ===========================================================================
  84908. * Initialize the various 'constant' tables.
  84909. */
  84910. local void tr_static_init()
  84911. {
  84912. #if defined(GEN_TREES_H) || !defined(STDC)
  84913. static int static_init_done = 0;
  84914. int n; /* iterates over tree elements */
  84915. int bits; /* bit counter */
  84916. int length; /* length value */
  84917. int code; /* code value */
  84918. int dist; /* distance index */
  84919. ush bl_count[MAX_BITS+1];
  84920. /* number of codes at each bit length for an optimal tree */
  84921. if (static_init_done) return;
  84922. /* For some embedded targets, global variables are not initialized: */
  84923. static_l_desc.static_tree = static_ltree;
  84924. static_l_desc.extra_bits = extra_lbits;
  84925. static_d_desc.static_tree = static_dtree;
  84926. static_d_desc.extra_bits = extra_dbits;
  84927. static_bl_desc.extra_bits = extra_blbits;
  84928. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84929. length = 0;
  84930. for (code = 0; code < LENGTH_CODES-1; code++) {
  84931. base_length[code] = length;
  84932. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84933. _length_code[length++] = (uch)code;
  84934. }
  84935. }
  84936. Assert (length == 256, "tr_static_init: length != 256");
  84937. /* Note that the length 255 (match length 258) can be represented
  84938. * in two different ways: code 284 + 5 bits or code 285, so we
  84939. * overwrite length_code[255] to use the best encoding:
  84940. */
  84941. _length_code[length-1] = (uch)code;
  84942. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84943. dist = 0;
  84944. for (code = 0 ; code < 16; code++) {
  84945. base_dist[code] = dist;
  84946. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84947. _dist_code[dist++] = (uch)code;
  84948. }
  84949. }
  84950. Assert (dist == 256, "tr_static_init: dist != 256");
  84951. dist >>= 7; /* from now on, all distances are divided by 128 */
  84952. for ( ; code < D_CODES; code++) {
  84953. base_dist[code] = dist << 7;
  84954. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84955. _dist_code[256 + dist++] = (uch)code;
  84956. }
  84957. }
  84958. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84959. /* Construct the codes of the static literal tree */
  84960. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84961. n = 0;
  84962. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84963. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84964. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84965. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84966. /* Codes 286 and 287 do not exist, but we must include them in the
  84967. * tree construction to get a canonical Huffman tree (longest code
  84968. * all ones)
  84969. */
  84970. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84971. /* The static distance tree is trivial: */
  84972. for (n = 0; n < D_CODES; n++) {
  84973. static_dtree[n].Len = 5;
  84974. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84975. }
  84976. static_init_done = 1;
  84977. # ifdef GEN_TREES_H
  84978. gen_trees_header();
  84979. # endif
  84980. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84981. }
  84982. /* ===========================================================================
  84983. * Genererate the file trees.h describing the static trees.
  84984. */
  84985. #ifdef GEN_TREES_H
  84986. # ifndef DEBUG
  84987. # include <stdio.h>
  84988. # endif
  84989. # define SEPARATOR(i, last, width) \
  84990. ((i) == (last)? "\n};\n\n" : \
  84991. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84992. void gen_trees_header()
  84993. {
  84994. FILE *header = fopen("trees.h", "w");
  84995. int i;
  84996. Assert (header != NULL, "Can't open trees.h");
  84997. fprintf(header,
  84998. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84999. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85000. for (i = 0; i < L_CODES+2; i++) {
  85001. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85002. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85003. }
  85004. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85005. for (i = 0; i < D_CODES; i++) {
  85006. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85007. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85008. }
  85009. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85010. for (i = 0; i < DIST_CODE_LEN; i++) {
  85011. fprintf(header, "%2u%s", _dist_code[i],
  85012. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85013. }
  85014. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85015. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85016. fprintf(header, "%2u%s", _length_code[i],
  85017. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85018. }
  85019. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85020. for (i = 0; i < LENGTH_CODES; i++) {
  85021. fprintf(header, "%1u%s", base_length[i],
  85022. SEPARATOR(i, LENGTH_CODES-1, 20));
  85023. }
  85024. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85025. for (i = 0; i < D_CODES; i++) {
  85026. fprintf(header, "%5u%s", base_dist[i],
  85027. SEPARATOR(i, D_CODES-1, 10));
  85028. }
  85029. fclose(header);
  85030. }
  85031. #endif /* GEN_TREES_H */
  85032. /* ===========================================================================
  85033. * Initialize the tree data structures for a new zlib stream.
  85034. */
  85035. void _tr_init(deflate_state *s)
  85036. {
  85037. tr_static_init();
  85038. s->l_desc.dyn_tree = s->dyn_ltree;
  85039. s->l_desc.stat_desc = &static_l_desc;
  85040. s->d_desc.dyn_tree = s->dyn_dtree;
  85041. s->d_desc.stat_desc = &static_d_desc;
  85042. s->bl_desc.dyn_tree = s->bl_tree;
  85043. s->bl_desc.stat_desc = &static_bl_desc;
  85044. s->bi_buf = 0;
  85045. s->bi_valid = 0;
  85046. s->last_eob_len = 8; /* enough lookahead for inflate */
  85047. #ifdef DEBUG
  85048. s->compressed_len = 0L;
  85049. s->bits_sent = 0L;
  85050. #endif
  85051. /* Initialize the first block of the first file: */
  85052. init_block(s);
  85053. }
  85054. /* ===========================================================================
  85055. * Initialize a new block.
  85056. */
  85057. local void init_block (deflate_state *s)
  85058. {
  85059. int n; /* iterates over tree elements */
  85060. /* Initialize the trees. */
  85061. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85062. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85063. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85064. s->dyn_ltree[END_BLOCK].Freq = 1;
  85065. s->opt_len = s->static_len = 0L;
  85066. s->last_lit = s->matches = 0;
  85067. }
  85068. #define SMALLEST 1
  85069. /* Index within the heap array of least frequent node in the Huffman tree */
  85070. /* ===========================================================================
  85071. * Remove the smallest element from the heap and recreate the heap with
  85072. * one less element. Updates heap and heap_len.
  85073. */
  85074. #define pqremove(s, tree, top) \
  85075. {\
  85076. top = s->heap[SMALLEST]; \
  85077. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85078. pqdownheap(s, tree, SMALLEST); \
  85079. }
  85080. /* ===========================================================================
  85081. * Compares to subtrees, using the tree depth as tie breaker when
  85082. * the subtrees have equal frequency. This minimizes the worst case length.
  85083. */
  85084. #define smaller(tree, n, m, depth) \
  85085. (tree[n].Freq < tree[m].Freq || \
  85086. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85087. /* ===========================================================================
  85088. * Restore the heap property by moving down the tree starting at node k,
  85089. * exchanging a node with the smallest of its two sons if necessary, stopping
  85090. * when the heap property is re-established (each father smaller than its
  85091. * two sons).
  85092. */
  85093. local void pqdownheap (deflate_state *s,
  85094. ct_data *tree, /* the tree to restore */
  85095. int k) /* node to move down */
  85096. {
  85097. int v = s->heap[k];
  85098. int j = k << 1; /* left son of k */
  85099. while (j <= s->heap_len) {
  85100. /* Set j to the smallest of the two sons: */
  85101. if (j < s->heap_len &&
  85102. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85103. j++;
  85104. }
  85105. /* Exit if v is smaller than both sons */
  85106. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85107. /* Exchange v with the smallest son */
  85108. s->heap[k] = s->heap[j]; k = j;
  85109. /* And continue down the tree, setting j to the left son of k */
  85110. j <<= 1;
  85111. }
  85112. s->heap[k] = v;
  85113. }
  85114. /* ===========================================================================
  85115. * Compute the optimal bit lengths for a tree and update the total bit length
  85116. * for the current block.
  85117. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85118. * above are the tree nodes sorted by increasing frequency.
  85119. * OUT assertions: the field len is set to the optimal bit length, the
  85120. * array bl_count contains the frequencies for each bit length.
  85121. * The length opt_len is updated; static_len is also updated if stree is
  85122. * not null.
  85123. */
  85124. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85125. {
  85126. ct_data *tree = desc->dyn_tree;
  85127. int max_code = desc->max_code;
  85128. const ct_data *stree = desc->stat_desc->static_tree;
  85129. const intf *extra = desc->stat_desc->extra_bits;
  85130. int base = desc->stat_desc->extra_base;
  85131. int max_length = desc->stat_desc->max_length;
  85132. int h; /* heap index */
  85133. int n, m; /* iterate over the tree elements */
  85134. int bits; /* bit length */
  85135. int xbits; /* extra bits */
  85136. ush f; /* frequency */
  85137. int overflow = 0; /* number of elements with bit length too large */
  85138. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85139. /* In a first pass, compute the optimal bit lengths (which may
  85140. * overflow in the case of the bit length tree).
  85141. */
  85142. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85143. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85144. n = s->heap[h];
  85145. bits = tree[tree[n].Dad].Len + 1;
  85146. if (bits > max_length) bits = max_length, overflow++;
  85147. tree[n].Len = (ush)bits;
  85148. /* We overwrite tree[n].Dad which is no longer needed */
  85149. if (n > max_code) continue; /* not a leaf node */
  85150. s->bl_count[bits]++;
  85151. xbits = 0;
  85152. if (n >= base) xbits = extra[n-base];
  85153. f = tree[n].Freq;
  85154. s->opt_len += (ulg)f * (bits + xbits);
  85155. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85156. }
  85157. if (overflow == 0) return;
  85158. Trace((stderr,"\nbit length overflow\n"));
  85159. /* This happens for example on obj2 and pic of the Calgary corpus */
  85160. /* Find the first bit length which could increase: */
  85161. do {
  85162. bits = max_length-1;
  85163. while (s->bl_count[bits] == 0) bits--;
  85164. s->bl_count[bits]--; /* move one leaf down the tree */
  85165. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85166. s->bl_count[max_length]--;
  85167. /* The brother of the overflow item also moves one step up,
  85168. * but this does not affect bl_count[max_length]
  85169. */
  85170. overflow -= 2;
  85171. } while (overflow > 0);
  85172. /* Now recompute all bit lengths, scanning in increasing frequency.
  85173. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85174. * lengths instead of fixing only the wrong ones. This idea is taken
  85175. * from 'ar' written by Haruhiko Okumura.)
  85176. */
  85177. for (bits = max_length; bits != 0; bits--) {
  85178. n = s->bl_count[bits];
  85179. while (n != 0) {
  85180. m = s->heap[--h];
  85181. if (m > max_code) continue;
  85182. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85183. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85184. s->opt_len += ((long)bits - (long)tree[m].Len)
  85185. *(long)tree[m].Freq;
  85186. tree[m].Len = (ush)bits;
  85187. }
  85188. n--;
  85189. }
  85190. }
  85191. }
  85192. /* ===========================================================================
  85193. * Generate the codes for a given tree and bit counts (which need not be
  85194. * optimal).
  85195. * IN assertion: the array bl_count contains the bit length statistics for
  85196. * the given tree and the field len is set for all tree elements.
  85197. * OUT assertion: the field code is set for all tree elements of non
  85198. * zero code length.
  85199. */
  85200. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85201. int max_code, /* largest code with non zero frequency */
  85202. ushf *bl_count) /* number of codes at each bit length */
  85203. {
  85204. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85205. ush code = 0; /* running code value */
  85206. int bits; /* bit index */
  85207. int n; /* code index */
  85208. /* The distribution counts are first used to generate the code values
  85209. * without bit reversal.
  85210. */
  85211. for (bits = 1; bits <= MAX_BITS; bits++) {
  85212. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85213. }
  85214. /* Check that the bit counts in bl_count are consistent. The last code
  85215. * must be all ones.
  85216. */
  85217. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85218. "inconsistent bit counts");
  85219. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85220. for (n = 0; n <= max_code; n++) {
  85221. int len = tree[n].Len;
  85222. if (len == 0) continue;
  85223. /* Now reverse the bits */
  85224. tree[n].Code = bi_reverse(next_code[len]++, len);
  85225. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85226. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85227. }
  85228. }
  85229. /* ===========================================================================
  85230. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85231. * Update the total bit length for the current block.
  85232. * IN assertion: the field freq is set for all tree elements.
  85233. * OUT assertions: the fields len and code are set to the optimal bit length
  85234. * and corresponding code. The length opt_len is updated; static_len is
  85235. * also updated if stree is not null. The field max_code is set.
  85236. */
  85237. local void build_tree (deflate_state *s,
  85238. tree_desc *desc) /* the tree descriptor */
  85239. {
  85240. ct_data *tree = desc->dyn_tree;
  85241. const ct_data *stree = desc->stat_desc->static_tree;
  85242. int elems = desc->stat_desc->elems;
  85243. int n, m; /* iterate over heap elements */
  85244. int max_code = -1; /* largest code with non zero frequency */
  85245. int node; /* new node being created */
  85246. /* Construct the initial heap, with least frequent element in
  85247. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85248. * heap[0] is not used.
  85249. */
  85250. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85251. for (n = 0; n < elems; n++) {
  85252. if (tree[n].Freq != 0) {
  85253. s->heap[++(s->heap_len)] = max_code = n;
  85254. s->depth[n] = 0;
  85255. } else {
  85256. tree[n].Len = 0;
  85257. }
  85258. }
  85259. /* The pkzip format requires that at least one distance code exists,
  85260. * and that at least one bit should be sent even if there is only one
  85261. * possible code. So to avoid special checks later on we force at least
  85262. * two codes of non zero frequency.
  85263. */
  85264. while (s->heap_len < 2) {
  85265. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85266. tree[node].Freq = 1;
  85267. s->depth[node] = 0;
  85268. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85269. /* node is 0 or 1 so it does not have extra bits */
  85270. }
  85271. desc->max_code = max_code;
  85272. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85273. * establish sub-heaps of increasing lengths:
  85274. */
  85275. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85276. /* Construct the Huffman tree by repeatedly combining the least two
  85277. * frequent nodes.
  85278. */
  85279. node = elems; /* next internal node of the tree */
  85280. do {
  85281. pqremove(s, tree, n); /* n = node of least frequency */
  85282. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85283. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85284. s->heap[--(s->heap_max)] = m;
  85285. /* Create a new node father of n and m */
  85286. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85287. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85288. s->depth[n] : s->depth[m]) + 1);
  85289. tree[n].Dad = tree[m].Dad = (ush)node;
  85290. #ifdef DUMP_BL_TREE
  85291. if (tree == s->bl_tree) {
  85292. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85293. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85294. }
  85295. #endif
  85296. /* and insert the new node in the heap */
  85297. s->heap[SMALLEST] = node++;
  85298. pqdownheap(s, tree, SMALLEST);
  85299. } while (s->heap_len >= 2);
  85300. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85301. /* At this point, the fields freq and dad are set. We can now
  85302. * generate the bit lengths.
  85303. */
  85304. gen_bitlen(s, (tree_desc *)desc);
  85305. /* The field len is now set, we can generate the bit codes */
  85306. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85307. }
  85308. /* ===========================================================================
  85309. * Scan a literal or distance tree to determine the frequencies of the codes
  85310. * in the bit length tree.
  85311. */
  85312. local void scan_tree (deflate_state *s,
  85313. ct_data *tree, /* the tree to be scanned */
  85314. int max_code) /* and its largest code of non zero frequency */
  85315. {
  85316. int n; /* iterates over all tree elements */
  85317. int prevlen = -1; /* last emitted length */
  85318. int curlen; /* length of current code */
  85319. int nextlen = tree[0].Len; /* length of next code */
  85320. int count = 0; /* repeat count of the current code */
  85321. int max_count = 7; /* max repeat count */
  85322. int min_count = 4; /* min repeat count */
  85323. if (nextlen == 0) max_count = 138, min_count = 3;
  85324. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85325. for (n = 0; n <= max_code; n++) {
  85326. curlen = nextlen; nextlen = tree[n+1].Len;
  85327. if (++count < max_count && curlen == nextlen) {
  85328. continue;
  85329. } else if (count < min_count) {
  85330. s->bl_tree[curlen].Freq += count;
  85331. } else if (curlen != 0) {
  85332. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85333. s->bl_tree[REP_3_6].Freq++;
  85334. } else if (count <= 10) {
  85335. s->bl_tree[REPZ_3_10].Freq++;
  85336. } else {
  85337. s->bl_tree[REPZ_11_138].Freq++;
  85338. }
  85339. count = 0; prevlen = curlen;
  85340. if (nextlen == 0) {
  85341. max_count = 138, min_count = 3;
  85342. } else if (curlen == nextlen) {
  85343. max_count = 6, min_count = 3;
  85344. } else {
  85345. max_count = 7, min_count = 4;
  85346. }
  85347. }
  85348. }
  85349. /* ===========================================================================
  85350. * Send a literal or distance tree in compressed form, using the codes in
  85351. * bl_tree.
  85352. */
  85353. local void send_tree (deflate_state *s,
  85354. ct_data *tree, /* the tree to be scanned */
  85355. int max_code) /* and its largest code of non zero frequency */
  85356. {
  85357. int n; /* iterates over all tree elements */
  85358. int prevlen = -1; /* last emitted length */
  85359. int curlen; /* length of current code */
  85360. int nextlen = tree[0].Len; /* length of next code */
  85361. int count = 0; /* repeat count of the current code */
  85362. int max_count = 7; /* max repeat count */
  85363. int min_count = 4; /* min repeat count */
  85364. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85365. if (nextlen == 0) max_count = 138, min_count = 3;
  85366. for (n = 0; n <= max_code; n++) {
  85367. curlen = nextlen; nextlen = tree[n+1].Len;
  85368. if (++count < max_count && curlen == nextlen) {
  85369. continue;
  85370. } else if (count < min_count) {
  85371. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85372. } else if (curlen != 0) {
  85373. if (curlen != prevlen) {
  85374. send_code(s, curlen, s->bl_tree); count--;
  85375. }
  85376. Assert(count >= 3 && count <= 6, " 3_6?");
  85377. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85378. } else if (count <= 10) {
  85379. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85380. } else {
  85381. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85382. }
  85383. count = 0; prevlen = curlen;
  85384. if (nextlen == 0) {
  85385. max_count = 138, min_count = 3;
  85386. } else if (curlen == nextlen) {
  85387. max_count = 6, min_count = 3;
  85388. } else {
  85389. max_count = 7, min_count = 4;
  85390. }
  85391. }
  85392. }
  85393. /* ===========================================================================
  85394. * Construct the Huffman tree for the bit lengths and return the index in
  85395. * bl_order of the last bit length code to send.
  85396. */
  85397. local int build_bl_tree (deflate_state *s)
  85398. {
  85399. int max_blindex; /* index of last bit length code of non zero freq */
  85400. /* Determine the bit length frequencies for literal and distance trees */
  85401. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85402. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85403. /* Build the bit length tree: */
  85404. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85405. /* opt_len now includes the length of the tree representations, except
  85406. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85407. */
  85408. /* Determine the number of bit length codes to send. The pkzip format
  85409. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85410. * 3 but the actual value used is 4.)
  85411. */
  85412. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85413. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85414. }
  85415. /* Update opt_len to include the bit length tree and counts */
  85416. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85417. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85418. s->opt_len, s->static_len));
  85419. return max_blindex;
  85420. }
  85421. /* ===========================================================================
  85422. * Send the header for a block using dynamic Huffman trees: the counts, the
  85423. * lengths of the bit length codes, the literal tree and the distance tree.
  85424. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85425. */
  85426. local void send_all_trees (deflate_state *s,
  85427. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85428. {
  85429. int rank; /* index in bl_order */
  85430. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85431. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85432. "too many codes");
  85433. Tracev((stderr, "\nbl counts: "));
  85434. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85435. send_bits(s, dcodes-1, 5);
  85436. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85437. for (rank = 0; rank < blcodes; rank++) {
  85438. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85439. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85440. }
  85441. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85442. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85443. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85444. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85445. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85446. }
  85447. /* ===========================================================================
  85448. * Send a stored block
  85449. */
  85450. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85451. {
  85452. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85453. #ifdef DEBUG
  85454. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85455. s->compressed_len += (stored_len + 4) << 3;
  85456. #endif
  85457. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85458. }
  85459. /* ===========================================================================
  85460. * Send one empty static block to give enough lookahead for inflate.
  85461. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85462. * The current inflate code requires 9 bits of lookahead. If the
  85463. * last two codes for the previous block (real code plus EOB) were coded
  85464. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85465. * the last real code. In this case we send two empty static blocks instead
  85466. * of one. (There are no problems if the previous block is stored or fixed.)
  85467. * To simplify the code, we assume the worst case of last real code encoded
  85468. * on one bit only.
  85469. */
  85470. void _tr_align (deflate_state *s)
  85471. {
  85472. send_bits(s, STATIC_TREES<<1, 3);
  85473. send_code(s, END_BLOCK, static_ltree);
  85474. #ifdef DEBUG
  85475. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85476. #endif
  85477. bi_flush(s);
  85478. /* Of the 10 bits for the empty block, we have already sent
  85479. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85480. * the EOB of the previous block) was thus at least one plus the length
  85481. * of the EOB plus what we have just sent of the empty static block.
  85482. */
  85483. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85484. send_bits(s, STATIC_TREES<<1, 3);
  85485. send_code(s, END_BLOCK, static_ltree);
  85486. #ifdef DEBUG
  85487. s->compressed_len += 10L;
  85488. #endif
  85489. bi_flush(s);
  85490. }
  85491. s->last_eob_len = 7;
  85492. }
  85493. /* ===========================================================================
  85494. * Determine the best encoding for the current block: dynamic trees, static
  85495. * trees or store, and output the encoded block to the zip file.
  85496. */
  85497. void _tr_flush_block (deflate_state *s,
  85498. charf *buf, /* input block, or NULL if too old */
  85499. ulg stored_len, /* length of input block */
  85500. int eof) /* true if this is the last block for a file */
  85501. {
  85502. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85503. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85504. /* Build the Huffman trees unless a stored block is forced */
  85505. if (s->level > 0) {
  85506. /* Check if the file is binary or text */
  85507. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85508. set_data_type(s);
  85509. /* Construct the literal and distance trees */
  85510. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85511. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85512. s->static_len));
  85513. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85514. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85515. s->static_len));
  85516. /* At this point, opt_len and static_len are the total bit lengths of
  85517. * the compressed block data, excluding the tree representations.
  85518. */
  85519. /* Build the bit length tree for the above two trees, and get the index
  85520. * in bl_order of the last bit length code to send.
  85521. */
  85522. max_blindex = build_bl_tree(s);
  85523. /* Determine the best encoding. Compute the block lengths in bytes. */
  85524. opt_lenb = (s->opt_len+3+7)>>3;
  85525. static_lenb = (s->static_len+3+7)>>3;
  85526. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85527. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85528. s->last_lit));
  85529. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85530. } else {
  85531. Assert(buf != (char*)0, "lost buf");
  85532. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85533. }
  85534. #ifdef FORCE_STORED
  85535. if (buf != (char*)0) { /* force stored block */
  85536. #else
  85537. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85538. /* 4: two words for the lengths */
  85539. #endif
  85540. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85541. * Otherwise we can't have processed more than WSIZE input bytes since
  85542. * the last block flush, because compression would have been
  85543. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85544. * transform a block into a stored block.
  85545. */
  85546. _tr_stored_block(s, buf, stored_len, eof);
  85547. #ifdef FORCE_STATIC
  85548. } else if (static_lenb >= 0) { /* force static trees */
  85549. #else
  85550. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85551. #endif
  85552. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85553. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85554. #ifdef DEBUG
  85555. s->compressed_len += 3 + s->static_len;
  85556. #endif
  85557. } else {
  85558. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85559. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85560. max_blindex+1);
  85561. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85562. #ifdef DEBUG
  85563. s->compressed_len += 3 + s->opt_len;
  85564. #endif
  85565. }
  85566. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85567. /* The above check is made mod 2^32, for files larger than 512 MB
  85568. * and uLong implemented on 32 bits.
  85569. */
  85570. init_block(s);
  85571. if (eof) {
  85572. bi_windup(s);
  85573. #ifdef DEBUG
  85574. s->compressed_len += 7; /* align on byte boundary */
  85575. #endif
  85576. }
  85577. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85578. s->compressed_len-7*eof));
  85579. }
  85580. /* ===========================================================================
  85581. * Save the match info and tally the frequency counts. Return true if
  85582. * the current block must be flushed.
  85583. */
  85584. int _tr_tally (deflate_state *s,
  85585. unsigned dist, /* distance of matched string */
  85586. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85587. {
  85588. s->d_buf[s->last_lit] = (ush)dist;
  85589. s->l_buf[s->last_lit++] = (uch)lc;
  85590. if (dist == 0) {
  85591. /* lc is the unmatched char */
  85592. s->dyn_ltree[lc].Freq++;
  85593. } else {
  85594. s->matches++;
  85595. /* Here, lc is the match length - MIN_MATCH */
  85596. dist--; /* dist = match distance - 1 */
  85597. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85598. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85599. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85600. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85601. s->dyn_dtree[d_code(dist)].Freq++;
  85602. }
  85603. #ifdef TRUNCATE_BLOCK
  85604. /* Try to guess if it is profitable to stop the current block here */
  85605. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85606. /* Compute an upper bound for the compressed length */
  85607. ulg out_length = (ulg)s->last_lit*8L;
  85608. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85609. int dcode;
  85610. for (dcode = 0; dcode < D_CODES; dcode++) {
  85611. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85612. (5L+extra_dbits[dcode]);
  85613. }
  85614. out_length >>= 3;
  85615. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85616. s->last_lit, in_length, out_length,
  85617. 100L - out_length*100L/in_length));
  85618. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85619. }
  85620. #endif
  85621. return (s->last_lit == s->lit_bufsize-1);
  85622. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85623. * on 16 bit machines and because stored blocks are restricted to
  85624. * 64K-1 bytes.
  85625. */
  85626. }
  85627. /* ===========================================================================
  85628. * Send the block data compressed using the given Huffman trees
  85629. */
  85630. local void compress_block (deflate_state *s,
  85631. ct_data *ltree, /* literal tree */
  85632. ct_data *dtree) /* distance tree */
  85633. {
  85634. unsigned dist; /* distance of matched string */
  85635. int lc; /* match length or unmatched char (if dist == 0) */
  85636. unsigned lx = 0; /* running index in l_buf */
  85637. unsigned code; /* the code to send */
  85638. int extra; /* number of extra bits to send */
  85639. if (s->last_lit != 0) do {
  85640. dist = s->d_buf[lx];
  85641. lc = s->l_buf[lx++];
  85642. if (dist == 0) {
  85643. send_code(s, lc, ltree); /* send a literal byte */
  85644. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85645. } else {
  85646. /* Here, lc is the match length - MIN_MATCH */
  85647. code = _length_code[lc];
  85648. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85649. extra = extra_lbits[code];
  85650. if (extra != 0) {
  85651. lc -= base_length[code];
  85652. send_bits(s, lc, extra); /* send the extra length bits */
  85653. }
  85654. dist--; /* dist is now the match distance - 1 */
  85655. code = d_code(dist);
  85656. Assert (code < D_CODES, "bad d_code");
  85657. send_code(s, code, dtree); /* send the distance code */
  85658. extra = extra_dbits[code];
  85659. if (extra != 0) {
  85660. dist -= base_dist[code];
  85661. send_bits(s, dist, extra); /* send the extra distance bits */
  85662. }
  85663. } /* literal or match pair ? */
  85664. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85665. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85666. "pendingBuf overflow");
  85667. } while (lx < s->last_lit);
  85668. send_code(s, END_BLOCK, ltree);
  85669. s->last_eob_len = ltree[END_BLOCK].Len;
  85670. }
  85671. /* ===========================================================================
  85672. * Set the data type to BINARY or TEXT, using a crude approximation:
  85673. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85674. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85675. * IN assertion: the fields Freq of dyn_ltree are set.
  85676. */
  85677. local void set_data_type (deflate_state *s)
  85678. {
  85679. int n;
  85680. for (n = 0; n < 9; n++)
  85681. if (s->dyn_ltree[n].Freq != 0)
  85682. break;
  85683. if (n == 9)
  85684. for (n = 14; n < 32; n++)
  85685. if (s->dyn_ltree[n].Freq != 0)
  85686. break;
  85687. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85688. }
  85689. /* ===========================================================================
  85690. * Reverse the first len bits of a code, using straightforward code (a faster
  85691. * method would use a table)
  85692. * IN assertion: 1 <= len <= 15
  85693. */
  85694. local unsigned bi_reverse (unsigned code, int len)
  85695. {
  85696. register unsigned res = 0;
  85697. do {
  85698. res |= code & 1;
  85699. code >>= 1, res <<= 1;
  85700. } while (--len > 0);
  85701. return res >> 1;
  85702. }
  85703. /* ===========================================================================
  85704. * Flush the bit buffer, keeping at most 7 bits in it.
  85705. */
  85706. local void bi_flush (deflate_state *s)
  85707. {
  85708. if (s->bi_valid == 16) {
  85709. put_short(s, s->bi_buf);
  85710. s->bi_buf = 0;
  85711. s->bi_valid = 0;
  85712. } else if (s->bi_valid >= 8) {
  85713. put_byte(s, (Byte)s->bi_buf);
  85714. s->bi_buf >>= 8;
  85715. s->bi_valid -= 8;
  85716. }
  85717. }
  85718. /* ===========================================================================
  85719. * Flush the bit buffer and align the output on a byte boundary
  85720. */
  85721. local void bi_windup (deflate_state *s)
  85722. {
  85723. if (s->bi_valid > 8) {
  85724. put_short(s, s->bi_buf);
  85725. } else if (s->bi_valid > 0) {
  85726. put_byte(s, (Byte)s->bi_buf);
  85727. }
  85728. s->bi_buf = 0;
  85729. s->bi_valid = 0;
  85730. #ifdef DEBUG
  85731. s->bits_sent = (s->bits_sent+7) & ~7;
  85732. #endif
  85733. }
  85734. /* ===========================================================================
  85735. * Copy a stored block, storing first the length and its
  85736. * one's complement if requested.
  85737. */
  85738. local void copy_block(deflate_state *s,
  85739. charf *buf, /* the input data */
  85740. unsigned len, /* its length */
  85741. int header) /* true if block header must be written */
  85742. {
  85743. bi_windup(s); /* align on byte boundary */
  85744. s->last_eob_len = 8; /* enough lookahead for inflate */
  85745. if (header) {
  85746. put_short(s, (ush)len);
  85747. put_short(s, (ush)~len);
  85748. #ifdef DEBUG
  85749. s->bits_sent += 2*16;
  85750. #endif
  85751. }
  85752. #ifdef DEBUG
  85753. s->bits_sent += (ulg)len<<3;
  85754. #endif
  85755. while (len--) {
  85756. put_byte(s, *buf++);
  85757. }
  85758. }
  85759. /*** End of inlined file: trees.c ***/
  85760. /*** Start of inlined file: zutil.c ***/
  85761. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85762. #ifndef NO_DUMMY_DECL
  85763. struct internal_state {int dummy;}; /* for buggy compilers */
  85764. #endif
  85765. const char * const z_errmsg[10] = {
  85766. "need dictionary", /* Z_NEED_DICT 2 */
  85767. "stream end", /* Z_STREAM_END 1 */
  85768. "", /* Z_OK 0 */
  85769. "file error", /* Z_ERRNO (-1) */
  85770. "stream error", /* Z_STREAM_ERROR (-2) */
  85771. "data error", /* Z_DATA_ERROR (-3) */
  85772. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85773. "buffer error", /* Z_BUF_ERROR (-5) */
  85774. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85775. ""};
  85776. /*const char * ZEXPORT zlibVersion()
  85777. {
  85778. return ZLIB_VERSION;
  85779. }
  85780. uLong ZEXPORT zlibCompileFlags()
  85781. {
  85782. uLong flags;
  85783. flags = 0;
  85784. switch (sizeof(uInt)) {
  85785. case 2: break;
  85786. case 4: flags += 1; break;
  85787. case 8: flags += 2; break;
  85788. default: flags += 3;
  85789. }
  85790. switch (sizeof(uLong)) {
  85791. case 2: break;
  85792. case 4: flags += 1 << 2; break;
  85793. case 8: flags += 2 << 2; break;
  85794. default: flags += 3 << 2;
  85795. }
  85796. switch (sizeof(voidpf)) {
  85797. case 2: break;
  85798. case 4: flags += 1 << 4; break;
  85799. case 8: flags += 2 << 4; break;
  85800. default: flags += 3 << 4;
  85801. }
  85802. switch (sizeof(z_off_t)) {
  85803. case 2: break;
  85804. case 4: flags += 1 << 6; break;
  85805. case 8: flags += 2 << 6; break;
  85806. default: flags += 3 << 6;
  85807. }
  85808. #ifdef DEBUG
  85809. flags += 1 << 8;
  85810. #endif
  85811. #if defined(ASMV) || defined(ASMINF)
  85812. flags += 1 << 9;
  85813. #endif
  85814. #ifdef ZLIB_WINAPI
  85815. flags += 1 << 10;
  85816. #endif
  85817. #ifdef BUILDFIXED
  85818. flags += 1 << 12;
  85819. #endif
  85820. #ifdef DYNAMIC_CRC_TABLE
  85821. flags += 1 << 13;
  85822. #endif
  85823. #ifdef NO_GZCOMPRESS
  85824. flags += 1L << 16;
  85825. #endif
  85826. #ifdef NO_GZIP
  85827. flags += 1L << 17;
  85828. #endif
  85829. #ifdef PKZIP_BUG_WORKAROUND
  85830. flags += 1L << 20;
  85831. #endif
  85832. #ifdef FASTEST
  85833. flags += 1L << 21;
  85834. #endif
  85835. #ifdef STDC
  85836. # ifdef NO_vsnprintf
  85837. flags += 1L << 25;
  85838. # ifdef HAS_vsprintf_void
  85839. flags += 1L << 26;
  85840. # endif
  85841. # else
  85842. # ifdef HAS_vsnprintf_void
  85843. flags += 1L << 26;
  85844. # endif
  85845. # endif
  85846. #else
  85847. flags += 1L << 24;
  85848. # ifdef NO_snprintf
  85849. flags += 1L << 25;
  85850. # ifdef HAS_sprintf_void
  85851. flags += 1L << 26;
  85852. # endif
  85853. # else
  85854. # ifdef HAS_snprintf_void
  85855. flags += 1L << 26;
  85856. # endif
  85857. # endif
  85858. #endif
  85859. return flags;
  85860. }*/
  85861. #ifdef DEBUG
  85862. # ifndef verbose
  85863. # define verbose 0
  85864. # endif
  85865. int z_verbose = verbose;
  85866. void z_error (const char *m)
  85867. {
  85868. fprintf(stderr, "%s\n", m);
  85869. exit(1);
  85870. }
  85871. #endif
  85872. /* exported to allow conversion of error code to string for compress() and
  85873. * uncompress()
  85874. */
  85875. const char * ZEXPORT zError(int err)
  85876. {
  85877. return ERR_MSG(err);
  85878. }
  85879. #if defined(_WIN32_WCE)
  85880. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85881. * errno. We define it as a global variable to simplify porting.
  85882. * Its value is always 0 and should not be used.
  85883. */
  85884. int errno = 0;
  85885. #endif
  85886. #ifndef HAVE_MEMCPY
  85887. void zmemcpy(dest, source, len)
  85888. Bytef* dest;
  85889. const Bytef* source;
  85890. uInt len;
  85891. {
  85892. if (len == 0) return;
  85893. do {
  85894. *dest++ = *source++; /* ??? to be unrolled */
  85895. } while (--len != 0);
  85896. }
  85897. int zmemcmp(s1, s2, len)
  85898. const Bytef* s1;
  85899. const Bytef* s2;
  85900. uInt len;
  85901. {
  85902. uInt j;
  85903. for (j = 0; j < len; j++) {
  85904. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85905. }
  85906. return 0;
  85907. }
  85908. void zmemzero(dest, len)
  85909. Bytef* dest;
  85910. uInt len;
  85911. {
  85912. if (len == 0) return;
  85913. do {
  85914. *dest++ = 0; /* ??? to be unrolled */
  85915. } while (--len != 0);
  85916. }
  85917. #endif
  85918. #ifdef SYS16BIT
  85919. #ifdef __TURBOC__
  85920. /* Turbo C in 16-bit mode */
  85921. # define MY_ZCALLOC
  85922. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85923. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85924. * must fix the pointer. Warning: the pointer must be put back to its
  85925. * original form in order to free it, use zcfree().
  85926. */
  85927. #define MAX_PTR 10
  85928. /* 10*64K = 640K */
  85929. local int next_ptr = 0;
  85930. typedef struct ptr_table_s {
  85931. voidpf org_ptr;
  85932. voidpf new_ptr;
  85933. } ptr_table;
  85934. local ptr_table table[MAX_PTR];
  85935. /* This table is used to remember the original form of pointers
  85936. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85937. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85938. * protected from concurrent access. This hack doesn't work anyway on
  85939. * a protected system like OS/2. Use Microsoft C instead.
  85940. */
  85941. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85942. {
  85943. voidpf buf = opaque; /* just to make some compilers happy */
  85944. ulg bsize = (ulg)items*size;
  85945. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85946. * will return a usable pointer which doesn't have to be normalized.
  85947. */
  85948. if (bsize < 65520L) {
  85949. buf = farmalloc(bsize);
  85950. if (*(ush*)&buf != 0) return buf;
  85951. } else {
  85952. buf = farmalloc(bsize + 16L);
  85953. }
  85954. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85955. table[next_ptr].org_ptr = buf;
  85956. /* Normalize the pointer to seg:0 */
  85957. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85958. *(ush*)&buf = 0;
  85959. table[next_ptr++].new_ptr = buf;
  85960. return buf;
  85961. }
  85962. void zcfree (voidpf opaque, voidpf ptr)
  85963. {
  85964. int n;
  85965. if (*(ush*)&ptr != 0) { /* object < 64K */
  85966. farfree(ptr);
  85967. return;
  85968. }
  85969. /* Find the original pointer */
  85970. for (n = 0; n < next_ptr; n++) {
  85971. if (ptr != table[n].new_ptr) continue;
  85972. farfree(table[n].org_ptr);
  85973. while (++n < next_ptr) {
  85974. table[n-1] = table[n];
  85975. }
  85976. next_ptr--;
  85977. return;
  85978. }
  85979. ptr = opaque; /* just to make some compilers happy */
  85980. Assert(0, "zcfree: ptr not found");
  85981. }
  85982. #endif /* __TURBOC__ */
  85983. #ifdef M_I86
  85984. /* Microsoft C in 16-bit mode */
  85985. # define MY_ZCALLOC
  85986. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85987. # define _halloc halloc
  85988. # define _hfree hfree
  85989. #endif
  85990. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85991. {
  85992. if (opaque) opaque = 0; /* to make compiler happy */
  85993. return _halloc((long)items, size);
  85994. }
  85995. void zcfree (voidpf opaque, voidpf ptr)
  85996. {
  85997. if (opaque) opaque = 0; /* to make compiler happy */
  85998. _hfree(ptr);
  85999. }
  86000. #endif /* M_I86 */
  86001. #endif /* SYS16BIT */
  86002. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86003. #ifndef STDC
  86004. extern voidp malloc OF((uInt size));
  86005. extern voidp calloc OF((uInt items, uInt size));
  86006. extern void free OF((voidpf ptr));
  86007. #endif
  86008. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86009. {
  86010. if (opaque) items += size - size; /* make compiler happy */
  86011. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86012. (voidpf)calloc(items, size);
  86013. }
  86014. void zcfree (voidpf opaque, voidpf ptr)
  86015. {
  86016. free(ptr);
  86017. if (opaque) return; /* make compiler happy */
  86018. }
  86019. #endif /* MY_ZCALLOC */
  86020. /*** End of inlined file: zutil.c ***/
  86021. #undef Byte
  86022. #else
  86023. #include <zlib.h>
  86024. #endif
  86025. }
  86026. #if JUCE_MSVC
  86027. #pragma warning (pop)
  86028. #endif
  86029. BEGIN_JUCE_NAMESPACE
  86030. // internal helper object that holds the zlib structures so they don't have to be
  86031. // included publicly.
  86032. class GZIPDecompressorInputStream::GZIPDecompressHelper
  86033. {
  86034. public:
  86035. GZIPDecompressHelper (const bool noWrap)
  86036. : finished (true),
  86037. needsDictionary (false),
  86038. error (true),
  86039. streamIsValid (false),
  86040. data (0),
  86041. dataSize (0)
  86042. {
  86043. using namespace zlibNamespace;
  86044. zerostruct (stream);
  86045. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86046. finished = error = ! streamIsValid;
  86047. }
  86048. ~GZIPDecompressHelper()
  86049. {
  86050. using namespace zlibNamespace;
  86051. if (streamIsValid)
  86052. inflateEnd (&stream);
  86053. }
  86054. bool needsInput() const throw() { return dataSize <= 0; }
  86055. void setInput (uint8* const data_, const int size) throw()
  86056. {
  86057. data = data_;
  86058. dataSize = size;
  86059. }
  86060. int doNextBlock (uint8* const dest, const int destSize)
  86061. {
  86062. using namespace zlibNamespace;
  86063. if (streamIsValid && data != 0 && ! finished)
  86064. {
  86065. stream.next_in = data;
  86066. stream.next_out = dest;
  86067. stream.avail_in = dataSize;
  86068. stream.avail_out = destSize;
  86069. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86070. {
  86071. case Z_STREAM_END:
  86072. finished = true;
  86073. // deliberate fall-through
  86074. case Z_OK:
  86075. data += dataSize - stream.avail_in;
  86076. dataSize = stream.avail_in;
  86077. return destSize - stream.avail_out;
  86078. case Z_NEED_DICT:
  86079. needsDictionary = true;
  86080. data += dataSize - stream.avail_in;
  86081. dataSize = stream.avail_in;
  86082. break;
  86083. case Z_DATA_ERROR:
  86084. case Z_MEM_ERROR:
  86085. error = true;
  86086. default:
  86087. break;
  86088. }
  86089. }
  86090. return 0;
  86091. }
  86092. bool finished, needsDictionary, error, streamIsValid;
  86093. enum { gzipDecompBufferSize = 32768 };
  86094. private:
  86095. zlibNamespace::z_stream stream;
  86096. uint8* data;
  86097. int dataSize;
  86098. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  86099. };
  86100. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86101. const bool deleteSourceWhenDestroyed,
  86102. const bool noWrap_,
  86103. const int64 uncompressedStreamLength_)
  86104. : sourceStream (sourceStream_),
  86105. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86106. uncompressedStreamLength (uncompressedStreamLength_),
  86107. noWrap (noWrap_),
  86108. isEof (false),
  86109. activeBufferSize (0),
  86110. originalSourcePos (sourceStream_->getPosition()),
  86111. currentPos (0),
  86112. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86113. helper (new GZIPDecompressHelper (noWrap_))
  86114. {
  86115. }
  86116. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  86117. : sourceStream (&sourceStream_),
  86118. uncompressedStreamLength (-1),
  86119. noWrap (false),
  86120. isEof (false),
  86121. activeBufferSize (0),
  86122. originalSourcePos (sourceStream_.getPosition()),
  86123. currentPos (0),
  86124. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86125. helper (new GZIPDecompressHelper (false))
  86126. {
  86127. }
  86128. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86129. {
  86130. }
  86131. int64 GZIPDecompressorInputStream::getTotalLength()
  86132. {
  86133. return uncompressedStreamLength;
  86134. }
  86135. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86136. {
  86137. if ((howMany > 0) && ! isEof)
  86138. {
  86139. jassert (destBuffer != 0);
  86140. if (destBuffer != 0)
  86141. {
  86142. int numRead = 0;
  86143. uint8* d = static_cast <uint8*> (destBuffer);
  86144. while (! helper->error)
  86145. {
  86146. const int n = helper->doNextBlock (d, howMany);
  86147. currentPos += n;
  86148. if (n == 0)
  86149. {
  86150. if (helper->finished || helper->needsDictionary)
  86151. {
  86152. isEof = true;
  86153. return numRead;
  86154. }
  86155. if (helper->needsInput())
  86156. {
  86157. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  86158. if (activeBufferSize > 0)
  86159. {
  86160. helper->setInput (buffer, activeBufferSize);
  86161. }
  86162. else
  86163. {
  86164. isEof = true;
  86165. return numRead;
  86166. }
  86167. }
  86168. }
  86169. else
  86170. {
  86171. numRead += n;
  86172. howMany -= n;
  86173. d += n;
  86174. if (howMany <= 0)
  86175. return numRead;
  86176. }
  86177. }
  86178. }
  86179. }
  86180. return 0;
  86181. }
  86182. bool GZIPDecompressorInputStream::isExhausted()
  86183. {
  86184. return helper->error || isEof;
  86185. }
  86186. int64 GZIPDecompressorInputStream::getPosition()
  86187. {
  86188. return currentPos;
  86189. }
  86190. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86191. {
  86192. if (newPos < currentPos)
  86193. {
  86194. // to go backwards, reset the stream and start again..
  86195. isEof = false;
  86196. activeBufferSize = 0;
  86197. currentPos = 0;
  86198. helper = new GZIPDecompressHelper (noWrap);
  86199. sourceStream->setPosition (originalSourcePos);
  86200. }
  86201. skipNextBytes (newPos - currentPos);
  86202. return true;
  86203. }
  86204. END_JUCE_NAMESPACE
  86205. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86206. #endif
  86207. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86208. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86209. #if JUCE_USE_FLAC
  86210. #if JUCE_WINDOWS
  86211. #include <windows.h>
  86212. #endif
  86213. namespace FlacNamespace
  86214. {
  86215. #if JUCE_INCLUDE_FLAC_CODE
  86216. #if JUCE_MSVC
  86217. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86218. #endif
  86219. #define FLAC__NO_DLL 1
  86220. #if ! defined (SIZE_MAX)
  86221. #define SIZE_MAX 0xffffffff
  86222. #endif
  86223. #define __STDC_LIMIT_MACROS 1
  86224. /*** Start of inlined file: all.h ***/
  86225. #ifndef FLAC__ALL_H
  86226. #define FLAC__ALL_H
  86227. /*** Start of inlined file: export.h ***/
  86228. #ifndef FLAC__EXPORT_H
  86229. #define FLAC__EXPORT_H
  86230. /** \file include/FLAC/export.h
  86231. *
  86232. * \brief
  86233. * This module contains #defines and symbols for exporting function
  86234. * calls, and providing version information and compiled-in features.
  86235. *
  86236. * See the \link flac_export export \endlink module.
  86237. */
  86238. /** \defgroup flac_export FLAC/export.h: export symbols
  86239. * \ingroup flac
  86240. *
  86241. * \brief
  86242. * This module contains #defines and symbols for exporting function
  86243. * calls, and providing version information and compiled-in features.
  86244. *
  86245. * If you are compiling with MSVC and will link to the static library
  86246. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86247. * make sure the symbols are exported properly.
  86248. *
  86249. * \{
  86250. */
  86251. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86252. #define FLAC_API
  86253. #else
  86254. #ifdef FLAC_API_EXPORTS
  86255. #define FLAC_API _declspec(dllexport)
  86256. #else
  86257. #define FLAC_API _declspec(dllimport)
  86258. #endif
  86259. #endif
  86260. /** These #defines will mirror the libtool-based library version number, see
  86261. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86262. */
  86263. #define FLAC_API_VERSION_CURRENT 10
  86264. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86265. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86266. #ifdef __cplusplus
  86267. extern "C" {
  86268. #endif
  86269. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86270. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86271. #ifdef __cplusplus
  86272. }
  86273. #endif
  86274. /* \} */
  86275. #endif
  86276. /*** End of inlined file: export.h ***/
  86277. /*** Start of inlined file: assert.h ***/
  86278. #ifndef FLAC__ASSERT_H
  86279. #define FLAC__ASSERT_H
  86280. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86281. #ifdef DEBUG
  86282. #include <assert.h>
  86283. #define FLAC__ASSERT(x) assert(x)
  86284. #define FLAC__ASSERT_DECLARATION(x) x
  86285. #else
  86286. #define FLAC__ASSERT(x)
  86287. #define FLAC__ASSERT_DECLARATION(x)
  86288. #endif
  86289. #endif
  86290. /*** End of inlined file: assert.h ***/
  86291. /*** Start of inlined file: callback.h ***/
  86292. #ifndef FLAC__CALLBACK_H
  86293. #define FLAC__CALLBACK_H
  86294. /*** Start of inlined file: ordinals.h ***/
  86295. #ifndef FLAC__ORDINALS_H
  86296. #define FLAC__ORDINALS_H
  86297. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86298. #include <inttypes.h>
  86299. #endif
  86300. typedef signed char FLAC__int8;
  86301. typedef unsigned char FLAC__uint8;
  86302. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86303. typedef __int16 FLAC__int16;
  86304. typedef __int32 FLAC__int32;
  86305. typedef __int64 FLAC__int64;
  86306. typedef unsigned __int16 FLAC__uint16;
  86307. typedef unsigned __int32 FLAC__uint32;
  86308. typedef unsigned __int64 FLAC__uint64;
  86309. #elif defined(__EMX__)
  86310. typedef short FLAC__int16;
  86311. typedef long FLAC__int32;
  86312. typedef long long FLAC__int64;
  86313. typedef unsigned short FLAC__uint16;
  86314. typedef unsigned long FLAC__uint32;
  86315. typedef unsigned long long FLAC__uint64;
  86316. #else
  86317. typedef int16_t FLAC__int16;
  86318. typedef int32_t FLAC__int32;
  86319. typedef int64_t FLAC__int64;
  86320. typedef uint16_t FLAC__uint16;
  86321. typedef uint32_t FLAC__uint32;
  86322. typedef uint64_t FLAC__uint64;
  86323. #endif
  86324. typedef int FLAC__bool;
  86325. typedef FLAC__uint8 FLAC__byte;
  86326. #ifdef true
  86327. #undef true
  86328. #endif
  86329. #ifdef false
  86330. #undef false
  86331. #endif
  86332. #ifndef __cplusplus
  86333. #define true 1
  86334. #define false 0
  86335. #endif
  86336. #endif
  86337. /*** End of inlined file: ordinals.h ***/
  86338. #include <stdlib.h> /* for size_t */
  86339. /** \file include/FLAC/callback.h
  86340. *
  86341. * \brief
  86342. * This module defines the structures for describing I/O callbacks
  86343. * to the other FLAC interfaces.
  86344. *
  86345. * See the detailed documentation for callbacks in the
  86346. * \link flac_callbacks callbacks \endlink module.
  86347. */
  86348. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86349. * \ingroup flac
  86350. *
  86351. * \brief
  86352. * This module defines the structures for describing I/O callbacks
  86353. * to the other FLAC interfaces.
  86354. *
  86355. * The purpose of the I/O callback functions is to create a common way
  86356. * for the metadata interfaces to handle I/O.
  86357. *
  86358. * Originally the metadata interfaces required filenames as the way of
  86359. * specifying FLAC files to operate on. This is problematic in some
  86360. * environments so there is an additional option to specify a set of
  86361. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86362. *
  86363. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86364. * opaque structure for a data source.
  86365. *
  86366. * The callback function prototypes are similar (but not identical) to the
  86367. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86368. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86369. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86370. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86371. * is required. \warning You generally CANNOT directly use fseek or ftell
  86372. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86373. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86374. * large files. You will have to find an equivalent function (e.g. ftello),
  86375. * or write a wrapper. The same is true for feof() since this is usually
  86376. * implemented as a macro, not as a function whose address can be taken.
  86377. *
  86378. * \{
  86379. */
  86380. #ifdef __cplusplus
  86381. extern "C" {
  86382. #endif
  86383. /** This is the opaque handle type used by the callbacks. Typically
  86384. * this is a \c FILE* or address of a file descriptor.
  86385. */
  86386. typedef void* FLAC__IOHandle;
  86387. /** Signature for the read callback.
  86388. * The signature and semantics match POSIX fread() implementations
  86389. * and can generally be used interchangeably.
  86390. *
  86391. * \param ptr The address of the read buffer.
  86392. * \param size The size of the records to be read.
  86393. * \param nmemb The number of records to be read.
  86394. * \param handle The handle to the data source.
  86395. * \retval size_t
  86396. * The number of records read.
  86397. */
  86398. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86399. /** Signature for the write callback.
  86400. * The signature and semantics match POSIX fwrite() implementations
  86401. * and can generally be used interchangeably.
  86402. *
  86403. * \param ptr The address of the write buffer.
  86404. * \param size The size of the records to be written.
  86405. * \param nmemb The number of records to be written.
  86406. * \param handle The handle to the data source.
  86407. * \retval size_t
  86408. * The number of records written.
  86409. */
  86410. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86411. /** Signature for the seek callback.
  86412. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86413. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86414. * and 32-bits wide.
  86415. *
  86416. * \param handle The handle to the data source.
  86417. * \param offset The new position, relative to \a whence
  86418. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86419. * \retval int
  86420. * \c 0 on success, \c -1 on error.
  86421. */
  86422. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86423. /** Signature for the tell callback.
  86424. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86425. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86426. * and 32-bits wide.
  86427. *
  86428. * \param handle The handle to the data source.
  86429. * \retval FLAC__int64
  86430. * The current position on success, \c -1 on error.
  86431. */
  86432. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86433. /** Signature for the EOF callback.
  86434. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86435. * on many systems, feof() is a macro, so in this case a wrapper function
  86436. * must be provided instead.
  86437. *
  86438. * \param handle The handle to the data source.
  86439. * \retval int
  86440. * \c 0 if not at end of file, nonzero if at end of file.
  86441. */
  86442. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86443. /** Signature for the close callback.
  86444. * The signature and semantics match POSIX fclose() implementations
  86445. * and can generally be used interchangeably.
  86446. *
  86447. * \param handle The handle to the data source.
  86448. * \retval int
  86449. * \c 0 on success, \c EOF on error.
  86450. */
  86451. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86452. /** A structure for holding a set of callbacks.
  86453. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86454. * describe which of the callbacks are required. The ones that are not
  86455. * required may be set to NULL.
  86456. *
  86457. * If the seek requirement for an interface is optional, you can signify that
  86458. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86459. */
  86460. typedef struct {
  86461. FLAC__IOCallback_Read read;
  86462. FLAC__IOCallback_Write write;
  86463. FLAC__IOCallback_Seek seek;
  86464. FLAC__IOCallback_Tell tell;
  86465. FLAC__IOCallback_Eof eof;
  86466. FLAC__IOCallback_Close close;
  86467. } FLAC__IOCallbacks;
  86468. /* \} */
  86469. #ifdef __cplusplus
  86470. }
  86471. #endif
  86472. #endif
  86473. /*** End of inlined file: callback.h ***/
  86474. /*** Start of inlined file: format.h ***/
  86475. #ifndef FLAC__FORMAT_H
  86476. #define FLAC__FORMAT_H
  86477. #ifdef __cplusplus
  86478. extern "C" {
  86479. #endif
  86480. /** \file include/FLAC/format.h
  86481. *
  86482. * \brief
  86483. * This module contains structure definitions for the representation
  86484. * of FLAC format components in memory. These are the basic
  86485. * structures used by the rest of the interfaces.
  86486. *
  86487. * See the detailed documentation in the
  86488. * \link flac_format format \endlink module.
  86489. */
  86490. /** \defgroup flac_format FLAC/format.h: format components
  86491. * \ingroup flac
  86492. *
  86493. * \brief
  86494. * This module contains structure definitions for the representation
  86495. * of FLAC format components in memory. These are the basic
  86496. * structures used by the rest of the interfaces.
  86497. *
  86498. * First, you should be familiar with the
  86499. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86500. * follow directly from the specification. As a user of libFLAC, the
  86501. * interesting parts really are the structures that describe the frame
  86502. * header and metadata blocks.
  86503. *
  86504. * The format structures here are very primitive, designed to store
  86505. * information in an efficient way. Reading information from the
  86506. * structures is easy but creating or modifying them directly is
  86507. * more complex. For the most part, as a user of a library, editing
  86508. * is not necessary; however, for metadata blocks it is, so there are
  86509. * convenience functions provided in the \link flac_metadata metadata
  86510. * module \endlink to simplify the manipulation of metadata blocks.
  86511. *
  86512. * \note
  86513. * It's not the best convention, but symbols ending in _LEN are in bits
  86514. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86515. * global variables because they are usually used when declaring byte
  86516. * arrays and some compilers require compile-time knowledge of array
  86517. * sizes when declared on the stack.
  86518. *
  86519. * \{
  86520. */
  86521. /*
  86522. Most of the values described in this file are defined by the FLAC
  86523. format specification. There is nothing to tune here.
  86524. */
  86525. /** The largest legal metadata type code. */
  86526. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86527. /** The minimum block size, in samples, permitted by the format. */
  86528. #define FLAC__MIN_BLOCK_SIZE (16u)
  86529. /** The maximum block size, in samples, permitted by the format. */
  86530. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86531. /** The maximum block size, in samples, permitted by the FLAC subset for
  86532. * sample rates up to 48kHz. */
  86533. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86534. /** The maximum number of channels permitted by the format. */
  86535. #define FLAC__MAX_CHANNELS (8u)
  86536. /** The minimum sample resolution permitted by the format. */
  86537. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86538. /** The maximum sample resolution permitted by the format. */
  86539. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86540. /** The maximum sample resolution permitted by libFLAC.
  86541. *
  86542. * \warning
  86543. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86544. * the reference encoder/decoder is currently limited to 24 bits because
  86545. * of prevalent 32-bit math, so make sure and use this value when
  86546. * appropriate.
  86547. */
  86548. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86549. /** The maximum sample rate permitted by the format. The value is
  86550. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86551. * as to why.
  86552. */
  86553. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86554. /** The maximum LPC order permitted by the format. */
  86555. #define FLAC__MAX_LPC_ORDER (32u)
  86556. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86557. * up to 48kHz. */
  86558. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86559. /** The minimum quantized linear predictor coefficient precision
  86560. * permitted by the format.
  86561. */
  86562. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86563. /** The maximum quantized linear predictor coefficient precision
  86564. * permitted by the format.
  86565. */
  86566. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86567. /** The maximum order of the fixed predictors permitted by the format. */
  86568. #define FLAC__MAX_FIXED_ORDER (4u)
  86569. /** The maximum Rice partition order permitted by the format. */
  86570. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86571. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86572. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86573. /** The version string of the release, stamped onto the libraries and binaries.
  86574. *
  86575. * \note
  86576. * This does not correspond to the shared library version number, which
  86577. * is used to determine binary compatibility.
  86578. */
  86579. extern FLAC_API const char *FLAC__VERSION_STRING;
  86580. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86581. * This is a NUL-terminated ASCII string; when inserted into the
  86582. * VORBIS_COMMENT the trailing null is stripped.
  86583. */
  86584. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86585. /** The byte string representation of the beginning of a FLAC stream. */
  86586. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86587. /** The 32-bit integer big-endian representation of the beginning of
  86588. * a FLAC stream.
  86589. */
  86590. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86591. /** The length of the FLAC signature in bits. */
  86592. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86593. /** The length of the FLAC signature in bytes. */
  86594. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86595. /*****************************************************************************
  86596. *
  86597. * Subframe structures
  86598. *
  86599. *****************************************************************************/
  86600. /*****************************************************************************/
  86601. /** An enumeration of the available entropy coding methods. */
  86602. typedef enum {
  86603. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86604. /**< Residual is coded by partitioning into contexts, each with it's own
  86605. * 4-bit Rice parameter. */
  86606. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86607. /**< Residual is coded by partitioning into contexts, each with it's own
  86608. * 5-bit Rice parameter. */
  86609. } FLAC__EntropyCodingMethodType;
  86610. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86611. *
  86612. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86613. * give the string equivalent. The contents should not be modified.
  86614. */
  86615. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86616. /** Contents of a Rice partitioned residual
  86617. */
  86618. typedef struct {
  86619. unsigned *parameters;
  86620. /**< The Rice parameters for each context. */
  86621. unsigned *raw_bits;
  86622. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86623. * partitions and zero for unescaped partitions.
  86624. */
  86625. unsigned capacity_by_order;
  86626. /**< The capacity of the \a parameters and \a raw_bits arrays
  86627. * specified as an order, i.e. the number of array elements
  86628. * allocated is 2 ^ \a capacity_by_order.
  86629. */
  86630. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86631. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86632. */
  86633. typedef struct {
  86634. unsigned order;
  86635. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86636. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86637. /**< The context's Rice parameters and/or raw bits. */
  86638. } FLAC__EntropyCodingMethod_PartitionedRice;
  86639. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86640. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86641. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86642. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86643. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86644. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86645. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86646. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86647. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86648. */
  86649. typedef struct {
  86650. FLAC__EntropyCodingMethodType type;
  86651. union {
  86652. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86653. } data;
  86654. } FLAC__EntropyCodingMethod;
  86655. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86656. /*****************************************************************************/
  86657. /** An enumeration of the available subframe types. */
  86658. typedef enum {
  86659. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86660. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86661. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86662. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86663. } FLAC__SubframeType;
  86664. /** Maps a FLAC__SubframeType to a C string.
  86665. *
  86666. * Using a FLAC__SubframeType as the index to this array will
  86667. * give the string equivalent. The contents should not be modified.
  86668. */
  86669. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86670. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86671. */
  86672. typedef struct {
  86673. FLAC__int32 value; /**< The constant signal value. */
  86674. } FLAC__Subframe_Constant;
  86675. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86676. */
  86677. typedef struct {
  86678. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86679. } FLAC__Subframe_Verbatim;
  86680. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86681. */
  86682. typedef struct {
  86683. FLAC__EntropyCodingMethod entropy_coding_method;
  86684. /**< The residual coding method. */
  86685. unsigned order;
  86686. /**< The polynomial order. */
  86687. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86688. /**< Warmup samples to prime the predictor, length == order. */
  86689. const FLAC__int32 *residual;
  86690. /**< The residual signal, length == (blocksize minus order) samples. */
  86691. } FLAC__Subframe_Fixed;
  86692. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86693. */
  86694. typedef struct {
  86695. FLAC__EntropyCodingMethod entropy_coding_method;
  86696. /**< The residual coding method. */
  86697. unsigned order;
  86698. /**< The FIR order. */
  86699. unsigned qlp_coeff_precision;
  86700. /**< Quantized FIR filter coefficient precision in bits. */
  86701. int quantization_level;
  86702. /**< The qlp coeff shift needed. */
  86703. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86704. /**< FIR filter coefficients. */
  86705. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86706. /**< Warmup samples to prime the predictor, length == order. */
  86707. const FLAC__int32 *residual;
  86708. /**< The residual signal, length == (blocksize minus order) samples. */
  86709. } FLAC__Subframe_LPC;
  86710. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86711. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86712. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86713. */
  86714. typedef struct {
  86715. FLAC__SubframeType type;
  86716. union {
  86717. FLAC__Subframe_Constant constant;
  86718. FLAC__Subframe_Fixed fixed;
  86719. FLAC__Subframe_LPC lpc;
  86720. FLAC__Subframe_Verbatim verbatim;
  86721. } data;
  86722. unsigned wasted_bits;
  86723. } FLAC__Subframe;
  86724. /** == 1 (bit)
  86725. *
  86726. * This used to be a zero-padding bit (hence the name
  86727. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86728. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86729. * to mean something else.
  86730. */
  86731. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86732. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86733. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86734. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86735. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86736. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86737. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86738. /*****************************************************************************/
  86739. /*****************************************************************************
  86740. *
  86741. * Frame structures
  86742. *
  86743. *****************************************************************************/
  86744. /** An enumeration of the available channel assignments. */
  86745. typedef enum {
  86746. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86747. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86748. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86749. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86750. } FLAC__ChannelAssignment;
  86751. /** Maps a FLAC__ChannelAssignment to a C string.
  86752. *
  86753. * Using a FLAC__ChannelAssignment as the index to this array will
  86754. * give the string equivalent. The contents should not be modified.
  86755. */
  86756. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86757. /** An enumeration of the possible frame numbering methods. */
  86758. typedef enum {
  86759. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86760. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86761. } FLAC__FrameNumberType;
  86762. /** Maps a FLAC__FrameNumberType to a C string.
  86763. *
  86764. * Using a FLAC__FrameNumberType as the index to this array will
  86765. * give the string equivalent. The contents should not be modified.
  86766. */
  86767. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86768. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86769. */
  86770. typedef struct {
  86771. unsigned blocksize;
  86772. /**< The number of samples per subframe. */
  86773. unsigned sample_rate;
  86774. /**< The sample rate in Hz. */
  86775. unsigned channels;
  86776. /**< The number of channels (== number of subframes). */
  86777. FLAC__ChannelAssignment channel_assignment;
  86778. /**< The channel assignment for the frame. */
  86779. unsigned bits_per_sample;
  86780. /**< The sample resolution. */
  86781. FLAC__FrameNumberType number_type;
  86782. /**< The numbering scheme used for the frame. As a convenience, the
  86783. * decoder will always convert a frame number to a sample number because
  86784. * the rules are complex. */
  86785. union {
  86786. FLAC__uint32 frame_number;
  86787. FLAC__uint64 sample_number;
  86788. } number;
  86789. /**< The frame number or sample number of first sample in frame;
  86790. * use the \a number_type value to determine which to use. */
  86791. FLAC__uint8 crc;
  86792. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86793. * of the raw frame header bytes, meaning everything before the CRC byte
  86794. * including the sync code.
  86795. */
  86796. } FLAC__FrameHeader;
  86797. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86798. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86799. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86800. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86801. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86802. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86803. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86804. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86805. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86806. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86807. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86808. */
  86809. typedef struct {
  86810. FLAC__uint16 crc;
  86811. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86812. * 0) of the bytes before the crc, back to and including the frame header
  86813. * sync code.
  86814. */
  86815. } FLAC__FrameFooter;
  86816. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86817. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86818. */
  86819. typedef struct {
  86820. FLAC__FrameHeader header;
  86821. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86822. FLAC__FrameFooter footer;
  86823. } FLAC__Frame;
  86824. /*****************************************************************************/
  86825. /*****************************************************************************
  86826. *
  86827. * Meta-data structures
  86828. *
  86829. *****************************************************************************/
  86830. /** An enumeration of the available metadata block types. */
  86831. typedef enum {
  86832. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86833. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86834. FLAC__METADATA_TYPE_PADDING = 1,
  86835. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86836. FLAC__METADATA_TYPE_APPLICATION = 2,
  86837. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86838. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86839. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86840. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86841. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86842. FLAC__METADATA_TYPE_CUESHEET = 5,
  86843. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86844. FLAC__METADATA_TYPE_PICTURE = 6,
  86845. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86846. FLAC__METADATA_TYPE_UNDEFINED = 7
  86847. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86848. } FLAC__MetadataType;
  86849. /** Maps a FLAC__MetadataType to a C string.
  86850. *
  86851. * Using a FLAC__MetadataType as the index to this array will
  86852. * give the string equivalent. The contents should not be modified.
  86853. */
  86854. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86855. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86856. */
  86857. typedef struct {
  86858. unsigned min_blocksize, max_blocksize;
  86859. unsigned min_framesize, max_framesize;
  86860. unsigned sample_rate;
  86861. unsigned channels;
  86862. unsigned bits_per_sample;
  86863. FLAC__uint64 total_samples;
  86864. FLAC__byte md5sum[16];
  86865. } FLAC__StreamMetadata_StreamInfo;
  86866. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86867. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86868. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86869. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86870. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86871. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86872. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86873. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86874. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86875. /** The total stream length of the STREAMINFO block in bytes. */
  86876. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86877. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86878. */
  86879. typedef struct {
  86880. int dummy;
  86881. /**< Conceptually this is an empty struct since we don't store the
  86882. * padding bytes. Empty structs are not allowed by some C compilers,
  86883. * hence the dummy.
  86884. */
  86885. } FLAC__StreamMetadata_Padding;
  86886. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86887. */
  86888. typedef struct {
  86889. FLAC__byte id[4];
  86890. FLAC__byte *data;
  86891. } FLAC__StreamMetadata_Application;
  86892. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86893. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86894. */
  86895. typedef struct {
  86896. FLAC__uint64 sample_number;
  86897. /**< The sample number of the target frame. */
  86898. FLAC__uint64 stream_offset;
  86899. /**< The offset, in bytes, of the target frame with respect to
  86900. * beginning of the first frame. */
  86901. unsigned frame_samples;
  86902. /**< The number of samples in the target frame. */
  86903. } FLAC__StreamMetadata_SeekPoint;
  86904. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86905. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86906. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86907. /** The total stream length of a seek point in bytes. */
  86908. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86909. /** The value used in the \a sample_number field of
  86910. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86911. * point (== 0xffffffffffffffff).
  86912. */
  86913. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86914. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86915. *
  86916. * \note From the format specification:
  86917. * - The seek points must be sorted by ascending sample number.
  86918. * - Each seek point's sample number must be the first sample of the
  86919. * target frame.
  86920. * - Each seek point's sample number must be unique within the table.
  86921. * - Existence of a SEEKTABLE block implies a correct setting of
  86922. * total_samples in the stream_info block.
  86923. * - Behavior is undefined when more than one SEEKTABLE block is
  86924. * present in a stream.
  86925. */
  86926. typedef struct {
  86927. unsigned num_points;
  86928. FLAC__StreamMetadata_SeekPoint *points;
  86929. } FLAC__StreamMetadata_SeekTable;
  86930. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86931. *
  86932. * For convenience, the APIs maintain a trailing NUL character at the end of
  86933. * \a entry which is not counted toward \a length, i.e.
  86934. * \code strlen(entry) == length \endcode
  86935. */
  86936. typedef struct {
  86937. FLAC__uint32 length;
  86938. FLAC__byte *entry;
  86939. } FLAC__StreamMetadata_VorbisComment_Entry;
  86940. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86941. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86942. */
  86943. typedef struct {
  86944. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86945. FLAC__uint32 num_comments;
  86946. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86947. } FLAC__StreamMetadata_VorbisComment;
  86948. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86949. /** FLAC CUESHEET track index structure. (See the
  86950. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86951. * the full description of each field.)
  86952. */
  86953. typedef struct {
  86954. FLAC__uint64 offset;
  86955. /**< Offset in samples, relative to the track offset, of the index
  86956. * point.
  86957. */
  86958. FLAC__byte number;
  86959. /**< The index point number. */
  86960. } FLAC__StreamMetadata_CueSheet_Index;
  86961. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86962. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86963. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86964. /** FLAC CUESHEET track structure. (See the
  86965. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86966. * the full description of each field.)
  86967. */
  86968. typedef struct {
  86969. FLAC__uint64 offset;
  86970. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86971. FLAC__byte number;
  86972. /**< The track number. */
  86973. char isrc[13];
  86974. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86975. unsigned type:1;
  86976. /**< The track type: 0 for audio, 1 for non-audio. */
  86977. unsigned pre_emphasis:1;
  86978. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86979. FLAC__byte num_indices;
  86980. /**< The number of track index points. */
  86981. FLAC__StreamMetadata_CueSheet_Index *indices;
  86982. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86983. } FLAC__StreamMetadata_CueSheet_Track;
  86984. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86985. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86986. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86987. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86988. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86989. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86990. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86991. /** FLAC CUESHEET structure. (See the
  86992. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86993. * for the full description of each field.)
  86994. */
  86995. typedef struct {
  86996. char media_catalog_number[129];
  86997. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86998. * general, the media catalog number may be 0 to 128 bytes long; any
  86999. * unused characters should be right-padded with NUL characters.
  87000. */
  87001. FLAC__uint64 lead_in;
  87002. /**< The number of lead-in samples. */
  87003. FLAC__bool is_cd;
  87004. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87005. unsigned num_tracks;
  87006. /**< The number of tracks. */
  87007. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87008. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87009. } FLAC__StreamMetadata_CueSheet;
  87010. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87011. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87012. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87013. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87014. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87015. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87016. typedef enum {
  87017. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87018. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87019. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87020. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87021. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87022. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87023. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87024. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87025. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87026. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87027. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87028. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87029. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87030. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87031. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87032. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87033. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87034. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87035. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87036. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87037. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87038. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87039. } FLAC__StreamMetadata_Picture_Type;
  87040. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87041. *
  87042. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87043. * will give the string equivalent. The contents should not be
  87044. * modified.
  87045. */
  87046. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87047. /** FLAC PICTURE structure. (See the
  87048. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87049. * for the full description of each field.)
  87050. */
  87051. typedef struct {
  87052. FLAC__StreamMetadata_Picture_Type type;
  87053. /**< The kind of picture stored. */
  87054. char *mime_type;
  87055. /**< Picture data's MIME type, in ASCII printable characters
  87056. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87057. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87058. * MIME type of '-->' is also allowed, in which case the picture
  87059. * data should be a complete URL. In file storage, the MIME type is
  87060. * stored as a 32-bit length followed by the ASCII string with no NUL
  87061. * terminator, but is converted to a plain C string in this structure
  87062. * for convenience.
  87063. */
  87064. FLAC__byte *description;
  87065. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87066. * the description is stored as a 32-bit length followed by the UTF-8
  87067. * string with no NUL terminator, but is converted to a plain C string
  87068. * in this structure for convenience.
  87069. */
  87070. FLAC__uint32 width;
  87071. /**< Picture's width in pixels. */
  87072. FLAC__uint32 height;
  87073. /**< Picture's height in pixels. */
  87074. FLAC__uint32 depth;
  87075. /**< Picture's color depth in bits-per-pixel. */
  87076. FLAC__uint32 colors;
  87077. /**< For indexed palettes (like GIF), picture's number of colors (the
  87078. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87079. */
  87080. FLAC__uint32 data_length;
  87081. /**< Length of binary picture data in bytes. */
  87082. FLAC__byte *data;
  87083. /**< Binary picture data. */
  87084. } FLAC__StreamMetadata_Picture;
  87085. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87086. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87087. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87088. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87089. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87090. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87091. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87092. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87093. /** Structure that is used when a metadata block of unknown type is loaded.
  87094. * The contents are opaque. The structure is used only internally to
  87095. * correctly handle unknown metadata.
  87096. */
  87097. typedef struct {
  87098. FLAC__byte *data;
  87099. } FLAC__StreamMetadata_Unknown;
  87100. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87101. */
  87102. typedef struct {
  87103. FLAC__MetadataType type;
  87104. /**< The type of the metadata block; used determine which member of the
  87105. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87106. * then \a data.unknown must be used. */
  87107. FLAC__bool is_last;
  87108. /**< \c true if this metadata block is the last, else \a false */
  87109. unsigned length;
  87110. /**< Length, in bytes, of the block data as it appears in the stream. */
  87111. union {
  87112. FLAC__StreamMetadata_StreamInfo stream_info;
  87113. FLAC__StreamMetadata_Padding padding;
  87114. FLAC__StreamMetadata_Application application;
  87115. FLAC__StreamMetadata_SeekTable seek_table;
  87116. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87117. FLAC__StreamMetadata_CueSheet cue_sheet;
  87118. FLAC__StreamMetadata_Picture picture;
  87119. FLAC__StreamMetadata_Unknown unknown;
  87120. } data;
  87121. /**< Polymorphic block data; use the \a type value to determine which
  87122. * to use. */
  87123. } FLAC__StreamMetadata;
  87124. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87125. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87126. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87127. /** The total stream length of a metadata block header in bytes. */
  87128. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87129. /*****************************************************************************/
  87130. /*****************************************************************************
  87131. *
  87132. * Utility functions
  87133. *
  87134. *****************************************************************************/
  87135. /** Tests that a sample rate is valid for FLAC.
  87136. *
  87137. * \param sample_rate The sample rate to test for compliance.
  87138. * \retval FLAC__bool
  87139. * \c true if the given sample rate conforms to the specification, else
  87140. * \c false.
  87141. */
  87142. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87143. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87144. * for valid sample rates are slightly more complex since the rate has to
  87145. * be expressible completely in the frame header.
  87146. *
  87147. * \param sample_rate The sample rate to test for compliance.
  87148. * \retval FLAC__bool
  87149. * \c true if the given sample rate conforms to the specification for the
  87150. * subset, else \c false.
  87151. */
  87152. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87153. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87154. * comment specification.
  87155. *
  87156. * Vorbis comment names must be composed only of characters from
  87157. * [0x20-0x3C,0x3E-0x7D].
  87158. *
  87159. * \param name A NUL-terminated string to be checked.
  87160. * \assert
  87161. * \code name != NULL \endcode
  87162. * \retval FLAC__bool
  87163. * \c false if entry name is illegal, else \c true.
  87164. */
  87165. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87166. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87167. * comment specification.
  87168. *
  87169. * Vorbis comment values must be valid UTF-8 sequences.
  87170. *
  87171. * \param value A string to be checked.
  87172. * \param length A the length of \a value in bytes. May be
  87173. * \c (unsigned)(-1) to indicate that \a value is a plain
  87174. * UTF-8 NUL-terminated string.
  87175. * \assert
  87176. * \code value != NULL \endcode
  87177. * \retval FLAC__bool
  87178. * \c false if entry name is illegal, else \c true.
  87179. */
  87180. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87181. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87182. * comment specification.
  87183. *
  87184. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87185. * 'value' must be legal according to
  87186. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87187. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87188. *
  87189. * \param entry An entry to be checked.
  87190. * \param length The length of \a entry in bytes.
  87191. * \assert
  87192. * \code value != NULL \endcode
  87193. * \retval FLAC__bool
  87194. * \c false if entry name is illegal, else \c true.
  87195. */
  87196. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87197. /** Check a seek table to see if it conforms to the FLAC specification.
  87198. * See the format specification for limits on the contents of the
  87199. * seek table.
  87200. *
  87201. * \param seek_table A pointer to a seek table to be checked.
  87202. * \assert
  87203. * \code seek_table != NULL \endcode
  87204. * \retval FLAC__bool
  87205. * \c false if seek table is illegal, else \c true.
  87206. */
  87207. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87208. /** Sort a seek table's seek points according to the format specification.
  87209. * This includes a "unique-ification" step to remove duplicates, i.e.
  87210. * seek points with identical \a sample_number values. Duplicate seek
  87211. * points are converted into placeholder points and sorted to the end of
  87212. * the table.
  87213. *
  87214. * \param seek_table A pointer to a seek table to be sorted.
  87215. * \assert
  87216. * \code seek_table != NULL \endcode
  87217. * \retval unsigned
  87218. * The number of duplicate seek points converted into placeholders.
  87219. */
  87220. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87221. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87222. * See the format specification for limits on the contents of the
  87223. * cue sheet.
  87224. *
  87225. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87226. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87227. * stringent requirements for a CD-DA (audio) disc.
  87228. * \param violation Address of a pointer to a string. If there is a
  87229. * violation, a pointer to a string explanation of the
  87230. * violation will be returned here. \a violation may be
  87231. * \c NULL if you don't need the returned string. Do not
  87232. * free the returned string; it will always point to static
  87233. * data.
  87234. * \assert
  87235. * \code cue_sheet != NULL \endcode
  87236. * \retval FLAC__bool
  87237. * \c false if cue sheet is illegal, else \c true.
  87238. */
  87239. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87240. /** Check picture data to see if it conforms to the FLAC specification.
  87241. * See the format specification for limits on the contents of the
  87242. * PICTURE block.
  87243. *
  87244. * \param picture A pointer to existing picture data to be checked.
  87245. * \param violation Address of a pointer to a string. If there is a
  87246. * violation, a pointer to a string explanation of the
  87247. * violation will be returned here. \a violation may be
  87248. * \c NULL if you don't need the returned string. Do not
  87249. * free the returned string; it will always point to static
  87250. * data.
  87251. * \assert
  87252. * \code picture != NULL \endcode
  87253. * \retval FLAC__bool
  87254. * \c false if picture data is illegal, else \c true.
  87255. */
  87256. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87257. /* \} */
  87258. #ifdef __cplusplus
  87259. }
  87260. #endif
  87261. #endif
  87262. /*** End of inlined file: format.h ***/
  87263. /*** Start of inlined file: metadata.h ***/
  87264. #ifndef FLAC__METADATA_H
  87265. #define FLAC__METADATA_H
  87266. #include <sys/types.h> /* for off_t */
  87267. /* --------------------------------------------------------------------
  87268. (For an example of how all these routines are used, see the source
  87269. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87270. metaflac in src/metaflac/)
  87271. ------------------------------------------------------------------*/
  87272. /** \file include/FLAC/metadata.h
  87273. *
  87274. * \brief
  87275. * This module provides functions for creating and manipulating FLAC
  87276. * metadata blocks in memory, and three progressively more powerful
  87277. * interfaces for traversing and editing metadata in FLAC files.
  87278. *
  87279. * See the detailed documentation for each interface in the
  87280. * \link flac_metadata metadata \endlink module.
  87281. */
  87282. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87283. * \ingroup flac
  87284. *
  87285. * \brief
  87286. * This module provides functions for creating and manipulating FLAC
  87287. * metadata blocks in memory, and three progressively more powerful
  87288. * interfaces for traversing and editing metadata in native FLAC files.
  87289. * Note that currently only the Chain interface (level 2) supports Ogg
  87290. * FLAC files, and it is read-only i.e. no writing back changed
  87291. * metadata to file.
  87292. *
  87293. * There are three metadata interfaces of increasing complexity:
  87294. *
  87295. * Level 0:
  87296. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87297. * PICTURE blocks.
  87298. *
  87299. * Level 1:
  87300. * Read-write access to all metadata blocks. This level is write-
  87301. * efficient in most cases (more on this below), and uses less memory
  87302. * than level 2.
  87303. *
  87304. * Level 2:
  87305. * Read-write access to all metadata blocks. This level is write-
  87306. * efficient in all cases, but uses more memory since all metadata for
  87307. * the whole file is read into memory and manipulated before writing
  87308. * out again.
  87309. *
  87310. * What do we mean by efficient? Since FLAC metadata appears at the
  87311. * beginning of the file, when writing metadata back to a FLAC file
  87312. * it is possible to grow or shrink the metadata such that the entire
  87313. * file must be rewritten. However, if the size remains the same during
  87314. * changes or PADDING blocks are utilized, only the metadata needs to be
  87315. * overwritten, which is much faster.
  87316. *
  87317. * Efficient means the whole file is rewritten at most one time, and only
  87318. * when necessary. Level 1 is not efficient only in the case that you
  87319. * cause more than one metadata block to grow or shrink beyond what can
  87320. * be accomodated by padding. In this case you should probably use level
  87321. * 2, which allows you to edit all the metadata for a file in memory and
  87322. * write it out all at once.
  87323. *
  87324. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87325. * front of the file.
  87326. *
  87327. * All levels access files via their filenames. In addition, level 2
  87328. * has additional alternative read and write functions that take an I/O
  87329. * handle and callbacks, for situations where access by filename is not
  87330. * possible.
  87331. *
  87332. * In addition to the three interfaces, this module defines functions for
  87333. * creating and manipulating various metadata objects in memory. As we see
  87334. * from the Format module, FLAC metadata blocks in memory are very primitive
  87335. * structures for storing information in an efficient way. Reading
  87336. * information from the structures is easy but creating or modifying them
  87337. * directly is more complex. The metadata object routines here facilitate
  87338. * this by taking care of the consistency and memory management drudgery.
  87339. *
  87340. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87341. * metadata however, you will not probably not need these.
  87342. *
  87343. * From a dependency standpoint, none of the encoders or decoders require
  87344. * the metadata module. This is so that embedded users can strip out the
  87345. * metadata module from libFLAC to reduce the size and complexity.
  87346. */
  87347. #ifdef __cplusplus
  87348. extern "C" {
  87349. #endif
  87350. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87351. * \ingroup flac_metadata
  87352. *
  87353. * \brief
  87354. * The level 0 interface consists of individual routines to read the
  87355. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87356. * only a filename.
  87357. *
  87358. * They try to skip any ID3v2 tag at the head of the file.
  87359. *
  87360. * \{
  87361. */
  87362. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87363. * will try to skip any ID3v2 tag at the head of the file.
  87364. *
  87365. * \param filename The path to the FLAC file to read.
  87366. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87367. * FLAC__StreamMetadata is a simple structure with no
  87368. * memory allocation involved, you pass the address of
  87369. * an existing structure. It need not be initialized.
  87370. * \assert
  87371. * \code filename != NULL \endcode
  87372. * \code streaminfo != NULL \endcode
  87373. * \retval FLAC__bool
  87374. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87375. * \c false if there was a memory allocation error, a file decoder error,
  87376. * or the file contained no STREAMINFO block. (A memory allocation error
  87377. * is possible because this function must set up a file decoder.)
  87378. */
  87379. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87380. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87381. * function will try to skip any ID3v2 tag at the head of the file.
  87382. *
  87383. * \param filename The path to the FLAC file to read.
  87384. * \param tags The address where the returned pointer will be
  87385. * stored. The \a tags object must be deleted by
  87386. * the caller using FLAC__metadata_object_delete().
  87387. * \assert
  87388. * \code filename != NULL \endcode
  87389. * \code tags != NULL \endcode
  87390. * \retval FLAC__bool
  87391. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87392. * and \a *tags will be set to the address of the metadata structure.
  87393. * Returns \c false if there was a memory allocation error, a file
  87394. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87395. * \a *tags will be set to \c NULL.
  87396. */
  87397. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87398. /** Read the CUESHEET metadata block of the given FLAC file. This
  87399. * function will try to skip any ID3v2 tag at the head of the file.
  87400. *
  87401. * \param filename The path to the FLAC file to read.
  87402. * \param cuesheet The address where the returned pointer will be
  87403. * stored. The \a cuesheet object must be deleted by
  87404. * the caller using FLAC__metadata_object_delete().
  87405. * \assert
  87406. * \code filename != NULL \endcode
  87407. * \code cuesheet != NULL \endcode
  87408. * \retval FLAC__bool
  87409. * \c true if a valid CUESHEET block was read from \a filename,
  87410. * and \a *cuesheet will be set to the address of the metadata
  87411. * structure. Returns \c false if there was a memory allocation
  87412. * error, a file decoder error, or the file contained no CUESHEET
  87413. * block, and \a *cuesheet will be set to \c NULL.
  87414. */
  87415. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87416. /** Read a PICTURE metadata block of the given FLAC file. This
  87417. * function will try to skip any ID3v2 tag at the head of the file.
  87418. * Since there can be more than one PICTURE block in a file, this
  87419. * function takes a number of parameters that act as constraints to
  87420. * the search. The PICTURE block with the largest area matching all
  87421. * the constraints will be returned, or \a *picture will be set to
  87422. * \c NULL if there was no such block.
  87423. *
  87424. * \param filename The path to the FLAC file to read.
  87425. * \param picture The address where the returned pointer will be
  87426. * stored. The \a picture object must be deleted by
  87427. * the caller using FLAC__metadata_object_delete().
  87428. * \param type The desired picture type. Use \c -1 to mean
  87429. * "any type".
  87430. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87431. * string will be matched exactly. Use \c NULL to
  87432. * mean "any MIME type".
  87433. * \param description The desired description. The string will be
  87434. * matched exactly. Use \c NULL to mean "any
  87435. * description".
  87436. * \param max_width The maximum width in pixels desired. Use
  87437. * \c (unsigned)(-1) to mean "any width".
  87438. * \param max_height The maximum height in pixels desired. Use
  87439. * \c (unsigned)(-1) to mean "any height".
  87440. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87441. * Use \c (unsigned)(-1) to mean "any depth".
  87442. * \param max_colors The maximum number of colors desired. Use
  87443. * \c (unsigned)(-1) to mean "any number of colors".
  87444. * \assert
  87445. * \code filename != NULL \endcode
  87446. * \code picture != NULL \endcode
  87447. * \retval FLAC__bool
  87448. * \c true if a valid PICTURE block was read from \a filename,
  87449. * and \a *picture will be set to the address of the metadata
  87450. * structure. Returns \c false if there was a memory allocation
  87451. * error, a file decoder error, or the file contained no PICTURE
  87452. * block, and \a *picture will be set to \c NULL.
  87453. */
  87454. 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);
  87455. /* \} */
  87456. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87457. * \ingroup flac_metadata
  87458. *
  87459. * \brief
  87460. * The level 1 interface provides read-write access to FLAC file metadata and
  87461. * operates directly on the FLAC file.
  87462. *
  87463. * The general usage of this interface is:
  87464. *
  87465. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87466. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87467. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87468. * see if the file is writable, or only read access is allowed.
  87469. * - Use FLAC__metadata_simple_iterator_next() and
  87470. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87471. * This is does not read the actual blocks themselves.
  87472. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87473. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87474. * forward from the front of the file.
  87475. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87476. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87477. * the current iterator position. The returned object is yours to modify
  87478. * and free.
  87479. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87480. * back. You must have write permission to the original file. Make sure to
  87481. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87482. * below.
  87483. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87484. * Use the object creation functions from
  87485. * \link flac_metadata_object here \endlink to generate new objects.
  87486. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87487. * currently referred to by the iterator, or replace it with padding.
  87488. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87489. * finished.
  87490. *
  87491. * \note
  87492. * The FLAC file remains open the whole time between
  87493. * FLAC__metadata_simple_iterator_init() and
  87494. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87495. * the file during this time.
  87496. *
  87497. * \note
  87498. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87499. * FLAC__StreamMetadata objects. These are managed automatically.
  87500. *
  87501. * \note
  87502. * If any of the modification functions
  87503. * (FLAC__metadata_simple_iterator_set_block(),
  87504. * FLAC__metadata_simple_iterator_delete_block(),
  87505. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87506. * you should delete the iterator as it may no longer be valid.
  87507. *
  87508. * \{
  87509. */
  87510. struct FLAC__Metadata_SimpleIterator;
  87511. /** The opaque structure definition for the level 1 iterator type.
  87512. * See the
  87513. * \link flac_metadata_level1 metadata level 1 module \endlink
  87514. * for a detailed description.
  87515. */
  87516. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87517. /** Status type for FLAC__Metadata_SimpleIterator.
  87518. *
  87519. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87520. */
  87521. typedef enum {
  87522. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87523. /**< The iterator is in the normal OK state */
  87524. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87525. /**< The data passed into a function violated the function's usage criteria */
  87526. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87527. /**< The iterator could not open the target file */
  87528. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87529. /**< The iterator could not find the FLAC signature at the start of the file */
  87530. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87531. /**< The iterator tried to write to a file that was not writable */
  87532. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87533. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87534. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87535. /**< The iterator encountered an error while reading the FLAC file */
  87536. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87537. /**< The iterator encountered an error while seeking in the FLAC file */
  87538. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87539. /**< The iterator encountered an error while writing the FLAC file */
  87540. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87541. /**< The iterator encountered an error renaming the FLAC file */
  87542. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87543. /**< The iterator encountered an error removing the temporary file */
  87544. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87545. /**< Memory allocation failed */
  87546. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87547. /**< The caller violated an assertion or an unexpected error occurred */
  87548. } FLAC__Metadata_SimpleIteratorStatus;
  87549. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87550. *
  87551. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87552. * will give the string equivalent. The contents should not be modified.
  87553. */
  87554. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87555. /** Create a new iterator instance.
  87556. *
  87557. * \retval FLAC__Metadata_SimpleIterator*
  87558. * \c NULL if there was an error allocating memory, else the new instance.
  87559. */
  87560. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87561. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87562. *
  87563. * \param iterator A pointer to an existing iterator.
  87564. * \assert
  87565. * \code iterator != NULL \endcode
  87566. */
  87567. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87568. /** Get the current status of the iterator. Call this after a function
  87569. * returns \c false to get the reason for the error. Also resets the status
  87570. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87571. *
  87572. * \param iterator A pointer to an existing iterator.
  87573. * \assert
  87574. * \code iterator != NULL \endcode
  87575. * \retval FLAC__Metadata_SimpleIteratorStatus
  87576. * The current status of the iterator.
  87577. */
  87578. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87579. /** Initialize the iterator to point to the first metadata block in the
  87580. * given FLAC file.
  87581. *
  87582. * \param iterator A pointer to an existing iterator.
  87583. * \param filename The path to the FLAC file.
  87584. * \param read_only If \c true, the FLAC file will be opened
  87585. * in read-only mode; if \c false, the FLAC
  87586. * file will be opened for edit even if no
  87587. * edits are performed.
  87588. * \param preserve_file_stats If \c true, the owner and modification
  87589. * time will be preserved even if the FLAC
  87590. * file is written to.
  87591. * \assert
  87592. * \code iterator != NULL \endcode
  87593. * \code filename != NULL \endcode
  87594. * \retval FLAC__bool
  87595. * \c false if a memory allocation error occurs, the file can't be
  87596. * opened, or another error occurs, else \c true.
  87597. */
  87598. 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);
  87599. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87600. * FLAC__metadata_simple_iterator_set_block() and
  87601. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87602. *
  87603. * \param iterator A pointer to an existing iterator.
  87604. * \assert
  87605. * \code iterator != NULL \endcode
  87606. * \retval FLAC__bool
  87607. * See above.
  87608. */
  87609. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87610. /** Moves the iterator forward one metadata block, returning \c false if
  87611. * already at the end.
  87612. *
  87613. * \param iterator A pointer to an existing initialized iterator.
  87614. * \assert
  87615. * \code iterator != NULL \endcode
  87616. * \a iterator has been successfully initialized with
  87617. * FLAC__metadata_simple_iterator_init()
  87618. * \retval FLAC__bool
  87619. * \c false if already at the last metadata block of the chain, else
  87620. * \c true.
  87621. */
  87622. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87623. /** Moves the iterator backward one metadata block, returning \c false if
  87624. * already at the beginning.
  87625. *
  87626. * \param iterator A pointer to an existing initialized iterator.
  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 false if already at the first metadata block of the chain, else
  87633. * \c true.
  87634. */
  87635. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87636. /** Returns a flag telling if the current metadata block is the last.
  87637. *
  87638. * \param iterator A pointer to an existing initialized iterator.
  87639. * \assert
  87640. * \code iterator != NULL \endcode
  87641. * \a iterator has been successfully initialized with
  87642. * FLAC__metadata_simple_iterator_init()
  87643. * \retval FLAC__bool
  87644. * \c true if the current metadata block is the last in the file,
  87645. * else \c false.
  87646. */
  87647. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87648. /** Get the offset of the metadata block at the current position. This
  87649. * avoids reading the actual block data which can save time for large
  87650. * blocks.
  87651. *
  87652. * \param iterator A pointer to an existing initialized iterator.
  87653. * \assert
  87654. * \code iterator != NULL \endcode
  87655. * \a iterator has been successfully initialized with
  87656. * FLAC__metadata_simple_iterator_init()
  87657. * \retval off_t
  87658. * The offset of the metadata block at the current iterator position.
  87659. * This is the byte offset relative to the beginning of the file of
  87660. * the current metadata block's header.
  87661. */
  87662. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87663. /** Get the type of the metadata block at the current position. This
  87664. * avoids reading the actual block data which can save time for large
  87665. * blocks.
  87666. *
  87667. * \param iterator A pointer to an existing initialized iterator.
  87668. * \assert
  87669. * \code iterator != NULL \endcode
  87670. * \a iterator has been successfully initialized with
  87671. * FLAC__metadata_simple_iterator_init()
  87672. * \retval FLAC__MetadataType
  87673. * The type of the metadata block at the current iterator position.
  87674. */
  87675. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87676. /** Get the length of the metadata block at the current position. This
  87677. * avoids reading the actual block data which can save time for large
  87678. * blocks.
  87679. *
  87680. * \param iterator A pointer to an existing initialized iterator.
  87681. * \assert
  87682. * \code iterator != NULL \endcode
  87683. * \a iterator has been successfully initialized with
  87684. * FLAC__metadata_simple_iterator_init()
  87685. * \retval unsigned
  87686. * The length of the metadata block at the current iterator position.
  87687. * The is same length as that in the
  87688. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87689. * i.e. the length of the metadata body that follows the header.
  87690. */
  87691. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87692. /** Get the application ID of the \c APPLICATION block at the current
  87693. * position. This avoids reading the actual block data which can save
  87694. * time for large blocks.
  87695. *
  87696. * \param iterator A pointer to an existing initialized iterator.
  87697. * \param id A pointer to a buffer of at least \c 4 bytes where
  87698. * the ID will be stored.
  87699. * \assert
  87700. * \code iterator != NULL \endcode
  87701. * \code id != NULL \endcode
  87702. * \a iterator has been successfully initialized with
  87703. * FLAC__metadata_simple_iterator_init()
  87704. * \retval FLAC__bool
  87705. * \c true if the ID was successfully read, else \c false, in which
  87706. * case you should check FLAC__metadata_simple_iterator_status() to
  87707. * find out why. If the status is
  87708. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87709. * current metadata block is not an \c APPLICATION block. Otherwise
  87710. * if the status is
  87711. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87712. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87713. * occurred and the iterator can no longer be used.
  87714. */
  87715. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87716. /** Get the metadata block at the current position. You can modify the
  87717. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87718. * write it back to the FLAC file.
  87719. *
  87720. * You must call FLAC__metadata_object_delete() on the returned object
  87721. * when you are finished with it.
  87722. *
  87723. * \param iterator A pointer to an existing initialized iterator.
  87724. * \assert
  87725. * \code iterator != NULL \endcode
  87726. * \a iterator has been successfully initialized with
  87727. * FLAC__metadata_simple_iterator_init()
  87728. * \retval FLAC__StreamMetadata*
  87729. * The current metadata block, or \c NULL if there was a memory
  87730. * allocation error.
  87731. */
  87732. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87733. /** Write a block back to the FLAC file. This function tries to be
  87734. * as efficient as possible; how the block is actually written is
  87735. * shown by the following:
  87736. *
  87737. * Existing block is a STREAMINFO block and the new block is a
  87738. * STREAMINFO block: the new block is written in place. Make sure
  87739. * you know what you're doing when changing the values of a
  87740. * STREAMINFO block.
  87741. *
  87742. * Existing block is a STREAMINFO block and the new block is a
  87743. * not a STREAMINFO block: this is an error since the first block
  87744. * must be a STREAMINFO block. Returns \c false without altering the
  87745. * file.
  87746. *
  87747. * Existing block is not a STREAMINFO block and the new block is a
  87748. * STREAMINFO block: this is an error since there may be only one
  87749. * STREAMINFO block. Returns \c false without altering the file.
  87750. *
  87751. * Existing block and new block are the same length: the existing
  87752. * block will be replaced by the new block, written in place.
  87753. *
  87754. * Existing block is longer than new block: if use_padding is \c true,
  87755. * the existing block will be overwritten in place with the new
  87756. * block followed by a PADDING block, if possible, to make the total
  87757. * size the same as the existing block. Remember that a padding
  87758. * block requires at least four bytes so if the difference in size
  87759. * between the new block and existing block is less than that, the
  87760. * entire file will have to be rewritten, using the new block's
  87761. * exact size. If use_padding is \c false, the entire file will be
  87762. * rewritten, replacing the existing block by the new block.
  87763. *
  87764. * Existing block is shorter than new block: if use_padding is \c true,
  87765. * the function will try and expand the new block into the following
  87766. * PADDING block, if it exists and doing so won't shrink the PADDING
  87767. * block to less than 4 bytes. If there is no following PADDING
  87768. * block, or it will shrink to less than 4 bytes, or use_padding is
  87769. * \c false, the entire file is rewritten, replacing the existing block
  87770. * with the new block. Note that in this case any following PADDING
  87771. * block is preserved as is.
  87772. *
  87773. * After writing the block, the iterator will remain in the same
  87774. * place, i.e. pointing to the new block.
  87775. *
  87776. * \param iterator A pointer to an existing initialized iterator.
  87777. * \param block The block to set.
  87778. * \param use_padding See above.
  87779. * \assert
  87780. * \code iterator != NULL \endcode
  87781. * \a iterator has been successfully initialized with
  87782. * FLAC__metadata_simple_iterator_init()
  87783. * \code block != NULL \endcode
  87784. * \retval FLAC__bool
  87785. * \c true if successful, else \c false.
  87786. */
  87787. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87788. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87789. * except that instead of writing over an existing block, it appends
  87790. * a block after the existing block. \a use_padding is again used to
  87791. * tell the function to try an expand into following padding in an
  87792. * attempt to avoid rewriting the entire file.
  87793. *
  87794. * This function will fail and return \c false if given a STREAMINFO
  87795. * block.
  87796. *
  87797. * After writing the block, the iterator will be pointing to the
  87798. * new block.
  87799. *
  87800. * \param iterator A pointer to an existing initialized iterator.
  87801. * \param block The block to set.
  87802. * \param use_padding See above.
  87803. * \assert
  87804. * \code iterator != NULL \endcode
  87805. * \a iterator has been successfully initialized with
  87806. * FLAC__metadata_simple_iterator_init()
  87807. * \code block != NULL \endcode
  87808. * \retval FLAC__bool
  87809. * \c true if successful, else \c false.
  87810. */
  87811. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87812. /** Deletes the block at the current position. This will cause the
  87813. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87814. * in which case the block will be replaced by an equal-sized PADDING
  87815. * block. The iterator will be left pointing to the block before the
  87816. * one just deleted.
  87817. *
  87818. * You may not delete the STREAMINFO block.
  87819. *
  87820. * \param iterator A pointer to an existing initialized iterator.
  87821. * \param use_padding See above.
  87822. * \assert
  87823. * \code iterator != NULL \endcode
  87824. * \a iterator has been successfully initialized with
  87825. * FLAC__metadata_simple_iterator_init()
  87826. * \retval FLAC__bool
  87827. * \c true if successful, else \c false.
  87828. */
  87829. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87830. /* \} */
  87831. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87832. * \ingroup flac_metadata
  87833. *
  87834. * \brief
  87835. * The level 2 interface provides read-write access to FLAC file metadata;
  87836. * all metadata is read into memory, operated on in memory, and then written
  87837. * to file, which is more efficient than level 1 when editing multiple blocks.
  87838. *
  87839. * Currently Ogg FLAC is supported for read only, via
  87840. * FLAC__metadata_chain_read_ogg() but a subsequent
  87841. * FLAC__metadata_chain_write() will fail.
  87842. *
  87843. * The general usage of this interface is:
  87844. *
  87845. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87846. * linked list of FLAC metadata blocks.
  87847. * - Read all metadata into the the chain from a FLAC file using
  87848. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87849. * check the status.
  87850. * - Optionally, consolidate the padding using
  87851. * FLAC__metadata_chain_merge_padding() or
  87852. * FLAC__metadata_chain_sort_padding().
  87853. * - Create a new iterator using FLAC__metadata_iterator_new()
  87854. * - Initialize the iterator to point to the first element in the chain
  87855. * using FLAC__metadata_iterator_init()
  87856. * - Traverse the chain using FLAC__metadata_iterator_next and
  87857. * FLAC__metadata_iterator_prev().
  87858. * - Get a block for reading or modification using
  87859. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87860. * inside the chain is returned, so the block is yours to modify.
  87861. * Changes will be reflected in the FLAC file when you write the
  87862. * chain. You can also add and delete blocks (see functions below).
  87863. * - When done, write out the chain using FLAC__metadata_chain_write().
  87864. * Make sure to read the whole comment to the function below.
  87865. * - Delete the chain using FLAC__metadata_chain_delete().
  87866. *
  87867. * \note
  87868. * Even though the FLAC file is not open while the chain is being
  87869. * manipulated, you must not alter the file externally during
  87870. * this time. The chain assumes the FLAC file will not change
  87871. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87872. * and FLAC__metadata_chain_write().
  87873. *
  87874. * \note
  87875. * Do not modify the is_last, length, or type fields of returned
  87876. * FLAC__StreamMetadata objects. These are managed automatically.
  87877. *
  87878. * \note
  87879. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87880. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87881. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87882. * become owned by the chain and they will be deleted when the chain is
  87883. * deleted.
  87884. *
  87885. * \{
  87886. */
  87887. struct FLAC__Metadata_Chain;
  87888. /** The opaque structure definition for the level 2 chain type.
  87889. */
  87890. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87891. struct FLAC__Metadata_Iterator;
  87892. /** The opaque structure definition for the level 2 iterator type.
  87893. */
  87894. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87895. typedef enum {
  87896. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87897. /**< The chain is in the normal OK state */
  87898. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87899. /**< The data passed into a function violated the function's usage criteria */
  87900. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87901. /**< The chain could not open the target file */
  87902. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87903. /**< The chain could not find the FLAC signature at the start of the file */
  87904. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87905. /**< The chain tried to write to a file that was not writable */
  87906. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87907. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87908. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87909. /**< The chain encountered an error while reading the FLAC file */
  87910. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87911. /**< The chain encountered an error while seeking in the FLAC file */
  87912. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87913. /**< The chain encountered an error while writing the FLAC file */
  87914. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87915. /**< The chain encountered an error renaming the FLAC file */
  87916. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87917. /**< The chain encountered an error removing the temporary file */
  87918. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87919. /**< Memory allocation failed */
  87920. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87921. /**< The caller violated an assertion or an unexpected error occurred */
  87922. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87923. /**< One or more of the required callbacks was NULL */
  87924. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87925. /**< FLAC__metadata_chain_write() was called on a chain read by
  87926. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87927. * or
  87928. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87929. * was called on a chain read by
  87930. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87931. * Matching read/write methods must always be used. */
  87932. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87933. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87934. * chain write requires a tempfile; use
  87935. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87936. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87937. * called when the chain write does not require a tempfile; use
  87938. * FLAC__metadata_chain_write_with_callbacks() instead.
  87939. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87940. * before writing via callbacks. */
  87941. } FLAC__Metadata_ChainStatus;
  87942. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87943. *
  87944. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87945. * will give the string equivalent. The contents should not be modified.
  87946. */
  87947. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87948. /*********** FLAC__Metadata_Chain ***********/
  87949. /** Create a new chain instance.
  87950. *
  87951. * \retval FLAC__Metadata_Chain*
  87952. * \c NULL if there was an error allocating memory, else the new instance.
  87953. */
  87954. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87955. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87956. *
  87957. * \param chain A pointer to an existing chain.
  87958. * \assert
  87959. * \code chain != NULL \endcode
  87960. */
  87961. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87962. /** Get the current status of the chain. Call this after a function
  87963. * returns \c false to get the reason for the error. Also resets the
  87964. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87965. *
  87966. * \param chain A pointer to an existing chain.
  87967. * \assert
  87968. * \code chain != NULL \endcode
  87969. * \retval FLAC__Metadata_ChainStatus
  87970. * The current status of the chain.
  87971. */
  87972. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87973. /** Read all metadata from a FLAC file into the chain.
  87974. *
  87975. * \param chain A pointer to an existing chain.
  87976. * \param filename The path to the FLAC file to read.
  87977. * \assert
  87978. * \code chain != NULL \endcode
  87979. * \code filename != NULL \endcode
  87980. * \retval FLAC__bool
  87981. * \c true if a valid list of metadata blocks was read from
  87982. * \a filename, else \c false. On failure, check the status with
  87983. * FLAC__metadata_chain_status().
  87984. */
  87985. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87986. /** Read all metadata from an Ogg FLAC file into the chain.
  87987. *
  87988. * \note Ogg FLAC metadata data writing is not supported yet and
  87989. * FLAC__metadata_chain_write() will fail.
  87990. *
  87991. * \param chain A pointer to an existing chain.
  87992. * \param filename The path to the Ogg FLAC file to read.
  87993. * \assert
  87994. * \code chain != NULL \endcode
  87995. * \code filename != NULL \endcode
  87996. * \retval FLAC__bool
  87997. * \c true if a valid list of metadata blocks was read from
  87998. * \a filename, else \c false. On failure, check the status with
  87999. * FLAC__metadata_chain_status().
  88000. */
  88001. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88002. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88003. *
  88004. * The \a handle need only be open for reading, but must be seekable.
  88005. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88006. * for Windows).
  88007. *
  88008. * \param chain A pointer to an existing chain.
  88009. * \param handle The I/O handle of the FLAC stream to read. The
  88010. * handle will NOT be closed after the metadata is read;
  88011. * that is the duty of the caller.
  88012. * \param callbacks
  88013. * A set of callbacks to use for I/O. The mandatory
  88014. * callbacks are \a read, \a seek, and \a tell.
  88015. * \assert
  88016. * \code chain != NULL \endcode
  88017. * \retval FLAC__bool
  88018. * \c true if a valid list of metadata blocks was read from
  88019. * \a handle, else \c false. On failure, check the status with
  88020. * FLAC__metadata_chain_status().
  88021. */
  88022. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88023. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88024. *
  88025. * The \a handle need only be open for reading, but must be seekable.
  88026. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88027. * for Windows).
  88028. *
  88029. * \note Ogg FLAC metadata data writing is not supported yet and
  88030. * FLAC__metadata_chain_write() will fail.
  88031. *
  88032. * \param chain A pointer to an existing chain.
  88033. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88034. * handle will NOT be closed after the metadata is read;
  88035. * that is the duty of the caller.
  88036. * \param callbacks
  88037. * A set of callbacks to use for I/O. The mandatory
  88038. * callbacks are \a read, \a seek, and \a tell.
  88039. * \assert
  88040. * \code chain != NULL \endcode
  88041. * \retval FLAC__bool
  88042. * \c true if a valid list of metadata blocks was read from
  88043. * \a handle, else \c false. On failure, check the status with
  88044. * FLAC__metadata_chain_status().
  88045. */
  88046. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88047. /** Checks if writing the given chain would require the use of a
  88048. * temporary file, or if it could be written in place.
  88049. *
  88050. * Under certain conditions, padding can be utilized so that writing
  88051. * edited metadata back to the FLAC file does not require rewriting the
  88052. * entire file. If rewriting is required, then a temporary workfile is
  88053. * required. When writing metadata using callbacks, you must check
  88054. * this function to know whether to call
  88055. * FLAC__metadata_chain_write_with_callbacks() or
  88056. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88057. * writing with FLAC__metadata_chain_write(), the temporary file is
  88058. * handled internally.
  88059. *
  88060. * \param chain A pointer to an existing chain.
  88061. * \param use_padding
  88062. * Whether or not padding will be allowed to be used
  88063. * during the write. The value of \a use_padding given
  88064. * here must match the value later passed to
  88065. * FLAC__metadata_chain_write_with_callbacks() or
  88066. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88067. * \assert
  88068. * \code chain != NULL \endcode
  88069. * \retval FLAC__bool
  88070. * \c true if writing the current chain would require a tempfile, or
  88071. * \c false if metadata can be written in place.
  88072. */
  88073. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88074. /** Write all metadata out to the FLAC file. This function tries to be as
  88075. * efficient as possible; how the metadata is actually written is shown by
  88076. * the following:
  88077. *
  88078. * If the current chain is the same size as the existing metadata, the new
  88079. * data is written in place.
  88080. *
  88081. * If the current chain is longer than the existing metadata, and
  88082. * \a use_padding is \c true, and the last block is a PADDING block of
  88083. * sufficient length, the function will truncate the final padding block
  88084. * so that the overall size of the metadata is the same as the existing
  88085. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88086. * the above conditions are met, the entire FLAC file must be rewritten.
  88087. * If you want to use padding this way it is a good idea to call
  88088. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88089. * amount of padding to work with, unless you need to preserve ordering
  88090. * of the PADDING blocks for some reason.
  88091. *
  88092. * If the current chain is shorter than the existing metadata, and
  88093. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88094. * is extended to make the overall size the same as the existing data. If
  88095. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88096. * PADDING block is added to the end of the new data to make it the same
  88097. * size as the existing data (if possible, see the note to
  88098. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88099. * and the new data is written in place. If none of the above apply or
  88100. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88101. *
  88102. * If \a preserve_file_stats is \c true, the owner and modification time will
  88103. * be preserved even if the FLAC file is written.
  88104. *
  88105. * For this write function to be used, the chain must have been read with
  88106. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88107. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88108. *
  88109. * \param chain A pointer to an existing chain.
  88110. * \param use_padding See above.
  88111. * \param preserve_file_stats See above.
  88112. * \assert
  88113. * \code chain != NULL \endcode
  88114. * \retval FLAC__bool
  88115. * \c true if the write succeeded, else \c false. On failure,
  88116. * check the status with FLAC__metadata_chain_status().
  88117. */
  88118. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88119. /** Write all metadata out to a FLAC stream via callbacks.
  88120. *
  88121. * (See FLAC__metadata_chain_write() for the details on how padding is
  88122. * used to write metadata in place if possible.)
  88123. *
  88124. * The \a handle must be open for updating and be seekable. The
  88125. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88126. * for Windows).
  88127. *
  88128. * For this write function to be used, the chain must have been read with
  88129. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88130. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88131. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88132. * \c false.
  88133. *
  88134. * \param chain A pointer to an existing chain.
  88135. * \param use_padding See FLAC__metadata_chain_write()
  88136. * \param handle The I/O handle of the FLAC stream to write. The
  88137. * handle will NOT be closed after the metadata is
  88138. * written; that is the duty of the caller.
  88139. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88140. * callbacks are \a write and \a seek.
  88141. * \assert
  88142. * \code chain != NULL \endcode
  88143. * \retval FLAC__bool
  88144. * \c true if the write succeeded, else \c false. On failure,
  88145. * check the status with FLAC__metadata_chain_status().
  88146. */
  88147. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88148. /** Write all metadata out to a FLAC stream via callbacks.
  88149. *
  88150. * (See FLAC__metadata_chain_write() for the details on how padding is
  88151. * used to write metadata in place if possible.)
  88152. *
  88153. * This version of the write-with-callbacks function must be used when
  88154. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88155. * this function, you must supply an I/O handle corresponding to the
  88156. * FLAC file to edit, and a temporary handle to which the new FLAC
  88157. * file will be written. It is the caller's job to move this temporary
  88158. * FLAC file on top of the original FLAC file to complete the metadata
  88159. * edit.
  88160. *
  88161. * The \a handle must be open for reading and be seekable. The
  88162. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88163. * for Windows).
  88164. *
  88165. * The \a temp_handle must be open for writing. The
  88166. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88167. * for Windows). It should be an empty stream, or at least positioned
  88168. * at the start-of-file (in which case it is the caller's duty to
  88169. * truncate it on return).
  88170. *
  88171. * For this write function to be used, the chain must have been read with
  88172. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88173. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88174. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88175. * \c true.
  88176. *
  88177. * \param chain A pointer to an existing chain.
  88178. * \param use_padding See FLAC__metadata_chain_write()
  88179. * \param handle The I/O handle of the original FLAC stream to read.
  88180. * The handle will NOT be closed after the metadata is
  88181. * written; that is the duty of the caller.
  88182. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88183. * The mandatory callbacks are \a read, \a seek, and
  88184. * \a eof.
  88185. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88186. * handle will NOT be closed after the metadata is
  88187. * written; that is the duty of the caller.
  88188. * \param temp_callbacks
  88189. * A set of callbacks to use for I/O on temp_handle.
  88190. * The only mandatory callback is \a write.
  88191. * \assert
  88192. * \code chain != NULL \endcode
  88193. * \retval FLAC__bool
  88194. * \c true if the write succeeded, else \c false. On failure,
  88195. * check the status with FLAC__metadata_chain_status().
  88196. */
  88197. 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);
  88198. /** Merge adjacent PADDING blocks into a single block.
  88199. *
  88200. * \note This function does not write to the FLAC file, it only
  88201. * modifies the chain.
  88202. *
  88203. * \warning Any iterator on the current chain will become invalid after this
  88204. * call. You should delete the iterator and get a new one.
  88205. *
  88206. * \param chain A pointer to an existing chain.
  88207. * \assert
  88208. * \code chain != NULL \endcode
  88209. */
  88210. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88211. /** This function will move all PADDING blocks to the end on the metadata,
  88212. * then merge them into a single block.
  88213. *
  88214. * \note This function does not write to the FLAC file, it only
  88215. * modifies the chain.
  88216. *
  88217. * \warning Any iterator on the current chain will become invalid after this
  88218. * call. You should delete the iterator and get a new one.
  88219. *
  88220. * \param chain A pointer to an existing chain.
  88221. * \assert
  88222. * \code chain != NULL \endcode
  88223. */
  88224. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88225. /*********** FLAC__Metadata_Iterator ***********/
  88226. /** Create a new iterator instance.
  88227. *
  88228. * \retval FLAC__Metadata_Iterator*
  88229. * \c NULL if there was an error allocating memory, else the new instance.
  88230. */
  88231. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88232. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88233. *
  88234. * \param iterator A pointer to an existing iterator.
  88235. * \assert
  88236. * \code iterator != NULL \endcode
  88237. */
  88238. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88239. /** Initialize the iterator to point to the first metadata block in the
  88240. * given chain.
  88241. *
  88242. * \param iterator A pointer to an existing iterator.
  88243. * \param chain A pointer to an existing and initialized (read) chain.
  88244. * \assert
  88245. * \code iterator != NULL \endcode
  88246. * \code chain != NULL \endcode
  88247. */
  88248. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88249. /** Moves the iterator forward one metadata block, returning \c false if
  88250. * already at the end.
  88251. *
  88252. * \param iterator A pointer to an existing initialized iterator.
  88253. * \assert
  88254. * \code iterator != NULL \endcode
  88255. * \a iterator has been successfully initialized with
  88256. * FLAC__metadata_iterator_init()
  88257. * \retval FLAC__bool
  88258. * \c false if already at the last metadata block of the chain, else
  88259. * \c true.
  88260. */
  88261. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88262. /** Moves the iterator backward one metadata block, returning \c false if
  88263. * already at the beginning.
  88264. *
  88265. * \param iterator A pointer to an existing initialized iterator.
  88266. * \assert
  88267. * \code iterator != NULL \endcode
  88268. * \a iterator has been successfully initialized with
  88269. * FLAC__metadata_iterator_init()
  88270. * \retval FLAC__bool
  88271. * \c false if already at the first metadata block of the chain, else
  88272. * \c true.
  88273. */
  88274. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88275. /** Get the type of the metadata block at the current position.
  88276. *
  88277. * \param iterator A pointer to an existing initialized iterator.
  88278. * \assert
  88279. * \code iterator != NULL \endcode
  88280. * \a iterator has been successfully initialized with
  88281. * FLAC__metadata_iterator_init()
  88282. * \retval FLAC__MetadataType
  88283. * The type of the metadata block at the current iterator position.
  88284. */
  88285. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88286. /** Get the metadata block at the current position. You can modify
  88287. * the block in place but must write the chain before the changes
  88288. * are reflected to the FLAC file. You do not need to call
  88289. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88290. * the pointer returned by FLAC__metadata_iterator_get_block()
  88291. * points directly into the chain.
  88292. *
  88293. * \warning
  88294. * Do not call FLAC__metadata_object_delete() on the returned object;
  88295. * to delete a block use FLAC__metadata_iterator_delete_block().
  88296. *
  88297. * \param iterator A pointer to an existing initialized iterator.
  88298. * \assert
  88299. * \code iterator != NULL \endcode
  88300. * \a iterator has been successfully initialized with
  88301. * FLAC__metadata_iterator_init()
  88302. * \retval FLAC__StreamMetadata*
  88303. * The current metadata block.
  88304. */
  88305. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88306. /** Set the metadata block at the current position, replacing the existing
  88307. * block. The new block passed in becomes owned by the chain and it will be
  88308. * deleted when the chain is deleted.
  88309. *
  88310. * \param iterator A pointer to an existing initialized iterator.
  88311. * \param block A pointer to a metadata block.
  88312. * \assert
  88313. * \code iterator != NULL \endcode
  88314. * \a iterator has been successfully initialized with
  88315. * FLAC__metadata_iterator_init()
  88316. * \code block != NULL \endcode
  88317. * \retval FLAC__bool
  88318. * \c false if the conditions in the above description are not met, or
  88319. * a memory allocation error occurs, otherwise \c true.
  88320. */
  88321. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88322. /** Removes the current block from the chain. If \a replace_with_padding is
  88323. * \c true, the block will instead be replaced with a padding block of equal
  88324. * size. You can not delete the STREAMINFO block. The iterator will be
  88325. * left pointing to the block before the one just "deleted", even if
  88326. * \a replace_with_padding is \c true.
  88327. *
  88328. * \param iterator A pointer to an existing initialized iterator.
  88329. * \param replace_with_padding See above.
  88330. * \assert
  88331. * \code iterator != NULL \endcode
  88332. * \a iterator has been successfully initialized with
  88333. * FLAC__metadata_iterator_init()
  88334. * \retval FLAC__bool
  88335. * \c false if the conditions in the above description are not met,
  88336. * otherwise \c true.
  88337. */
  88338. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88339. /** Insert a new block before the current block. You cannot insert a block
  88340. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88341. * as there can be only one, the one that already exists at the head when you
  88342. * read in a chain. The chain takes ownership of the new block and it will be
  88343. * deleted when the chain is deleted. The iterator will be left pointing to
  88344. * the new block.
  88345. *
  88346. * \param iterator A pointer to an existing initialized iterator.
  88347. * \param block A pointer to a metadata block to insert.
  88348. * \assert
  88349. * \code iterator != NULL \endcode
  88350. * \a iterator has been successfully initialized with
  88351. * FLAC__metadata_iterator_init()
  88352. * \retval FLAC__bool
  88353. * \c false if the conditions in the above description are not met, or
  88354. * a memory allocation error occurs, otherwise \c true.
  88355. */
  88356. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88357. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88358. * block as there can be only one, the one that already exists at the head when
  88359. * you read in a chain. The chain takes ownership of the new block and it will
  88360. * be deleted when the chain is deleted. The iterator will be left pointing to
  88361. * the new block.
  88362. *
  88363. * \param iterator A pointer to an existing initialized iterator.
  88364. * \param block A pointer to a metadata block to insert.
  88365. * \assert
  88366. * \code iterator != NULL \endcode
  88367. * \a iterator has been successfully initialized with
  88368. * FLAC__metadata_iterator_init()
  88369. * \retval FLAC__bool
  88370. * \c false if the conditions in the above description are not met, or
  88371. * a memory allocation error occurs, otherwise \c true.
  88372. */
  88373. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88374. /* \} */
  88375. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88376. * \ingroup flac_metadata
  88377. *
  88378. * \brief
  88379. * This module contains methods for manipulating FLAC metadata objects.
  88380. *
  88381. * Since many are variable length we have to be careful about the memory
  88382. * management. We decree that all pointers to data in the object are
  88383. * owned by the object and memory-managed by the object.
  88384. *
  88385. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88386. * functions to create all instances. When using the
  88387. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88388. * \a copy to \c true to have the function make it's own copy of the data, or
  88389. * to \c false to give the object ownership of your data. In the latter case
  88390. * your pointer must be freeable by free() and will be free()d when the object
  88391. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88392. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88393. * the length argument is 0 and the \a copy argument is \c false.
  88394. *
  88395. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88396. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88397. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88398. * case of a memory allocation error.
  88399. *
  88400. * We don't have the convenience of C++ here, so note that the library relies
  88401. * on you to keep the types straight. In other words, if you pass, for
  88402. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88403. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88404. * failure.
  88405. *
  88406. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88407. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88408. * toward the length or stored in the stream, but it can make working with plain
  88409. * comments (those that don't contain embedded-NULs in the value) easier.
  88410. * Entries passed into these functions have trailing NULs added if missing, and
  88411. * returned entries are guaranteed to have a trailing NUL.
  88412. *
  88413. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88414. * comment entry/name/value will first validate that it complies with the Vorbis
  88415. * comment specification and return false if it does not.
  88416. *
  88417. * There is no need to recalculate the length field on metadata blocks you
  88418. * have modified. They will be calculated automatically before they are
  88419. * written back to a file.
  88420. *
  88421. * \{
  88422. */
  88423. /** Create a new metadata object instance of the given type.
  88424. *
  88425. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88426. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88427. * the vendor string set (but zero comments).
  88428. *
  88429. * Do not pass in a value greater than or equal to
  88430. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88431. * doing.
  88432. *
  88433. * \param type Type of object to create
  88434. * \retval FLAC__StreamMetadata*
  88435. * \c NULL if there was an error allocating memory or the type code is
  88436. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88437. */
  88438. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88439. /** Create a copy of an existing metadata object.
  88440. *
  88441. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88442. * object is also copied. The caller takes ownership of the new block and
  88443. * is responsible for freeing it with FLAC__metadata_object_delete().
  88444. *
  88445. * \param object Pointer to object to copy.
  88446. * \assert
  88447. * \code object != NULL \endcode
  88448. * \retval FLAC__StreamMetadata*
  88449. * \c NULL if there was an error allocating memory, else the new instance.
  88450. */
  88451. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88452. /** Free a metadata object. Deletes the object pointed to by \a object.
  88453. *
  88454. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88455. * object is also deleted.
  88456. *
  88457. * \param object A pointer to an existing object.
  88458. * \assert
  88459. * \code object != NULL \endcode
  88460. */
  88461. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88462. /** Compares two metadata objects.
  88463. *
  88464. * The compare is "deep", i.e. dynamically allocated data within the
  88465. * object is also compared.
  88466. *
  88467. * \param block1 A pointer to an existing object.
  88468. * \param block2 A pointer to an existing object.
  88469. * \assert
  88470. * \code block1 != NULL \endcode
  88471. * \code block2 != NULL \endcode
  88472. * \retval FLAC__bool
  88473. * \c true if objects are identical, else \c false.
  88474. */
  88475. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88476. /** Sets the application data of an APPLICATION block.
  88477. *
  88478. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88479. * takes ownership of the pointer. The existing data will be freed if this
  88480. * function is successful, otherwise the original data will remain if \a copy
  88481. * is \c true and malloc() fails.
  88482. *
  88483. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88484. *
  88485. * \param object A pointer to an existing APPLICATION object.
  88486. * \param data A pointer to the data to set.
  88487. * \param length The length of \a data in bytes.
  88488. * \param copy See above.
  88489. * \assert
  88490. * \code object != NULL \endcode
  88491. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88492. * \code (data != NULL && length > 0) ||
  88493. * (data == NULL && length == 0 && copy == false) \endcode
  88494. * \retval FLAC__bool
  88495. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88496. */
  88497. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88498. /** Resize the seekpoint array.
  88499. *
  88500. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88501. * points will be added to the end.
  88502. *
  88503. * \param object A pointer to an existing SEEKTABLE object.
  88504. * \param new_num_points The desired length of the array; may be \c 0.
  88505. * \assert
  88506. * \code object != NULL \endcode
  88507. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88508. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88509. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88510. * \retval FLAC__bool
  88511. * \c false if memory allocation error, else \c true.
  88512. */
  88513. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88514. /** Set a seekpoint in a seektable.
  88515. *
  88516. * \param object A pointer to an existing SEEKTABLE object.
  88517. * \param point_num Index into seekpoint array to set.
  88518. * \param point The point to set.
  88519. * \assert
  88520. * \code object != NULL \endcode
  88521. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88522. * \code object->data.seek_table.num_points > point_num \endcode
  88523. */
  88524. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88525. /** Insert a seekpoint into a seektable.
  88526. *
  88527. * \param object A pointer to an existing SEEKTABLE object.
  88528. * \param point_num Index into seekpoint array to set.
  88529. * \param point The point to set.
  88530. * \assert
  88531. * \code object != NULL \endcode
  88532. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88533. * \code object->data.seek_table.num_points >= point_num \endcode
  88534. * \retval FLAC__bool
  88535. * \c false if memory allocation error, else \c true.
  88536. */
  88537. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88538. /** Delete a seekpoint from a seektable.
  88539. *
  88540. * \param object A pointer to an existing SEEKTABLE object.
  88541. * \param point_num Index into seekpoint array to set.
  88542. * \assert
  88543. * \code object != NULL \endcode
  88544. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88545. * \code object->data.seek_table.num_points > point_num \endcode
  88546. * \retval FLAC__bool
  88547. * \c false if memory allocation error, else \c true.
  88548. */
  88549. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88550. /** Check a seektable to see if it conforms to the FLAC specification.
  88551. * See the format specification for limits on the contents of the
  88552. * seektable.
  88553. *
  88554. * \param object A pointer to an existing SEEKTABLE object.
  88555. * \assert
  88556. * \code object != NULL \endcode
  88557. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88558. * \retval FLAC__bool
  88559. * \c false if seek table is illegal, else \c true.
  88560. */
  88561. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88562. /** Append a number of placeholder points to the end of a seek table.
  88563. *
  88564. * \note
  88565. * As with the other ..._seektable_template_... functions, you should
  88566. * call FLAC__metadata_object_seektable_template_sort() when finished
  88567. * to make the seek table legal.
  88568. *
  88569. * \param object A pointer to an existing SEEKTABLE object.
  88570. * \param num The number of placeholder points to append.
  88571. * \assert
  88572. * \code object != NULL \endcode
  88573. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88574. * \retval FLAC__bool
  88575. * \c false if memory allocation fails, else \c true.
  88576. */
  88577. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88578. /** Append a specific seek point template to the end of a seek table.
  88579. *
  88580. * \note
  88581. * As with the other ..._seektable_template_... functions, you should
  88582. * call FLAC__metadata_object_seektable_template_sort() when finished
  88583. * to make the seek table legal.
  88584. *
  88585. * \param object A pointer to an existing SEEKTABLE object.
  88586. * \param sample_number The sample number of the seek point template.
  88587. * \assert
  88588. * \code object != NULL \endcode
  88589. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88590. * \retval FLAC__bool
  88591. * \c false if memory allocation fails, else \c true.
  88592. */
  88593. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88594. /** Append specific seek point templates to the end of a seek table.
  88595. *
  88596. * \note
  88597. * As with the other ..._seektable_template_... functions, you should
  88598. * call FLAC__metadata_object_seektable_template_sort() when finished
  88599. * to make the seek table legal.
  88600. *
  88601. * \param object A pointer to an existing SEEKTABLE object.
  88602. * \param sample_numbers An array of sample numbers for the seek points.
  88603. * \param num The number of seek point templates to append.
  88604. * \assert
  88605. * \code object != NULL \endcode
  88606. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88607. * \retval FLAC__bool
  88608. * \c false if memory allocation fails, else \c true.
  88609. */
  88610. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88611. /** Append a set of evenly-spaced seek point templates to the end of a
  88612. * seek table.
  88613. *
  88614. * \note
  88615. * As with the other ..._seektable_template_... functions, you should
  88616. * call FLAC__metadata_object_seektable_template_sort() when finished
  88617. * to make the seek table legal.
  88618. *
  88619. * \param object A pointer to an existing SEEKTABLE object.
  88620. * \param num The number of placeholder points to append.
  88621. * \param total_samples The total number of samples to be encoded;
  88622. * the seekpoints will be spaced approximately
  88623. * \a total_samples / \a num samples apart.
  88624. * \assert
  88625. * \code object != NULL \endcode
  88626. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88627. * \code total_samples > 0 \endcode
  88628. * \retval FLAC__bool
  88629. * \c false if memory allocation fails, else \c true.
  88630. */
  88631. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88632. /** Append a set of evenly-spaced seek point templates to the end of a
  88633. * seek table.
  88634. *
  88635. * \note
  88636. * As with the other ..._seektable_template_... functions, you should
  88637. * call FLAC__metadata_object_seektable_template_sort() when finished
  88638. * to make the seek table legal.
  88639. *
  88640. * \param object A pointer to an existing SEEKTABLE object.
  88641. * \param samples The number of samples apart to space the placeholder
  88642. * points. The first point will be at sample \c 0, the
  88643. * second at sample \a samples, then 2*\a samples, and
  88644. * so on. As long as \a samples and \a total_samples
  88645. * are greater than \c 0, there will always be at least
  88646. * one seekpoint at sample \c 0.
  88647. * \param total_samples The total number of samples to be encoded;
  88648. * the seekpoints will be spaced
  88649. * \a samples samples apart.
  88650. * \assert
  88651. * \code object != NULL \endcode
  88652. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88653. * \code samples > 0 \endcode
  88654. * \code total_samples > 0 \endcode
  88655. * \retval FLAC__bool
  88656. * \c false if memory allocation fails, else \c true.
  88657. */
  88658. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88659. /** Sort a seek table's seek points according to the format specification,
  88660. * removing duplicates.
  88661. *
  88662. * \param object A pointer to a seek table to be sorted.
  88663. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88664. * If \c true, duplicates are deleted and the seek table is
  88665. * shrunk appropriately; the number of placeholder points
  88666. * present in the seek table will be the same after the call
  88667. * as before.
  88668. * \assert
  88669. * \code object != NULL \endcode
  88670. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88671. * \retval FLAC__bool
  88672. * \c false if realloc() fails, else \c true.
  88673. */
  88674. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88675. /** Sets the vendor string in a VORBIS_COMMENT block.
  88676. *
  88677. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88678. * one already.
  88679. *
  88680. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88681. * takes ownership of the \c entry.entry pointer.
  88682. *
  88683. * \note If this function returns \c false, the caller still owns the
  88684. * pointer.
  88685. *
  88686. * \param object A pointer to an existing VORBIS_COMMENT object.
  88687. * \param entry The entry to set the vendor string to.
  88688. * \param copy See above.
  88689. * \assert
  88690. * \code object != NULL \endcode
  88691. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88692. * \code (entry.entry != NULL && entry.length > 0) ||
  88693. * (entry.entry == NULL && entry.length == 0) \endcode
  88694. * \retval FLAC__bool
  88695. * \c false if memory allocation fails or \a entry does not comply with the
  88696. * Vorbis comment specification, else \c true.
  88697. */
  88698. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88699. /** Resize the comment array.
  88700. *
  88701. * If the size shrinks, elements will truncated; if it grows, new empty
  88702. * fields will be added to the end.
  88703. *
  88704. * \param object A pointer to an existing VORBIS_COMMENT object.
  88705. * \param new_num_comments The desired length of the array; may be \c 0.
  88706. * \assert
  88707. * \code object != NULL \endcode
  88708. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88709. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88710. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88711. * \retval FLAC__bool
  88712. * \c false if memory allocation fails, else \c true.
  88713. */
  88714. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88715. /** Sets a comment in a VORBIS_COMMENT block.
  88716. *
  88717. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88718. * one already.
  88719. *
  88720. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88721. * takes ownership of the \c entry.entry pointer.
  88722. *
  88723. * \note If this function returns \c false, the caller still owns the
  88724. * pointer.
  88725. *
  88726. * \param object A pointer to an existing VORBIS_COMMENT object.
  88727. * \param comment_num Index into comment array to set.
  88728. * \param entry The entry to set the comment to.
  88729. * \param copy See above.
  88730. * \assert
  88731. * \code object != NULL \endcode
  88732. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88733. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88734. * \code (entry.entry != NULL && entry.length > 0) ||
  88735. * (entry.entry == NULL && entry.length == 0) \endcode
  88736. * \retval FLAC__bool
  88737. * \c false if memory allocation fails or \a entry does not comply with the
  88738. * Vorbis comment specification, else \c true.
  88739. */
  88740. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88741. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88742. *
  88743. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88744. * one already.
  88745. *
  88746. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88747. * takes ownership of the \c entry.entry pointer.
  88748. *
  88749. * \note If this function returns \c false, the caller still owns the
  88750. * pointer.
  88751. *
  88752. * \param object A pointer to an existing VORBIS_COMMENT object.
  88753. * \param comment_num The index at which to insert the comment. The comments
  88754. * at and after \a comment_num move right one position.
  88755. * To append a comment to the end, set \a comment_num to
  88756. * \c object->data.vorbis_comment.num_comments .
  88757. * \param entry The comment to insert.
  88758. * \param copy See above.
  88759. * \assert
  88760. * \code object != NULL \endcode
  88761. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88762. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88763. * \code (entry.entry != NULL && entry.length > 0) ||
  88764. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88765. * \retval FLAC__bool
  88766. * \c false if memory allocation fails or \a entry does not comply with the
  88767. * Vorbis comment specification, else \c true.
  88768. */
  88769. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88770. /** Appends a comment to a VORBIS_COMMENT block.
  88771. *
  88772. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88773. * one already.
  88774. *
  88775. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88776. * takes ownership of the \c entry.entry pointer.
  88777. *
  88778. * \note If this function returns \c false, the caller still owns the
  88779. * pointer.
  88780. *
  88781. * \param object A pointer to an existing VORBIS_COMMENT object.
  88782. * \param entry The comment to insert.
  88783. * \param copy See above.
  88784. * \assert
  88785. * \code object != NULL \endcode
  88786. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88787. * \code (entry.entry != NULL && entry.length > 0) ||
  88788. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88789. * \retval FLAC__bool
  88790. * \c false if memory allocation fails or \a entry does not comply with the
  88791. * Vorbis comment specification, else \c true.
  88792. */
  88793. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88794. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88795. *
  88796. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88797. * one already.
  88798. *
  88799. * Depending on the the value of \a all, either all or just the first comment
  88800. * whose field name(s) match the given entry's name will be replaced by the
  88801. * given entry. If no comments match, \a entry will simply be appended.
  88802. *
  88803. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88804. * takes ownership of the \c entry.entry pointer.
  88805. *
  88806. * \note If this function returns \c false, the caller still owns the
  88807. * pointer.
  88808. *
  88809. * \param object A pointer to an existing VORBIS_COMMENT object.
  88810. * \param entry The comment to insert.
  88811. * \param all If \c true, all comments whose field name matches
  88812. * \a entry's field name will be removed, and \a entry will
  88813. * be inserted at the position of the first matching
  88814. * comment. If \c false, only the first comment whose
  88815. * field name matches \a entry's field name will be
  88816. * replaced with \a entry.
  88817. * \param copy See above.
  88818. * \assert
  88819. * \code object != NULL \endcode
  88820. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88821. * \code (entry.entry != NULL && entry.length > 0) ||
  88822. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88823. * \retval FLAC__bool
  88824. * \c false if memory allocation fails or \a entry does not comply with the
  88825. * Vorbis comment specification, else \c true.
  88826. */
  88827. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88828. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88829. *
  88830. * \param object A pointer to an existing VORBIS_COMMENT object.
  88831. * \param comment_num The index of the comment to delete.
  88832. * \assert
  88833. * \code object != NULL \endcode
  88834. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88835. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88836. * \retval FLAC__bool
  88837. * \c false if realloc() fails, else \c true.
  88838. */
  88839. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88840. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88841. *
  88842. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88843. * memory and shall be owned by the caller. For convenience the entry will
  88844. * have a terminating NUL.
  88845. *
  88846. * \param entry A pointer to a Vorbis comment entry. The entry's
  88847. * \c entry pointer should not point to allocated
  88848. * memory as it will be overwritten.
  88849. * \param field_name The field name in ASCII, \c NUL terminated.
  88850. * \param field_value The field value in UTF-8, \c NUL terminated.
  88851. * \assert
  88852. * \code entry != NULL \endcode
  88853. * \code field_name != NULL \endcode
  88854. * \code field_value != NULL \endcode
  88855. * \retval FLAC__bool
  88856. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88857. * not comply with the Vorbis comment specification, else \c true.
  88858. */
  88859. 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);
  88860. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88861. *
  88862. * The returned pointers to name and value will be allocated by malloc()
  88863. * and shall be owned by the caller.
  88864. *
  88865. * \param entry An existing Vorbis comment entry.
  88866. * \param field_name The address of where the returned pointer to the
  88867. * field name will be stored.
  88868. * \param field_value The address of where the returned pointer to the
  88869. * field value will be stored.
  88870. * \assert
  88871. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88872. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88873. * \code field_name != NULL \endcode
  88874. * \code field_value != NULL \endcode
  88875. * \retval FLAC__bool
  88876. * \c false if memory allocation fails or \a entry does not comply with the
  88877. * Vorbis comment specification, else \c true.
  88878. */
  88879. 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);
  88880. /** Check if the given Vorbis comment entry's field name matches the given
  88881. * field name.
  88882. *
  88883. * \param entry An existing Vorbis comment entry.
  88884. * \param field_name The field name to check.
  88885. * \param field_name_length The length of \a field_name, not including the
  88886. * terminating \c NUL.
  88887. * \assert
  88888. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88889. * \retval FLAC__bool
  88890. * \c true if the field names match, else \c false
  88891. */
  88892. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88893. /** Find a Vorbis comment with the given field name.
  88894. *
  88895. * The search begins at entry number \a offset; use an offset of 0 to
  88896. * search from the beginning of the comment array.
  88897. *
  88898. * \param object A pointer to an existing VORBIS_COMMENT object.
  88899. * \param offset The offset into the comment array from where to start
  88900. * the search.
  88901. * \param field_name The field name of the comment to find.
  88902. * \assert
  88903. * \code object != NULL \endcode
  88904. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88905. * \code field_name != NULL \endcode
  88906. * \retval int
  88907. * The offset in the comment array of the first comment whose field
  88908. * name matches \a field_name, or \c -1 if no match was found.
  88909. */
  88910. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88911. /** Remove first Vorbis comment matching the given field name.
  88912. *
  88913. * \param object A pointer to an existing VORBIS_COMMENT object.
  88914. * \param field_name The field name of comment to delete.
  88915. * \assert
  88916. * \code object != NULL \endcode
  88917. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88918. * \retval int
  88919. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88920. * \c 1 for one matching entry deleted.
  88921. */
  88922. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88923. /** Remove all Vorbis comments matching the given field name.
  88924. *
  88925. * \param object A pointer to an existing VORBIS_COMMENT object.
  88926. * \param field_name The field name of comments to delete.
  88927. * \assert
  88928. * \code object != NULL \endcode
  88929. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88930. * \retval int
  88931. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88932. * else the number of matching entries deleted.
  88933. */
  88934. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88935. /** Create a new CUESHEET track instance.
  88936. *
  88937. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88938. *
  88939. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88940. * \c NULL if there was an error allocating memory, else the new instance.
  88941. */
  88942. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88943. /** Create a copy of an existing CUESHEET track object.
  88944. *
  88945. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88946. * object is also copied. The caller takes ownership of the new object and
  88947. * is responsible for freeing it with
  88948. * FLAC__metadata_object_cuesheet_track_delete().
  88949. *
  88950. * \param object Pointer to object to copy.
  88951. * \assert
  88952. * \code object != NULL \endcode
  88953. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88954. * \c NULL if there was an error allocating memory, else the new instance.
  88955. */
  88956. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88957. /** Delete a CUESHEET track object
  88958. *
  88959. * \param object A pointer to an existing CUESHEET track object.
  88960. * \assert
  88961. * \code object != NULL \endcode
  88962. */
  88963. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88964. /** Resize a track's index point array.
  88965. *
  88966. * If the size shrinks, elements will truncated; if it grows, new blank
  88967. * indices will be added to the end.
  88968. *
  88969. * \param object A pointer to an existing CUESHEET object.
  88970. * \param track_num The index of the track to modify. NOTE: this is not
  88971. * necessarily the same as the track's \a number field.
  88972. * \param new_num_indices The desired length of the array; may be \c 0.
  88973. * \assert
  88974. * \code object != NULL \endcode
  88975. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88976. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88977. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88978. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88979. * \retval FLAC__bool
  88980. * \c false if memory allocation error, else \c true.
  88981. */
  88982. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88983. /** Insert an index point in a CUESHEET track at the given index.
  88984. *
  88985. * \param object A pointer to an existing CUESHEET object.
  88986. * \param track_num The index of the track to modify. NOTE: this is not
  88987. * necessarily the same as the track's \a number field.
  88988. * \param index_num The index into the track's index array at which to
  88989. * insert the index point. NOTE: this is not necessarily
  88990. * the same as the index point's \a number field. The
  88991. * indices at and after \a index_num move right one
  88992. * position. To append an index point to the end, set
  88993. * \a index_num to
  88994. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88995. * \param index The index point to insert.
  88996. * \assert
  88997. * \code object != NULL \endcode
  88998. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88999. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89000. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89001. * \retval FLAC__bool
  89002. * \c false if realloc() fails, else \c true.
  89003. */
  89004. 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);
  89005. /** Insert a blank index point in a CUESHEET track at the given index.
  89006. *
  89007. * A blank index point is one in which all field values are zero.
  89008. *
  89009. * \param object A pointer to an existing CUESHEET object.
  89010. * \param track_num The index of the track to modify. NOTE: this is not
  89011. * necessarily the same as the track's \a number field.
  89012. * \param index_num The index into the track's index array at which to
  89013. * insert the index point. NOTE: this is not necessarily
  89014. * the same as the index point's \a number field. The
  89015. * indices at and after \a index_num move right one
  89016. * position. To append an index point to the end, set
  89017. * \a index_num to
  89018. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89019. * \assert
  89020. * \code object != NULL \endcode
  89021. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89022. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89023. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89024. * \retval FLAC__bool
  89025. * \c false if realloc() fails, else \c true.
  89026. */
  89027. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89028. /** Delete an index point in a CUESHEET track at the given index.
  89029. *
  89030. * \param object A pointer to an existing CUESHEET object.
  89031. * \param track_num The index into the track array of the track to
  89032. * modify. NOTE: this is not necessarily the same
  89033. * as the track's \a number field.
  89034. * \param index_num The index into the track's index array of the index
  89035. * to delete. NOTE: this is not necessarily the same
  89036. * as the index's \a number field.
  89037. * \assert
  89038. * \code object != NULL \endcode
  89039. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89040. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89041. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89042. * \retval FLAC__bool
  89043. * \c false if realloc() fails, else \c true.
  89044. */
  89045. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89046. /** Resize the track array.
  89047. *
  89048. * If the size shrinks, elements will truncated; if it grows, new blank
  89049. * tracks will be added to the end.
  89050. *
  89051. * \param object A pointer to an existing CUESHEET object.
  89052. * \param new_num_tracks The desired length of the array; may be \c 0.
  89053. * \assert
  89054. * \code object != NULL \endcode
  89055. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89056. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89057. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89058. * \retval FLAC__bool
  89059. * \c false if memory allocation error, else \c true.
  89060. */
  89061. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89062. /** Sets a track in a CUESHEET block.
  89063. *
  89064. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89065. * takes ownership of the \a track pointer.
  89066. *
  89067. * \param object A pointer to an existing CUESHEET object.
  89068. * \param track_num Index into track array to set. NOTE: this is not
  89069. * necessarily the same as the track's \a number field.
  89070. * \param track The track to set the track to. You may safely pass in
  89071. * a const pointer if \a copy is \c true.
  89072. * \param copy See above.
  89073. * \assert
  89074. * \code object != NULL \endcode
  89075. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89076. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89077. * \code (track->indices != NULL && track->num_indices > 0) ||
  89078. * (track->indices == NULL && track->num_indices == 0)
  89079. * \retval FLAC__bool
  89080. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89081. */
  89082. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89083. /** Insert a track in a CUESHEET block at the given index.
  89084. *
  89085. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89086. * takes ownership of the \a track pointer.
  89087. *
  89088. * \param object A pointer to an existing CUESHEET object.
  89089. * \param track_num The index at which to insert the track. NOTE: this
  89090. * is not necessarily the same as the track's \a number
  89091. * field. The tracks at and after \a track_num move right
  89092. * one position. To append a track to the end, set
  89093. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89094. * \param track The track to insert. You may safely pass in a const
  89095. * pointer if \a copy is \c true.
  89096. * \param copy See above.
  89097. * \assert
  89098. * \code object != NULL \endcode
  89099. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89100. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89101. * \retval FLAC__bool
  89102. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89103. */
  89104. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89105. /** Insert a blank track in a CUESHEET block at the given index.
  89106. *
  89107. * A blank track is one in which all field values are zero.
  89108. *
  89109. * \param object A pointer to an existing CUESHEET object.
  89110. * \param track_num The index at which to insert the track. NOTE: this
  89111. * is not necessarily the same as the track's \a number
  89112. * field. The tracks at and after \a track_num move right
  89113. * one position. To append a track to the end, set
  89114. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89115. * \assert
  89116. * \code object != NULL \endcode
  89117. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89118. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89119. * \retval FLAC__bool
  89120. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89121. */
  89122. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89123. /** Delete a track in a CUESHEET block at the given index.
  89124. *
  89125. * \param object A pointer to an existing CUESHEET object.
  89126. * \param track_num The index into the track array of the track to
  89127. * delete. NOTE: this is not necessarily the same
  89128. * as the track's \a number field.
  89129. * \assert
  89130. * \code object != NULL \endcode
  89131. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89132. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89133. * \retval FLAC__bool
  89134. * \c false if realloc() fails, else \c true.
  89135. */
  89136. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89137. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89138. * See the format specification for limits on the contents of the
  89139. * cue sheet.
  89140. *
  89141. * \param object A pointer to an existing CUESHEET object.
  89142. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89143. * stringent requirements for a CD-DA (audio) disc.
  89144. * \param violation Address of a pointer to a string. If there is a
  89145. * violation, a pointer to a string explanation of the
  89146. * violation will be returned here. \a violation may be
  89147. * \c NULL if you don't need the returned string. Do not
  89148. * free the returned string; it will always point to static
  89149. * data.
  89150. * \assert
  89151. * \code object != NULL \endcode
  89152. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89153. * \retval FLAC__bool
  89154. * \c false if cue sheet is illegal, else \c true.
  89155. */
  89156. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89157. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89158. * assumes the cue sheet corresponds to a CD; the result is undefined
  89159. * if the cuesheet's is_cd bit is not set.
  89160. *
  89161. * \param object A pointer to an existing CUESHEET object.
  89162. * \assert
  89163. * \code object != NULL \endcode
  89164. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89165. * \retval FLAC__uint32
  89166. * The unsigned integer representation of the CDDB/freedb ID
  89167. */
  89168. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89169. /** Sets the MIME type of a PICTURE block.
  89170. *
  89171. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89172. * takes ownership of the pointer. The existing string will be freed if this
  89173. * function is successful, otherwise the original string will remain if \a copy
  89174. * is \c true and malloc() fails.
  89175. *
  89176. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89177. *
  89178. * \param object A pointer to an existing PICTURE object.
  89179. * \param mime_type A pointer to the MIME type string. The string must be
  89180. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89181. * is done.
  89182. * \param copy See above.
  89183. * \assert
  89184. * \code object != NULL \endcode
  89185. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89186. * \code (mime_type != NULL) \endcode
  89187. * \retval FLAC__bool
  89188. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89189. */
  89190. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89191. /** Sets the description of a PICTURE block.
  89192. *
  89193. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89194. * takes ownership of the pointer. The existing string will be freed if this
  89195. * function is successful, otherwise the original string will remain if \a copy
  89196. * is \c true and malloc() fails.
  89197. *
  89198. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89199. *
  89200. * \param object A pointer to an existing PICTURE object.
  89201. * \param description A pointer to the description string. The string must be
  89202. * valid UTF-8, NUL-terminated. No validation is done.
  89203. * \param copy See above.
  89204. * \assert
  89205. * \code object != NULL \endcode
  89206. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89207. * \code (description != NULL) \endcode
  89208. * \retval FLAC__bool
  89209. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89210. */
  89211. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89212. /** Sets the picture data of a PICTURE block.
  89213. *
  89214. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89215. * takes ownership of the pointer. Also sets the \a data_length field of the
  89216. * metadata object to what is passed in as the \a length parameter. The
  89217. * existing data will be freed if this function is successful, otherwise the
  89218. * original data and data_length will remain if \a copy is \c true and
  89219. * malloc() fails.
  89220. *
  89221. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89222. *
  89223. * \param object A pointer to an existing PICTURE object.
  89224. * \param data A pointer to the data to set.
  89225. * \param length The length of \a data in bytes.
  89226. * \param copy See above.
  89227. * \assert
  89228. * \code object != NULL \endcode
  89229. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89230. * \code (data != NULL && length > 0) ||
  89231. * (data == NULL && length == 0 && copy == false) \endcode
  89232. * \retval FLAC__bool
  89233. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89234. */
  89235. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89236. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89237. * See the format specification for limits on the contents of the
  89238. * PICTURE block.
  89239. *
  89240. * \param object A pointer to existing PICTURE block to be checked.
  89241. * \param violation Address of a pointer to a string. If there is a
  89242. * violation, a pointer to a string explanation of the
  89243. * violation will be returned here. \a violation may be
  89244. * \c NULL if you don't need the returned string. Do not
  89245. * free the returned string; it will always point to static
  89246. * data.
  89247. * \assert
  89248. * \code object != NULL \endcode
  89249. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89250. * \retval FLAC__bool
  89251. * \c false if PICTURE block is illegal, else \c true.
  89252. */
  89253. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89254. /* \} */
  89255. #ifdef __cplusplus
  89256. }
  89257. #endif
  89258. #endif
  89259. /*** End of inlined file: metadata.h ***/
  89260. /*** Start of inlined file: stream_decoder.h ***/
  89261. #ifndef FLAC__STREAM_DECODER_H
  89262. #define FLAC__STREAM_DECODER_H
  89263. #include <stdio.h> /* for FILE */
  89264. #ifdef __cplusplus
  89265. extern "C" {
  89266. #endif
  89267. /** \file include/FLAC/stream_decoder.h
  89268. *
  89269. * \brief
  89270. * This module contains the functions which implement the stream
  89271. * decoder.
  89272. *
  89273. * See the detailed documentation in the
  89274. * \link flac_stream_decoder stream decoder \endlink module.
  89275. */
  89276. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89277. * \ingroup flac
  89278. *
  89279. * \brief
  89280. * This module describes the decoder layers provided by libFLAC.
  89281. *
  89282. * The stream decoder can be used to decode complete streams either from
  89283. * the client via callbacks, or directly from a file, depending on how
  89284. * it is initialized. When decoding via callbacks, the client provides
  89285. * callbacks for reading FLAC data and writing decoded samples, and
  89286. * handling metadata and errors. If the client also supplies seek-related
  89287. * callback, the decoder function for sample-accurate seeking within the
  89288. * FLAC input is also available. When decoding from a file, the client
  89289. * needs only supply a filename or open \c FILE* and write/metadata/error
  89290. * callbacks; the rest of the callbacks are supplied internally. For more
  89291. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89292. */
  89293. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89294. * \ingroup flac_decoder
  89295. *
  89296. * \brief
  89297. * This module contains the functions which implement the stream
  89298. * decoder.
  89299. *
  89300. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89301. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89302. *
  89303. * The basic usage of this decoder is as follows:
  89304. * - The program creates an instance of a decoder using
  89305. * FLAC__stream_decoder_new().
  89306. * - The program overrides the default settings using
  89307. * FLAC__stream_decoder_set_*() functions.
  89308. * - The program initializes the instance to validate the settings and
  89309. * prepare for decoding using
  89310. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89311. * or FLAC__stream_decoder_init_file() for native FLAC,
  89312. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89313. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89314. * - The program calls the FLAC__stream_decoder_process_*() functions
  89315. * to decode data, which subsequently calls the callbacks.
  89316. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89317. * which flushes the input and output and resets the decoder to the
  89318. * uninitialized state.
  89319. * - The instance may be used again or deleted with
  89320. * FLAC__stream_decoder_delete().
  89321. *
  89322. * In more detail, the program will create a new instance by calling
  89323. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89324. * functions to override the default decoder options, and call
  89325. * one of the FLAC__stream_decoder_init_*() functions.
  89326. *
  89327. * There are three initialization functions for native FLAC, one for
  89328. * setting up the decoder to decode FLAC data from the client via
  89329. * callbacks, and two for decoding directly from a FLAC file.
  89330. *
  89331. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89332. * You must also supply several callbacks for handling I/O. Some (like
  89333. * seeking) are optional, depending on the capabilities of the input.
  89334. *
  89335. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89336. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89337. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89338. * the other callbacks internally.
  89339. *
  89340. * There are three similarly-named init functions for decoding from Ogg
  89341. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89342. * library has been built with Ogg support.
  89343. *
  89344. * Once the decoder is initialized, your program will call one of several
  89345. * functions to start the decoding process:
  89346. *
  89347. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89348. * most one metadata block or audio frame and return, calling either the
  89349. * metadata callback or write callback, respectively, once. If the decoder
  89350. * loses sync it will return with only the error callback being called.
  89351. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89352. * to process the stream from the current location and stop upon reaching
  89353. * the first audio frame. The client will get one metadata, write, or error
  89354. * callback per metadata block, audio frame, or sync error, respectively.
  89355. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89356. * to process the stream from the current location until the read callback
  89357. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89358. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89359. * write, or error callback per metadata block, audio frame, or sync error,
  89360. * respectively.
  89361. *
  89362. * When the decoder has finished decoding (normally or through an abort),
  89363. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89364. * ensures the decoder is in the correct state and frees memory. Then the
  89365. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89366. * again to decode another stream.
  89367. *
  89368. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89369. * At any point after the stream decoder has been initialized, the client can
  89370. * call this function to seek to an exact sample within the stream.
  89371. * Subsequently, the first time the write callback is called it will be
  89372. * passed a (possibly partial) block starting at that sample.
  89373. *
  89374. * If the client cannot seek via the callback interface provided, but still
  89375. * has another way of seeking, it can flush the decoder using
  89376. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89377. * through the read callback.
  89378. *
  89379. * The stream decoder also provides MD5 signature checking. If this is
  89380. * turned on before initialization, FLAC__stream_decoder_finish() will
  89381. * report when the decoded MD5 signature does not match the one stored
  89382. * in the STREAMINFO block. MD5 checking is automatically turned off
  89383. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89384. * in the STREAMINFO block or when a seek is attempted.
  89385. *
  89386. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89387. * attention. By default, the decoder only calls the metadata_callback for
  89388. * the STREAMINFO block. These functions allow you to tell the decoder
  89389. * explicitly which blocks to parse and return via the metadata_callback
  89390. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89391. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89392. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89393. * which blocks to return. Remember that metadata blocks can potentially
  89394. * be big (for example, cover art) so filtering out the ones you don't
  89395. * use can reduce the memory requirements of the decoder. Also note the
  89396. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89397. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89398. * filtering APPLICATION blocks based on the application ID.
  89399. *
  89400. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89401. * they still can legally be filtered from the metadata_callback.
  89402. *
  89403. * \note
  89404. * The "set" functions may only be called when the decoder is in the
  89405. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89406. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89407. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89408. * return \c true, otherwise \c false.
  89409. *
  89410. * \note
  89411. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89412. * defaults, including the callbacks.
  89413. *
  89414. * \{
  89415. */
  89416. /** State values for a FLAC__StreamDecoder
  89417. *
  89418. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89419. */
  89420. typedef enum {
  89421. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89422. /**< The decoder is ready to search for metadata. */
  89423. FLAC__STREAM_DECODER_READ_METADATA,
  89424. /**< The decoder is ready to or is in the process of reading metadata. */
  89425. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89426. /**< The decoder is ready to or is in the process of searching for the
  89427. * frame sync code.
  89428. */
  89429. FLAC__STREAM_DECODER_READ_FRAME,
  89430. /**< The decoder is ready to or is in the process of reading a frame. */
  89431. FLAC__STREAM_DECODER_END_OF_STREAM,
  89432. /**< The decoder has reached the end of the stream. */
  89433. FLAC__STREAM_DECODER_OGG_ERROR,
  89434. /**< An error occurred in the underlying Ogg layer. */
  89435. FLAC__STREAM_DECODER_SEEK_ERROR,
  89436. /**< An error occurred while seeking. The decoder must be flushed
  89437. * with FLAC__stream_decoder_flush() or reset with
  89438. * FLAC__stream_decoder_reset() before decoding can continue.
  89439. */
  89440. FLAC__STREAM_DECODER_ABORTED,
  89441. /**< The decoder was aborted by the read callback. */
  89442. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89443. /**< An error occurred allocating memory. The decoder is in an invalid
  89444. * state and can no longer be used.
  89445. */
  89446. FLAC__STREAM_DECODER_UNINITIALIZED
  89447. /**< The decoder is in the uninitialized state; one of the
  89448. * FLAC__stream_decoder_init_*() functions must be called before samples
  89449. * can be processed.
  89450. */
  89451. } FLAC__StreamDecoderState;
  89452. /** Maps a FLAC__StreamDecoderState to a C string.
  89453. *
  89454. * Using a FLAC__StreamDecoderState as the index to this array
  89455. * will give the string equivalent. The contents should not be modified.
  89456. */
  89457. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89458. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89459. */
  89460. typedef enum {
  89461. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89462. /**< Initialization was successful. */
  89463. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89464. /**< The library was not compiled with support for the given container
  89465. * format.
  89466. */
  89467. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89468. /**< A required callback was not supplied. */
  89469. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89470. /**< An error occurred allocating memory. */
  89471. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89472. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89473. * FLAC__stream_decoder_init_ogg_file(). */
  89474. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89475. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89476. * already initialized, usually because
  89477. * FLAC__stream_decoder_finish() was not called.
  89478. */
  89479. } FLAC__StreamDecoderInitStatus;
  89480. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89481. *
  89482. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89483. * will give the string equivalent. The contents should not be modified.
  89484. */
  89485. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89486. /** Return values for the FLAC__StreamDecoder read callback.
  89487. */
  89488. typedef enum {
  89489. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89490. /**< The read was OK and decoding can continue. */
  89491. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89492. /**< The read was attempted while at the end of the stream. Note that
  89493. * the client must only return this value when the read callback was
  89494. * called when already at the end of the stream. Otherwise, if the read
  89495. * itself moves to the end of the stream, the client should still return
  89496. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89497. * the next read callback it should return
  89498. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89499. * of \c 0.
  89500. */
  89501. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89502. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89503. } FLAC__StreamDecoderReadStatus;
  89504. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89505. *
  89506. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89507. * will give the string equivalent. The contents should not be modified.
  89508. */
  89509. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89510. /** Return values for the FLAC__StreamDecoder seek callback.
  89511. */
  89512. typedef enum {
  89513. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89514. /**< The seek was OK and decoding can continue. */
  89515. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89516. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89517. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89518. /**< Client does not support seeking. */
  89519. } FLAC__StreamDecoderSeekStatus;
  89520. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89521. *
  89522. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89523. * will give the string equivalent. The contents should not be modified.
  89524. */
  89525. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89526. /** Return values for the FLAC__StreamDecoder tell callback.
  89527. */
  89528. typedef enum {
  89529. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89530. /**< The tell was OK and decoding can continue. */
  89531. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89532. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89533. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89534. /**< Client does not support telling the position. */
  89535. } FLAC__StreamDecoderTellStatus;
  89536. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89537. *
  89538. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89539. * will give the string equivalent. The contents should not be modified.
  89540. */
  89541. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89542. /** Return values for the FLAC__StreamDecoder length callback.
  89543. */
  89544. typedef enum {
  89545. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89546. /**< The length call was OK and decoding can continue. */
  89547. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89548. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89549. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89550. /**< Client does not support reporting the length. */
  89551. } FLAC__StreamDecoderLengthStatus;
  89552. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89553. *
  89554. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89555. * will give the string equivalent. The contents should not be modified.
  89556. */
  89557. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89558. /** Return values for the FLAC__StreamDecoder write callback.
  89559. */
  89560. typedef enum {
  89561. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89562. /**< The write was OK and decoding can continue. */
  89563. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89564. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89565. } FLAC__StreamDecoderWriteStatus;
  89566. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89567. *
  89568. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89569. * will give the string equivalent. The contents should not be modified.
  89570. */
  89571. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89572. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89573. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89574. * all. The rest could be caused by bad sync (false synchronization on
  89575. * data that is not the start of a frame) or corrupted data. The error
  89576. * itself is the decoder's best guess at what happened assuming a correct
  89577. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89578. * could be caused by a correct sync on the start of a frame, but some
  89579. * data in the frame header was corrupted. Or it could be the result of
  89580. * syncing on a point the stream that looked like the starting of a frame
  89581. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89582. * could be because the decoder encountered a valid frame made by a future
  89583. * version of the encoder which it cannot parse, or because of a false
  89584. * sync making it appear as though an encountered frame was generated by
  89585. * a future encoder.
  89586. */
  89587. typedef enum {
  89588. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89589. /**< An error in the stream caused the decoder to lose synchronization. */
  89590. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89591. /**< The decoder encountered a corrupted frame header. */
  89592. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89593. /**< The frame's data did not match the CRC in the footer. */
  89594. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89595. /**< The decoder encountered reserved fields in use in the stream. */
  89596. } FLAC__StreamDecoderErrorStatus;
  89597. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89598. *
  89599. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89600. * will give the string equivalent. The contents should not be modified.
  89601. */
  89602. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89603. /***********************************************************************
  89604. *
  89605. * class FLAC__StreamDecoder
  89606. *
  89607. ***********************************************************************/
  89608. struct FLAC__StreamDecoderProtected;
  89609. struct FLAC__StreamDecoderPrivate;
  89610. /** The opaque structure definition for the stream decoder type.
  89611. * See the \link flac_stream_decoder stream decoder module \endlink
  89612. * for a detailed description.
  89613. */
  89614. typedef struct {
  89615. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89616. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89617. } FLAC__StreamDecoder;
  89618. /** Signature for the read callback.
  89619. *
  89620. * A function pointer matching this signature must be passed to
  89621. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89622. * called when the decoder needs more input data. The address of the
  89623. * buffer to be filled is supplied, along with the number of bytes the
  89624. * buffer can hold. The callback may choose to supply less data and
  89625. * modify the byte count but must be careful not to overflow the buffer.
  89626. * The callback then returns a status code chosen from
  89627. * FLAC__StreamDecoderReadStatus.
  89628. *
  89629. * Here is an example of a read callback for stdio streams:
  89630. * \code
  89631. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89632. * {
  89633. * FILE *file = ((MyClientData*)client_data)->file;
  89634. * if(*bytes > 0) {
  89635. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89636. * if(ferror(file))
  89637. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89638. * else if(*bytes == 0)
  89639. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89640. * else
  89641. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89642. * }
  89643. * else
  89644. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89645. * }
  89646. * \endcode
  89647. *
  89648. * \note In general, FLAC__StreamDecoder functions which change the
  89649. * state should not be called on the \a decoder while in the callback.
  89650. *
  89651. * \param decoder The decoder instance calling the callback.
  89652. * \param buffer A pointer to a location for the callee to store
  89653. * data to be decoded.
  89654. * \param bytes A pointer to the size of the buffer. On entry
  89655. * to the callback, it contains the maximum number
  89656. * of bytes that may be stored in \a buffer. The
  89657. * callee must set it to the actual number of bytes
  89658. * stored (0 in case of error or end-of-stream) before
  89659. * returning.
  89660. * \param client_data The callee's client data set through
  89661. * FLAC__stream_decoder_init_*().
  89662. * \retval FLAC__StreamDecoderReadStatus
  89663. * The callee's return status. Note that the callback should return
  89664. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89665. * zero bytes were read and there is no more data to be read.
  89666. */
  89667. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89668. /** Signature for the seek callback.
  89669. *
  89670. * A function pointer matching this signature may be passed to
  89671. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89672. * called when the decoder needs to seek the input stream. The decoder
  89673. * will pass the absolute byte offset to seek to, 0 meaning the
  89674. * beginning of the stream.
  89675. *
  89676. * Here is an example of a seek callback for stdio streams:
  89677. * \code
  89678. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89679. * {
  89680. * FILE *file = ((MyClientData*)client_data)->file;
  89681. * if(file == stdin)
  89682. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89683. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89684. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89685. * else
  89686. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89687. * }
  89688. * \endcode
  89689. *
  89690. * \note In general, FLAC__StreamDecoder functions which change the
  89691. * state should not be called on the \a decoder while in the callback.
  89692. *
  89693. * \param decoder The decoder instance calling the callback.
  89694. * \param absolute_byte_offset The offset from the beginning of the stream
  89695. * to seek to.
  89696. * \param client_data The callee's client data set through
  89697. * FLAC__stream_decoder_init_*().
  89698. * \retval FLAC__StreamDecoderSeekStatus
  89699. * The callee's return status.
  89700. */
  89701. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89702. /** Signature for the tell callback.
  89703. *
  89704. * A function pointer matching this signature may be passed to
  89705. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89706. * called when the decoder wants to know the current position of the
  89707. * stream. The callback should return the byte offset from the
  89708. * beginning of the stream.
  89709. *
  89710. * Here is an example of a tell callback for stdio streams:
  89711. * \code
  89712. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89713. * {
  89714. * FILE *file = ((MyClientData*)client_data)->file;
  89715. * off_t pos;
  89716. * if(file == stdin)
  89717. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89718. * else if((pos = ftello(file)) < 0)
  89719. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89720. * else {
  89721. * *absolute_byte_offset = (FLAC__uint64)pos;
  89722. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89723. * }
  89724. * }
  89725. * \endcode
  89726. *
  89727. * \note In general, FLAC__StreamDecoder functions which change the
  89728. * state should not be called on the \a decoder while in the callback.
  89729. *
  89730. * \param decoder The decoder instance calling the callback.
  89731. * \param absolute_byte_offset A pointer to storage for the current offset
  89732. * from the beginning of the stream.
  89733. * \param client_data The callee's client data set through
  89734. * FLAC__stream_decoder_init_*().
  89735. * \retval FLAC__StreamDecoderTellStatus
  89736. * The callee's return status.
  89737. */
  89738. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89739. /** Signature for the length callback.
  89740. *
  89741. * A function pointer matching this signature may be passed to
  89742. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89743. * called when the decoder wants to know the total length of the stream
  89744. * in bytes.
  89745. *
  89746. * Here is an example of a length callback for stdio streams:
  89747. * \code
  89748. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89749. * {
  89750. * FILE *file = ((MyClientData*)client_data)->file;
  89751. * struct stat filestats;
  89752. *
  89753. * if(file == stdin)
  89754. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89755. * else if(fstat(fileno(file), &filestats) != 0)
  89756. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89757. * else {
  89758. * *stream_length = (FLAC__uint64)filestats.st_size;
  89759. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89760. * }
  89761. * }
  89762. * \endcode
  89763. *
  89764. * \note In general, FLAC__StreamDecoder functions which change the
  89765. * state should not be called on the \a decoder while in the callback.
  89766. *
  89767. * \param decoder The decoder instance calling the callback.
  89768. * \param stream_length A pointer to storage for the length of the stream
  89769. * in bytes.
  89770. * \param client_data The callee's client data set through
  89771. * FLAC__stream_decoder_init_*().
  89772. * \retval FLAC__StreamDecoderLengthStatus
  89773. * The callee's return status.
  89774. */
  89775. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89776. /** Signature for the EOF callback.
  89777. *
  89778. * A function pointer matching this signature may be passed to
  89779. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89780. * called when the decoder needs to know if the end of the stream has
  89781. * been reached.
  89782. *
  89783. * Here is an example of a EOF callback for stdio streams:
  89784. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89785. * \code
  89786. * {
  89787. * FILE *file = ((MyClientData*)client_data)->file;
  89788. * return feof(file)? true : false;
  89789. * }
  89790. * \endcode
  89791. *
  89792. * \note In general, FLAC__StreamDecoder functions which change the
  89793. * state should not be called on the \a decoder while in the callback.
  89794. *
  89795. * \param decoder The decoder instance calling the callback.
  89796. * \param client_data The callee's client data set through
  89797. * FLAC__stream_decoder_init_*().
  89798. * \retval FLAC__bool
  89799. * \c true if the currently at the end of the stream, else \c false.
  89800. */
  89801. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89802. /** Signature for the write callback.
  89803. *
  89804. * A function pointer matching this signature must be passed to one of
  89805. * the FLAC__stream_decoder_init_*() functions.
  89806. * The supplied function will be called when the decoder has decoded a
  89807. * single audio frame. The decoder will pass the frame metadata as well
  89808. * as an array of pointers (one for each channel) pointing to the
  89809. * decoded audio.
  89810. *
  89811. * \note In general, FLAC__StreamDecoder functions which change the
  89812. * state should not be called on the \a decoder while in the callback.
  89813. *
  89814. * \param decoder The decoder instance calling the callback.
  89815. * \param frame The description of the decoded frame. See
  89816. * FLAC__Frame.
  89817. * \param buffer An array of pointers to decoded channels of data.
  89818. * Each pointer will point to an array of signed
  89819. * samples of length \a frame->header.blocksize.
  89820. * Channels will be ordered according to the FLAC
  89821. * specification; see the documentation for the
  89822. * <A HREF="../format.html#frame_header">frame header</A>.
  89823. * \param client_data The callee's client data set through
  89824. * FLAC__stream_decoder_init_*().
  89825. * \retval FLAC__StreamDecoderWriteStatus
  89826. * The callee's return status.
  89827. */
  89828. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89829. /** Signature for the metadata callback.
  89830. *
  89831. * A function pointer matching this signature must be passed to one of
  89832. * the FLAC__stream_decoder_init_*() functions.
  89833. * The supplied function will be called when the decoder has decoded a
  89834. * metadata block. In a valid FLAC file there will always be one
  89835. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89836. * These will be supplied by the decoder in the same order as they
  89837. * appear in the stream and always before the first audio frame (i.e.
  89838. * write callback). The metadata block that is passed in must not be
  89839. * modified, and it doesn't live beyond the callback, so you should make
  89840. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89841. * elsewhere. Since metadata blocks can potentially be large, by
  89842. * default the decoder only calls the metadata callback for the
  89843. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89844. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89845. *
  89846. * \note In general, FLAC__StreamDecoder functions which change the
  89847. * state should not be called on the \a decoder while in the callback.
  89848. *
  89849. * \param decoder The decoder instance calling the callback.
  89850. * \param metadata The decoded metadata block.
  89851. * \param client_data The callee's client data set through
  89852. * FLAC__stream_decoder_init_*().
  89853. */
  89854. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89855. /** Signature for the error callback.
  89856. *
  89857. * A function pointer matching this signature must be passed to one of
  89858. * the FLAC__stream_decoder_init_*() functions.
  89859. * The supplied function will be called whenever an error occurs during
  89860. * decoding.
  89861. *
  89862. * \note In general, FLAC__StreamDecoder functions which change the
  89863. * state should not be called on the \a decoder while in the callback.
  89864. *
  89865. * \param decoder The decoder instance calling the callback.
  89866. * \param status The error encountered by the decoder.
  89867. * \param client_data The callee's client data set through
  89868. * FLAC__stream_decoder_init_*().
  89869. */
  89870. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89871. /***********************************************************************
  89872. *
  89873. * Class constructor/destructor
  89874. *
  89875. ***********************************************************************/
  89876. /** Create a new stream decoder instance. The instance is created with
  89877. * default settings; see the individual FLAC__stream_decoder_set_*()
  89878. * functions for each setting's default.
  89879. *
  89880. * \retval FLAC__StreamDecoder*
  89881. * \c NULL if there was an error allocating memory, else the new instance.
  89882. */
  89883. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89884. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89885. *
  89886. * \param decoder A pointer to an existing decoder.
  89887. * \assert
  89888. * \code decoder != NULL \endcode
  89889. */
  89890. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89891. /***********************************************************************
  89892. *
  89893. * Public class method prototypes
  89894. *
  89895. ***********************************************************************/
  89896. /** Set the serial number for the FLAC stream within the Ogg container.
  89897. * The default behavior is to use the serial number of the first Ogg
  89898. * page. Setting a serial number here will explicitly specify which
  89899. * stream is to be decoded.
  89900. *
  89901. * \note
  89902. * This does not need to be set for native FLAC decoding.
  89903. *
  89904. * \default \c use serial number of first page
  89905. * \param decoder A decoder instance to set.
  89906. * \param serial_number See above.
  89907. * \assert
  89908. * \code decoder != NULL \endcode
  89909. * \retval FLAC__bool
  89910. * \c false if the decoder is already initialized, else \c true.
  89911. */
  89912. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89913. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89914. * compute the MD5 signature of the unencoded audio data while decoding
  89915. * and compare it to the signature from the STREAMINFO block, if it
  89916. * exists, during FLAC__stream_decoder_finish().
  89917. *
  89918. * MD5 signature checking will be turned off (until the next
  89919. * FLAC__stream_decoder_reset()) if there is no signature in the
  89920. * STREAMINFO block or when a seek is attempted.
  89921. *
  89922. * Clients that do not use the MD5 check should leave this off to speed
  89923. * up decoding.
  89924. *
  89925. * \default \c false
  89926. * \param decoder A decoder instance to set.
  89927. * \param value Flag value (see above).
  89928. * \assert
  89929. * \code decoder != NULL \endcode
  89930. * \retval FLAC__bool
  89931. * \c false if the decoder is already initialized, else \c true.
  89932. */
  89933. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89934. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89935. *
  89936. * \default By default, only the \c STREAMINFO block is returned via the
  89937. * metadata callback.
  89938. * \param decoder A decoder instance to set.
  89939. * \param type See above.
  89940. * \assert
  89941. * \code decoder != NULL \endcode
  89942. * \a type is valid
  89943. * \retval FLAC__bool
  89944. * \c false if the decoder is already initialized, else \c true.
  89945. */
  89946. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89947. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89948. * given \a id.
  89949. *
  89950. * \default By default, only the \c STREAMINFO block is returned via the
  89951. * metadata callback.
  89952. * \param decoder A decoder instance to set.
  89953. * \param id See above.
  89954. * \assert
  89955. * \code decoder != NULL \endcode
  89956. * \code id != NULL \endcode
  89957. * \retval FLAC__bool
  89958. * \c false if the decoder is already initialized, else \c true.
  89959. */
  89960. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89961. /** Direct the decoder to pass on all metadata blocks of any type.
  89962. *
  89963. * \default By default, only the \c STREAMINFO block is returned via the
  89964. * metadata callback.
  89965. * \param decoder A decoder instance to set.
  89966. * \assert
  89967. * \code decoder != NULL \endcode
  89968. * \retval FLAC__bool
  89969. * \c false if the decoder is already initialized, else \c true.
  89970. */
  89971. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89972. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89973. *
  89974. * \default By default, only the \c STREAMINFO block is returned via the
  89975. * metadata callback.
  89976. * \param decoder A decoder instance to set.
  89977. * \param type See above.
  89978. * \assert
  89979. * \code decoder != NULL \endcode
  89980. * \a type is valid
  89981. * \retval FLAC__bool
  89982. * \c false if the decoder is already initialized, else \c true.
  89983. */
  89984. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89985. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89986. * the given \a id.
  89987. *
  89988. * \default By default, only the \c STREAMINFO block is returned via the
  89989. * metadata callback.
  89990. * \param decoder A decoder instance to set.
  89991. * \param id See above.
  89992. * \assert
  89993. * \code decoder != NULL \endcode
  89994. * \code id != NULL \endcode
  89995. * \retval FLAC__bool
  89996. * \c false if the decoder is already initialized, else \c true.
  89997. */
  89998. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89999. /** Direct the decoder to filter out all metadata blocks of any type.
  90000. *
  90001. * \default By default, only the \c STREAMINFO block is returned via the
  90002. * metadata callback.
  90003. * \param decoder A decoder instance to set.
  90004. * \assert
  90005. * \code decoder != NULL \endcode
  90006. * \retval FLAC__bool
  90007. * \c false if the decoder is already initialized, else \c true.
  90008. */
  90009. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90010. /** Get the current decoder state.
  90011. *
  90012. * \param decoder A decoder instance to query.
  90013. * \assert
  90014. * \code decoder != NULL \endcode
  90015. * \retval FLAC__StreamDecoderState
  90016. * The current decoder state.
  90017. */
  90018. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90019. /** Get the current decoder state as a C string.
  90020. *
  90021. * \param decoder A decoder instance to query.
  90022. * \assert
  90023. * \code decoder != NULL \endcode
  90024. * \retval const char *
  90025. * The decoder state as a C string. Do not modify the contents.
  90026. */
  90027. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90028. /** Get the "MD5 signature checking" flag.
  90029. * This is the value of the setting, not whether or not the decoder is
  90030. * currently checking the MD5 (remember, it can be turned off automatically
  90031. * by a seek). When the decoder is reset the flag will be restored to the
  90032. * value returned by this function.
  90033. *
  90034. * \param decoder A decoder instance to query.
  90035. * \assert
  90036. * \code decoder != NULL \endcode
  90037. * \retval FLAC__bool
  90038. * See above.
  90039. */
  90040. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90041. /** Get the total number of samples in the stream being decoded.
  90042. * Will only be valid after decoding has started and will contain the
  90043. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90044. *
  90045. * \param decoder A decoder instance to query.
  90046. * \assert
  90047. * \code decoder != NULL \endcode
  90048. * \retval unsigned
  90049. * See above.
  90050. */
  90051. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90052. /** Get the current number of channels in the stream being decoded.
  90053. * Will only be valid after decoding has started and will contain the
  90054. * value from the most recently decoded frame header.
  90055. *
  90056. * \param decoder A decoder instance to query.
  90057. * \assert
  90058. * \code decoder != NULL \endcode
  90059. * \retval unsigned
  90060. * See above.
  90061. */
  90062. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90063. /** Get the current channel assignment in the stream being decoded.
  90064. * Will only be valid after decoding has started and will contain the
  90065. * value from the most recently decoded frame header.
  90066. *
  90067. * \param decoder A decoder instance to query.
  90068. * \assert
  90069. * \code decoder != NULL \endcode
  90070. * \retval FLAC__ChannelAssignment
  90071. * See above.
  90072. */
  90073. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90074. /** Get the current sample resolution in the stream being decoded.
  90075. * Will only be valid after decoding has started and will contain the
  90076. * value from the most recently decoded frame header.
  90077. *
  90078. * \param decoder A decoder instance to query.
  90079. * \assert
  90080. * \code decoder != NULL \endcode
  90081. * \retval unsigned
  90082. * See above.
  90083. */
  90084. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90085. /** Get the current sample rate in Hz of the stream being decoded.
  90086. * Will only be valid after decoding has started and will contain the
  90087. * value from the most recently decoded frame header.
  90088. *
  90089. * \param decoder A decoder instance to query.
  90090. * \assert
  90091. * \code decoder != NULL \endcode
  90092. * \retval unsigned
  90093. * See above.
  90094. */
  90095. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90096. /** Get the current blocksize of the stream being decoded.
  90097. * Will only be valid after decoding has started and will contain the
  90098. * value from the most recently decoded frame header.
  90099. *
  90100. * \param decoder A decoder instance to query.
  90101. * \assert
  90102. * \code decoder != NULL \endcode
  90103. * \retval unsigned
  90104. * See above.
  90105. */
  90106. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90107. /** Returns the decoder's current read position within the stream.
  90108. * The position is the byte offset from the start of the stream.
  90109. * Bytes before this position have been fully decoded. Note that
  90110. * there may still be undecoded bytes in the decoder's read FIFO.
  90111. * The returned position is correct even after a seek.
  90112. *
  90113. * \warning This function currently only works for native FLAC,
  90114. * not Ogg FLAC streams.
  90115. *
  90116. * \param decoder A decoder instance to query.
  90117. * \param position Address at which to return the desired position.
  90118. * \assert
  90119. * \code decoder != NULL \endcode
  90120. * \code position != NULL \endcode
  90121. * \retval FLAC__bool
  90122. * \c true if successful, \c false if the stream is not native FLAC,
  90123. * or there was an error from the 'tell' callback or it returned
  90124. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90125. */
  90126. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90127. /** Initialize the decoder instance to decode native FLAC streams.
  90128. *
  90129. * This flavor of initialization sets up the decoder to decode from a
  90130. * native FLAC stream. I/O is performed via callbacks to the client.
  90131. * For decoding from a plain file via filename or open FILE*,
  90132. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90133. * provide a simpler interface.
  90134. *
  90135. * This function should be called after FLAC__stream_decoder_new() and
  90136. * FLAC__stream_decoder_set_*() but before any of the
  90137. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90138. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90139. * if initialization succeeded.
  90140. *
  90141. * \param decoder An uninitialized decoder instance.
  90142. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90143. * pointer must not be \c NULL.
  90144. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90145. * pointer may be \c NULL if seeking is not
  90146. * supported. If \a seek_callback is not \c NULL then a
  90147. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90148. * Alternatively, a dummy seek callback that just
  90149. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90150. * may also be supplied, all though this is slightly
  90151. * less efficient for the decoder.
  90152. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90153. * pointer may be \c NULL if not supported by the client. If
  90154. * \a seek_callback is not \c NULL then a
  90155. * \a tell_callback must also be supplied.
  90156. * Alternatively, a dummy tell callback that just
  90157. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90158. * may also be supplied, all though this is slightly
  90159. * less efficient for the decoder.
  90160. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90161. * pointer may be \c NULL if not supported by the client. If
  90162. * \a seek_callback is not \c NULL then a
  90163. * \a length_callback must also be supplied.
  90164. * Alternatively, a dummy length callback that just
  90165. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90166. * may also be supplied, all though this is slightly
  90167. * less efficient for the decoder.
  90168. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90169. * pointer may be \c NULL if not supported by the client. If
  90170. * \a seek_callback is not \c NULL then a
  90171. * \a eof_callback must also be supplied.
  90172. * Alternatively, a dummy length callback that just
  90173. * returns \c false
  90174. * may also be supplied, all though this is slightly
  90175. * less efficient for the decoder.
  90176. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90177. * pointer must not be \c NULL.
  90178. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90179. * pointer may be \c NULL if the callback is not
  90180. * desired.
  90181. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90182. * pointer must not be \c NULL.
  90183. * \param client_data This value will be supplied to callbacks in their
  90184. * \a client_data argument.
  90185. * \assert
  90186. * \code decoder != NULL \endcode
  90187. * \retval FLAC__StreamDecoderInitStatus
  90188. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90189. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90190. */
  90191. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90192. FLAC__StreamDecoder *decoder,
  90193. FLAC__StreamDecoderReadCallback read_callback,
  90194. FLAC__StreamDecoderSeekCallback seek_callback,
  90195. FLAC__StreamDecoderTellCallback tell_callback,
  90196. FLAC__StreamDecoderLengthCallback length_callback,
  90197. FLAC__StreamDecoderEofCallback eof_callback,
  90198. FLAC__StreamDecoderWriteCallback write_callback,
  90199. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90200. FLAC__StreamDecoderErrorCallback error_callback,
  90201. void *client_data
  90202. );
  90203. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90204. *
  90205. * This flavor of initialization sets up the decoder to decode from a
  90206. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90207. * client. For decoding from a plain file via filename or open FILE*,
  90208. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90209. * provide a simpler interface.
  90210. *
  90211. * This function should be called after FLAC__stream_decoder_new() and
  90212. * FLAC__stream_decoder_set_*() but before any of the
  90213. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90214. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90215. * if initialization succeeded.
  90216. *
  90217. * \note Support for Ogg FLAC in the library is optional. If this
  90218. * library has been built without support for Ogg FLAC, this function
  90219. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90220. *
  90221. * \param decoder An uninitialized decoder instance.
  90222. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90223. * pointer must not be \c NULL.
  90224. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90225. * pointer may be \c NULL if seeking is not
  90226. * supported. If \a seek_callback is not \c NULL then a
  90227. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90228. * Alternatively, a dummy seek callback that just
  90229. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90230. * may also be supplied, all though this is slightly
  90231. * less efficient for the decoder.
  90232. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90233. * pointer may be \c NULL if not supported by the client. If
  90234. * \a seek_callback is not \c NULL then a
  90235. * \a tell_callback must also be supplied.
  90236. * Alternatively, a dummy tell callback that just
  90237. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90238. * may also be supplied, all though this is slightly
  90239. * less efficient for the decoder.
  90240. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90241. * pointer may be \c NULL if not supported by the client. If
  90242. * \a seek_callback is not \c NULL then a
  90243. * \a length_callback must also be supplied.
  90244. * Alternatively, a dummy length callback that just
  90245. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90246. * may also be supplied, all though this is slightly
  90247. * less efficient for the decoder.
  90248. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90249. * pointer may be \c NULL if not supported by the client. If
  90250. * \a seek_callback is not \c NULL then a
  90251. * \a eof_callback must also be supplied.
  90252. * Alternatively, a dummy length callback that just
  90253. * returns \c false
  90254. * may also be supplied, all though this is slightly
  90255. * less efficient for the decoder.
  90256. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90257. * pointer must not be \c NULL.
  90258. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90259. * pointer may be \c NULL if the callback is not
  90260. * desired.
  90261. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90262. * pointer must not be \c NULL.
  90263. * \param client_data This value will be supplied to callbacks in their
  90264. * \a client_data argument.
  90265. * \assert
  90266. * \code decoder != NULL \endcode
  90267. * \retval FLAC__StreamDecoderInitStatus
  90268. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90269. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90270. */
  90271. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90272. FLAC__StreamDecoder *decoder,
  90273. FLAC__StreamDecoderReadCallback read_callback,
  90274. FLAC__StreamDecoderSeekCallback seek_callback,
  90275. FLAC__StreamDecoderTellCallback tell_callback,
  90276. FLAC__StreamDecoderLengthCallback length_callback,
  90277. FLAC__StreamDecoderEofCallback eof_callback,
  90278. FLAC__StreamDecoderWriteCallback write_callback,
  90279. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90280. FLAC__StreamDecoderErrorCallback error_callback,
  90281. void *client_data
  90282. );
  90283. /** Initialize the decoder instance to decode native FLAC files.
  90284. *
  90285. * This flavor of initialization sets up the decoder to decode from a
  90286. * plain native FLAC file. For non-stdio streams, you must use
  90287. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90288. *
  90289. * This function should be called after FLAC__stream_decoder_new() and
  90290. * FLAC__stream_decoder_set_*() but before any of the
  90291. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90292. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90293. * if initialization succeeded.
  90294. *
  90295. * \param decoder An uninitialized decoder instance.
  90296. * \param file An open FLAC file. The file should have been
  90297. * opened with mode \c "rb" and rewound. The file
  90298. * becomes owned by the decoder and should not be
  90299. * manipulated by the client while decoding.
  90300. * Unless \a file is \c stdin, it will be closed
  90301. * when FLAC__stream_decoder_finish() is called.
  90302. * Note however that seeking will not work when
  90303. * decoding from \c stdout since it is not seekable.
  90304. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90305. * pointer must not be \c NULL.
  90306. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90307. * pointer may be \c NULL if the callback is not
  90308. * desired.
  90309. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90310. * pointer must not be \c NULL.
  90311. * \param client_data This value will be supplied to callbacks in their
  90312. * \a client_data argument.
  90313. * \assert
  90314. * \code decoder != NULL \endcode
  90315. * \code file != NULL \endcode
  90316. * \retval FLAC__StreamDecoderInitStatus
  90317. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90318. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90319. */
  90320. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90321. FLAC__StreamDecoder *decoder,
  90322. FILE *file,
  90323. FLAC__StreamDecoderWriteCallback write_callback,
  90324. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90325. FLAC__StreamDecoderErrorCallback error_callback,
  90326. void *client_data
  90327. );
  90328. /** Initialize the decoder instance to decode Ogg FLAC files.
  90329. *
  90330. * This flavor of initialization sets up the decoder to decode from a
  90331. * plain Ogg FLAC file. For non-stdio streams, you must use
  90332. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90333. *
  90334. * This function should be called after FLAC__stream_decoder_new() and
  90335. * FLAC__stream_decoder_set_*() but before any of the
  90336. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90337. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90338. * if initialization succeeded.
  90339. *
  90340. * \note Support for Ogg FLAC in the library is optional. If this
  90341. * library has been built without support for Ogg FLAC, this function
  90342. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90343. *
  90344. * \param decoder An uninitialized decoder instance.
  90345. * \param file An open FLAC file. The file should have been
  90346. * opened with mode \c "rb" and rewound. The file
  90347. * becomes owned by the decoder and should not be
  90348. * manipulated by the client while decoding.
  90349. * Unless \a file is \c stdin, it will be closed
  90350. * when FLAC__stream_decoder_finish() is called.
  90351. * Note however that seeking will not work when
  90352. * decoding from \c stdout since it is not seekable.
  90353. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90354. * pointer must not be \c NULL.
  90355. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90356. * pointer may be \c NULL if the callback is not
  90357. * desired.
  90358. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90359. * pointer must not be \c NULL.
  90360. * \param client_data This value will be supplied to callbacks in their
  90361. * \a client_data argument.
  90362. * \assert
  90363. * \code decoder != NULL \endcode
  90364. * \code file != NULL \endcode
  90365. * \retval FLAC__StreamDecoderInitStatus
  90366. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90367. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90368. */
  90369. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90370. FLAC__StreamDecoder *decoder,
  90371. FILE *file,
  90372. FLAC__StreamDecoderWriteCallback write_callback,
  90373. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90374. FLAC__StreamDecoderErrorCallback error_callback,
  90375. void *client_data
  90376. );
  90377. /** Initialize the decoder instance to decode native FLAC files.
  90378. *
  90379. * This flavor of initialization sets up the decoder to decode from a plain
  90380. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90381. * example, with Unicode filenames on Windows), you must use
  90382. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90383. * and provide callbacks for the I/O.
  90384. *
  90385. * This function should be called after FLAC__stream_decoder_new() and
  90386. * FLAC__stream_decoder_set_*() but before any of the
  90387. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90388. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90389. * if initialization succeeded.
  90390. *
  90391. * \param decoder An uninitialized decoder instance.
  90392. * \param filename The name of the file to decode from. The file will
  90393. * be opened with fopen(). Use \c NULL to decode from
  90394. * \c stdin. Note that \c stdin is not seekable.
  90395. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90396. * pointer must not be \c NULL.
  90397. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90398. * pointer may be \c NULL if the callback is not
  90399. * desired.
  90400. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90401. * pointer must not be \c NULL.
  90402. * \param client_data This value will be supplied to callbacks in their
  90403. * \a client_data argument.
  90404. * \assert
  90405. * \code decoder != NULL \endcode
  90406. * \retval FLAC__StreamDecoderInitStatus
  90407. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90408. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90409. */
  90410. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90411. FLAC__StreamDecoder *decoder,
  90412. const char *filename,
  90413. FLAC__StreamDecoderWriteCallback write_callback,
  90414. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90415. FLAC__StreamDecoderErrorCallback error_callback,
  90416. void *client_data
  90417. );
  90418. /** Initialize the decoder instance to decode Ogg FLAC files.
  90419. *
  90420. * This flavor of initialization sets up the decoder to decode from a plain
  90421. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90422. * example, with Unicode filenames on Windows), you must use
  90423. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90424. * and provide callbacks for the I/O.
  90425. *
  90426. * This function should be called after FLAC__stream_decoder_new() and
  90427. * FLAC__stream_decoder_set_*() but before any of the
  90428. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90429. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90430. * if initialization succeeded.
  90431. *
  90432. * \note Support for Ogg FLAC in the library is optional. If this
  90433. * library has been built without support for Ogg FLAC, this function
  90434. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90435. *
  90436. * \param decoder An uninitialized decoder instance.
  90437. * \param filename The name of the file to decode from. The file will
  90438. * be opened with fopen(). Use \c NULL to decode from
  90439. * \c stdin. Note that \c stdin is not seekable.
  90440. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90441. * pointer must not be \c NULL.
  90442. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90443. * pointer may be \c NULL if the callback is not
  90444. * desired.
  90445. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90446. * pointer must not be \c NULL.
  90447. * \param client_data This value will be supplied to callbacks in their
  90448. * \a client_data argument.
  90449. * \assert
  90450. * \code decoder != NULL \endcode
  90451. * \retval FLAC__StreamDecoderInitStatus
  90452. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90453. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90454. */
  90455. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90456. FLAC__StreamDecoder *decoder,
  90457. const char *filename,
  90458. FLAC__StreamDecoderWriteCallback write_callback,
  90459. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90460. FLAC__StreamDecoderErrorCallback error_callback,
  90461. void *client_data
  90462. );
  90463. /** Finish the decoding process.
  90464. * Flushes the decoding buffer, releases resources, resets the decoder
  90465. * settings to their defaults, and returns the decoder state to
  90466. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90467. *
  90468. * In the event of a prematurely-terminated decode, it is not strictly
  90469. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90470. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90471. * with a FLAC__stream_decoder_finish().
  90472. *
  90473. * \param decoder An uninitialized decoder instance.
  90474. * \assert
  90475. * \code decoder != NULL \endcode
  90476. * \retval FLAC__bool
  90477. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90478. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90479. * signature does not match the one computed by the decoder; else
  90480. * \c true.
  90481. */
  90482. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90483. /** Flush the stream input.
  90484. * The decoder's input buffer will be cleared and the state set to
  90485. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90486. * off MD5 checking.
  90487. *
  90488. * \param decoder A decoder instance.
  90489. * \assert
  90490. * \code decoder != NULL \endcode
  90491. * \retval FLAC__bool
  90492. * \c true if successful, else \c false if a memory allocation
  90493. * error occurs (in which case the state will be set to
  90494. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90495. */
  90496. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90497. /** Reset the decoding process.
  90498. * The decoder's input buffer will be cleared and the state set to
  90499. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90500. * FLAC__stream_decoder_finish() except that the settings are
  90501. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90502. * before decoding again. MD5 checking will be restored to its original
  90503. * setting.
  90504. *
  90505. * If the decoder is seekable, or was initialized with
  90506. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90507. * the decoder will also attempt to seek to the beginning of the file.
  90508. * If this rewind fails, this function will return \c false. It follows
  90509. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90510. * \c stdin.
  90511. *
  90512. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90513. * and is not seekable (i.e. no seek callback was provided or the seek
  90514. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90515. * is the duty of the client to start feeding data from the beginning of
  90516. * the stream on the next FLAC__stream_decoder_process() or
  90517. * FLAC__stream_decoder_process_interleaved() call.
  90518. *
  90519. * \param decoder A decoder instance.
  90520. * \assert
  90521. * \code decoder != NULL \endcode
  90522. * \retval FLAC__bool
  90523. * \c true if successful, else \c false if a memory allocation occurs
  90524. * (in which case the state will be set to
  90525. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90526. * occurs (the state will be unchanged).
  90527. */
  90528. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90529. /** Decode one metadata block or audio frame.
  90530. * This version instructs the decoder to decode a either a single metadata
  90531. * block or a single frame and stop, unless the callbacks return a fatal
  90532. * error or the read callback returns
  90533. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90534. *
  90535. * As the decoder needs more input it will call the read callback.
  90536. * Depending on what was decoded, the metadata or write callback will be
  90537. * called with the decoded metadata block or audio frame.
  90538. *
  90539. * Unless there is a fatal read error or end of stream, this function
  90540. * will return once one whole frame is decoded. In other words, if the
  90541. * stream is not synchronized or points to a corrupt frame header, the
  90542. * decoder will continue to try and resync until it gets to a valid
  90543. * frame, then decode one frame, then return. If the decoder points to
  90544. * a frame whose frame CRC in the frame footer does not match the
  90545. * computed frame CRC, this function will issue a
  90546. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90547. * error callback, and return, having decoded one complete, although
  90548. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90549. * correct length to the write callback.)
  90550. *
  90551. * \param decoder An initialized decoder instance.
  90552. * \assert
  90553. * \code decoder != NULL \endcode
  90554. * \retval FLAC__bool
  90555. * \c false if any fatal read, write, or memory allocation error
  90556. * occurred (meaning decoding must stop), else \c true; for more
  90557. * information about the decoder, check the decoder state with
  90558. * FLAC__stream_decoder_get_state().
  90559. */
  90560. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90561. /** Decode until the end of the metadata.
  90562. * This version instructs the decoder to decode from the current position
  90563. * and continue until all the metadata has been read, or until the
  90564. * callbacks return a fatal error or the read callback returns
  90565. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90566. *
  90567. * As the decoder needs more input it will call the read callback.
  90568. * As each metadata block is decoded, the metadata callback will be called
  90569. * with the decoded metadata.
  90570. *
  90571. * \param decoder An initialized decoder instance.
  90572. * \assert
  90573. * \code decoder != NULL \endcode
  90574. * \retval FLAC__bool
  90575. * \c false if any fatal read, write, or memory allocation error
  90576. * occurred (meaning decoding must stop), else \c true; for more
  90577. * information about the decoder, check the decoder state with
  90578. * FLAC__stream_decoder_get_state().
  90579. */
  90580. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90581. /** Decode until the end of the stream.
  90582. * This version instructs the decoder to decode from the current position
  90583. * and continue until the end of stream (the read callback returns
  90584. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90585. * callbacks return a fatal error.
  90586. *
  90587. * As the decoder needs more input it will call the read callback.
  90588. * As each metadata block and frame is decoded, the metadata or write
  90589. * callback will be called with the decoded metadata or frame.
  90590. *
  90591. * \param decoder An initialized decoder instance.
  90592. * \assert
  90593. * \code decoder != NULL \endcode
  90594. * \retval FLAC__bool
  90595. * \c false if any fatal read, write, or memory allocation error
  90596. * occurred (meaning decoding must stop), else \c true; for more
  90597. * information about the decoder, check the decoder state with
  90598. * FLAC__stream_decoder_get_state().
  90599. */
  90600. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90601. /** Skip one audio frame.
  90602. * This version instructs the decoder to 'skip' a single frame and stop,
  90603. * unless the callbacks return a fatal error or the read callback returns
  90604. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90605. *
  90606. * The decoding flow is the same as what occurs when
  90607. * FLAC__stream_decoder_process_single() is called to process an audio
  90608. * frame, except that this function does not decode the parsed data into
  90609. * PCM or call the write callback. The integrity of the frame is still
  90610. * checked the same way as in the other process functions.
  90611. *
  90612. * This function will return once one whole frame is skipped, in the
  90613. * same way that FLAC__stream_decoder_process_single() will return once
  90614. * one whole frame is decoded.
  90615. *
  90616. * This function can be used in more quickly determining FLAC frame
  90617. * boundaries when decoding of the actual data is not needed, for
  90618. * example when an application is separating a FLAC stream into frames
  90619. * for editing or storing in a container. To do this, the application
  90620. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90621. * to the next frame, then use
  90622. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90623. * boundary.
  90624. *
  90625. * This function should only be called when the stream has advanced
  90626. * past all the metadata, otherwise it will return \c false.
  90627. *
  90628. * \param decoder An initialized decoder instance not in a metadata
  90629. * state.
  90630. * \assert
  90631. * \code decoder != NULL \endcode
  90632. * \retval FLAC__bool
  90633. * \c false if any fatal read, write, or memory allocation error
  90634. * occurred (meaning decoding must stop), or if the decoder
  90635. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90636. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90637. * information about the decoder, check the decoder state with
  90638. * FLAC__stream_decoder_get_state().
  90639. */
  90640. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90641. /** Flush the input and seek to an absolute sample.
  90642. * Decoding will resume at the given sample. Note that because of
  90643. * this, the next write callback may contain a partial block. The
  90644. * client must support seeking the input or this function will fail
  90645. * and return \c false. Furthermore, if the decoder state is
  90646. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90647. * with FLAC__stream_decoder_flush() or reset with
  90648. * FLAC__stream_decoder_reset() before decoding can continue.
  90649. *
  90650. * \param decoder A decoder instance.
  90651. * \param sample The target sample number to seek to.
  90652. * \assert
  90653. * \code decoder != NULL \endcode
  90654. * \retval FLAC__bool
  90655. * \c true if successful, else \c false.
  90656. */
  90657. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90658. /* \} */
  90659. #ifdef __cplusplus
  90660. }
  90661. #endif
  90662. #endif
  90663. /*** End of inlined file: stream_decoder.h ***/
  90664. /*** Start of inlined file: stream_encoder.h ***/
  90665. #ifndef FLAC__STREAM_ENCODER_H
  90666. #define FLAC__STREAM_ENCODER_H
  90667. #include <stdio.h> /* for FILE */
  90668. #ifdef __cplusplus
  90669. extern "C" {
  90670. #endif
  90671. /** \file include/FLAC/stream_encoder.h
  90672. *
  90673. * \brief
  90674. * This module contains the functions which implement the stream
  90675. * encoder.
  90676. *
  90677. * See the detailed documentation in the
  90678. * \link flac_stream_encoder stream encoder \endlink module.
  90679. */
  90680. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90681. * \ingroup flac
  90682. *
  90683. * \brief
  90684. * This module describes the encoder layers provided by libFLAC.
  90685. *
  90686. * The stream encoder can be used to encode complete streams either to the
  90687. * client via callbacks, or directly to a file, depending on how it is
  90688. * initialized. When encoding via callbacks, the client provides a write
  90689. * callback which will be called whenever FLAC data is ready to be written.
  90690. * If the client also supplies a seek callback, the encoder will also
  90691. * automatically handle the writing back of metadata discovered while
  90692. * encoding, like stream info, seek points offsets, etc. When encoding to
  90693. * a file, the client needs only supply a filename or open \c FILE* and an
  90694. * optional progress callback for periodic notification of progress; the
  90695. * write and seek callbacks are supplied internally. For more info see the
  90696. * \link flac_stream_encoder stream encoder \endlink module.
  90697. */
  90698. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90699. * \ingroup flac_encoder
  90700. *
  90701. * \brief
  90702. * This module contains the functions which implement the stream
  90703. * encoder.
  90704. *
  90705. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90706. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90707. *
  90708. * The basic usage of this encoder is as follows:
  90709. * - The program creates an instance of an encoder using
  90710. * FLAC__stream_encoder_new().
  90711. * - The program overrides the default settings using
  90712. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90713. * functions should be called:
  90714. * - FLAC__stream_encoder_set_channels()
  90715. * - FLAC__stream_encoder_set_bits_per_sample()
  90716. * - FLAC__stream_encoder_set_sample_rate()
  90717. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90718. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90719. * - If the application wants to control the compression level or set its own
  90720. * metadata, then the following should also be called:
  90721. * - FLAC__stream_encoder_set_compression_level()
  90722. * - FLAC__stream_encoder_set_verify()
  90723. * - FLAC__stream_encoder_set_metadata()
  90724. * - The rest of the set functions should only be called if the client needs
  90725. * exact control over how the audio is compressed; thorough understanding
  90726. * of the FLAC format is necessary to achieve good results.
  90727. * - The program initializes the instance to validate the settings and
  90728. * prepare for encoding using
  90729. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90730. * or FLAC__stream_encoder_init_file() for native FLAC
  90731. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90732. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90733. * - The program calls FLAC__stream_encoder_process() or
  90734. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90735. * subsequently calls the callbacks when there is encoder data ready
  90736. * to be written.
  90737. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90738. * which causes the encoder to encode any data still in its input pipe,
  90739. * update the metadata with the final encoding statistics if output
  90740. * seeking is possible, and finally reset the encoder to the
  90741. * uninitialized state.
  90742. * - The instance may be used again or deleted with
  90743. * FLAC__stream_encoder_delete().
  90744. *
  90745. * In more detail, the stream encoder functions similarly to the
  90746. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90747. * callbacks and more options. Typically the client will create a new
  90748. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90749. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90750. * calling one of the FLAC__stream_encoder_init_*() functions.
  90751. *
  90752. * Unlike the decoders, the stream encoder has many options that can
  90753. * affect the speed and compression ratio. When setting these parameters
  90754. * you should have some basic knowledge of the format (see the
  90755. * <A HREF="../documentation.html#format">user-level documentation</A>
  90756. * or the <A HREF="../format.html">formal description</A>). The
  90757. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90758. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90759. * functions will do this, so make sure to pay attention to the state
  90760. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90761. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90762. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90763. * the constructor.
  90764. *
  90765. * There are three initialization functions for native FLAC, one for
  90766. * setting up the encoder to encode FLAC data to the client via
  90767. * callbacks, and two for encoding directly to a file.
  90768. *
  90769. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90770. * You must also supply a write callback which will be called anytime
  90771. * there is raw encoded data to write. If the client can seek the output
  90772. * it is best to also supply seek and tell callbacks, as this allows the
  90773. * encoder to go back after encoding is finished to write back
  90774. * information that was collected while encoding, like seek point offsets,
  90775. * frame sizes, etc.
  90776. *
  90777. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90778. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90779. * filename or open \c FILE*; the encoder will handle all the callbacks
  90780. * internally. You may also supply a progress callback for periodic
  90781. * notification of the encoding progress.
  90782. *
  90783. * There are three similarly-named init functions for encoding to Ogg
  90784. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90785. * library has been built with Ogg support.
  90786. *
  90787. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90788. * call the write callback several times, once with the \c fLaC signature,
  90789. * and once for each encoded metadata block. Note that for Ogg FLAC
  90790. * encoding you will usually get at least twice the number of callbacks than
  90791. * with native FLAC, one for the Ogg page header and one for the page body.
  90792. *
  90793. * After initializing the instance, the client may feed audio data to the
  90794. * encoder in one of two ways:
  90795. *
  90796. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90797. * will pass an array of pointers to buffers, one for each channel, to
  90798. * the encoder, each of the same length. The samples need not be
  90799. * block-aligned, but each channel should have the same number of samples.
  90800. * - Channel interleaved, through
  90801. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90802. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90803. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90804. * Again, the samples need not be block-aligned but they must be
  90805. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90806. * the last value channelN_sampleM.
  90807. *
  90808. * Note that for either process call, each sample in the buffers should be a
  90809. * signed integer, right-justified to the resolution set by
  90810. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90811. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90812. *
  90813. * When the client is finished encoding data, it calls
  90814. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90815. * data still in its input pipe, and call the metadata callback with the
  90816. * final encoding statistics. Then the instance may be deleted with
  90817. * FLAC__stream_encoder_delete() or initialized again to encode another
  90818. * stream.
  90819. *
  90820. * For programs that write their own metadata, but that do not know the
  90821. * actual metadata until after encoding, it is advantageous to instruct
  90822. * the encoder to write a PADDING block of the correct size, so that
  90823. * instead of rewriting the whole stream after encoding, the program can
  90824. * just overwrite the PADDING block. If only the maximum size of the
  90825. * metadata is known, the program can write a slightly larger padding
  90826. * block, then split it after encoding.
  90827. *
  90828. * Make sure you understand how lengths are calculated. All FLAC metadata
  90829. * blocks have a 4 byte header which contains the type and length. This
  90830. * length does not include the 4 bytes of the header. See the format page
  90831. * for the specification of metadata blocks and their lengths.
  90832. *
  90833. * \note
  90834. * If you are writing the FLAC data to a file via callbacks, make sure it
  90835. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90836. * after the first encoding pass, the encoder will try to seek back to the
  90837. * beginning of the stream, to the STREAMINFO block, to write some data
  90838. * there. (If using FLAC__stream_encoder_init*_file() or
  90839. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90840. *
  90841. * \note
  90842. * The "set" functions may only be called when the encoder is in the
  90843. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90844. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90845. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90846. * return \c true, otherwise \c false.
  90847. *
  90848. * \note
  90849. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90850. * defaults.
  90851. *
  90852. * \{
  90853. */
  90854. /** State values for a FLAC__StreamEncoder.
  90855. *
  90856. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90857. *
  90858. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90859. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90860. * must be deleted with FLAC__stream_encoder_delete().
  90861. */
  90862. typedef enum {
  90863. FLAC__STREAM_ENCODER_OK = 0,
  90864. /**< The encoder is in the normal OK state and samples can be processed. */
  90865. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90866. /**< The encoder is in the uninitialized state; one of the
  90867. * FLAC__stream_encoder_init_*() functions must be called before samples
  90868. * can be processed.
  90869. */
  90870. FLAC__STREAM_ENCODER_OGG_ERROR,
  90871. /**< An error occurred in the underlying Ogg layer. */
  90872. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90873. /**< An error occurred in the underlying verify stream decoder;
  90874. * check FLAC__stream_encoder_get_verify_decoder_state().
  90875. */
  90876. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90877. /**< The verify decoder detected a mismatch between the original
  90878. * audio signal and the decoded audio signal.
  90879. */
  90880. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90881. /**< One of the callbacks returned a fatal error. */
  90882. FLAC__STREAM_ENCODER_IO_ERROR,
  90883. /**< An I/O error occurred while opening/reading/writing a file.
  90884. * Check \c errno.
  90885. */
  90886. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90887. /**< An error occurred while writing the stream; usually, the
  90888. * write_callback returned an error.
  90889. */
  90890. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90891. /**< Memory allocation failed. */
  90892. } FLAC__StreamEncoderState;
  90893. /** Maps a FLAC__StreamEncoderState to a C string.
  90894. *
  90895. * Using a FLAC__StreamEncoderState as the index to this array
  90896. * will give the string equivalent. The contents should not be modified.
  90897. */
  90898. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90899. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90900. */
  90901. typedef enum {
  90902. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90903. /**< Initialization was successful. */
  90904. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90905. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90906. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90907. /**< The library was not compiled with support for the given container
  90908. * format.
  90909. */
  90910. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90911. /**< A required callback was not supplied. */
  90912. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90913. /**< The encoder has an invalid setting for number of channels. */
  90914. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90915. /**< The encoder has an invalid setting for bits-per-sample.
  90916. * FLAC supports 4-32 bps but the reference encoder currently supports
  90917. * only up to 24 bps.
  90918. */
  90919. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90920. /**< The encoder has an invalid setting for the input sample rate. */
  90921. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90922. /**< The encoder has an invalid setting for the block size. */
  90923. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90924. /**< The encoder has an invalid setting for the maximum LPC order. */
  90925. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90926. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90927. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90928. /**< The specified block size is less than the maximum LPC order. */
  90929. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90930. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90931. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90932. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90933. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90934. * - One of the metadata blocks contains an undefined type
  90935. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90936. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90937. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90938. */
  90939. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90940. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90941. * already initialized, usually because
  90942. * FLAC__stream_encoder_finish() was not called.
  90943. */
  90944. } FLAC__StreamEncoderInitStatus;
  90945. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90946. *
  90947. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90948. * will give the string equivalent. The contents should not be modified.
  90949. */
  90950. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90951. /** Return values for the FLAC__StreamEncoder read callback.
  90952. */
  90953. typedef enum {
  90954. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90955. /**< The read was OK and decoding can continue. */
  90956. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90957. /**< The read was attempted at the end of the stream. */
  90958. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90959. /**< An unrecoverable error occurred. */
  90960. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90961. /**< Client does not support reading back from the output. */
  90962. } FLAC__StreamEncoderReadStatus;
  90963. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90964. *
  90965. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90966. * will give the string equivalent. The contents should not be modified.
  90967. */
  90968. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90969. /** Return values for the FLAC__StreamEncoder write callback.
  90970. */
  90971. typedef enum {
  90972. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90973. /**< The write was OK and encoding can continue. */
  90974. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90975. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90976. } FLAC__StreamEncoderWriteStatus;
  90977. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90978. *
  90979. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90980. * will give the string equivalent. The contents should not be modified.
  90981. */
  90982. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90983. /** Return values for the FLAC__StreamEncoder seek callback.
  90984. */
  90985. typedef enum {
  90986. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90987. /**< The seek was OK and encoding can continue. */
  90988. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90989. /**< An unrecoverable error occurred. */
  90990. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90991. /**< Client does not support seeking. */
  90992. } FLAC__StreamEncoderSeekStatus;
  90993. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90994. *
  90995. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90996. * will give the string equivalent. The contents should not be modified.
  90997. */
  90998. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90999. /** Return values for the FLAC__StreamEncoder tell callback.
  91000. */
  91001. typedef enum {
  91002. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91003. /**< The tell was OK and encoding can continue. */
  91004. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91005. /**< An unrecoverable error occurred. */
  91006. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91007. /**< Client does not support seeking. */
  91008. } FLAC__StreamEncoderTellStatus;
  91009. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91010. *
  91011. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91012. * will give the string equivalent. The contents should not be modified.
  91013. */
  91014. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91015. /***********************************************************************
  91016. *
  91017. * class FLAC__StreamEncoder
  91018. *
  91019. ***********************************************************************/
  91020. struct FLAC__StreamEncoderProtected;
  91021. struct FLAC__StreamEncoderPrivate;
  91022. /** The opaque structure definition for the stream encoder type.
  91023. * See the \link flac_stream_encoder stream encoder module \endlink
  91024. * for a detailed description.
  91025. */
  91026. typedef struct {
  91027. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91028. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91029. } FLAC__StreamEncoder;
  91030. /** Signature for the read callback.
  91031. *
  91032. * A function pointer matching this signature must be passed to
  91033. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91034. * The supplied function will be called when the encoder needs to read back
  91035. * encoded data. This happens during the metadata callback, when the encoder
  91036. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91037. * while encoding. The address of the buffer to be filled is supplied, along
  91038. * with the number of bytes the buffer can hold. The callback may choose to
  91039. * supply less data and modify the byte count but must be careful not to
  91040. * overflow the buffer. The callback then returns a status code chosen from
  91041. * FLAC__StreamEncoderReadStatus.
  91042. *
  91043. * Here is an example of a read callback for stdio streams:
  91044. * \code
  91045. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91046. * {
  91047. * FILE *file = ((MyClientData*)client_data)->file;
  91048. * if(*bytes > 0) {
  91049. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91050. * if(ferror(file))
  91051. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91052. * else if(*bytes == 0)
  91053. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91054. * else
  91055. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91056. * }
  91057. * else
  91058. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91059. * }
  91060. * \endcode
  91061. *
  91062. * \note In general, FLAC__StreamEncoder functions which change the
  91063. * state should not be called on the \a encoder while in the callback.
  91064. *
  91065. * \param encoder The encoder instance calling the callback.
  91066. * \param buffer A pointer to a location for the callee to store
  91067. * data to be encoded.
  91068. * \param bytes A pointer to the size of the buffer. On entry
  91069. * to the callback, it contains the maximum number
  91070. * of bytes that may be stored in \a buffer. The
  91071. * callee must set it to the actual number of bytes
  91072. * stored (0 in case of error or end-of-stream) before
  91073. * returning.
  91074. * \param client_data The callee's client data set through
  91075. * FLAC__stream_encoder_set_client_data().
  91076. * \retval FLAC__StreamEncoderReadStatus
  91077. * The callee's return status.
  91078. */
  91079. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91080. /** Signature for the write callback.
  91081. *
  91082. * A function pointer matching this signature must be passed to
  91083. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91084. * by the encoder anytime there is raw encoded data ready to write. It may
  91085. * include metadata mixed with encoded audio frames and the data is not
  91086. * guaranteed to be aligned on frame or metadata block boundaries.
  91087. *
  91088. * The only duty of the callback is to write out the \a bytes worth of data
  91089. * in \a buffer to the current position in the output stream. The arguments
  91090. * \a samples and \a current_frame are purely informational. If \a samples
  91091. * is greater than \c 0, then \a current_frame will hold the current frame
  91092. * number that is being written; otherwise it indicates that the write
  91093. * callback is being called to write metadata.
  91094. *
  91095. * \note
  91096. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91097. * write callback will be called twice when writing each audio
  91098. * frame; once for the page header, and once for the page body.
  91099. * When writing the page header, the \a samples argument to the
  91100. * write callback will be \c 0.
  91101. *
  91102. * \note In general, FLAC__StreamEncoder functions which change the
  91103. * state should not be called on the \a encoder while in the callback.
  91104. *
  91105. * \param encoder The encoder instance calling the callback.
  91106. * \param buffer An array of encoded data of length \a bytes.
  91107. * \param bytes The byte length of \a buffer.
  91108. * \param samples The number of samples encoded by \a buffer.
  91109. * \c 0 has a special meaning; see above.
  91110. * \param current_frame The number of the current frame being encoded.
  91111. * \param client_data The callee's client data set through
  91112. * FLAC__stream_encoder_init_*().
  91113. * \retval FLAC__StreamEncoderWriteStatus
  91114. * The callee's return status.
  91115. */
  91116. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91117. /** Signature for the seek callback.
  91118. *
  91119. * A function pointer matching this signature may be passed to
  91120. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91121. * when the encoder needs to seek the output stream. The encoder will pass
  91122. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91123. *
  91124. * Here is an example of a seek callback for stdio streams:
  91125. * \code
  91126. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91127. * {
  91128. * FILE *file = ((MyClientData*)client_data)->file;
  91129. * if(file == stdin)
  91130. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91131. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91132. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91133. * else
  91134. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91135. * }
  91136. * \endcode
  91137. *
  91138. * \note In general, FLAC__StreamEncoder functions which change the
  91139. * state should not be called on the \a encoder while in the callback.
  91140. *
  91141. * \param encoder The encoder instance calling the callback.
  91142. * \param absolute_byte_offset The offset from the beginning of the stream
  91143. * to seek to.
  91144. * \param client_data The callee's client data set through
  91145. * FLAC__stream_encoder_init_*().
  91146. * \retval FLAC__StreamEncoderSeekStatus
  91147. * The callee's return status.
  91148. */
  91149. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91150. /** Signature for the tell callback.
  91151. *
  91152. * A function pointer matching this signature may be passed to
  91153. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91154. * when the encoder needs to know the current position of the output stream.
  91155. *
  91156. * \warning
  91157. * The callback must return the true current byte offset of the output to
  91158. * which the encoder is writing. If you are buffering the output, make
  91159. * sure and take this into account. If you are writing directly to a
  91160. * FILE* from your write callback, ftell() is sufficient. If you are
  91161. * writing directly to a file descriptor from your write callback, you
  91162. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91163. * these points to rewrite metadata after encoding.
  91164. *
  91165. * Here is an example of a tell callback for stdio streams:
  91166. * \code
  91167. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91168. * {
  91169. * FILE *file = ((MyClientData*)client_data)->file;
  91170. * off_t pos;
  91171. * if(file == stdin)
  91172. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91173. * else if((pos = ftello(file)) < 0)
  91174. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91175. * else {
  91176. * *absolute_byte_offset = (FLAC__uint64)pos;
  91177. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91178. * }
  91179. * }
  91180. * \endcode
  91181. *
  91182. * \note In general, FLAC__StreamEncoder functions which change the
  91183. * state should not be called on the \a encoder while in the callback.
  91184. *
  91185. * \param encoder The encoder instance calling the callback.
  91186. * \param absolute_byte_offset The address at which to store the current
  91187. * position of the output.
  91188. * \param client_data The callee's client data set through
  91189. * FLAC__stream_encoder_init_*().
  91190. * \retval FLAC__StreamEncoderTellStatus
  91191. * The callee's return status.
  91192. */
  91193. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91194. /** Signature for the metadata callback.
  91195. *
  91196. * A function pointer matching this signature may be passed to
  91197. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91198. * once at the end of encoding with the populated STREAMINFO structure. This
  91199. * is so the client can seek back to the beginning of the file and write the
  91200. * STREAMINFO block with the correct statistics after encoding (like
  91201. * minimum/maximum frame size and total samples).
  91202. *
  91203. * \note In general, FLAC__StreamEncoder functions which change the
  91204. * state should not be called on the \a encoder while in the callback.
  91205. *
  91206. * \param encoder The encoder instance calling the callback.
  91207. * \param metadata The final populated STREAMINFO block.
  91208. * \param client_data The callee's client data set through
  91209. * FLAC__stream_encoder_init_*().
  91210. */
  91211. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91212. /** Signature for the progress callback.
  91213. *
  91214. * A function pointer matching this signature may be passed to
  91215. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91216. * The supplied function will be called when the encoder has finished
  91217. * writing a frame. The \c total_frames_estimate argument to the
  91218. * callback will be based on the value from
  91219. * FLAC__stream_encoder_set_total_samples_estimate().
  91220. *
  91221. * \note In general, FLAC__StreamEncoder functions which change the
  91222. * state should not be called on the \a encoder while in the callback.
  91223. *
  91224. * \param encoder The encoder instance calling the callback.
  91225. * \param bytes_written Bytes written so far.
  91226. * \param samples_written Samples written so far.
  91227. * \param frames_written Frames written so far.
  91228. * \param total_frames_estimate The estimate of the total number of
  91229. * frames to be written.
  91230. * \param client_data The callee's client data set through
  91231. * FLAC__stream_encoder_init_*().
  91232. */
  91233. 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);
  91234. /***********************************************************************
  91235. *
  91236. * Class constructor/destructor
  91237. *
  91238. ***********************************************************************/
  91239. /** Create a new stream encoder instance. The instance is created with
  91240. * default settings; see the individual FLAC__stream_encoder_set_*()
  91241. * functions for each setting's default.
  91242. *
  91243. * \retval FLAC__StreamEncoder*
  91244. * \c NULL if there was an error allocating memory, else the new instance.
  91245. */
  91246. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91247. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91248. *
  91249. * \param encoder A pointer to an existing encoder.
  91250. * \assert
  91251. * \code encoder != NULL \endcode
  91252. */
  91253. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91254. /***********************************************************************
  91255. *
  91256. * Public class method prototypes
  91257. *
  91258. ***********************************************************************/
  91259. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91260. *
  91261. * \note
  91262. * This does not need to be set for native FLAC encoding.
  91263. *
  91264. * \note
  91265. * It is recommended to set a serial number explicitly as the default of '0'
  91266. * may collide with other streams.
  91267. *
  91268. * \default \c 0
  91269. * \param encoder An encoder instance to set.
  91270. * \param serial_number See above.
  91271. * \assert
  91272. * \code encoder != NULL \endcode
  91273. * \retval FLAC__bool
  91274. * \c false if the encoder is already initialized, else \c true.
  91275. */
  91276. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91277. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91278. * encoded output by feeding it through an internal decoder and comparing
  91279. * the original signal against the decoded signal. If a mismatch occurs,
  91280. * the process call will return \c false. Note that this will slow the
  91281. * encoding process by the extra time required for decoding and comparison.
  91282. *
  91283. * \default \c false
  91284. * \param encoder An encoder instance to set.
  91285. * \param value Flag value (see above).
  91286. * \assert
  91287. * \code encoder != NULL \endcode
  91288. * \retval FLAC__bool
  91289. * \c false if the encoder is already initialized, else \c true.
  91290. */
  91291. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91292. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91293. * the encoder will comply with the Subset and will check the
  91294. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91295. * comply. If \c false, the settings may take advantage of the full
  91296. * range that the format allows.
  91297. *
  91298. * Make sure you know what it entails before setting this to \c false.
  91299. *
  91300. * \default \c true
  91301. * \param encoder An encoder instance to set.
  91302. * \param value Flag value (see above).
  91303. * \assert
  91304. * \code encoder != NULL \endcode
  91305. * \retval FLAC__bool
  91306. * \c false if the encoder is already initialized, else \c true.
  91307. */
  91308. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91309. /** Set the number of channels to be encoded.
  91310. *
  91311. * \default \c 2
  91312. * \param encoder An encoder instance to set.
  91313. * \param value See above.
  91314. * \assert
  91315. * \code encoder != NULL \endcode
  91316. * \retval FLAC__bool
  91317. * \c false if the encoder is already initialized, else \c true.
  91318. */
  91319. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91320. /** Set the sample resolution of the input to be encoded.
  91321. *
  91322. * \warning
  91323. * Do not feed the encoder data that is wider than the value you
  91324. * set here or you will generate an invalid stream.
  91325. *
  91326. * \default \c 16
  91327. * \param encoder An encoder instance to set.
  91328. * \param value See above.
  91329. * \assert
  91330. * \code encoder != NULL \endcode
  91331. * \retval FLAC__bool
  91332. * \c false if the encoder is already initialized, else \c true.
  91333. */
  91334. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91335. /** Set the sample rate (in Hz) of the input to be encoded.
  91336. *
  91337. * \default \c 44100
  91338. * \param encoder An encoder instance to set.
  91339. * \param value See above.
  91340. * \assert
  91341. * \code encoder != NULL \endcode
  91342. * \retval FLAC__bool
  91343. * \c false if the encoder is already initialized, else \c true.
  91344. */
  91345. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91346. /** Set the compression level
  91347. *
  91348. * The compression level is roughly proportional to the amount of effort
  91349. * the encoder expends to compress the file. A higher level usually
  91350. * means more computation but higher compression. The default level is
  91351. * suitable for most applications.
  91352. *
  91353. * Currently the levels range from \c 0 (fastest, least compression) to
  91354. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91355. * treated as \c 8.
  91356. *
  91357. * This function automatically calls the following other \c _set_
  91358. * functions with appropriate values, so the client does not need to
  91359. * unless it specifically wants to override them:
  91360. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91361. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91362. * - FLAC__stream_encoder_set_apodization()
  91363. * - FLAC__stream_encoder_set_max_lpc_order()
  91364. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91365. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91366. * - FLAC__stream_encoder_set_do_escape_coding()
  91367. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91368. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91369. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91370. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91371. *
  91372. * The actual values set for each level are:
  91373. * <table>
  91374. * <tr>
  91375. * <td><b>level</b><td>
  91376. * <td>do mid-side stereo<td>
  91377. * <td>loose mid-side stereo<td>
  91378. * <td>apodization<td>
  91379. * <td>max lpc order<td>
  91380. * <td>qlp coeff precision<td>
  91381. * <td>qlp coeff prec search<td>
  91382. * <td>escape coding<td>
  91383. * <td>exhaustive model search<td>
  91384. * <td>min residual partition order<td>
  91385. * <td>max residual partition order<td>
  91386. * <td>rice parameter search dist<td>
  91387. * </tr>
  91388. * <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>
  91389. * <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>
  91390. * <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>
  91391. * <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>
  91392. * <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>
  91393. * <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>
  91394. * <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>
  91395. * <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>
  91396. * <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>
  91397. * </table>
  91398. *
  91399. * \default \c 5
  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_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91408. /** Set the blocksize to use while encoding.
  91409. *
  91410. * The number of samples to use per frame. Use \c 0 to let the encoder
  91411. * estimate a blocksize; this is usually best.
  91412. *
  91413. * \default \c 0
  91414. * \param encoder An encoder instance to set.
  91415. * \param value See above.
  91416. * \assert
  91417. * \code encoder != NULL \endcode
  91418. * \retval FLAC__bool
  91419. * \c false if the encoder is already initialized, else \c true.
  91420. */
  91421. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91422. /** Set to \c true to enable mid-side encoding on stereo input. The
  91423. * number of channels must be 2 for this to have any effect. Set to
  91424. * \c false to use only independent channel coding.
  91425. *
  91426. * \default \c false
  91427. * \param encoder An encoder instance to set.
  91428. * \param value Flag value (see above).
  91429. * \assert
  91430. * \code encoder != NULL \endcode
  91431. * \retval FLAC__bool
  91432. * \c false if the encoder is already initialized, else \c true.
  91433. */
  91434. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91435. /** Set to \c true to enable adaptive switching between mid-side and
  91436. * left-right encoding on stereo input. Set to \c false to use
  91437. * exhaustive searching. Setting this to \c true requires
  91438. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91439. * \c true in order to have any effect.
  91440. *
  91441. * \default \c false
  91442. * \param encoder An encoder instance to set.
  91443. * \param value Flag value (see above).
  91444. * \assert
  91445. * \code encoder != NULL \endcode
  91446. * \retval FLAC__bool
  91447. * \c false if the encoder is already initialized, else \c true.
  91448. */
  91449. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91450. /** Sets the apodization function(s) the encoder will use when windowing
  91451. * audio data for LPC analysis.
  91452. *
  91453. * The \a specification is a plain ASCII string which specifies exactly
  91454. * which functions to use. There may be more than one (up to 32),
  91455. * separated by \c ';' characters. Some functions take one or more
  91456. * comma-separated arguments in parentheses.
  91457. *
  91458. * The available functions are \c bartlett, \c bartlett_hann,
  91459. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91460. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91461. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91462. *
  91463. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91464. * (0<STDDEV<=0.5).
  91465. *
  91466. * For \c tukey(P), P specifies the fraction of the window that is
  91467. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91468. * corresponds to \c hann.
  91469. *
  91470. * Example specifications are \c "blackman" or
  91471. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91472. *
  91473. * Any function that is specified erroneously is silently dropped. Up
  91474. * to 32 functions are kept, the rest are dropped. If the specification
  91475. * is empty the encoder defaults to \c "tukey(0.5)".
  91476. *
  91477. * When more than one function is specified, then for every subframe the
  91478. * encoder will try each of them separately and choose the window that
  91479. * results in the smallest compressed subframe.
  91480. *
  91481. * Note that each function specified causes the encoder to occupy a
  91482. * floating point array in which to store the window.
  91483. *
  91484. * \default \c "tukey(0.5)"
  91485. * \param encoder An encoder instance to set.
  91486. * \param specification See above.
  91487. * \assert
  91488. * \code encoder != NULL \endcode
  91489. * \code specification != NULL \endcode
  91490. * \retval FLAC__bool
  91491. * \c false if the encoder is already initialized, else \c true.
  91492. */
  91493. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91494. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91495. *
  91496. * \default \c 0
  91497. * \param encoder An encoder instance to set.
  91498. * \param value See above.
  91499. * \assert
  91500. * \code encoder != NULL \endcode
  91501. * \retval FLAC__bool
  91502. * \c false if the encoder is already initialized, else \c true.
  91503. */
  91504. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91505. /** Set the precision, in bits, of the quantized linear predictor
  91506. * coefficients, or \c 0 to let the encoder select it based on the
  91507. * blocksize.
  91508. *
  91509. * \note
  91510. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91511. * be less than 32.
  91512. *
  91513. * \default \c 0
  91514. * \param encoder An encoder instance to set.
  91515. * \param value See above.
  91516. * \assert
  91517. * \code encoder != NULL \endcode
  91518. * \retval FLAC__bool
  91519. * \c false if the encoder is already initialized, else \c true.
  91520. */
  91521. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91522. /** Set to \c false to use only the specified quantized linear predictor
  91523. * coefficient precision, or \c true to search neighboring precision
  91524. * values and use the best one.
  91525. *
  91526. * \default \c false
  91527. * \param encoder An encoder instance to set.
  91528. * \param value See above.
  91529. * \assert
  91530. * \code encoder != NULL \endcode
  91531. * \retval FLAC__bool
  91532. * \c false if the encoder is already initialized, else \c true.
  91533. */
  91534. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91535. /** Deprecated. Setting this value has no effect.
  91536. *
  91537. * \default \c false
  91538. * \param encoder An encoder instance to set.
  91539. * \param value See above.
  91540. * \assert
  91541. * \code encoder != NULL \endcode
  91542. * \retval FLAC__bool
  91543. * \c false if the encoder is already initialized, else \c true.
  91544. */
  91545. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91546. /** Set to \c false to let the encoder estimate the best model order
  91547. * based on the residual signal energy, or \c true to force the
  91548. * encoder to evaluate all order models and select the best.
  91549. *
  91550. * \default \c false
  91551. * \param encoder An encoder instance to set.
  91552. * \param value See above.
  91553. * \assert
  91554. * \code encoder != NULL \endcode
  91555. * \retval FLAC__bool
  91556. * \c false if the encoder is already initialized, else \c true.
  91557. */
  91558. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91559. /** Set the minimum partition order to search when coding the residual.
  91560. * This is used in tandem with
  91561. * FLAC__stream_encoder_set_max_residual_partition_order().
  91562. *
  91563. * The partition order determines the context size in the residual.
  91564. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91565. *
  91566. * Set both min and max values to \c 0 to force a single context,
  91567. * whose Rice parameter is based on the residual signal variance.
  91568. * Otherwise, set a min and max order, and the encoder will search
  91569. * all orders, using the mean of each context for its Rice parameter,
  91570. * and use the best.
  91571. *
  91572. * \default \c 0
  91573. * \param encoder An encoder instance to set.
  91574. * \param value See above.
  91575. * \assert
  91576. * \code encoder != NULL \endcode
  91577. * \retval FLAC__bool
  91578. * \c false if the encoder is already initialized, else \c true.
  91579. */
  91580. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91581. /** Set the maximum partition order to search when coding the residual.
  91582. * This is used in tandem with
  91583. * FLAC__stream_encoder_set_min_residual_partition_order().
  91584. *
  91585. * The partition order determines the context size in the residual.
  91586. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91587. *
  91588. * Set both min and max values to \c 0 to force a single context,
  91589. * whose Rice parameter is based on the residual signal variance.
  91590. * Otherwise, set a min and max order, and the encoder will search
  91591. * all orders, using the mean of each context for its Rice parameter,
  91592. * and use the best.
  91593. *
  91594. * \default \c 0
  91595. * \param encoder An encoder instance to set.
  91596. * \param value See above.
  91597. * \assert
  91598. * \code encoder != NULL \endcode
  91599. * \retval FLAC__bool
  91600. * \c false if the encoder is already initialized, else \c true.
  91601. */
  91602. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91603. /** Deprecated. Setting this value has no effect.
  91604. *
  91605. * \default \c 0
  91606. * \param encoder An encoder instance to set.
  91607. * \param value See above.
  91608. * \assert
  91609. * \code encoder != NULL \endcode
  91610. * \retval FLAC__bool
  91611. * \c false if the encoder is already initialized, else \c true.
  91612. */
  91613. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91614. /** Set an estimate of the total samples that will be encoded.
  91615. * This is merely an estimate and may be set to \c 0 if unknown.
  91616. * This value will be written to the STREAMINFO block before encoding,
  91617. * and can remove the need for the caller to rewrite the value later
  91618. * if the value is known before encoding.
  91619. *
  91620. * \default \c 0
  91621. * \param encoder An encoder instance to set.
  91622. * \param value See above.
  91623. * \assert
  91624. * \code encoder != NULL \endcode
  91625. * \retval FLAC__bool
  91626. * \c false if the encoder is already initialized, else \c true.
  91627. */
  91628. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91629. /** Set the metadata blocks to be emitted to the stream before encoding.
  91630. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91631. * array of pointers to metadata blocks. The array is non-const since
  91632. * the encoder may need to change the \a is_last flag inside them, and
  91633. * in some cases update seek point offsets. Otherwise, the encoder will
  91634. * not modify or free the blocks. It is up to the caller to free the
  91635. * metadata blocks after encoding finishes.
  91636. *
  91637. * \note
  91638. * The encoder stores only copies of the pointers in the \a metadata array;
  91639. * the metadata blocks themselves must survive at least until after
  91640. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91641. *
  91642. * \note
  91643. * The STREAMINFO block is always written and no STREAMINFO block may
  91644. * occur in the supplied array.
  91645. *
  91646. * \note
  91647. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91648. * in the \a metadata array, but the client has specified that it does not
  91649. * support seeking, then the SEEKTABLE will be written verbatim. However
  91650. * by itself this is not very useful as the client will not know the stream
  91651. * offsets for the seekpoints ahead of time. In order to get a proper
  91652. * seektable the client must support seeking. See next note.
  91653. *
  91654. * \note
  91655. * SEEKTABLE blocks are handled specially. Since you will not know
  91656. * the values for the seek point stream offsets, you should pass in
  91657. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91658. * required sample numbers (or placeholder points), with \c 0 for the
  91659. * \a frame_samples and \a stream_offset fields for each point. If the
  91660. * client has specified that it supports seeking by providing a seek
  91661. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91662. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91663. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91664. * then while it is encoding the encoder will fill the stream offsets in
  91665. * for you and when encoding is finished, it will seek back and write the
  91666. * real values into the SEEKTABLE block in the stream. There are helper
  91667. * routines for manipulating seektable template blocks; see metadata.h:
  91668. * FLAC__metadata_object_seektable_template_*(). If the client does
  91669. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91670. * will slow down or remove the ability to seek in the FLAC stream.
  91671. *
  91672. * \note
  91673. * The encoder instance \b will modify the first \c SEEKTABLE block
  91674. * as it transforms the template to a valid seektable while encoding,
  91675. * but it is still up to the caller to free all metadata blocks after
  91676. * encoding.
  91677. *
  91678. * \note
  91679. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91680. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91681. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91682. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91683. * block is present in the \a metadata array, libFLAC will write an
  91684. * empty one, containing only the vendor string.
  91685. *
  91686. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91687. * the second metadata block of the stream. The encoder already supplies
  91688. * the STREAMINFO block automatically. If \a metadata does not contain a
  91689. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91690. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91691. * first, the init function will reorder \a metadata by moving the
  91692. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91693. * blocks will remain as they were.
  91694. *
  91695. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91696. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91697. * return \c false.
  91698. *
  91699. * \default \c NULL, 0
  91700. * \param encoder An encoder instance to set.
  91701. * \param metadata See above.
  91702. * \param num_blocks See above.
  91703. * \assert
  91704. * \code encoder != NULL \endcode
  91705. * \retval FLAC__bool
  91706. * \c false if the encoder is already initialized, else \c true.
  91707. * \c false if the encoder is already initialized, or if
  91708. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91709. */
  91710. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91711. /** Get the current encoder state.
  91712. *
  91713. * \param encoder An encoder instance to query.
  91714. * \assert
  91715. * \code encoder != NULL \endcode
  91716. * \retval FLAC__StreamEncoderState
  91717. * The current encoder state.
  91718. */
  91719. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91720. /** Get the state of the verify stream decoder.
  91721. * Useful when the stream encoder state is
  91722. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91723. *
  91724. * \param encoder An encoder instance to query.
  91725. * \assert
  91726. * \code encoder != NULL \endcode
  91727. * \retval FLAC__StreamDecoderState
  91728. * The verify stream decoder state.
  91729. */
  91730. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91731. /** Get the current encoder state as a C string.
  91732. * This version automatically resolves
  91733. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91734. * verify decoder's state.
  91735. *
  91736. * \param encoder A encoder instance to query.
  91737. * \assert
  91738. * \code encoder != NULL \endcode
  91739. * \retval const char *
  91740. * The encoder state as a C string. Do not modify the contents.
  91741. */
  91742. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91743. /** Get relevant values about the nature of a verify decoder error.
  91744. * Useful when the stream encoder state is
  91745. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91746. * be addresses in which the stats will be returned, or NULL if value
  91747. * is not desired.
  91748. *
  91749. * \param encoder An encoder instance to query.
  91750. * \param absolute_sample The absolute sample number of the mismatch.
  91751. * \param frame_number The number of the frame in which the mismatch occurred.
  91752. * \param channel The channel in which the mismatch occurred.
  91753. * \param sample The number of the sample (relative to the frame) in
  91754. * which the mismatch occurred.
  91755. * \param expected The expected value for the sample in question.
  91756. * \param got The actual value returned by the decoder.
  91757. * \assert
  91758. * \code encoder != NULL \endcode
  91759. */
  91760. 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);
  91761. /** Get the "verify" flag.
  91762. *
  91763. * \param encoder An encoder instance to query.
  91764. * \assert
  91765. * \code encoder != NULL \endcode
  91766. * \retval FLAC__bool
  91767. * See FLAC__stream_encoder_set_verify().
  91768. */
  91769. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91770. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91771. *
  91772. * \param encoder An encoder instance to query.
  91773. * \assert
  91774. * \code encoder != NULL \endcode
  91775. * \retval FLAC__bool
  91776. * See FLAC__stream_encoder_set_streamable_subset().
  91777. */
  91778. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91779. /** Get the number of input channels being processed.
  91780. *
  91781. * \param encoder An encoder instance to query.
  91782. * \assert
  91783. * \code encoder != NULL \endcode
  91784. * \retval unsigned
  91785. * See FLAC__stream_encoder_set_channels().
  91786. */
  91787. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91788. /** Get the input sample resolution setting.
  91789. *
  91790. * \param encoder An encoder instance to query.
  91791. * \assert
  91792. * \code encoder != NULL \endcode
  91793. * \retval unsigned
  91794. * See FLAC__stream_encoder_set_bits_per_sample().
  91795. */
  91796. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91797. /** Get the input sample rate setting.
  91798. *
  91799. * \param encoder An encoder instance to query.
  91800. * \assert
  91801. * \code encoder != NULL \endcode
  91802. * \retval unsigned
  91803. * See FLAC__stream_encoder_set_sample_rate().
  91804. */
  91805. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91806. /** Get the blocksize setting.
  91807. *
  91808. * \param encoder An encoder instance to query.
  91809. * \assert
  91810. * \code encoder != NULL \endcode
  91811. * \retval unsigned
  91812. * See FLAC__stream_encoder_set_blocksize().
  91813. */
  91814. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91815. /** Get the "mid/side stereo coding" flag.
  91816. *
  91817. * \param encoder An encoder instance to query.
  91818. * \assert
  91819. * \code encoder != NULL \endcode
  91820. * \retval FLAC__bool
  91821. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91822. */
  91823. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91824. /** Get the "adaptive mid/side switching" flag.
  91825. *
  91826. * \param encoder An encoder instance to query.
  91827. * \assert
  91828. * \code encoder != NULL \endcode
  91829. * \retval FLAC__bool
  91830. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91831. */
  91832. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91833. /** Get the maximum LPC order setting.
  91834. *
  91835. * \param encoder An encoder instance to query.
  91836. * \assert
  91837. * \code encoder != NULL \endcode
  91838. * \retval unsigned
  91839. * See FLAC__stream_encoder_set_max_lpc_order().
  91840. */
  91841. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91842. /** Get the quantized linear predictor coefficient precision setting.
  91843. *
  91844. * \param encoder An encoder instance to query.
  91845. * \assert
  91846. * \code encoder != NULL \endcode
  91847. * \retval unsigned
  91848. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91849. */
  91850. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91851. /** Get the qlp coefficient precision search flag.
  91852. *
  91853. * \param encoder An encoder instance to query.
  91854. * \assert
  91855. * \code encoder != NULL \endcode
  91856. * \retval FLAC__bool
  91857. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91858. */
  91859. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91860. /** Get the "escape coding" flag.
  91861. *
  91862. * \param encoder An encoder instance to query.
  91863. * \assert
  91864. * \code encoder != NULL \endcode
  91865. * \retval FLAC__bool
  91866. * See FLAC__stream_encoder_set_do_escape_coding().
  91867. */
  91868. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91869. /** Get the exhaustive model search flag.
  91870. *
  91871. * \param encoder An encoder instance to query.
  91872. * \assert
  91873. * \code encoder != NULL \endcode
  91874. * \retval FLAC__bool
  91875. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91876. */
  91877. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91878. /** Get the minimum residual partition order setting.
  91879. *
  91880. * \param encoder An encoder instance to query.
  91881. * \assert
  91882. * \code encoder != NULL \endcode
  91883. * \retval unsigned
  91884. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91885. */
  91886. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91887. /** Get maximum residual partition order setting.
  91888. *
  91889. * \param encoder An encoder instance to query.
  91890. * \assert
  91891. * \code encoder != NULL \endcode
  91892. * \retval unsigned
  91893. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91894. */
  91895. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91896. /** Get the Rice parameter search distance setting.
  91897. *
  91898. * \param encoder An encoder instance to query.
  91899. * \assert
  91900. * \code encoder != NULL \endcode
  91901. * \retval unsigned
  91902. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91903. */
  91904. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91905. /** Get the previously set estimate of the total samples to be encoded.
  91906. * The encoder merely mimics back the value given to
  91907. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91908. * other way of knowing how many samples the client will encode.
  91909. *
  91910. * \param encoder An encoder instance to set.
  91911. * \assert
  91912. * \code encoder != NULL \endcode
  91913. * \retval FLAC__uint64
  91914. * See FLAC__stream_encoder_get_total_samples_estimate().
  91915. */
  91916. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91917. /** Initialize the encoder instance to encode native FLAC streams.
  91918. *
  91919. * This flavor of initialization sets up the encoder to encode to a
  91920. * native FLAC stream. I/O is performed via callbacks to the client.
  91921. * For encoding to a plain file via filename or open \c FILE*,
  91922. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91923. * provide a simpler interface.
  91924. *
  91925. * This function should be called after FLAC__stream_encoder_new() and
  91926. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91927. * or FLAC__stream_encoder_process_interleaved().
  91928. * initialization succeeded.
  91929. *
  91930. * The call to FLAC__stream_encoder_init_stream() currently will also
  91931. * immediately call the write callback several times, once with the \c fLaC
  91932. * signature, and once for each encoded metadata block.
  91933. *
  91934. * \param encoder An uninitialized encoder instance.
  91935. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91936. * pointer must not be \c NULL.
  91937. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91938. * pointer may be \c NULL if seeking is not
  91939. * supported. The encoder uses seeking to go back
  91940. * and write some some stream statistics to the
  91941. * STREAMINFO block; this is recommended but not
  91942. * necessary to create a valid FLAC stream. If
  91943. * \a seek_callback is not \c NULL then a
  91944. * \a tell_callback must also be supplied.
  91945. * Alternatively, a dummy seek callback that just
  91946. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91947. * may also be supplied, all though this is slightly
  91948. * less efficient for the encoder.
  91949. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91950. * pointer may be \c NULL if seeking is not
  91951. * supported. If \a seek_callback is \c NULL then
  91952. * this argument will be ignored. If
  91953. * \a seek_callback is not \c NULL then a
  91954. * \a tell_callback must also be supplied.
  91955. * Alternatively, a dummy tell callback that just
  91956. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91957. * may also be supplied, all though this is slightly
  91958. * less efficient for the encoder.
  91959. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91960. * pointer may be \c NULL if the callback is not
  91961. * desired. If the client provides a seek callback,
  91962. * this function is not necessary as the encoder
  91963. * will automatically seek back and update the
  91964. * STREAMINFO block. It may also be \c NULL if the
  91965. * client does not support seeking, since it will
  91966. * have no way of going back to update the
  91967. * STREAMINFO. However the client can still supply
  91968. * a callback if it would like to know the details
  91969. * from the STREAMINFO.
  91970. * \param client_data This value will be supplied to callbacks in their
  91971. * \a client_data argument.
  91972. * \assert
  91973. * \code encoder != NULL \endcode
  91974. * \retval FLAC__StreamEncoderInitStatus
  91975. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91976. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91977. */
  91978. 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);
  91979. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91980. *
  91981. * This flavor of initialization sets up the encoder to encode to a FLAC
  91982. * stream in an Ogg container. I/O is performed via callbacks to the
  91983. * client. For encoding to a plain file via filename or open \c FILE*,
  91984. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91985. * provide a simpler interface.
  91986. *
  91987. * This function should be called after FLAC__stream_encoder_new() and
  91988. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91989. * or FLAC__stream_encoder_process_interleaved().
  91990. * initialization succeeded.
  91991. *
  91992. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91993. * immediately call the write callback several times to write the metadata
  91994. * packets.
  91995. *
  91996. * \param encoder An uninitialized encoder instance.
  91997. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91998. * pointer must not be \c NULL if \a seek_callback
  91999. * is non-NULL since they are both needed to be
  92000. * able to write data back to the Ogg FLAC stream
  92001. * in the post-encode phase.
  92002. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92003. * pointer must not be \c NULL.
  92004. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92005. * pointer may be \c NULL if seeking is not
  92006. * supported. The encoder uses seeking to go back
  92007. * and write some some stream statistics to the
  92008. * STREAMINFO block; this is recommended but not
  92009. * necessary to create a valid FLAC stream. If
  92010. * \a seek_callback is not \c NULL then a
  92011. * \a tell_callback must also be supplied.
  92012. * Alternatively, a dummy seek callback that just
  92013. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92014. * may also be supplied, all though this is slightly
  92015. * less efficient for the encoder.
  92016. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92017. * pointer may be \c NULL if seeking is not
  92018. * supported. If \a seek_callback is \c NULL then
  92019. * this argument will be ignored. If
  92020. * \a seek_callback is not \c NULL then a
  92021. * \a tell_callback must also be supplied.
  92022. * Alternatively, a dummy tell callback that just
  92023. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92024. * may also be supplied, all though this is slightly
  92025. * less efficient for the encoder.
  92026. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92027. * pointer may be \c NULL if the callback is not
  92028. * desired. If the client provides a seek callback,
  92029. * this function is not necessary as the encoder
  92030. * will automatically seek back and update the
  92031. * STREAMINFO block. It may also be \c NULL if the
  92032. * client does not support seeking, since it will
  92033. * have no way of going back to update the
  92034. * STREAMINFO. However the client can still supply
  92035. * a callback if it would like to know the details
  92036. * from the STREAMINFO.
  92037. * \param client_data This value will be supplied to callbacks in their
  92038. * \a client_data argument.
  92039. * \assert
  92040. * \code encoder != NULL \endcode
  92041. * \retval FLAC__StreamEncoderInitStatus
  92042. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92043. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92044. */
  92045. 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);
  92046. /** Initialize the encoder instance to encode native FLAC files.
  92047. *
  92048. * This flavor of initialization sets up the encoder to encode to a
  92049. * plain native FLAC file. For non-stdio streams, you must use
  92050. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92051. *
  92052. * This function should be called after FLAC__stream_encoder_new() and
  92053. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92054. * or FLAC__stream_encoder_process_interleaved().
  92055. * initialization succeeded.
  92056. *
  92057. * \param encoder An uninitialized encoder instance.
  92058. * \param file An open file. The file should have been opened
  92059. * with mode \c "w+b" and rewound. The file
  92060. * becomes owned by the encoder and should not be
  92061. * manipulated by the client while encoding.
  92062. * Unless \a file is \c stdout, it will be closed
  92063. * when FLAC__stream_encoder_finish() is called.
  92064. * Note however that a proper SEEKTABLE cannot be
  92065. * created when encoding to \c stdout since it is
  92066. * not seekable.
  92067. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92068. * pointer may be \c NULL if the callback is not
  92069. * desired.
  92070. * \param client_data This value will be supplied to callbacks in their
  92071. * \a client_data argument.
  92072. * \assert
  92073. * \code encoder != NULL \endcode
  92074. * \code file != NULL \endcode
  92075. * \retval FLAC__StreamEncoderInitStatus
  92076. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92077. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92078. */
  92079. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92080. /** Initialize the encoder instance to encode Ogg FLAC files.
  92081. *
  92082. * This flavor of initialization sets up the encoder to encode to a
  92083. * plain Ogg FLAC file. For non-stdio streams, you must use
  92084. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92085. *
  92086. * This function should be called after FLAC__stream_encoder_new() and
  92087. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92088. * or FLAC__stream_encoder_process_interleaved().
  92089. * initialization succeeded.
  92090. *
  92091. * \param encoder An uninitialized encoder instance.
  92092. * \param file An open file. The file should have been opened
  92093. * with mode \c "w+b" and rewound. The file
  92094. * becomes owned by the encoder and should not be
  92095. * manipulated by the client while encoding.
  92096. * Unless \a file is \c stdout, it will be closed
  92097. * when FLAC__stream_encoder_finish() is called.
  92098. * Note however that a proper SEEKTABLE cannot be
  92099. * created when encoding to \c stdout since it is
  92100. * not seekable.
  92101. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92102. * pointer may be \c NULL if the callback is not
  92103. * desired.
  92104. * \param client_data This value will be supplied to callbacks in their
  92105. * \a client_data argument.
  92106. * \assert
  92107. * \code encoder != NULL \endcode
  92108. * \code file != NULL \endcode
  92109. * \retval FLAC__StreamEncoderInitStatus
  92110. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92111. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92112. */
  92113. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92114. /** Initialize the encoder instance to encode native FLAC files.
  92115. *
  92116. * This flavor of initialization sets up the encoder to encode to a plain
  92117. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92118. * with Unicode filenames on Windows), you must use
  92119. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92120. * and provide callbacks for the I/O.
  92121. *
  92122. * This function should be called after FLAC__stream_encoder_new() and
  92123. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92124. * or FLAC__stream_encoder_process_interleaved().
  92125. * initialization succeeded.
  92126. *
  92127. * \param encoder An uninitialized encoder instance.
  92128. * \param filename The name of the file to encode to. The file will
  92129. * be opened with fopen(). Use \c NULL to encode to
  92130. * \c stdout. Note however that a proper SEEKTABLE
  92131. * cannot be created when encoding to \c stdout since
  92132. * it is not seekable.
  92133. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92134. * pointer may be \c NULL if the callback is not
  92135. * desired.
  92136. * \param client_data This value will be supplied to callbacks in their
  92137. * \a client_data argument.
  92138. * \assert
  92139. * \code encoder != NULL \endcode
  92140. * \retval FLAC__StreamEncoderInitStatus
  92141. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92142. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92143. */
  92144. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92145. /** Initialize the encoder instance to encode Ogg FLAC files.
  92146. *
  92147. * This flavor of initialization sets up the encoder to encode to a plain
  92148. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92149. * with Unicode filenames on Windows), you must use
  92150. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92151. * and provide callbacks for the I/O.
  92152. *
  92153. * This function should be called after FLAC__stream_encoder_new() and
  92154. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92155. * or FLAC__stream_encoder_process_interleaved().
  92156. * initialization succeeded.
  92157. *
  92158. * \param encoder An uninitialized encoder instance.
  92159. * \param filename The name of the file to encode to. The file will
  92160. * be opened with fopen(). Use \c NULL to encode to
  92161. * \c stdout. Note however that a proper SEEKTABLE
  92162. * cannot be created when encoding to \c stdout since
  92163. * it is not seekable.
  92164. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92165. * pointer may be \c NULL if the callback is not
  92166. * desired.
  92167. * \param client_data This value will be supplied to callbacks in their
  92168. * \a client_data argument.
  92169. * \assert
  92170. * \code encoder != NULL \endcode
  92171. * \retval FLAC__StreamEncoderInitStatus
  92172. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92173. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92174. */
  92175. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92176. /** Finish the encoding process.
  92177. * Flushes the encoding buffer, releases resources, resets the encoder
  92178. * settings to their defaults, and returns the encoder state to
  92179. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92180. * one or more write callbacks before returning, and will generate
  92181. * a metadata callback.
  92182. *
  92183. * Note that in the course of processing the last frame, errors can
  92184. * occur, so the caller should be sure to check the return value to
  92185. * ensure the file was encoded properly.
  92186. *
  92187. * In the event of a prematurely-terminated encode, it is not strictly
  92188. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92189. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92190. * with a FLAC__stream_encoder_finish().
  92191. *
  92192. * \param encoder An uninitialized encoder instance.
  92193. * \assert
  92194. * \code encoder != NULL \endcode
  92195. * \retval FLAC__bool
  92196. * \c false if an error occurred processing the last frame; or if verify
  92197. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92198. * verify mismatch; else \c true. If \c false, caller should check the
  92199. * state with FLAC__stream_encoder_get_state() for more information
  92200. * about the error.
  92201. */
  92202. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92203. /** Submit data for encoding.
  92204. * This version allows you to supply the input data via an array of
  92205. * pointers, each pointer pointing to an array of \a samples samples
  92206. * representing one channel. The samples need not be block-aligned,
  92207. * but each channel should have the same number of samples. Each sample
  92208. * should be a signed integer, right-justified to the resolution set by
  92209. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92210. * resolution is 16 bits per sample, the samples should all be in the
  92211. * range [-32768,32767].
  92212. *
  92213. * For applications where channel order is important, channels must
  92214. * follow the order as described in the
  92215. * <A HREF="../format.html#frame_header">frame header</A>.
  92216. *
  92217. * \param encoder An initialized encoder instance in the OK state.
  92218. * \param buffer An array of pointers to each channel's signal.
  92219. * \param samples The number of samples in one channel.
  92220. * \assert
  92221. * \code encoder != NULL \endcode
  92222. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92223. * \retval FLAC__bool
  92224. * \c true if successful, else \c false; in this case, check the
  92225. * encoder state with FLAC__stream_encoder_get_state() to see what
  92226. * went wrong.
  92227. */
  92228. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92229. /** Submit data for encoding.
  92230. * This version allows you to supply the input data where the channels
  92231. * are interleaved into a single array (i.e. channel0_sample0,
  92232. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92233. * The samples need not be block-aligned but they must be
  92234. * sample-aligned, i.e. the first value should be channel0_sample0
  92235. * and the last value channelN_sampleM. Each sample should be a signed
  92236. * integer, right-justified to the resolution set by
  92237. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92238. * resolution is 16 bits per sample, the samples should all be in the
  92239. * range [-32768,32767].
  92240. *
  92241. * For applications where channel order is important, channels must
  92242. * follow the order as described in the
  92243. * <A HREF="../format.html#frame_header">frame header</A>.
  92244. *
  92245. * \param encoder An initialized encoder instance in the OK state.
  92246. * \param buffer An array of channel-interleaved data (see above).
  92247. * \param samples The number of samples in one channel, the same as for
  92248. * FLAC__stream_encoder_process(). For example, if
  92249. * encoding two channels, \c 1000 \a samples corresponds
  92250. * to a \a buffer of 2000 values.
  92251. * \assert
  92252. * \code encoder != NULL \endcode
  92253. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92254. * \retval FLAC__bool
  92255. * \c true if successful, else \c false; in this case, check the
  92256. * encoder state with FLAC__stream_encoder_get_state() to see what
  92257. * went wrong.
  92258. */
  92259. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92260. /* \} */
  92261. #ifdef __cplusplus
  92262. }
  92263. #endif
  92264. #endif
  92265. /*** End of inlined file: stream_encoder.h ***/
  92266. #ifdef _MSC_VER
  92267. /* OPT: an MSVC built-in would be better */
  92268. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92269. {
  92270. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92271. return (x>>16) | (x<<16);
  92272. }
  92273. #endif
  92274. #if defined(_MSC_VER) && defined(_X86_)
  92275. /* OPT: an MSVC built-in would be better */
  92276. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92277. {
  92278. __asm {
  92279. mov edx, start
  92280. mov ecx, len
  92281. test ecx, ecx
  92282. loop1:
  92283. jz done1
  92284. mov eax, [edx]
  92285. bswap eax
  92286. mov [edx], eax
  92287. add edx, 4
  92288. dec ecx
  92289. jmp short loop1
  92290. done1:
  92291. }
  92292. }
  92293. #endif
  92294. /** \mainpage
  92295. *
  92296. * \section intro Introduction
  92297. *
  92298. * This is the documentation for the FLAC C and C++ APIs. It is
  92299. * highly interconnected; this introduction should give you a top
  92300. * level idea of the structure and how to find the information you
  92301. * need. As a prerequisite you should have at least a basic
  92302. * knowledge of the FLAC format, documented
  92303. * <A HREF="../format.html">here</A>.
  92304. *
  92305. * \section c_api FLAC C API
  92306. *
  92307. * The FLAC C API is the interface to libFLAC, a set of structures
  92308. * describing the components of FLAC streams, and functions for
  92309. * encoding and decoding streams, as well as manipulating FLAC
  92310. * metadata in files. The public include files will be installed
  92311. * in your include area (for example /usr/include/FLAC/...).
  92312. *
  92313. * By writing a little code and linking against libFLAC, it is
  92314. * relatively easy to add FLAC support to another program. The
  92315. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92316. * Complete source code of libFLAC as well as the command-line
  92317. * encoder and plugins is available and is a useful source of
  92318. * examples.
  92319. *
  92320. * Aside from encoders and decoders, libFLAC provides a powerful
  92321. * metadata interface for manipulating metadata in FLAC files. It
  92322. * allows the user to add, delete, and modify FLAC metadata blocks
  92323. * and it can automatically take advantage of PADDING blocks to avoid
  92324. * rewriting the entire FLAC file when changing the size of the
  92325. * metadata.
  92326. *
  92327. * libFLAC usually only requires the standard C library and C math
  92328. * library. In particular, threading is not used so there is no
  92329. * dependency on a thread library. However, libFLAC does not use
  92330. * global variables and should be thread-safe.
  92331. *
  92332. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92333. * However the metadata editing interfaces currently have limited
  92334. * read-only support for Ogg FLAC files.
  92335. *
  92336. * \section cpp_api FLAC C++ API
  92337. *
  92338. * The FLAC C++ API is a set of classes that encapsulate the
  92339. * structures and functions in libFLAC. They provide slightly more
  92340. * functionality with respect to metadata but are otherwise
  92341. * equivalent. For the most part, they share the same usage as
  92342. * their counterparts in libFLAC, and the FLAC C API documentation
  92343. * can be used as a supplement. The public include files
  92344. * for the C++ API will be installed in your include area (for
  92345. * example /usr/include/FLAC++/...).
  92346. *
  92347. * libFLAC++ is also licensed under
  92348. * <A HREF="../license.html">Xiph's BSD license</A>.
  92349. *
  92350. * \section getting_started Getting Started
  92351. *
  92352. * A good starting point for learning the API is to browse through
  92353. * the <A HREF="modules.html">modules</A>. Modules are logical
  92354. * groupings of related functions or classes, which correspond roughly
  92355. * to header files or sections of header files. Each module includes a
  92356. * detailed description of the general usage of its functions or
  92357. * classes.
  92358. *
  92359. * From there you can go on to look at the documentation of
  92360. * individual functions. You can see different views of the individual
  92361. * functions through the links in top bar across this page.
  92362. *
  92363. * If you prefer a more hands-on approach, you can jump right to some
  92364. * <A HREF="../documentation_example_code.html">example code</A>.
  92365. *
  92366. * \section porting_guide Porting Guide
  92367. *
  92368. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92369. * has been introduced which gives detailed instructions on how to
  92370. * port your code to newer versions of FLAC.
  92371. *
  92372. * \section embedded_developers Embedded Developers
  92373. *
  92374. * libFLAC has grown larger over time as more functionality has been
  92375. * included, but much of it may be unnecessary for a particular embedded
  92376. * implementation. Unused parts may be pruned by some simple editing of
  92377. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92378. * metadata interface are all independent from each other.
  92379. *
  92380. * It is easiest to just describe the dependencies:
  92381. *
  92382. * - All modules depend on the \link flac_format Format \endlink module.
  92383. * - The decoders and encoders depend on the bitbuffer.
  92384. * - The decoder is independent of the encoder. The encoder uses the
  92385. * decoder because of the verify feature, but this can be removed if
  92386. * not needed.
  92387. * - Parts of the metadata interface require the stream decoder (but not
  92388. * the encoder).
  92389. * - Ogg support is selectable through the compile time macro
  92390. * \c FLAC__HAS_OGG.
  92391. *
  92392. * For example, if your application only requires the stream decoder, no
  92393. * encoder, and no metadata interface, you can remove the stream encoder
  92394. * and the metadata interface, which will greatly reduce the size of the
  92395. * library.
  92396. *
  92397. * Also, there are several places in the libFLAC code with comments marked
  92398. * with "OPT:" where a #define can be changed to enable code that might be
  92399. * faster on a specific platform. Experimenting with these can yield faster
  92400. * binaries.
  92401. */
  92402. /** \defgroup porting Porting Guide for New Versions
  92403. *
  92404. * This module describes differences in the library interfaces from
  92405. * version to version. It assists in the porting of code that uses
  92406. * the libraries to newer versions of FLAC.
  92407. *
  92408. * One simple facility for making porting easier that has been added
  92409. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92410. * library's includes (e.g. \c include/FLAC/export.h). The
  92411. * \c #defines mirror the libraries'
  92412. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92413. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92414. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92415. * These can be used to support multiple versions of an API during the
  92416. * transition phase, e.g.
  92417. *
  92418. * \code
  92419. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92420. * legacy code
  92421. * #else
  92422. * new code
  92423. * #endif
  92424. * \endcode
  92425. *
  92426. * The the source will work for multiple versions and the legacy code can
  92427. * easily be removed when the transition is complete.
  92428. *
  92429. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92430. * include/FLAC/export.h), which can be used to determine whether or not
  92431. * the library has been compiled with support for Ogg FLAC. This is
  92432. * simpler than trying to call an Ogg init function and catching the
  92433. * error.
  92434. */
  92435. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92436. * \ingroup porting
  92437. *
  92438. * \brief
  92439. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92440. *
  92441. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92442. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92443. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92444. * decoding layers and three encoding layers have been merged into a
  92445. * single stream decoder and stream encoder. That is, the functionality
  92446. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92447. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92448. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92449. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92450. * is there is now a single API that can be used to encode or decode
  92451. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92452. * on both seekable and non-seekable streams.
  92453. *
  92454. * Instead of creating an encoder or decoder of a certain layer, now the
  92455. * client will always create a FLAC__StreamEncoder or
  92456. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92457. * initialization function. For example, for the decoder,
  92458. * FLAC__stream_decoder_init() has been replaced by
  92459. * FLAC__stream_decoder_init_stream(). This init function takes
  92460. * callbacks for the I/O, and the seeking callbacks are optional. This
  92461. * allows the client to use the same object for seekable and
  92462. * non-seekable streams. For decoding a FLAC file directly, the client
  92463. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92464. * and fewer callbacks; most of the other callbacks are supplied
  92465. * internally. For situations where fopen()ing by filename is not
  92466. * possible (e.g. Unicode filenames on Windows) the client can instead
  92467. * open the file itself and supply the FILE* to
  92468. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92469. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92470. * Since the callbacks and client data are now passed to the init
  92471. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92472. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92473. * rest of the calls to the decoder are the same as before.
  92474. *
  92475. * There are counterpart init functions for Ogg FLAC, e.g.
  92476. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92477. * and callbacks are the same as for native FLAC.
  92478. *
  92479. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92480. * been set up like so:
  92481. *
  92482. * \code
  92483. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92484. * if(decoder == NULL) do_something;
  92485. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92486. * [... other settings ...]
  92487. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92488. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92489. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92490. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92491. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92492. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92493. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92494. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92495. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92496. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92497. * \endcode
  92498. *
  92499. * In FLAC 1.1.3 it is like this:
  92500. *
  92501. * \code
  92502. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92503. * if(decoder == NULL) do_something;
  92504. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92505. * [... other settings ...]
  92506. * if(FLAC__stream_decoder_init_stream(
  92507. * decoder,
  92508. * my_read_callback,
  92509. * my_seek_callback, // or NULL
  92510. * my_tell_callback, // or NULL
  92511. * my_length_callback, // or NULL
  92512. * my_eof_callback, // or NULL
  92513. * my_write_callback,
  92514. * my_metadata_callback, // or NULL
  92515. * my_error_callback,
  92516. * my_client_data
  92517. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92518. * \endcode
  92519. *
  92520. * or you could do;
  92521. *
  92522. * \code
  92523. * [...]
  92524. * FILE *file = fopen("somefile.flac","rb");
  92525. * if(file == NULL) do_somthing;
  92526. * if(FLAC__stream_decoder_init_FILE(
  92527. * decoder,
  92528. * file,
  92529. * my_write_callback,
  92530. * my_metadata_callback, // or NULL
  92531. * my_error_callback,
  92532. * my_client_data
  92533. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92534. * \endcode
  92535. *
  92536. * or just:
  92537. *
  92538. * \code
  92539. * [...]
  92540. * if(FLAC__stream_decoder_init_file(
  92541. * decoder,
  92542. * "somefile.flac",
  92543. * my_write_callback,
  92544. * my_metadata_callback, // or NULL
  92545. * my_error_callback,
  92546. * my_client_data
  92547. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92548. * \endcode
  92549. *
  92550. * Another small change to the decoder is in how it handles unparseable
  92551. * streams. Before, when the decoder found an unparseable stream
  92552. * (reserved for when the decoder encounters a stream from a future
  92553. * encoder that it can't parse), it changed the state to
  92554. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92555. * drops sync and calls the error callback with a new error code
  92556. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92557. * more robust. If your error callback does not discriminate on the the
  92558. * error state, your code does not need to be changed.
  92559. *
  92560. * The encoder now has a new setting:
  92561. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92562. * method used to window the data before LPC analysis. You only need to
  92563. * add a call to this function if the default is not suitable. There
  92564. * are also two new convenience functions that may be useful:
  92565. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92566. * FLAC__metadata_get_cuesheet().
  92567. *
  92568. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92569. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92570. * is now \c size_t instead of \c unsigned.
  92571. */
  92572. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92573. * \ingroup porting
  92574. *
  92575. * \brief
  92576. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92577. *
  92578. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92579. * There was a slight change in the implementation of
  92580. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92581. * of the \a metadata array of pointers so the client no longer needs
  92582. * to maintain it after the call. The objects themselves that are
  92583. * pointed to by the array are still not copied though and must be
  92584. * maintained until the call to FLAC__stream_encoder_finish().
  92585. */
  92586. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92587. * \ingroup porting
  92588. *
  92589. * \brief
  92590. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92591. *
  92592. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92593. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92594. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92595. *
  92596. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92597. * has changed to reflect the conversion of one of the reserved bits
  92598. * into active use. It used to be \c 2 and now is \c 1. However the
  92599. * FLAC frame header length has not changed, so to skip the proper
  92600. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92601. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92602. */
  92603. /** \defgroup flac FLAC C API
  92604. *
  92605. * The FLAC C API is the interface to libFLAC, a set of structures
  92606. * describing the components of FLAC streams, and functions for
  92607. * encoding and decoding streams, as well as manipulating FLAC
  92608. * metadata in files.
  92609. *
  92610. * You should start with the format components as all other modules
  92611. * are dependent on it.
  92612. */
  92613. #endif
  92614. /*** End of inlined file: all.h ***/
  92615. /*** Start of inlined file: bitmath.c ***/
  92616. /*** Start of inlined file: juce_FlacHeader.h ***/
  92617. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92618. // tasks..
  92619. #define VERSION "1.2.1"
  92620. #define FLAC__NO_DLL 1
  92621. #if JUCE_MSVC
  92622. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92623. #endif
  92624. #if JUCE_MAC
  92625. #define FLAC__SYS_DARWIN 1
  92626. #endif
  92627. /*** End of inlined file: juce_FlacHeader.h ***/
  92628. #if JUCE_USE_FLAC
  92629. #if HAVE_CONFIG_H
  92630. # include <config.h>
  92631. #endif
  92632. /*** Start of inlined file: bitmath.h ***/
  92633. #ifndef FLAC__PRIVATE__BITMATH_H
  92634. #define FLAC__PRIVATE__BITMATH_H
  92635. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92636. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92637. unsigned FLAC__bitmath_silog2(int v);
  92638. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92639. #endif
  92640. /*** End of inlined file: bitmath.h ***/
  92641. /* An example of what FLAC__bitmath_ilog2() computes:
  92642. *
  92643. * ilog2( 0) = assertion failure
  92644. * ilog2( 1) = 0
  92645. * ilog2( 2) = 1
  92646. * ilog2( 3) = 1
  92647. * ilog2( 4) = 2
  92648. * ilog2( 5) = 2
  92649. * ilog2( 6) = 2
  92650. * ilog2( 7) = 2
  92651. * ilog2( 8) = 3
  92652. * ilog2( 9) = 3
  92653. * ilog2(10) = 3
  92654. * ilog2(11) = 3
  92655. * ilog2(12) = 3
  92656. * ilog2(13) = 3
  92657. * ilog2(14) = 3
  92658. * ilog2(15) = 3
  92659. * ilog2(16) = 4
  92660. * ilog2(17) = 4
  92661. * ilog2(18) = 4
  92662. */
  92663. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92664. {
  92665. unsigned l = 0;
  92666. FLAC__ASSERT(v > 0);
  92667. while(v >>= 1)
  92668. l++;
  92669. return l;
  92670. }
  92671. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92672. {
  92673. unsigned l = 0;
  92674. FLAC__ASSERT(v > 0);
  92675. while(v >>= 1)
  92676. l++;
  92677. return l;
  92678. }
  92679. /* An example of what FLAC__bitmath_silog2() computes:
  92680. *
  92681. * silog2(-10) = 5
  92682. * silog2(- 9) = 5
  92683. * silog2(- 8) = 4
  92684. * silog2(- 7) = 4
  92685. * silog2(- 6) = 4
  92686. * silog2(- 5) = 4
  92687. * silog2(- 4) = 3
  92688. * silog2(- 3) = 3
  92689. * silog2(- 2) = 2
  92690. * silog2(- 1) = 2
  92691. * silog2( 0) = 0
  92692. * silog2( 1) = 2
  92693. * silog2( 2) = 3
  92694. * silog2( 3) = 3
  92695. * silog2( 4) = 4
  92696. * silog2( 5) = 4
  92697. * silog2( 6) = 4
  92698. * silog2( 7) = 4
  92699. * silog2( 8) = 5
  92700. * silog2( 9) = 5
  92701. * silog2( 10) = 5
  92702. */
  92703. unsigned FLAC__bitmath_silog2(int v)
  92704. {
  92705. while(1) {
  92706. if(v == 0) {
  92707. return 0;
  92708. }
  92709. else if(v > 0) {
  92710. unsigned l = 0;
  92711. while(v) {
  92712. l++;
  92713. v >>= 1;
  92714. }
  92715. return l+1;
  92716. }
  92717. else if(v == -1) {
  92718. return 2;
  92719. }
  92720. else {
  92721. v++;
  92722. v = -v;
  92723. }
  92724. }
  92725. }
  92726. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92727. {
  92728. while(1) {
  92729. if(v == 0) {
  92730. return 0;
  92731. }
  92732. else if(v > 0) {
  92733. unsigned l = 0;
  92734. while(v) {
  92735. l++;
  92736. v >>= 1;
  92737. }
  92738. return l+1;
  92739. }
  92740. else if(v == -1) {
  92741. return 2;
  92742. }
  92743. else {
  92744. v++;
  92745. v = -v;
  92746. }
  92747. }
  92748. }
  92749. #endif
  92750. /*** End of inlined file: bitmath.c ***/
  92751. /*** Start of inlined file: bitreader.c ***/
  92752. /*** Start of inlined file: juce_FlacHeader.h ***/
  92753. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92754. // tasks..
  92755. #define VERSION "1.2.1"
  92756. #define FLAC__NO_DLL 1
  92757. #if JUCE_MSVC
  92758. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92759. #endif
  92760. #if JUCE_MAC
  92761. #define FLAC__SYS_DARWIN 1
  92762. #endif
  92763. /*** End of inlined file: juce_FlacHeader.h ***/
  92764. #if JUCE_USE_FLAC
  92765. #if HAVE_CONFIG_H
  92766. # include <config.h>
  92767. #endif
  92768. #include <stdlib.h> /* for malloc() */
  92769. #include <string.h> /* for memcpy(), memset() */
  92770. #ifdef _MSC_VER
  92771. #include <winsock.h> /* for ntohl() */
  92772. #elif defined FLAC__SYS_DARWIN
  92773. #include <machine/endian.h> /* for ntohl() */
  92774. #elif defined __MINGW32__
  92775. #include <winsock.h> /* for ntohl() */
  92776. #else
  92777. #include <netinet/in.h> /* for ntohl() */
  92778. #endif
  92779. /*** Start of inlined file: bitreader.h ***/
  92780. #ifndef FLAC__PRIVATE__BITREADER_H
  92781. #define FLAC__PRIVATE__BITREADER_H
  92782. #include <stdio.h> /* for FILE */
  92783. /*** Start of inlined file: cpu.h ***/
  92784. #ifndef FLAC__PRIVATE__CPU_H
  92785. #define FLAC__PRIVATE__CPU_H
  92786. #ifdef HAVE_CONFIG_H
  92787. #include <config.h>
  92788. #endif
  92789. typedef enum {
  92790. FLAC__CPUINFO_TYPE_IA32,
  92791. FLAC__CPUINFO_TYPE_PPC,
  92792. FLAC__CPUINFO_TYPE_UNKNOWN
  92793. } FLAC__CPUInfo_Type;
  92794. typedef struct {
  92795. FLAC__bool cpuid;
  92796. FLAC__bool bswap;
  92797. FLAC__bool cmov;
  92798. FLAC__bool mmx;
  92799. FLAC__bool fxsr;
  92800. FLAC__bool sse;
  92801. FLAC__bool sse2;
  92802. FLAC__bool sse3;
  92803. FLAC__bool ssse3;
  92804. FLAC__bool _3dnow;
  92805. FLAC__bool ext3dnow;
  92806. FLAC__bool extmmx;
  92807. } FLAC__CPUInfo_IA32;
  92808. typedef struct {
  92809. FLAC__bool altivec;
  92810. FLAC__bool ppc64;
  92811. } FLAC__CPUInfo_PPC;
  92812. typedef struct {
  92813. FLAC__bool use_asm;
  92814. FLAC__CPUInfo_Type type;
  92815. union {
  92816. FLAC__CPUInfo_IA32 ia32;
  92817. FLAC__CPUInfo_PPC ppc;
  92818. } data;
  92819. } FLAC__CPUInfo;
  92820. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92821. #ifndef FLAC__NO_ASM
  92822. #ifdef FLAC__CPU_IA32
  92823. #ifdef FLAC__HAS_NASM
  92824. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92825. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92826. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92827. #endif
  92828. #endif
  92829. #endif
  92830. #endif
  92831. /*** End of inlined file: cpu.h ***/
  92832. /*
  92833. * opaque structure definition
  92834. */
  92835. struct FLAC__BitReader;
  92836. typedef struct FLAC__BitReader FLAC__BitReader;
  92837. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92838. /*
  92839. * construction, deletion, initialization, etc functions
  92840. */
  92841. FLAC__BitReader *FLAC__bitreader_new(void);
  92842. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92843. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92844. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92845. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92846. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92847. /*
  92848. * CRC functions
  92849. */
  92850. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92851. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92852. /*
  92853. * info functions
  92854. */
  92855. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92856. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92857. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92858. /*
  92859. * read functions
  92860. */
  92861. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92862. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92863. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92864. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92865. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92866. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92867. 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! */
  92868. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92869. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92870. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92871. #ifndef FLAC__NO_ASM
  92872. # ifdef FLAC__CPU_IA32
  92873. # ifdef FLAC__HAS_NASM
  92874. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92875. # endif
  92876. # endif
  92877. #endif
  92878. #if 0 /* UNUSED */
  92879. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92880. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92881. #endif
  92882. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92883. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92884. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92885. #endif
  92886. /*** End of inlined file: bitreader.h ***/
  92887. /*** Start of inlined file: crc.h ***/
  92888. #ifndef FLAC__PRIVATE__CRC_H
  92889. #define FLAC__PRIVATE__CRC_H
  92890. /* 8 bit CRC generator, MSB shifted first
  92891. ** polynomial = x^8 + x^2 + x^1 + x^0
  92892. ** init = 0
  92893. */
  92894. extern FLAC__byte const FLAC__crc8_table[256];
  92895. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92896. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92897. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92898. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92899. /* 16 bit CRC generator, MSB shifted first
  92900. ** polynomial = x^16 + x^15 + x^2 + x^0
  92901. ** init = 0
  92902. */
  92903. extern unsigned FLAC__crc16_table[256];
  92904. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92905. /* this alternate may be faster on some systems/compilers */
  92906. #if 0
  92907. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92908. #endif
  92909. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92910. #endif
  92911. /*** End of inlined file: crc.h ***/
  92912. /* Things should be fastest when this matches the machine word size */
  92913. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92914. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92915. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92916. typedef FLAC__uint32 brword;
  92917. #define FLAC__BYTES_PER_WORD 4
  92918. #define FLAC__BITS_PER_WORD 32
  92919. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92920. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92921. #if WORDS_BIGENDIAN
  92922. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92923. #else
  92924. #if defined (_MSC_VER) && defined (_X86_)
  92925. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92926. #else
  92927. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92928. #endif
  92929. #endif
  92930. /* counts the # of zero MSBs in a word */
  92931. #define COUNT_ZERO_MSBS(word) ( \
  92932. (word) <= 0xffff ? \
  92933. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92934. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92935. )
  92936. /* this alternate might be slightly faster on some systems/compilers: */
  92937. #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])) )
  92938. /*
  92939. * This should be at least twice as large as the largest number of words
  92940. * required to represent any 'number' (in any encoding) you are going to
  92941. * read. With FLAC this is on the order of maybe a few hundred bits.
  92942. * If the buffer is smaller than that, the decoder won't be able to read
  92943. * in a whole number that is in a variable length encoding (e.g. Rice).
  92944. * But to be practical it should be at least 1K bytes.
  92945. *
  92946. * Increase this number to decrease the number of read callbacks, at the
  92947. * expense of using more memory. Or decrease for the reverse effect,
  92948. * keeping in mind the limit from the first paragraph. The optimal size
  92949. * also depends on the CPU cache size and other factors; some twiddling
  92950. * may be necessary to squeeze out the best performance.
  92951. */
  92952. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92953. static const unsigned char byte_to_unary_table[] = {
  92954. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92955. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92956. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92957. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92958. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92959. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92960. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92961. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92970. };
  92971. #ifdef min
  92972. #undef min
  92973. #endif
  92974. #define min(x,y) ((x)<(y)?(x):(y))
  92975. #ifdef max
  92976. #undef max
  92977. #endif
  92978. #define max(x,y) ((x)>(y)?(x):(y))
  92979. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92980. #ifdef _MSC_VER
  92981. #define FLAC__U64L(x) x
  92982. #else
  92983. #define FLAC__U64L(x) x##LLU
  92984. #endif
  92985. #ifndef FLaC__INLINE
  92986. #define FLaC__INLINE
  92987. #endif
  92988. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92989. struct FLAC__BitReader {
  92990. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92991. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92992. brword *buffer;
  92993. unsigned capacity; /* in words */
  92994. unsigned words; /* # of completed words in buffer */
  92995. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92996. unsigned consumed_words; /* #words ... */
  92997. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92998. unsigned read_crc16; /* the running frame CRC */
  92999. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93000. FLAC__BitReaderReadCallback read_callback;
  93001. void *client_data;
  93002. FLAC__CPUInfo cpu_info;
  93003. };
  93004. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93005. {
  93006. register unsigned crc = br->read_crc16;
  93007. #if FLAC__BYTES_PER_WORD == 4
  93008. switch(br->crc16_align) {
  93009. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93010. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93011. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93012. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93013. }
  93014. #elif FLAC__BYTES_PER_WORD == 8
  93015. switch(br->crc16_align) {
  93016. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93017. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93018. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93019. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93020. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93021. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93022. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93023. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93024. }
  93025. #else
  93026. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93027. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93028. br->read_crc16 = crc;
  93029. #endif
  93030. br->crc16_align = 0;
  93031. }
  93032. /* would be static except it needs to be called by asm routines */
  93033. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93034. {
  93035. unsigned start, end;
  93036. size_t bytes;
  93037. FLAC__byte *target;
  93038. /* first shift the unconsumed buffer data toward the front as much as possible */
  93039. if(br->consumed_words > 0) {
  93040. start = br->consumed_words;
  93041. end = br->words + (br->bytes? 1:0);
  93042. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93043. br->words -= start;
  93044. br->consumed_words = 0;
  93045. }
  93046. /*
  93047. * set the target for reading, taking into account word alignment and endianness
  93048. */
  93049. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93050. if(bytes == 0)
  93051. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93052. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93053. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93054. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93055. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93056. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93057. * ^^-------target, bytes=3
  93058. * on LE machines, have to byteswap the odd tail word so nothing is
  93059. * overwritten:
  93060. */
  93061. #if WORDS_BIGENDIAN
  93062. #else
  93063. if(br->bytes)
  93064. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93065. #endif
  93066. /* now it looks like:
  93067. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93068. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93069. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93070. * ^^-------target, bytes=3
  93071. */
  93072. /* read in the data; note that the callback may return a smaller number of bytes */
  93073. if(!br->read_callback(target, &bytes, br->client_data))
  93074. return false;
  93075. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93076. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93077. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93078. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93079. * now have to byteswap on LE machines:
  93080. */
  93081. #if WORDS_BIGENDIAN
  93082. #else
  93083. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93084. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93085. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93086. start = br->words;
  93087. local_swap32_block_(br->buffer + start, end - start);
  93088. }
  93089. else
  93090. # endif
  93091. for(start = br->words; start < end; start++)
  93092. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93093. #endif
  93094. /* now it looks like:
  93095. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93096. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93097. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93098. * finally we'll update the reader values:
  93099. */
  93100. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93101. br->words = end / FLAC__BYTES_PER_WORD;
  93102. br->bytes = end % FLAC__BYTES_PER_WORD;
  93103. return true;
  93104. }
  93105. /***********************************************************************
  93106. *
  93107. * Class constructor/destructor
  93108. *
  93109. ***********************************************************************/
  93110. FLAC__BitReader *FLAC__bitreader_new(void)
  93111. {
  93112. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93113. /* calloc() implies:
  93114. memset(br, 0, sizeof(FLAC__BitReader));
  93115. br->buffer = 0;
  93116. br->capacity = 0;
  93117. br->words = br->bytes = 0;
  93118. br->consumed_words = br->consumed_bits = 0;
  93119. br->read_callback = 0;
  93120. br->client_data = 0;
  93121. */
  93122. return br;
  93123. }
  93124. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93125. {
  93126. FLAC__ASSERT(0 != br);
  93127. FLAC__bitreader_free(br);
  93128. free(br);
  93129. }
  93130. /***********************************************************************
  93131. *
  93132. * Public class methods
  93133. *
  93134. ***********************************************************************/
  93135. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93136. {
  93137. FLAC__ASSERT(0 != br);
  93138. br->words = br->bytes = 0;
  93139. br->consumed_words = br->consumed_bits = 0;
  93140. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93141. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93142. if(br->buffer == 0)
  93143. return false;
  93144. br->read_callback = rcb;
  93145. br->client_data = cd;
  93146. br->cpu_info = cpu;
  93147. return true;
  93148. }
  93149. void FLAC__bitreader_free(FLAC__BitReader *br)
  93150. {
  93151. FLAC__ASSERT(0 != br);
  93152. if(0 != br->buffer)
  93153. free(br->buffer);
  93154. br->buffer = 0;
  93155. br->capacity = 0;
  93156. br->words = br->bytes = 0;
  93157. br->consumed_words = br->consumed_bits = 0;
  93158. br->read_callback = 0;
  93159. br->client_data = 0;
  93160. }
  93161. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93162. {
  93163. br->words = br->bytes = 0;
  93164. br->consumed_words = br->consumed_bits = 0;
  93165. return true;
  93166. }
  93167. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93168. {
  93169. unsigned i, j;
  93170. if(br == 0) {
  93171. fprintf(out, "bitreader is NULL\n");
  93172. }
  93173. else {
  93174. 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);
  93175. for(i = 0; i < br->words; i++) {
  93176. fprintf(out, "%08X: ", i);
  93177. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93178. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93179. fprintf(out, ".");
  93180. else
  93181. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93182. fprintf(out, "\n");
  93183. }
  93184. if(br->bytes > 0) {
  93185. fprintf(out, "%08X: ", i);
  93186. for(j = 0; j < br->bytes*8; j++)
  93187. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93188. fprintf(out, ".");
  93189. else
  93190. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93191. fprintf(out, "\n");
  93192. }
  93193. }
  93194. }
  93195. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93196. {
  93197. FLAC__ASSERT(0 != br);
  93198. FLAC__ASSERT(0 != br->buffer);
  93199. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93200. br->read_crc16 = (unsigned)seed;
  93201. br->crc16_align = br->consumed_bits;
  93202. }
  93203. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93204. {
  93205. FLAC__ASSERT(0 != br);
  93206. FLAC__ASSERT(0 != br->buffer);
  93207. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93208. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93209. /* CRC any tail bytes in a partially-consumed word */
  93210. if(br->consumed_bits) {
  93211. const brword tail = br->buffer[br->consumed_words];
  93212. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93213. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93214. }
  93215. return br->read_crc16;
  93216. }
  93217. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93218. {
  93219. return ((br->consumed_bits & 7) == 0);
  93220. }
  93221. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93222. {
  93223. return 8 - (br->consumed_bits & 7);
  93224. }
  93225. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93226. {
  93227. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93228. }
  93229. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93230. {
  93231. FLAC__ASSERT(0 != br);
  93232. FLAC__ASSERT(0 != br->buffer);
  93233. FLAC__ASSERT(bits <= 32);
  93234. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93235. FLAC__ASSERT(br->consumed_words <= br->words);
  93236. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93237. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93238. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93239. *val = 0;
  93240. return true;
  93241. }
  93242. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93243. if(!bitreader_read_from_client_(br))
  93244. return false;
  93245. }
  93246. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93247. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93248. if(br->consumed_bits) {
  93249. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93250. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93251. const brword word = br->buffer[br->consumed_words];
  93252. if(bits < n) {
  93253. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93254. br->consumed_bits += bits;
  93255. return true;
  93256. }
  93257. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93258. bits -= n;
  93259. crc16_update_word_(br, word);
  93260. br->consumed_words++;
  93261. br->consumed_bits = 0;
  93262. 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 */
  93263. *val <<= bits;
  93264. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93265. br->consumed_bits = bits;
  93266. }
  93267. return true;
  93268. }
  93269. else {
  93270. const brword word = br->buffer[br->consumed_words];
  93271. if(bits < FLAC__BITS_PER_WORD) {
  93272. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93273. br->consumed_bits = bits;
  93274. return true;
  93275. }
  93276. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93277. *val = word;
  93278. crc16_update_word_(br, word);
  93279. br->consumed_words++;
  93280. return true;
  93281. }
  93282. }
  93283. else {
  93284. /* in this case we're starting our read at a partial tail word;
  93285. * the reader has guaranteed that we have at least 'bits' bits
  93286. * available to read, which makes this case simpler.
  93287. */
  93288. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93289. if(br->consumed_bits) {
  93290. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93291. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93292. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93293. br->consumed_bits += bits;
  93294. return true;
  93295. }
  93296. else {
  93297. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93298. br->consumed_bits += bits;
  93299. return true;
  93300. }
  93301. }
  93302. }
  93303. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93304. {
  93305. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93306. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93307. return false;
  93308. /* sign-extend: */
  93309. *val <<= (32-bits);
  93310. *val >>= (32-bits);
  93311. return true;
  93312. }
  93313. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93314. {
  93315. FLAC__uint32 hi, lo;
  93316. if(bits > 32) {
  93317. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93318. return false;
  93319. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93320. return false;
  93321. *val = hi;
  93322. *val <<= 32;
  93323. *val |= lo;
  93324. }
  93325. else {
  93326. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93327. return false;
  93328. *val = lo;
  93329. }
  93330. return true;
  93331. }
  93332. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93333. {
  93334. FLAC__uint32 x8, x32 = 0;
  93335. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93336. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93337. return false;
  93338. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93339. return false;
  93340. x32 |= (x8 << 8);
  93341. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93342. return false;
  93343. x32 |= (x8 << 16);
  93344. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93345. return false;
  93346. x32 |= (x8 << 24);
  93347. *val = x32;
  93348. return true;
  93349. }
  93350. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93351. {
  93352. /*
  93353. * OPT: a faster implementation is possible but probably not that useful
  93354. * since this is only called a couple of times in the metadata readers.
  93355. */
  93356. FLAC__ASSERT(0 != br);
  93357. FLAC__ASSERT(0 != br->buffer);
  93358. if(bits > 0) {
  93359. const unsigned n = br->consumed_bits & 7;
  93360. unsigned m;
  93361. FLAC__uint32 x;
  93362. if(n != 0) {
  93363. m = min(8-n, bits);
  93364. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93365. return false;
  93366. bits -= m;
  93367. }
  93368. m = bits / 8;
  93369. if(m > 0) {
  93370. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93371. return false;
  93372. bits %= 8;
  93373. }
  93374. if(bits > 0) {
  93375. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93376. return false;
  93377. }
  93378. }
  93379. return true;
  93380. }
  93381. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93382. {
  93383. FLAC__uint32 x;
  93384. FLAC__ASSERT(0 != br);
  93385. FLAC__ASSERT(0 != br->buffer);
  93386. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93387. /* step 1: skip over partial head word to get word aligned */
  93388. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93389. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93390. return false;
  93391. nvals--;
  93392. }
  93393. if(0 == nvals)
  93394. return true;
  93395. /* step 2: skip whole words in chunks */
  93396. while(nvals >= FLAC__BYTES_PER_WORD) {
  93397. if(br->consumed_words < br->words) {
  93398. br->consumed_words++;
  93399. nvals -= FLAC__BYTES_PER_WORD;
  93400. }
  93401. else if(!bitreader_read_from_client_(br))
  93402. return false;
  93403. }
  93404. /* step 3: skip any remainder from partial tail bytes */
  93405. while(nvals) {
  93406. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93407. return false;
  93408. nvals--;
  93409. }
  93410. return true;
  93411. }
  93412. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93413. {
  93414. FLAC__uint32 x;
  93415. FLAC__ASSERT(0 != br);
  93416. FLAC__ASSERT(0 != br->buffer);
  93417. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93418. /* step 1: read from partial head word to get word aligned */
  93419. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93420. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93421. return false;
  93422. *val++ = (FLAC__byte)x;
  93423. nvals--;
  93424. }
  93425. if(0 == nvals)
  93426. return true;
  93427. /* step 2: read whole words in chunks */
  93428. while(nvals >= FLAC__BYTES_PER_WORD) {
  93429. if(br->consumed_words < br->words) {
  93430. const brword word = br->buffer[br->consumed_words++];
  93431. #if FLAC__BYTES_PER_WORD == 4
  93432. val[0] = (FLAC__byte)(word >> 24);
  93433. val[1] = (FLAC__byte)(word >> 16);
  93434. val[2] = (FLAC__byte)(word >> 8);
  93435. val[3] = (FLAC__byte)word;
  93436. #elif FLAC__BYTES_PER_WORD == 8
  93437. val[0] = (FLAC__byte)(word >> 56);
  93438. val[1] = (FLAC__byte)(word >> 48);
  93439. val[2] = (FLAC__byte)(word >> 40);
  93440. val[3] = (FLAC__byte)(word >> 32);
  93441. val[4] = (FLAC__byte)(word >> 24);
  93442. val[5] = (FLAC__byte)(word >> 16);
  93443. val[6] = (FLAC__byte)(word >> 8);
  93444. val[7] = (FLAC__byte)word;
  93445. #else
  93446. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93447. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93448. #endif
  93449. val += FLAC__BYTES_PER_WORD;
  93450. nvals -= FLAC__BYTES_PER_WORD;
  93451. }
  93452. else if(!bitreader_read_from_client_(br))
  93453. return false;
  93454. }
  93455. /* step 3: read any remainder from partial tail bytes */
  93456. while(nvals) {
  93457. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93458. return false;
  93459. *val++ = (FLAC__byte)x;
  93460. nvals--;
  93461. }
  93462. return true;
  93463. }
  93464. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93465. #if 0 /* slow but readable version */
  93466. {
  93467. unsigned bit;
  93468. FLAC__ASSERT(0 != br);
  93469. FLAC__ASSERT(0 != br->buffer);
  93470. *val = 0;
  93471. while(1) {
  93472. if(!FLAC__bitreader_read_bit(br, &bit))
  93473. return false;
  93474. if(bit)
  93475. break;
  93476. else
  93477. *val++;
  93478. }
  93479. return true;
  93480. }
  93481. #else
  93482. {
  93483. unsigned i;
  93484. FLAC__ASSERT(0 != br);
  93485. FLAC__ASSERT(0 != br->buffer);
  93486. *val = 0;
  93487. while(1) {
  93488. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93489. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93490. if(b) {
  93491. i = COUNT_ZERO_MSBS(b);
  93492. *val += i;
  93493. i++;
  93494. br->consumed_bits += i;
  93495. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93496. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93497. br->consumed_words++;
  93498. br->consumed_bits = 0;
  93499. }
  93500. return true;
  93501. }
  93502. else {
  93503. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93504. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93505. br->consumed_words++;
  93506. br->consumed_bits = 0;
  93507. /* didn't find stop bit yet, have to keep going... */
  93508. }
  93509. }
  93510. /* at this point we've eaten up all the whole words; have to try
  93511. * reading through any tail bytes before calling the read callback.
  93512. * this is a repeat of the above logic adjusted for the fact we
  93513. * don't have a whole word. note though if the client is feeding
  93514. * us data a byte at a time (unlikely), br->consumed_bits may not
  93515. * be zero.
  93516. */
  93517. if(br->bytes) {
  93518. const unsigned end = br->bytes * 8;
  93519. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93520. if(b) {
  93521. i = COUNT_ZERO_MSBS(b);
  93522. *val += i;
  93523. i++;
  93524. br->consumed_bits += i;
  93525. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93526. return true;
  93527. }
  93528. else {
  93529. *val += end - br->consumed_bits;
  93530. br->consumed_bits += end;
  93531. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93532. /* didn't find stop bit yet, have to keep going... */
  93533. }
  93534. }
  93535. if(!bitreader_read_from_client_(br))
  93536. return false;
  93537. }
  93538. }
  93539. #endif
  93540. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93541. {
  93542. FLAC__uint32 lsbs = 0, msbs = 0;
  93543. unsigned uval;
  93544. FLAC__ASSERT(0 != br);
  93545. FLAC__ASSERT(0 != br->buffer);
  93546. FLAC__ASSERT(parameter <= 31);
  93547. /* read the unary MSBs and end bit */
  93548. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93549. return false;
  93550. /* read the binary LSBs */
  93551. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93552. return false;
  93553. /* compose the value */
  93554. uval = (msbs << parameter) | lsbs;
  93555. if(uval & 1)
  93556. *val = -((int)(uval >> 1)) - 1;
  93557. else
  93558. *val = (int)(uval >> 1);
  93559. return true;
  93560. }
  93561. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93562. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93563. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93564. /* OPT: possibly faster version for use with MSVC */
  93565. #ifdef _MSC_VER
  93566. {
  93567. unsigned i;
  93568. unsigned uval = 0;
  93569. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93570. /* try and get br->consumed_words and br->consumed_bits into register;
  93571. * must remember to flush them back to *br before calling other
  93572. * bitwriter functions that use them, and before returning */
  93573. register unsigned cwords;
  93574. register unsigned cbits;
  93575. FLAC__ASSERT(0 != br);
  93576. FLAC__ASSERT(0 != br->buffer);
  93577. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93578. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93579. FLAC__ASSERT(parameter < 32);
  93580. /* 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 */
  93581. if(nvals == 0)
  93582. return true;
  93583. cbits = br->consumed_bits;
  93584. cwords = br->consumed_words;
  93585. while(1) {
  93586. /* read unary part */
  93587. while(1) {
  93588. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93589. brword b = br->buffer[cwords] << cbits;
  93590. if(b) {
  93591. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93592. __asm {
  93593. bsr eax, b
  93594. not eax
  93595. and eax, 31
  93596. mov i, eax
  93597. }
  93598. #else
  93599. i = COUNT_ZERO_MSBS(b);
  93600. #endif
  93601. uval += i;
  93602. bits = parameter;
  93603. i++;
  93604. cbits += i;
  93605. if(cbits == FLAC__BITS_PER_WORD) {
  93606. crc16_update_word_(br, br->buffer[cwords]);
  93607. cwords++;
  93608. cbits = 0;
  93609. }
  93610. goto break1;
  93611. }
  93612. else {
  93613. uval += FLAC__BITS_PER_WORD - cbits;
  93614. crc16_update_word_(br, br->buffer[cwords]);
  93615. cwords++;
  93616. cbits = 0;
  93617. /* didn't find stop bit yet, have to keep going... */
  93618. }
  93619. }
  93620. /* at this point we've eaten up all the whole words; have to try
  93621. * reading through any tail bytes before calling the read callback.
  93622. * this is a repeat of the above logic adjusted for the fact we
  93623. * don't have a whole word. note though if the client is feeding
  93624. * us data a byte at a time (unlikely), br->consumed_bits may not
  93625. * be zero.
  93626. */
  93627. if(br->bytes) {
  93628. const unsigned end = br->bytes * 8;
  93629. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93630. if(b) {
  93631. i = COUNT_ZERO_MSBS(b);
  93632. uval += i;
  93633. bits = parameter;
  93634. i++;
  93635. cbits += i;
  93636. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93637. goto break1;
  93638. }
  93639. else {
  93640. uval += end - cbits;
  93641. cbits += end;
  93642. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93643. /* didn't find stop bit yet, have to keep going... */
  93644. }
  93645. }
  93646. /* flush registers and read; bitreader_read_from_client_() does
  93647. * not touch br->consumed_bits at all but we still need to set
  93648. * it in case it fails and we have to return false.
  93649. */
  93650. br->consumed_bits = cbits;
  93651. br->consumed_words = cwords;
  93652. if(!bitreader_read_from_client_(br))
  93653. return false;
  93654. cwords = br->consumed_words;
  93655. }
  93656. break1:
  93657. /* read binary part */
  93658. FLAC__ASSERT(cwords <= br->words);
  93659. if(bits) {
  93660. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93661. /* flush registers and read; bitreader_read_from_client_() does
  93662. * not touch br->consumed_bits at all but we still need to set
  93663. * it in case it fails and we have to return false.
  93664. */
  93665. br->consumed_bits = cbits;
  93666. br->consumed_words = cwords;
  93667. if(!bitreader_read_from_client_(br))
  93668. return false;
  93669. cwords = br->consumed_words;
  93670. }
  93671. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93672. if(cbits) {
  93673. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93674. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93675. const brword word = br->buffer[cwords];
  93676. if(bits < n) {
  93677. uval <<= bits;
  93678. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93679. cbits += bits;
  93680. goto break2;
  93681. }
  93682. uval <<= n;
  93683. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93684. bits -= n;
  93685. crc16_update_word_(br, word);
  93686. cwords++;
  93687. cbits = 0;
  93688. 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 */
  93689. uval <<= bits;
  93690. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93691. cbits = bits;
  93692. }
  93693. goto break2;
  93694. }
  93695. else {
  93696. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93697. uval <<= bits;
  93698. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93699. cbits = bits;
  93700. goto break2;
  93701. }
  93702. }
  93703. else {
  93704. /* in this case we're starting our read at a partial tail word;
  93705. * the reader has guaranteed that we have at least 'bits' bits
  93706. * available to read, which makes this case simpler.
  93707. */
  93708. uval <<= bits;
  93709. if(cbits) {
  93710. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93711. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93712. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93713. cbits += bits;
  93714. goto break2;
  93715. }
  93716. else {
  93717. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93718. cbits += bits;
  93719. goto break2;
  93720. }
  93721. }
  93722. }
  93723. break2:
  93724. /* compose the value */
  93725. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93726. /* are we done? */
  93727. --nvals;
  93728. if(nvals == 0) {
  93729. br->consumed_bits = cbits;
  93730. br->consumed_words = cwords;
  93731. return true;
  93732. }
  93733. uval = 0;
  93734. ++vals;
  93735. }
  93736. }
  93737. #else
  93738. {
  93739. unsigned i;
  93740. unsigned uval = 0;
  93741. /* try and get br->consumed_words and br->consumed_bits into register;
  93742. * must remember to flush them back to *br before calling other
  93743. * bitwriter functions that use them, and before returning */
  93744. register unsigned cwords;
  93745. register unsigned cbits;
  93746. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93747. FLAC__ASSERT(0 != br);
  93748. FLAC__ASSERT(0 != br->buffer);
  93749. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93750. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93751. FLAC__ASSERT(parameter < 32);
  93752. /* 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 */
  93753. if(nvals == 0)
  93754. return true;
  93755. cbits = br->consumed_bits;
  93756. cwords = br->consumed_words;
  93757. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93758. while(1) {
  93759. /* read unary part */
  93760. while(1) {
  93761. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93762. brword b = br->buffer[cwords] << cbits;
  93763. if(b) {
  93764. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93765. asm volatile (
  93766. "bsrl %1, %0;"
  93767. "notl %0;"
  93768. "andl $31, %0;"
  93769. : "=r"(i)
  93770. : "r"(b)
  93771. );
  93772. #else
  93773. i = COUNT_ZERO_MSBS(b);
  93774. #endif
  93775. uval += i;
  93776. cbits += i;
  93777. cbits++; /* skip over stop bit */
  93778. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93779. crc16_update_word_(br, br->buffer[cwords]);
  93780. cwords++;
  93781. cbits = 0;
  93782. }
  93783. goto break1;
  93784. }
  93785. else {
  93786. uval += FLAC__BITS_PER_WORD - cbits;
  93787. crc16_update_word_(br, br->buffer[cwords]);
  93788. cwords++;
  93789. cbits = 0;
  93790. /* didn't find stop bit yet, have to keep going... */
  93791. }
  93792. }
  93793. /* at this point we've eaten up all the whole words; have to try
  93794. * reading through any tail bytes before calling the read callback.
  93795. * this is a repeat of the above logic adjusted for the fact we
  93796. * don't have a whole word. note though if the client is feeding
  93797. * us data a byte at a time (unlikely), br->consumed_bits may not
  93798. * be zero.
  93799. */
  93800. if(br->bytes) {
  93801. const unsigned end = br->bytes * 8;
  93802. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93803. if(b) {
  93804. i = COUNT_ZERO_MSBS(b);
  93805. uval += i;
  93806. cbits += i;
  93807. cbits++; /* skip over stop bit */
  93808. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93809. goto break1;
  93810. }
  93811. else {
  93812. uval += end - cbits;
  93813. cbits += end;
  93814. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93815. /* didn't find stop bit yet, have to keep going... */
  93816. }
  93817. }
  93818. /* flush registers and read; bitreader_read_from_client_() does
  93819. * not touch br->consumed_bits at all but we still need to set
  93820. * it in case it fails and we have to return false.
  93821. */
  93822. br->consumed_bits = cbits;
  93823. br->consumed_words = cwords;
  93824. if(!bitreader_read_from_client_(br))
  93825. return false;
  93826. cwords = br->consumed_words;
  93827. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93828. /* + uval to offset our count by the # of unary bits already
  93829. * consumed before the read, because we will add these back
  93830. * in all at once at break1
  93831. */
  93832. }
  93833. break1:
  93834. ucbits -= uval;
  93835. ucbits--; /* account for stop bit */
  93836. /* read binary part */
  93837. FLAC__ASSERT(cwords <= br->words);
  93838. if(parameter) {
  93839. while(ucbits < parameter) {
  93840. /* flush registers and read; bitreader_read_from_client_() does
  93841. * not touch br->consumed_bits at all but we still need to set
  93842. * it in case it fails and we have to return false.
  93843. */
  93844. br->consumed_bits = cbits;
  93845. br->consumed_words = cwords;
  93846. if(!bitreader_read_from_client_(br))
  93847. return false;
  93848. cwords = br->consumed_words;
  93849. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93850. }
  93851. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93852. if(cbits) {
  93853. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93854. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93855. const brword word = br->buffer[cwords];
  93856. if(parameter < n) {
  93857. uval <<= parameter;
  93858. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93859. cbits += parameter;
  93860. }
  93861. else {
  93862. uval <<= n;
  93863. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93864. crc16_update_word_(br, word);
  93865. cwords++;
  93866. cbits = parameter - n;
  93867. 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 */
  93868. uval <<= cbits;
  93869. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93870. }
  93871. }
  93872. }
  93873. else {
  93874. cbits = parameter;
  93875. uval <<= parameter;
  93876. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93877. }
  93878. }
  93879. else {
  93880. /* in this case we're starting our read at a partial tail word;
  93881. * the reader has guaranteed that we have at least 'parameter'
  93882. * bits available to read, which makes this case simpler.
  93883. */
  93884. uval <<= parameter;
  93885. if(cbits) {
  93886. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93887. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93888. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93889. cbits += parameter;
  93890. }
  93891. else {
  93892. cbits = parameter;
  93893. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93894. }
  93895. }
  93896. }
  93897. ucbits -= parameter;
  93898. /* compose the value */
  93899. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93900. /* are we done? */
  93901. --nvals;
  93902. if(nvals == 0) {
  93903. br->consumed_bits = cbits;
  93904. br->consumed_words = cwords;
  93905. return true;
  93906. }
  93907. uval = 0;
  93908. ++vals;
  93909. }
  93910. }
  93911. #endif
  93912. #if 0 /* UNUSED */
  93913. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93914. {
  93915. FLAC__uint32 lsbs = 0, msbs = 0;
  93916. unsigned bit, uval, k;
  93917. FLAC__ASSERT(0 != br);
  93918. FLAC__ASSERT(0 != br->buffer);
  93919. k = FLAC__bitmath_ilog2(parameter);
  93920. /* read the unary MSBs and end bit */
  93921. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93922. return false;
  93923. /* read the binary LSBs */
  93924. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93925. return false;
  93926. if(parameter == 1u<<k) {
  93927. /* compose the value */
  93928. uval = (msbs << k) | lsbs;
  93929. }
  93930. else {
  93931. unsigned d = (1 << (k+1)) - parameter;
  93932. if(lsbs >= d) {
  93933. if(!FLAC__bitreader_read_bit(br, &bit))
  93934. return false;
  93935. lsbs <<= 1;
  93936. lsbs |= bit;
  93937. lsbs -= d;
  93938. }
  93939. /* compose the value */
  93940. uval = msbs * parameter + lsbs;
  93941. }
  93942. /* unfold unsigned to signed */
  93943. if(uval & 1)
  93944. *val = -((int)(uval >> 1)) - 1;
  93945. else
  93946. *val = (int)(uval >> 1);
  93947. return true;
  93948. }
  93949. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93950. {
  93951. FLAC__uint32 lsbs, msbs = 0;
  93952. unsigned bit, k;
  93953. FLAC__ASSERT(0 != br);
  93954. FLAC__ASSERT(0 != br->buffer);
  93955. k = FLAC__bitmath_ilog2(parameter);
  93956. /* read the unary MSBs and end bit */
  93957. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93958. return false;
  93959. /* read the binary LSBs */
  93960. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93961. return false;
  93962. if(parameter == 1u<<k) {
  93963. /* compose the value */
  93964. *val = (msbs << k) | lsbs;
  93965. }
  93966. else {
  93967. unsigned d = (1 << (k+1)) - parameter;
  93968. if(lsbs >= d) {
  93969. if(!FLAC__bitreader_read_bit(br, &bit))
  93970. return false;
  93971. lsbs <<= 1;
  93972. lsbs |= bit;
  93973. lsbs -= d;
  93974. }
  93975. /* compose the value */
  93976. *val = msbs * parameter + lsbs;
  93977. }
  93978. return true;
  93979. }
  93980. #endif /* UNUSED */
  93981. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93982. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93983. {
  93984. FLAC__uint32 v = 0;
  93985. FLAC__uint32 x;
  93986. unsigned i;
  93987. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93988. return false;
  93989. if(raw)
  93990. raw[(*rawlen)++] = (FLAC__byte)x;
  93991. if(!(x & 0x80)) { /* 0xxxxxxx */
  93992. v = x;
  93993. i = 0;
  93994. }
  93995. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93996. v = x & 0x1F;
  93997. i = 1;
  93998. }
  93999. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94000. v = x & 0x0F;
  94001. i = 2;
  94002. }
  94003. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94004. v = x & 0x07;
  94005. i = 3;
  94006. }
  94007. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94008. v = x & 0x03;
  94009. i = 4;
  94010. }
  94011. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94012. v = x & 0x01;
  94013. i = 5;
  94014. }
  94015. else {
  94016. *val = 0xffffffff;
  94017. return true;
  94018. }
  94019. for( ; i; i--) {
  94020. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94021. return false;
  94022. if(raw)
  94023. raw[(*rawlen)++] = (FLAC__byte)x;
  94024. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94025. *val = 0xffffffff;
  94026. return true;
  94027. }
  94028. v <<= 6;
  94029. v |= (x & 0x3F);
  94030. }
  94031. *val = v;
  94032. return true;
  94033. }
  94034. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94035. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94036. {
  94037. FLAC__uint64 v = 0;
  94038. FLAC__uint32 x;
  94039. unsigned i;
  94040. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94041. return false;
  94042. if(raw)
  94043. raw[(*rawlen)++] = (FLAC__byte)x;
  94044. if(!(x & 0x80)) { /* 0xxxxxxx */
  94045. v = x;
  94046. i = 0;
  94047. }
  94048. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94049. v = x & 0x1F;
  94050. i = 1;
  94051. }
  94052. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94053. v = x & 0x0F;
  94054. i = 2;
  94055. }
  94056. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94057. v = x & 0x07;
  94058. i = 3;
  94059. }
  94060. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94061. v = x & 0x03;
  94062. i = 4;
  94063. }
  94064. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94065. v = x & 0x01;
  94066. i = 5;
  94067. }
  94068. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94069. v = 0;
  94070. i = 6;
  94071. }
  94072. else {
  94073. *val = FLAC__U64L(0xffffffffffffffff);
  94074. return true;
  94075. }
  94076. for( ; i; i--) {
  94077. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94078. return false;
  94079. if(raw)
  94080. raw[(*rawlen)++] = (FLAC__byte)x;
  94081. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94082. *val = FLAC__U64L(0xffffffffffffffff);
  94083. return true;
  94084. }
  94085. v <<= 6;
  94086. v |= (x & 0x3F);
  94087. }
  94088. *val = v;
  94089. return true;
  94090. }
  94091. #endif
  94092. /*** End of inlined file: bitreader.c ***/
  94093. /*** Start of inlined file: bitwriter.c ***/
  94094. /*** Start of inlined file: juce_FlacHeader.h ***/
  94095. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94096. // tasks..
  94097. #define VERSION "1.2.1"
  94098. #define FLAC__NO_DLL 1
  94099. #if JUCE_MSVC
  94100. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94101. #endif
  94102. #if JUCE_MAC
  94103. #define FLAC__SYS_DARWIN 1
  94104. #endif
  94105. /*** End of inlined file: juce_FlacHeader.h ***/
  94106. #if JUCE_USE_FLAC
  94107. #if HAVE_CONFIG_H
  94108. # include <config.h>
  94109. #endif
  94110. #include <stdlib.h> /* for malloc() */
  94111. #include <string.h> /* for memcpy(), memset() */
  94112. #ifdef _MSC_VER
  94113. #include <winsock.h> /* for ntohl() */
  94114. #elif defined FLAC__SYS_DARWIN
  94115. #include <machine/endian.h> /* for ntohl() */
  94116. #elif defined __MINGW32__
  94117. #include <winsock.h> /* for ntohl() */
  94118. #else
  94119. #include <netinet/in.h> /* for ntohl() */
  94120. #endif
  94121. #if 0 /* UNUSED */
  94122. #endif
  94123. /*** Start of inlined file: bitwriter.h ***/
  94124. #ifndef FLAC__PRIVATE__BITWRITER_H
  94125. #define FLAC__PRIVATE__BITWRITER_H
  94126. #include <stdio.h> /* for FILE */
  94127. /*
  94128. * opaque structure definition
  94129. */
  94130. struct FLAC__BitWriter;
  94131. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94132. /*
  94133. * construction, deletion, initialization, etc functions
  94134. */
  94135. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94136. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94137. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94138. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94139. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94140. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94141. /*
  94142. * CRC functions
  94143. *
  94144. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94145. */
  94146. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94147. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94148. /*
  94149. * info functions
  94150. */
  94151. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94152. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94153. /*
  94154. * direct buffer access
  94155. *
  94156. * there may be no calls on the bitwriter between get and release.
  94157. * the bitwriter continues to own the returned buffer.
  94158. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94159. */
  94160. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94161. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94162. /*
  94163. * write functions
  94164. */
  94165. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94166. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94167. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94168. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94169. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94170. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94171. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94172. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94173. #if 0 /* UNUSED */
  94174. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94175. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94176. #endif
  94177. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94178. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94179. #if 0 /* UNUSED */
  94180. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94181. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94182. #endif
  94183. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94184. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94185. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94186. #endif
  94187. /*** End of inlined file: bitwriter.h ***/
  94188. /*** Start of inlined file: alloc.h ***/
  94189. #ifndef FLAC__SHARE__ALLOC_H
  94190. #define FLAC__SHARE__ALLOC_H
  94191. #if HAVE_CONFIG_H
  94192. # include <config.h>
  94193. #endif
  94194. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94195. * before #including this file, otherwise SIZE_MAX might not be defined
  94196. */
  94197. #include <limits.h> /* for SIZE_MAX */
  94198. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94199. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94200. #endif
  94201. #include <stdlib.h> /* for size_t, malloc(), etc */
  94202. #ifndef SIZE_MAX
  94203. # ifndef SIZE_T_MAX
  94204. # ifdef _MSC_VER
  94205. # define SIZE_T_MAX UINT_MAX
  94206. # else
  94207. # error
  94208. # endif
  94209. # endif
  94210. # define SIZE_MAX SIZE_T_MAX
  94211. #endif
  94212. #ifndef FLaC__INLINE
  94213. #define FLaC__INLINE
  94214. #endif
  94215. /* avoid malloc()ing 0 bytes, see:
  94216. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94217. */
  94218. static FLaC__INLINE void *safe_malloc_(size_t size)
  94219. {
  94220. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94221. if(!size)
  94222. size++;
  94223. return malloc(size);
  94224. }
  94225. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94226. {
  94227. if(!nmemb || !size)
  94228. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94229. return calloc(nmemb, size);
  94230. }
  94231. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94232. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94233. {
  94234. size2 += size1;
  94235. if(size2 < size1)
  94236. return 0;
  94237. return safe_malloc_(size2);
  94238. }
  94239. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94240. {
  94241. size2 += size1;
  94242. if(size2 < size1)
  94243. return 0;
  94244. size3 += size2;
  94245. if(size3 < size2)
  94246. return 0;
  94247. return safe_malloc_(size3);
  94248. }
  94249. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94250. {
  94251. size2 += size1;
  94252. if(size2 < size1)
  94253. return 0;
  94254. size3 += size2;
  94255. if(size3 < size2)
  94256. return 0;
  94257. size4 += size3;
  94258. if(size4 < size3)
  94259. return 0;
  94260. return safe_malloc_(size4);
  94261. }
  94262. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94263. #if 0
  94264. needs support for cases where sizeof(size_t) != 4
  94265. {
  94266. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94267. if(sizeof(size_t) == 4) {
  94268. if ((double)size1 * (double)size2 < 4294967296.0)
  94269. return malloc(size1*size2);
  94270. }
  94271. return 0;
  94272. }
  94273. #else
  94274. /* better? */
  94275. {
  94276. if(!size1 || !size2)
  94277. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94278. if(size1 > SIZE_MAX / size2)
  94279. return 0;
  94280. return malloc(size1*size2);
  94281. }
  94282. #endif
  94283. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94284. {
  94285. if(!size1 || !size2 || !size3)
  94286. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94287. if(size1 > SIZE_MAX / size2)
  94288. return 0;
  94289. size1 *= size2;
  94290. if(size1 > SIZE_MAX / size3)
  94291. return 0;
  94292. return malloc(size1*size3);
  94293. }
  94294. /* size1*size2 + size3 */
  94295. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94296. {
  94297. if(!size1 || !size2)
  94298. return safe_malloc_(size3);
  94299. if(size1 > SIZE_MAX / size2)
  94300. return 0;
  94301. return safe_malloc_add_2op_(size1*size2, size3);
  94302. }
  94303. /* size1 * (size2 + size3) */
  94304. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94305. {
  94306. if(!size1 || (!size2 && !size3))
  94307. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94308. size2 += size3;
  94309. if(size2 < size3)
  94310. return 0;
  94311. return safe_malloc_mul_2op_(size1, size2);
  94312. }
  94313. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94314. {
  94315. size2 += size1;
  94316. if(size2 < size1)
  94317. return 0;
  94318. return realloc(ptr, size2);
  94319. }
  94320. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94321. {
  94322. size2 += size1;
  94323. if(size2 < size1)
  94324. return 0;
  94325. size3 += size2;
  94326. if(size3 < size2)
  94327. return 0;
  94328. return realloc(ptr, size3);
  94329. }
  94330. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94331. {
  94332. size2 += size1;
  94333. if(size2 < size1)
  94334. return 0;
  94335. size3 += size2;
  94336. if(size3 < size2)
  94337. return 0;
  94338. size4 += size3;
  94339. if(size4 < size3)
  94340. return 0;
  94341. return realloc(ptr, size4);
  94342. }
  94343. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94344. {
  94345. if(!size1 || !size2)
  94346. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94347. if(size1 > SIZE_MAX / size2)
  94348. return 0;
  94349. return realloc(ptr, size1*size2);
  94350. }
  94351. /* size1 * (size2 + size3) */
  94352. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94353. {
  94354. if(!size1 || (!size2 && !size3))
  94355. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94356. size2 += size3;
  94357. if(size2 < size3)
  94358. return 0;
  94359. return safe_realloc_mul_2op_(ptr, size1, size2);
  94360. }
  94361. #endif
  94362. /*** End of inlined file: alloc.h ***/
  94363. /* Things should be fastest when this matches the machine word size */
  94364. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94365. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94366. typedef FLAC__uint32 bwword;
  94367. #define FLAC__BYTES_PER_WORD 4
  94368. #define FLAC__BITS_PER_WORD 32
  94369. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94370. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94371. #if WORDS_BIGENDIAN
  94372. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94373. #else
  94374. #ifdef _MSC_VER
  94375. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94376. #else
  94377. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94378. #endif
  94379. #endif
  94380. /*
  94381. * The default capacity here doesn't matter too much. The buffer always grows
  94382. * to hold whatever is written to it. Usually the encoder will stop adding at
  94383. * a frame or metadata block, then write that out and clear the buffer for the
  94384. * next one.
  94385. */
  94386. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94387. /* When growing, increment 4K at a time */
  94388. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94389. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94390. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94391. #ifdef min
  94392. #undef min
  94393. #endif
  94394. #define min(x,y) ((x)<(y)?(x):(y))
  94395. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94396. #ifdef _MSC_VER
  94397. #define FLAC__U64L(x) x
  94398. #else
  94399. #define FLAC__U64L(x) x##LLU
  94400. #endif
  94401. #ifndef FLaC__INLINE
  94402. #define FLaC__INLINE
  94403. #endif
  94404. struct FLAC__BitWriter {
  94405. bwword *buffer;
  94406. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94407. unsigned capacity; /* capacity of buffer in words */
  94408. unsigned words; /* # of complete words in buffer */
  94409. unsigned bits; /* # of used bits in accum */
  94410. };
  94411. /* * WATCHOUT: The current implementation only grows the buffer. */
  94412. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94413. {
  94414. unsigned new_capacity;
  94415. bwword *new_buffer;
  94416. FLAC__ASSERT(0 != bw);
  94417. FLAC__ASSERT(0 != bw->buffer);
  94418. /* calculate total words needed to store 'bits_to_add' additional bits */
  94419. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94420. /* it's possible (due to pessimism in the growth estimation that
  94421. * leads to this call) that we don't actually need to grow
  94422. */
  94423. if(bw->capacity >= new_capacity)
  94424. return true;
  94425. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94426. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94427. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94428. /* make sure we got everything right */
  94429. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94430. FLAC__ASSERT(new_capacity > bw->capacity);
  94431. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94432. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94433. if(new_buffer == 0)
  94434. return false;
  94435. bw->buffer = new_buffer;
  94436. bw->capacity = new_capacity;
  94437. return true;
  94438. }
  94439. /***********************************************************************
  94440. *
  94441. * Class constructor/destructor
  94442. *
  94443. ***********************************************************************/
  94444. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94445. {
  94446. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94447. /* note that calloc() sets all members to 0 for us */
  94448. return bw;
  94449. }
  94450. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94451. {
  94452. FLAC__ASSERT(0 != bw);
  94453. FLAC__bitwriter_free(bw);
  94454. free(bw);
  94455. }
  94456. /***********************************************************************
  94457. *
  94458. * Public class methods
  94459. *
  94460. ***********************************************************************/
  94461. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94462. {
  94463. FLAC__ASSERT(0 != bw);
  94464. bw->words = bw->bits = 0;
  94465. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94466. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94467. if(bw->buffer == 0)
  94468. return false;
  94469. return true;
  94470. }
  94471. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94472. {
  94473. FLAC__ASSERT(0 != bw);
  94474. if(0 != bw->buffer)
  94475. free(bw->buffer);
  94476. bw->buffer = 0;
  94477. bw->capacity = 0;
  94478. bw->words = bw->bits = 0;
  94479. }
  94480. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94481. {
  94482. bw->words = bw->bits = 0;
  94483. }
  94484. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94485. {
  94486. unsigned i, j;
  94487. if(bw == 0) {
  94488. fprintf(out, "bitwriter is NULL\n");
  94489. }
  94490. else {
  94491. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94492. for(i = 0; i < bw->words; i++) {
  94493. fprintf(out, "%08X: ", i);
  94494. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94495. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94496. fprintf(out, "\n");
  94497. }
  94498. if(bw->bits > 0) {
  94499. fprintf(out, "%08X: ", i);
  94500. for(j = 0; j < bw->bits; j++)
  94501. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94502. fprintf(out, "\n");
  94503. }
  94504. }
  94505. }
  94506. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94507. {
  94508. const FLAC__byte *buffer;
  94509. size_t bytes;
  94510. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94511. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94512. return false;
  94513. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94514. FLAC__bitwriter_release_buffer(bw);
  94515. return true;
  94516. }
  94517. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94518. {
  94519. const FLAC__byte *buffer;
  94520. size_t bytes;
  94521. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94522. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94523. return false;
  94524. *crc = FLAC__crc8(buffer, bytes);
  94525. FLAC__bitwriter_release_buffer(bw);
  94526. return true;
  94527. }
  94528. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94529. {
  94530. return ((bw->bits & 7) == 0);
  94531. }
  94532. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94533. {
  94534. return FLAC__TOTAL_BITS(bw);
  94535. }
  94536. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94537. {
  94538. FLAC__ASSERT((bw->bits & 7) == 0);
  94539. /* double protection */
  94540. if(bw->bits & 7)
  94541. return false;
  94542. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94543. if(bw->bits) {
  94544. FLAC__ASSERT(bw->words <= bw->capacity);
  94545. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94546. return false;
  94547. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94548. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94549. }
  94550. /* now we can just return what we have */
  94551. *buffer = (FLAC__byte*)bw->buffer;
  94552. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94553. return true;
  94554. }
  94555. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94556. {
  94557. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94558. * get-mode' flag could be added everywhere and then cleared here
  94559. */
  94560. (void)bw;
  94561. }
  94562. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94563. {
  94564. unsigned n;
  94565. FLAC__ASSERT(0 != bw);
  94566. FLAC__ASSERT(0 != bw->buffer);
  94567. if(bits == 0)
  94568. return true;
  94569. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94570. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94571. return false;
  94572. /* first part gets to word alignment */
  94573. if(bw->bits) {
  94574. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94575. bw->accum <<= n;
  94576. bits -= n;
  94577. bw->bits += n;
  94578. if(bw->bits == FLAC__BITS_PER_WORD) {
  94579. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94580. bw->bits = 0;
  94581. }
  94582. else
  94583. return true;
  94584. }
  94585. /* do whole words */
  94586. while(bits >= FLAC__BITS_PER_WORD) {
  94587. bw->buffer[bw->words++] = 0;
  94588. bits -= FLAC__BITS_PER_WORD;
  94589. }
  94590. /* do any leftovers */
  94591. if(bits > 0) {
  94592. bw->accum = 0;
  94593. bw->bits = bits;
  94594. }
  94595. return true;
  94596. }
  94597. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94598. {
  94599. register unsigned left;
  94600. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94601. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94602. FLAC__ASSERT(0 != bw);
  94603. FLAC__ASSERT(0 != bw->buffer);
  94604. FLAC__ASSERT(bits <= 32);
  94605. if(bits == 0)
  94606. return true;
  94607. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94608. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94609. return false;
  94610. left = FLAC__BITS_PER_WORD - bw->bits;
  94611. if(bits < left) {
  94612. bw->accum <<= bits;
  94613. bw->accum |= val;
  94614. bw->bits += bits;
  94615. }
  94616. 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 */
  94617. bw->accum <<= left;
  94618. bw->accum |= val >> (bw->bits = bits - left);
  94619. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94620. bw->accum = val;
  94621. }
  94622. else {
  94623. bw->accum = val;
  94624. bw->bits = 0;
  94625. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94626. }
  94627. return true;
  94628. }
  94629. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94630. {
  94631. /* zero-out unused bits */
  94632. if(bits < 32)
  94633. val &= (~(0xffffffff << bits));
  94634. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94635. }
  94636. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94637. {
  94638. /* this could be a little faster but it's not used for much */
  94639. if(bits > 32) {
  94640. return
  94641. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94642. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94643. }
  94644. else
  94645. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94646. }
  94647. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94648. {
  94649. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94650. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94651. return false;
  94652. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94653. return false;
  94654. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94655. return false;
  94656. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94657. return false;
  94658. return true;
  94659. }
  94660. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94661. {
  94662. unsigned i;
  94663. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94664. for(i = 0; i < nvals; i++) {
  94665. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94666. return false;
  94667. }
  94668. return true;
  94669. }
  94670. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94671. {
  94672. if(val < 32)
  94673. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94674. else
  94675. return
  94676. FLAC__bitwriter_write_zeroes(bw, val) &&
  94677. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94678. }
  94679. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94680. {
  94681. FLAC__uint32 uval;
  94682. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94683. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94684. uval = (val<<1) ^ (val>>31);
  94685. return 1 + parameter + (uval >> parameter);
  94686. }
  94687. #if 0 /* UNUSED */
  94688. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94689. {
  94690. unsigned bits, msbs, uval;
  94691. unsigned k;
  94692. FLAC__ASSERT(parameter > 0);
  94693. /* fold signed to unsigned */
  94694. if(val < 0)
  94695. uval = (unsigned)(((-(++val)) << 1) + 1);
  94696. else
  94697. uval = (unsigned)(val << 1);
  94698. k = FLAC__bitmath_ilog2(parameter);
  94699. if(parameter == 1u<<k) {
  94700. FLAC__ASSERT(k <= 30);
  94701. msbs = uval >> k;
  94702. bits = 1 + k + msbs;
  94703. }
  94704. else {
  94705. unsigned q, r, d;
  94706. d = (1 << (k+1)) - parameter;
  94707. q = uval / parameter;
  94708. r = uval - (q * parameter);
  94709. bits = 1 + q + k;
  94710. if(r >= d)
  94711. bits++;
  94712. }
  94713. return bits;
  94714. }
  94715. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94716. {
  94717. unsigned bits, msbs;
  94718. unsigned k;
  94719. FLAC__ASSERT(parameter > 0);
  94720. k = FLAC__bitmath_ilog2(parameter);
  94721. if(parameter == 1u<<k) {
  94722. FLAC__ASSERT(k <= 30);
  94723. msbs = uval >> k;
  94724. bits = 1 + k + msbs;
  94725. }
  94726. else {
  94727. unsigned q, r, d;
  94728. d = (1 << (k+1)) - parameter;
  94729. q = uval / parameter;
  94730. r = uval - (q * parameter);
  94731. bits = 1 + q + k;
  94732. if(r >= d)
  94733. bits++;
  94734. }
  94735. return bits;
  94736. }
  94737. #endif /* UNUSED */
  94738. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94739. {
  94740. unsigned total_bits, interesting_bits, msbs;
  94741. FLAC__uint32 uval, pattern;
  94742. FLAC__ASSERT(0 != bw);
  94743. FLAC__ASSERT(0 != bw->buffer);
  94744. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94745. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94746. uval = (val<<1) ^ (val>>31);
  94747. msbs = uval >> parameter;
  94748. interesting_bits = 1 + parameter;
  94749. total_bits = interesting_bits + msbs;
  94750. pattern = 1 << parameter; /* the unary end bit */
  94751. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94752. if(total_bits <= 32)
  94753. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94754. else
  94755. return
  94756. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94757. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94758. }
  94759. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94760. {
  94761. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94762. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94763. FLAC__uint32 uval;
  94764. unsigned left;
  94765. const unsigned lsbits = 1 + parameter;
  94766. unsigned msbits;
  94767. FLAC__ASSERT(0 != bw);
  94768. FLAC__ASSERT(0 != bw->buffer);
  94769. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94770. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94771. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94772. while(nvals) {
  94773. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94774. uval = (*vals<<1) ^ (*vals>>31);
  94775. msbits = uval >> parameter;
  94776. #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) */
  94777. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94778. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94779. bw->bits = bw->bits + msbits + lsbits;
  94780. uval |= mask1; /* set stop bit */
  94781. uval &= mask2; /* mask off unused top bits */
  94782. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94783. bw->accum <<= msbits;
  94784. bw->accum <<= lsbits;
  94785. bw->accum |= uval;
  94786. if(bw->bits == FLAC__BITS_PER_WORD) {
  94787. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94788. bw->bits = 0;
  94789. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94790. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94791. FLAC__ASSERT(bw->capacity == bw->words);
  94792. return false;
  94793. }
  94794. }
  94795. }
  94796. else {
  94797. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94798. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94799. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94800. bw->bits = bw->bits + msbits + lsbits;
  94801. uval |= mask1; /* set stop bit */
  94802. uval &= mask2; /* mask off unused top bits */
  94803. bw->accum <<= msbits + lsbits;
  94804. bw->accum |= uval;
  94805. }
  94806. else {
  94807. #endif
  94808. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94809. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94810. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94811. return false;
  94812. if(msbits) {
  94813. /* first part gets to word alignment */
  94814. if(bw->bits) {
  94815. left = FLAC__BITS_PER_WORD - bw->bits;
  94816. if(msbits < left) {
  94817. bw->accum <<= msbits;
  94818. bw->bits += msbits;
  94819. goto break1;
  94820. }
  94821. else {
  94822. bw->accum <<= left;
  94823. msbits -= left;
  94824. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94825. bw->bits = 0;
  94826. }
  94827. }
  94828. /* do whole words */
  94829. while(msbits >= FLAC__BITS_PER_WORD) {
  94830. bw->buffer[bw->words++] = 0;
  94831. msbits -= FLAC__BITS_PER_WORD;
  94832. }
  94833. /* do any leftovers */
  94834. if(msbits > 0) {
  94835. bw->accum = 0;
  94836. bw->bits = msbits;
  94837. }
  94838. }
  94839. break1:
  94840. uval |= mask1; /* set stop bit */
  94841. uval &= mask2; /* mask off unused top bits */
  94842. left = FLAC__BITS_PER_WORD - bw->bits;
  94843. if(lsbits < left) {
  94844. bw->accum <<= lsbits;
  94845. bw->accum |= uval;
  94846. bw->bits += lsbits;
  94847. }
  94848. else {
  94849. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94850. * be > lsbits (because of previous assertions) so it would have
  94851. * triggered the (lsbits<left) case above.
  94852. */
  94853. FLAC__ASSERT(bw->bits);
  94854. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94855. bw->accum <<= left;
  94856. bw->accum |= uval >> (bw->bits = lsbits - left);
  94857. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94858. bw->accum = uval;
  94859. }
  94860. #if 1
  94861. }
  94862. #endif
  94863. vals++;
  94864. nvals--;
  94865. }
  94866. return true;
  94867. }
  94868. #if 0 /* UNUSED */
  94869. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94870. {
  94871. unsigned total_bits, msbs, uval;
  94872. unsigned k;
  94873. FLAC__ASSERT(0 != bw);
  94874. FLAC__ASSERT(0 != bw->buffer);
  94875. FLAC__ASSERT(parameter > 0);
  94876. /* fold signed to unsigned */
  94877. if(val < 0)
  94878. uval = (unsigned)(((-(++val)) << 1) + 1);
  94879. else
  94880. uval = (unsigned)(val << 1);
  94881. k = FLAC__bitmath_ilog2(parameter);
  94882. if(parameter == 1u<<k) {
  94883. unsigned pattern;
  94884. FLAC__ASSERT(k <= 30);
  94885. msbs = uval >> k;
  94886. total_bits = 1 + k + msbs;
  94887. pattern = 1 << k; /* the unary end bit */
  94888. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94889. if(total_bits <= 32) {
  94890. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94891. return false;
  94892. }
  94893. else {
  94894. /* write the unary MSBs */
  94895. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94896. return false;
  94897. /* write the unary end bit and binary LSBs */
  94898. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94899. return false;
  94900. }
  94901. }
  94902. else {
  94903. unsigned q, r, d;
  94904. d = (1 << (k+1)) - parameter;
  94905. q = uval / parameter;
  94906. r = uval - (q * parameter);
  94907. /* write the unary MSBs */
  94908. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94909. return false;
  94910. /* write the unary end bit */
  94911. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94912. return false;
  94913. /* write the binary LSBs */
  94914. if(r >= d) {
  94915. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94916. return false;
  94917. }
  94918. else {
  94919. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94920. return false;
  94921. }
  94922. }
  94923. return true;
  94924. }
  94925. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94926. {
  94927. unsigned total_bits, msbs;
  94928. unsigned k;
  94929. FLAC__ASSERT(0 != bw);
  94930. FLAC__ASSERT(0 != bw->buffer);
  94931. FLAC__ASSERT(parameter > 0);
  94932. k = FLAC__bitmath_ilog2(parameter);
  94933. if(parameter == 1u<<k) {
  94934. unsigned pattern;
  94935. FLAC__ASSERT(k <= 30);
  94936. msbs = uval >> k;
  94937. total_bits = 1 + k + msbs;
  94938. pattern = 1 << k; /* the unary end bit */
  94939. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94940. if(total_bits <= 32) {
  94941. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94942. return false;
  94943. }
  94944. else {
  94945. /* write the unary MSBs */
  94946. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94947. return false;
  94948. /* write the unary end bit and binary LSBs */
  94949. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94950. return false;
  94951. }
  94952. }
  94953. else {
  94954. unsigned q, r, d;
  94955. d = (1 << (k+1)) - parameter;
  94956. q = uval / parameter;
  94957. r = uval - (q * parameter);
  94958. /* write the unary MSBs */
  94959. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94960. return false;
  94961. /* write the unary end bit */
  94962. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94963. return false;
  94964. /* write the binary LSBs */
  94965. if(r >= d) {
  94966. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94967. return false;
  94968. }
  94969. else {
  94970. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94971. return false;
  94972. }
  94973. }
  94974. return true;
  94975. }
  94976. #endif /* UNUSED */
  94977. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94978. {
  94979. FLAC__bool ok = 1;
  94980. FLAC__ASSERT(0 != bw);
  94981. FLAC__ASSERT(0 != bw->buffer);
  94982. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94983. if(val < 0x80) {
  94984. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94985. }
  94986. else if(val < 0x800) {
  94987. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94988. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94989. }
  94990. else if(val < 0x10000) {
  94991. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94992. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94993. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94994. }
  94995. else if(val < 0x200000) {
  94996. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94997. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94998. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94999. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95000. }
  95001. else if(val < 0x4000000) {
  95002. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95003. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95004. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95005. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95006. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95007. }
  95008. else {
  95009. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95010. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95011. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95012. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95013. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95014. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95015. }
  95016. return ok;
  95017. }
  95018. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95019. {
  95020. FLAC__bool ok = 1;
  95021. FLAC__ASSERT(0 != bw);
  95022. FLAC__ASSERT(0 != bw->buffer);
  95023. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95024. if(val < 0x80) {
  95025. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95026. }
  95027. else if(val < 0x800) {
  95028. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95029. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95030. }
  95031. else if(val < 0x10000) {
  95032. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95033. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95034. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95035. }
  95036. else if(val < 0x200000) {
  95037. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95038. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95039. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95040. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95041. }
  95042. else if(val < 0x4000000) {
  95043. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95044. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95045. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95046. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95047. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95048. }
  95049. else if(val < 0x80000000) {
  95050. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95051. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95052. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95053. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95054. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95055. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95056. }
  95057. else {
  95058. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95059. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95060. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95061. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95062. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95063. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95064. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95065. }
  95066. return ok;
  95067. }
  95068. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95069. {
  95070. /* 0-pad to byte boundary */
  95071. if(bw->bits & 7u)
  95072. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95073. else
  95074. return true;
  95075. }
  95076. #endif
  95077. /*** End of inlined file: bitwriter.c ***/
  95078. /*** Start of inlined file: cpu.c ***/
  95079. /*** Start of inlined file: juce_FlacHeader.h ***/
  95080. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95081. // tasks..
  95082. #define VERSION "1.2.1"
  95083. #define FLAC__NO_DLL 1
  95084. #if JUCE_MSVC
  95085. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95086. #endif
  95087. #if JUCE_MAC
  95088. #define FLAC__SYS_DARWIN 1
  95089. #endif
  95090. /*** End of inlined file: juce_FlacHeader.h ***/
  95091. #if JUCE_USE_FLAC
  95092. #if HAVE_CONFIG_H
  95093. # include <config.h>
  95094. #endif
  95095. #include <stdlib.h>
  95096. #include <stdio.h>
  95097. #if defined FLAC__CPU_IA32
  95098. # include <signal.h>
  95099. #elif defined FLAC__CPU_PPC
  95100. # if !defined FLAC__NO_ASM
  95101. # if defined FLAC__SYS_DARWIN
  95102. # include <sys/sysctl.h>
  95103. # include <mach/mach.h>
  95104. # include <mach/mach_host.h>
  95105. # include <mach/host_info.h>
  95106. # include <mach/machine.h>
  95107. # ifndef CPU_SUBTYPE_POWERPC_970
  95108. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95109. # endif
  95110. # else /* FLAC__SYS_DARWIN */
  95111. # include <signal.h>
  95112. # include <setjmp.h>
  95113. static sigjmp_buf jmpbuf;
  95114. static volatile sig_atomic_t canjump = 0;
  95115. static void sigill_handler (int sig)
  95116. {
  95117. if (!canjump) {
  95118. signal (sig, SIG_DFL);
  95119. raise (sig);
  95120. }
  95121. canjump = 0;
  95122. siglongjmp (jmpbuf, 1);
  95123. }
  95124. # endif /* FLAC__SYS_DARWIN */
  95125. # endif /* FLAC__NO_ASM */
  95126. #endif /* FLAC__CPU_PPC */
  95127. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95128. #include <sys/param.h>
  95129. #include <sys/sysctl.h>
  95130. #include <machine/cpu.h>
  95131. #endif
  95132. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95133. #include <sys/types.h>
  95134. #include <sys/sysctl.h>
  95135. #endif
  95136. #if defined(__APPLE__)
  95137. /* how to get sysctlbyname()? */
  95138. #endif
  95139. /* these are flags in EDX of CPUID AX=00000001 */
  95140. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95141. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95142. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95143. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95144. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95145. /* these are flags in ECX of CPUID AX=00000001 */
  95146. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95147. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95148. /* these are flags in EDX of CPUID AX=80000001 */
  95149. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95150. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95151. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95152. /*
  95153. * Extra stuff needed for detection of OS support for SSE on IA-32
  95154. */
  95155. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95156. # if defined(__linux__)
  95157. /*
  95158. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95159. * modify the return address to jump over the offending SSE instruction
  95160. * and also the operation following it that indicates the instruction
  95161. * executed successfully. In this way we use no global variables and
  95162. * stay thread-safe.
  95163. *
  95164. * 3 + 3 + 6:
  95165. * 3 bytes for "xorps xmm0,xmm0"
  95166. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95167. * 6 bytes extra in case our estimate is wrong
  95168. * 12 bytes puts us in the NOP "landing zone"
  95169. */
  95170. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95171. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95172. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95173. {
  95174. (void)signal;
  95175. sc.eip += 3 + 3 + 6;
  95176. }
  95177. # else
  95178. # include <sys/ucontext.h>
  95179. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95180. {
  95181. (void)signal, (void)si;
  95182. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95183. }
  95184. # endif
  95185. # elif defined(_MSC_VER)
  95186. # include <windows.h>
  95187. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95188. # ifdef USE_TRY_CATCH_FLAVOR
  95189. # else
  95190. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95191. {
  95192. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95193. ep->ContextRecord->Eip += 3 + 3 + 6;
  95194. return EXCEPTION_CONTINUE_EXECUTION;
  95195. }
  95196. return EXCEPTION_CONTINUE_SEARCH;
  95197. }
  95198. # endif
  95199. # endif
  95200. #endif
  95201. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95202. {
  95203. /*
  95204. * IA32-specific
  95205. */
  95206. #ifdef FLAC__CPU_IA32
  95207. info->type = FLAC__CPUINFO_TYPE_IA32;
  95208. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95209. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95210. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95211. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95212. info->data.ia32.cmov = false;
  95213. info->data.ia32.mmx = false;
  95214. info->data.ia32.fxsr = false;
  95215. info->data.ia32.sse = false;
  95216. info->data.ia32.sse2 = false;
  95217. info->data.ia32.sse3 = false;
  95218. info->data.ia32.ssse3 = false;
  95219. info->data.ia32._3dnow = false;
  95220. info->data.ia32.ext3dnow = false;
  95221. info->data.ia32.extmmx = false;
  95222. if(info->data.ia32.cpuid) {
  95223. /* http://www.sandpile.org/ia32/cpuid.htm */
  95224. FLAC__uint32 flags_edx, flags_ecx;
  95225. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95226. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95227. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95228. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95229. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95230. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95231. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95232. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95233. #ifdef FLAC__USE_3DNOW
  95234. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95235. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95236. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95237. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95238. #else
  95239. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95240. #endif
  95241. #ifdef DEBUG
  95242. fprintf(stderr, "CPU info (IA-32):\n");
  95243. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95244. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95245. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95246. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95247. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95248. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95249. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95250. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95251. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95252. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95253. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95254. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95255. #endif
  95256. /*
  95257. * now have to check for OS support of SSE/SSE2
  95258. */
  95259. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95260. #if defined FLAC__NO_SSE_OS
  95261. /* assume user knows better than us; turn it off */
  95262. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95263. #elif defined FLAC__SSE_OS
  95264. /* assume user knows better than us; leave as detected above */
  95265. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95266. int sse = 0;
  95267. size_t len;
  95268. /* at least one of these must work: */
  95269. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95270. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95271. if(!sse)
  95272. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95273. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95274. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95275. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95276. size_t len = sizeof(val);
  95277. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95278. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95279. else { /* double-check SSE2 */
  95280. mib[1] = CPU_SSE2;
  95281. len = sizeof(val);
  95282. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95283. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95284. }
  95285. # else
  95286. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95287. # endif
  95288. #elif defined(__linux__)
  95289. int sse = 0;
  95290. struct sigaction sigill_save;
  95291. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95292. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95293. #else
  95294. struct sigaction sigill_sse;
  95295. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95296. __sigemptyset(&sigill_sse.sa_mask);
  95297. 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 */
  95298. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95299. #endif
  95300. {
  95301. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95302. /* see sigill_handler_sse_os() for an explanation of the following: */
  95303. asm volatile (
  95304. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95305. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95306. "incl %0\n\t" /* SIGILL handler will jump over this */
  95307. /* landing zone */
  95308. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95309. "nop\n\t"
  95310. "nop\n\t"
  95311. "nop\n\t"
  95312. "nop\n\t"
  95313. "nop\n\t"
  95314. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95315. "nop\n\t"
  95316. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95317. : "=r"(sse)
  95318. : "r"(sse)
  95319. );
  95320. sigaction(SIGILL, &sigill_save, NULL);
  95321. }
  95322. if(!sse)
  95323. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95324. #elif defined(_MSC_VER)
  95325. # ifdef USE_TRY_CATCH_FLAVOR
  95326. _try {
  95327. __asm {
  95328. # if _MSC_VER <= 1200
  95329. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95330. _emit 0x0F
  95331. _emit 0x57
  95332. _emit 0xC0
  95333. # else
  95334. xorps xmm0,xmm0
  95335. # endif
  95336. }
  95337. }
  95338. _except(EXCEPTION_EXECUTE_HANDLER) {
  95339. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95340. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95341. }
  95342. # else
  95343. int sse = 0;
  95344. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95345. /* see GCC version above for explanation */
  95346. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95347. /* http://www.codeproject.com/cpp/gccasm.asp */
  95348. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95349. __asm {
  95350. # if _MSC_VER <= 1200
  95351. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95352. _emit 0x0F
  95353. _emit 0x57
  95354. _emit 0xC0
  95355. # else
  95356. xorps xmm0,xmm0
  95357. # endif
  95358. inc sse
  95359. nop
  95360. nop
  95361. nop
  95362. nop
  95363. nop
  95364. nop
  95365. nop
  95366. nop
  95367. nop
  95368. }
  95369. SetUnhandledExceptionFilter(save);
  95370. if(!sse)
  95371. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95372. # endif
  95373. #else
  95374. /* no way to test, disable to be safe */
  95375. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95376. #endif
  95377. #ifdef DEBUG
  95378. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95379. #endif
  95380. }
  95381. }
  95382. #else
  95383. info->use_asm = false;
  95384. #endif
  95385. /*
  95386. * PPC-specific
  95387. */
  95388. #elif defined FLAC__CPU_PPC
  95389. info->type = FLAC__CPUINFO_TYPE_PPC;
  95390. # if !defined FLAC__NO_ASM
  95391. info->use_asm = true;
  95392. # ifdef FLAC__USE_ALTIVEC
  95393. # if defined FLAC__SYS_DARWIN
  95394. {
  95395. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95396. size_t len = sizeof(val);
  95397. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95398. }
  95399. {
  95400. host_basic_info_data_t hostInfo;
  95401. mach_msg_type_number_t infoCount;
  95402. infoCount = HOST_BASIC_INFO_COUNT;
  95403. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95404. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95405. }
  95406. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95407. {
  95408. /* no Darwin, do it the brute-force way */
  95409. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95410. info->data.ppc.altivec = 0;
  95411. info->data.ppc.ppc64 = 0;
  95412. signal (SIGILL, sigill_handler);
  95413. canjump = 0;
  95414. if (!sigsetjmp (jmpbuf, 1)) {
  95415. canjump = 1;
  95416. asm volatile (
  95417. "mtspr 256, %0\n\t"
  95418. "vand %%v0, %%v0, %%v0"
  95419. :
  95420. : "r" (-1)
  95421. );
  95422. info->data.ppc.altivec = 1;
  95423. }
  95424. canjump = 0;
  95425. if (!sigsetjmp (jmpbuf, 1)) {
  95426. int x = 0;
  95427. canjump = 1;
  95428. /* PPC64 hardware implements the cntlzd instruction */
  95429. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95430. info->data.ppc.ppc64 = 1;
  95431. }
  95432. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95433. }
  95434. # endif
  95435. # else /* !FLAC__USE_ALTIVEC */
  95436. info->data.ppc.altivec = 0;
  95437. info->data.ppc.ppc64 = 0;
  95438. # endif
  95439. # else
  95440. info->use_asm = false;
  95441. # endif
  95442. /*
  95443. * unknown CPI
  95444. */
  95445. #else
  95446. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95447. info->use_asm = false;
  95448. #endif
  95449. }
  95450. #endif
  95451. /*** End of inlined file: cpu.c ***/
  95452. /*** Start of inlined file: crc.c ***/
  95453. /*** Start of inlined file: juce_FlacHeader.h ***/
  95454. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95455. // tasks..
  95456. #define VERSION "1.2.1"
  95457. #define FLAC__NO_DLL 1
  95458. #if JUCE_MSVC
  95459. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95460. #endif
  95461. #if JUCE_MAC
  95462. #define FLAC__SYS_DARWIN 1
  95463. #endif
  95464. /*** End of inlined file: juce_FlacHeader.h ***/
  95465. #if JUCE_USE_FLAC
  95466. #if HAVE_CONFIG_H
  95467. # include <config.h>
  95468. #endif
  95469. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95470. FLAC__byte const FLAC__crc8_table[256] = {
  95471. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95472. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95473. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95474. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95475. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95476. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95477. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95478. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95479. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95480. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95481. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95482. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95483. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95484. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95485. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95486. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95487. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95488. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95489. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95490. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95491. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95492. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95493. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95494. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95495. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95496. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95497. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95498. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95499. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95500. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95501. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95502. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95503. };
  95504. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95505. unsigned FLAC__crc16_table[256] = {
  95506. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95507. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95508. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95509. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95510. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95511. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95512. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95513. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95514. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95515. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95516. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95517. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95518. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95519. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95520. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95521. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95522. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95523. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95524. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95525. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95526. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95527. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95528. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95529. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95530. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95531. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95532. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95533. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95534. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95535. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95536. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95537. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95538. };
  95539. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95540. {
  95541. *crc = FLAC__crc8_table[*crc ^ data];
  95542. }
  95543. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95544. {
  95545. while(len--)
  95546. *crc = FLAC__crc8_table[*crc ^ *data++];
  95547. }
  95548. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95549. {
  95550. FLAC__uint8 crc = 0;
  95551. while(len--)
  95552. crc = FLAC__crc8_table[crc ^ *data++];
  95553. return crc;
  95554. }
  95555. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95556. {
  95557. unsigned crc = 0;
  95558. while(len--)
  95559. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95560. return crc;
  95561. }
  95562. #endif
  95563. /*** End of inlined file: crc.c ***/
  95564. /*** Start of inlined file: fixed.c ***/
  95565. /*** Start of inlined file: juce_FlacHeader.h ***/
  95566. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95567. // tasks..
  95568. #define VERSION "1.2.1"
  95569. #define FLAC__NO_DLL 1
  95570. #if JUCE_MSVC
  95571. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95572. #endif
  95573. #if JUCE_MAC
  95574. #define FLAC__SYS_DARWIN 1
  95575. #endif
  95576. /*** End of inlined file: juce_FlacHeader.h ***/
  95577. #if JUCE_USE_FLAC
  95578. #if HAVE_CONFIG_H
  95579. # include <config.h>
  95580. #endif
  95581. #include <math.h>
  95582. #include <string.h>
  95583. /*** Start of inlined file: fixed.h ***/
  95584. #ifndef FLAC__PRIVATE__FIXED_H
  95585. #define FLAC__PRIVATE__FIXED_H
  95586. #ifdef HAVE_CONFIG_H
  95587. #include <config.h>
  95588. #endif
  95589. /*** Start of inlined file: float.h ***/
  95590. #ifndef FLAC__PRIVATE__FLOAT_H
  95591. #define FLAC__PRIVATE__FLOAT_H
  95592. #ifdef HAVE_CONFIG_H
  95593. #include <config.h>
  95594. #endif
  95595. /*
  95596. * These typedefs make it easier to ensure that integer versions of
  95597. * the library really only contain integer operations. All the code
  95598. * in libFLAC should use FLAC__float and FLAC__double in place of
  95599. * float and double, and be protected by checks of the macro
  95600. * FLAC__INTEGER_ONLY_LIBRARY.
  95601. *
  95602. * FLAC__real is the basic floating point type used in LPC analysis.
  95603. */
  95604. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95605. typedef double FLAC__double;
  95606. typedef float FLAC__float;
  95607. /*
  95608. * WATCHOUT: changing FLAC__real will change the signatures of many
  95609. * functions that have assembly language equivalents and break them.
  95610. */
  95611. typedef float FLAC__real;
  95612. #else
  95613. /*
  95614. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95615. * for the integer part and lower 16 bits for the fractional part.
  95616. */
  95617. typedef FLAC__int32 FLAC__fixedpoint;
  95618. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95619. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95620. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95621. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95622. extern const FLAC__fixedpoint FLAC__FP_E;
  95623. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95624. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95625. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95626. /*
  95627. * FLAC__fixedpoint_log2()
  95628. * --------------------------------------------------------------------
  95629. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95630. * algorithm by Knuth for x >= 1.0
  95631. *
  95632. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95633. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95634. *
  95635. * 'precision' roughly limits the number of iterations that are done;
  95636. * use (unsigned)(-1) for maximum precision.
  95637. *
  95638. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95639. * function will punt and return 0.
  95640. *
  95641. * The return value will also have 'fracbits' fractional bits.
  95642. */
  95643. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95644. #endif
  95645. #endif
  95646. /*** End of inlined file: float.h ***/
  95647. /*** Start of inlined file: format.h ***/
  95648. #ifndef FLAC__PRIVATE__FORMAT_H
  95649. #define FLAC__PRIVATE__FORMAT_H
  95650. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95651. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95652. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95653. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95654. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95655. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95656. #endif
  95657. /*** End of inlined file: format.h ***/
  95658. /*
  95659. * FLAC__fixed_compute_best_predictor()
  95660. * --------------------------------------------------------------------
  95661. * Compute the best fixed predictor and the expected bits-per-sample
  95662. * of the residual signal for each order. The _wide() version uses
  95663. * 64-bit integers which is statistically necessary when bits-per-
  95664. * sample + log2(blocksize) > 30
  95665. *
  95666. * IN data[0,data_len-1]
  95667. * IN data_len
  95668. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95669. */
  95670. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95671. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95672. # ifndef FLAC__NO_ASM
  95673. # ifdef FLAC__CPU_IA32
  95674. # ifdef FLAC__HAS_NASM
  95675. 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]);
  95676. # endif
  95677. # endif
  95678. # endif
  95679. 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]);
  95680. #else
  95681. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95682. 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]);
  95683. #endif
  95684. /*
  95685. * FLAC__fixed_compute_residual()
  95686. * --------------------------------------------------------------------
  95687. * Compute the residual signal obtained from sutracting the predicted
  95688. * signal from the original.
  95689. *
  95690. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95691. * IN data_len length of original signal
  95692. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95693. * OUT residual[0,data_len-1] residual signal
  95694. */
  95695. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95696. /*
  95697. * FLAC__fixed_restore_signal()
  95698. * --------------------------------------------------------------------
  95699. * Restore the original signal by summing the residual and the
  95700. * predictor.
  95701. *
  95702. * IN residual[0,data_len-1] residual signal
  95703. * IN data_len length of original signal
  95704. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95705. * *** IMPORTANT: the caller must pass in the historical samples:
  95706. * IN data[-order,-1] previously-reconstructed historical samples
  95707. * OUT data[0,data_len-1] original signal
  95708. */
  95709. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95710. #endif
  95711. /*** End of inlined file: fixed.h ***/
  95712. #ifndef M_LN2
  95713. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95714. #define M_LN2 0.69314718055994530942
  95715. #endif
  95716. #ifdef min
  95717. #undef min
  95718. #endif
  95719. #define min(x,y) ((x) < (y)? (x) : (y))
  95720. #ifdef local_abs
  95721. #undef local_abs
  95722. #endif
  95723. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95724. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95725. /* rbps stands for residual bits per sample
  95726. *
  95727. * (ln(2) * err)
  95728. * rbps = log (-----------)
  95729. * 2 ( n )
  95730. */
  95731. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95732. {
  95733. FLAC__uint32 rbps;
  95734. unsigned bits; /* the number of bits required to represent a number */
  95735. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95736. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95737. FLAC__ASSERT(err > 0);
  95738. FLAC__ASSERT(n > 0);
  95739. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95740. if(err <= n)
  95741. return 0;
  95742. /*
  95743. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95744. * These allow us later to know we won't lose too much precision in the
  95745. * fixed-point division (err<<fracbits)/n.
  95746. */
  95747. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95748. err <<= fracbits;
  95749. err /= n;
  95750. /* err now holds err/n with fracbits fractional bits */
  95751. /*
  95752. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95753. * our purposes.
  95754. */
  95755. FLAC__ASSERT(err > 0);
  95756. bits = FLAC__bitmath_ilog2(err)+1;
  95757. if(bits > 16) {
  95758. err >>= (bits-16);
  95759. fracbits -= (bits-16);
  95760. }
  95761. rbps = (FLAC__uint32)err;
  95762. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95763. rbps *= FLAC__FP_LN2;
  95764. fracbits += 16;
  95765. FLAC__ASSERT(fracbits >= 0);
  95766. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95767. {
  95768. const int f = fracbits & 3;
  95769. if(f) {
  95770. rbps >>= f;
  95771. fracbits -= f;
  95772. }
  95773. }
  95774. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95775. if(rbps == 0)
  95776. return 0;
  95777. /*
  95778. * The return value must have 16 fractional bits. Since the whole part
  95779. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95780. * must be >= -3, these assertion allows us to be able to shift rbps
  95781. * left if necessary to get 16 fracbits without losing any bits of the
  95782. * whole part of rbps.
  95783. *
  95784. * There is a slight chance due to accumulated error that the whole part
  95785. * will require 6 bits, so we use 6 in the assertion. Really though as
  95786. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95787. */
  95788. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95789. FLAC__ASSERT(fracbits >= -3);
  95790. /* now shift the decimal point into place */
  95791. if(fracbits < 16)
  95792. return rbps << (16-fracbits);
  95793. else if(fracbits > 16)
  95794. return rbps >> (fracbits-16);
  95795. else
  95796. return rbps;
  95797. }
  95798. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95799. {
  95800. FLAC__uint32 rbps;
  95801. unsigned bits; /* the number of bits required to represent a number */
  95802. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95803. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95804. FLAC__ASSERT(err > 0);
  95805. FLAC__ASSERT(n > 0);
  95806. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95807. if(err <= n)
  95808. return 0;
  95809. /*
  95810. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95811. * These allow us later to know we won't lose too much precision in the
  95812. * fixed-point division (err<<fracbits)/n.
  95813. */
  95814. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95815. err <<= fracbits;
  95816. err /= n;
  95817. /* err now holds err/n with fracbits fractional bits */
  95818. /*
  95819. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95820. * our purposes.
  95821. */
  95822. FLAC__ASSERT(err > 0);
  95823. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95824. if(bits > 16) {
  95825. err >>= (bits-16);
  95826. fracbits -= (bits-16);
  95827. }
  95828. rbps = (FLAC__uint32)err;
  95829. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95830. rbps *= FLAC__FP_LN2;
  95831. fracbits += 16;
  95832. FLAC__ASSERT(fracbits >= 0);
  95833. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95834. {
  95835. const int f = fracbits & 3;
  95836. if(f) {
  95837. rbps >>= f;
  95838. fracbits -= f;
  95839. }
  95840. }
  95841. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95842. if(rbps == 0)
  95843. return 0;
  95844. /*
  95845. * The return value must have 16 fractional bits. Since the whole part
  95846. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95847. * must be >= -3, these assertion allows us to be able to shift rbps
  95848. * left if necessary to get 16 fracbits without losing any bits of the
  95849. * whole part of rbps.
  95850. *
  95851. * There is a slight chance due to accumulated error that the whole part
  95852. * will require 6 bits, so we use 6 in the assertion. Really though as
  95853. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95854. */
  95855. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95856. FLAC__ASSERT(fracbits >= -3);
  95857. /* now shift the decimal point into place */
  95858. if(fracbits < 16)
  95859. return rbps << (16-fracbits);
  95860. else if(fracbits > 16)
  95861. return rbps >> (fracbits-16);
  95862. else
  95863. return rbps;
  95864. }
  95865. #endif
  95866. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95867. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95868. #else
  95869. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95870. #endif
  95871. {
  95872. FLAC__int32 last_error_0 = data[-1];
  95873. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95874. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95875. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95876. FLAC__int32 error, save;
  95877. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95878. unsigned i, order;
  95879. for(i = 0; i < data_len; i++) {
  95880. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95881. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95882. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95883. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95884. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95885. }
  95886. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95887. order = 0;
  95888. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95889. order = 1;
  95890. else if(total_error_2 < min(total_error_3, total_error_4))
  95891. order = 2;
  95892. else if(total_error_3 < total_error_4)
  95893. order = 3;
  95894. else
  95895. order = 4;
  95896. /* Estimate the expected number of bits per residual signal sample. */
  95897. /* 'total_error*' is linearly related to the variance of the residual */
  95898. /* signal, so we use it directly to compute E(|x|) */
  95899. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95900. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95901. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95902. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95903. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95904. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95905. 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);
  95906. 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);
  95907. 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);
  95908. 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);
  95909. 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);
  95910. #else
  95911. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95912. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95913. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95914. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95915. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95916. #endif
  95917. return order;
  95918. }
  95919. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95920. 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])
  95921. #else
  95922. 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])
  95923. #endif
  95924. {
  95925. FLAC__int32 last_error_0 = data[-1];
  95926. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95927. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95928. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95929. FLAC__int32 error, save;
  95930. /* total_error_* are 64-bits to avoid overflow when encoding
  95931. * erratic signals when the bits-per-sample and blocksize are
  95932. * large.
  95933. */
  95934. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95935. unsigned i, order;
  95936. for(i = 0; i < data_len; i++) {
  95937. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95938. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95939. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95940. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95941. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95942. }
  95943. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95944. order = 0;
  95945. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95946. order = 1;
  95947. else if(total_error_2 < min(total_error_3, total_error_4))
  95948. order = 2;
  95949. else if(total_error_3 < total_error_4)
  95950. order = 3;
  95951. else
  95952. order = 4;
  95953. /* Estimate the expected number of bits per residual signal sample. */
  95954. /* 'total_error*' is linearly related to the variance of the residual */
  95955. /* signal, so we use it directly to compute E(|x|) */
  95956. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95957. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95958. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95959. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95960. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95961. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95962. #if defined _MSC_VER || defined __MINGW32__
  95963. /* with MSVC you have to spoon feed it the casting */
  95964. 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);
  95965. 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);
  95966. 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);
  95967. 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);
  95968. 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);
  95969. #else
  95970. 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);
  95971. 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);
  95972. 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);
  95973. 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);
  95974. 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);
  95975. #endif
  95976. #else
  95977. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95978. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95979. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95980. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95981. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95982. #endif
  95983. return order;
  95984. }
  95985. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95986. {
  95987. const int idata_len = (int)data_len;
  95988. int i;
  95989. switch(order) {
  95990. case 0:
  95991. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95992. memcpy(residual, data, sizeof(residual[0])*data_len);
  95993. break;
  95994. case 1:
  95995. for(i = 0; i < idata_len; i++)
  95996. residual[i] = data[i] - data[i-1];
  95997. break;
  95998. case 2:
  95999. for(i = 0; i < idata_len; i++)
  96000. #if 1 /* OPT: may be faster with some compilers on some systems */
  96001. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96002. #else
  96003. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96004. #endif
  96005. break;
  96006. case 3:
  96007. for(i = 0; i < idata_len; i++)
  96008. #if 1 /* OPT: may be faster with some compilers on some systems */
  96009. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96010. #else
  96011. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96012. #endif
  96013. break;
  96014. case 4:
  96015. for(i = 0; i < idata_len; i++)
  96016. #if 1 /* OPT: may be faster with some compilers on some systems */
  96017. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96018. #else
  96019. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96020. #endif
  96021. break;
  96022. default:
  96023. FLAC__ASSERT(0);
  96024. }
  96025. }
  96026. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96027. {
  96028. int i, idata_len = (int)data_len;
  96029. switch(order) {
  96030. case 0:
  96031. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96032. memcpy(data, residual, sizeof(residual[0])*data_len);
  96033. break;
  96034. case 1:
  96035. for(i = 0; i < idata_len; i++)
  96036. data[i] = residual[i] + data[i-1];
  96037. break;
  96038. case 2:
  96039. for(i = 0; i < idata_len; i++)
  96040. #if 1 /* OPT: may be faster with some compilers on some systems */
  96041. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96042. #else
  96043. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96044. #endif
  96045. break;
  96046. case 3:
  96047. for(i = 0; i < idata_len; i++)
  96048. #if 1 /* OPT: may be faster with some compilers on some systems */
  96049. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96050. #else
  96051. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96052. #endif
  96053. break;
  96054. case 4:
  96055. for(i = 0; i < idata_len; i++)
  96056. #if 1 /* OPT: may be faster with some compilers on some systems */
  96057. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96058. #else
  96059. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96060. #endif
  96061. break;
  96062. default:
  96063. FLAC__ASSERT(0);
  96064. }
  96065. }
  96066. #endif
  96067. /*** End of inlined file: fixed.c ***/
  96068. /*** Start of inlined file: float.c ***/
  96069. /*** Start of inlined file: juce_FlacHeader.h ***/
  96070. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96071. // tasks..
  96072. #define VERSION "1.2.1"
  96073. #define FLAC__NO_DLL 1
  96074. #if JUCE_MSVC
  96075. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96076. #endif
  96077. #if JUCE_MAC
  96078. #define FLAC__SYS_DARWIN 1
  96079. #endif
  96080. /*** End of inlined file: juce_FlacHeader.h ***/
  96081. #if JUCE_USE_FLAC
  96082. #if HAVE_CONFIG_H
  96083. # include <config.h>
  96084. #endif
  96085. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96086. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96087. #ifdef _MSC_VER
  96088. #define FLAC__U64L(x) x
  96089. #else
  96090. #define FLAC__U64L(x) x##LLU
  96091. #endif
  96092. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96093. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96094. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96095. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96096. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96097. /* Lookup tables for Knuth's logarithm algorithm */
  96098. #define LOG2_LOOKUP_PRECISION 16
  96099. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96100. {
  96101. /*
  96102. * 0 fraction bits
  96103. */
  96104. /* undefined */ 0x00000000,
  96105. /* lg(2/1) = */ 0x00000001,
  96106. /* lg(4/3) = */ 0x00000000,
  96107. /* lg(8/7) = */ 0x00000000,
  96108. /* lg(16/15) = */ 0x00000000,
  96109. /* lg(32/31) = */ 0x00000000,
  96110. /* lg(64/63) = */ 0x00000000,
  96111. /* lg(128/127) = */ 0x00000000,
  96112. /* lg(256/255) = */ 0x00000000,
  96113. /* lg(512/511) = */ 0x00000000,
  96114. /* lg(1024/1023) = */ 0x00000000,
  96115. /* lg(2048/2047) = */ 0x00000000,
  96116. /* lg(4096/4095) = */ 0x00000000,
  96117. /* lg(8192/8191) = */ 0x00000000,
  96118. /* lg(16384/16383) = */ 0x00000000,
  96119. /* lg(32768/32767) = */ 0x00000000
  96120. },
  96121. {
  96122. /*
  96123. * 4 fraction bits
  96124. */
  96125. /* undefined */ 0x00000000,
  96126. /* lg(2/1) = */ 0x00000010,
  96127. /* lg(4/3) = */ 0x00000007,
  96128. /* lg(8/7) = */ 0x00000003,
  96129. /* lg(16/15) = */ 0x00000001,
  96130. /* lg(32/31) = */ 0x00000001,
  96131. /* lg(64/63) = */ 0x00000000,
  96132. /* lg(128/127) = */ 0x00000000,
  96133. /* lg(256/255) = */ 0x00000000,
  96134. /* lg(512/511) = */ 0x00000000,
  96135. /* lg(1024/1023) = */ 0x00000000,
  96136. /* lg(2048/2047) = */ 0x00000000,
  96137. /* lg(4096/4095) = */ 0x00000000,
  96138. /* lg(8192/8191) = */ 0x00000000,
  96139. /* lg(16384/16383) = */ 0x00000000,
  96140. /* lg(32768/32767) = */ 0x00000000
  96141. },
  96142. {
  96143. /*
  96144. * 8 fraction bits
  96145. */
  96146. /* undefined */ 0x00000000,
  96147. /* lg(2/1) = */ 0x00000100,
  96148. /* lg(4/3) = */ 0x0000006a,
  96149. /* lg(8/7) = */ 0x00000031,
  96150. /* lg(16/15) = */ 0x00000018,
  96151. /* lg(32/31) = */ 0x0000000c,
  96152. /* lg(64/63) = */ 0x00000006,
  96153. /* lg(128/127) = */ 0x00000003,
  96154. /* lg(256/255) = */ 0x00000001,
  96155. /* lg(512/511) = */ 0x00000001,
  96156. /* lg(1024/1023) = */ 0x00000000,
  96157. /* lg(2048/2047) = */ 0x00000000,
  96158. /* lg(4096/4095) = */ 0x00000000,
  96159. /* lg(8192/8191) = */ 0x00000000,
  96160. /* lg(16384/16383) = */ 0x00000000,
  96161. /* lg(32768/32767) = */ 0x00000000
  96162. },
  96163. {
  96164. /*
  96165. * 12 fraction bits
  96166. */
  96167. /* undefined */ 0x00000000,
  96168. /* lg(2/1) = */ 0x00001000,
  96169. /* lg(4/3) = */ 0x000006a4,
  96170. /* lg(8/7) = */ 0x00000315,
  96171. /* lg(16/15) = */ 0x0000017d,
  96172. /* lg(32/31) = */ 0x000000bc,
  96173. /* lg(64/63) = */ 0x0000005d,
  96174. /* lg(128/127) = */ 0x0000002e,
  96175. /* lg(256/255) = */ 0x00000017,
  96176. /* lg(512/511) = */ 0x0000000c,
  96177. /* lg(1024/1023) = */ 0x00000006,
  96178. /* lg(2048/2047) = */ 0x00000003,
  96179. /* lg(4096/4095) = */ 0x00000001,
  96180. /* lg(8192/8191) = */ 0x00000001,
  96181. /* lg(16384/16383) = */ 0x00000000,
  96182. /* lg(32768/32767) = */ 0x00000000
  96183. },
  96184. {
  96185. /*
  96186. * 16 fraction bits
  96187. */
  96188. /* undefined */ 0x00000000,
  96189. /* lg(2/1) = */ 0x00010000,
  96190. /* lg(4/3) = */ 0x00006a40,
  96191. /* lg(8/7) = */ 0x00003151,
  96192. /* lg(16/15) = */ 0x000017d6,
  96193. /* lg(32/31) = */ 0x00000bba,
  96194. /* lg(64/63) = */ 0x000005d1,
  96195. /* lg(128/127) = */ 0x000002e6,
  96196. /* lg(256/255) = */ 0x00000172,
  96197. /* lg(512/511) = */ 0x000000b9,
  96198. /* lg(1024/1023) = */ 0x0000005c,
  96199. /* lg(2048/2047) = */ 0x0000002e,
  96200. /* lg(4096/4095) = */ 0x00000017,
  96201. /* lg(8192/8191) = */ 0x0000000c,
  96202. /* lg(16384/16383) = */ 0x00000006,
  96203. /* lg(32768/32767) = */ 0x00000003
  96204. },
  96205. {
  96206. /*
  96207. * 20 fraction bits
  96208. */
  96209. /* undefined */ 0x00000000,
  96210. /* lg(2/1) = */ 0x00100000,
  96211. /* lg(4/3) = */ 0x0006a3fe,
  96212. /* lg(8/7) = */ 0x00031513,
  96213. /* lg(16/15) = */ 0x00017d60,
  96214. /* lg(32/31) = */ 0x0000bb9d,
  96215. /* lg(64/63) = */ 0x00005d10,
  96216. /* lg(128/127) = */ 0x00002e59,
  96217. /* lg(256/255) = */ 0x00001721,
  96218. /* lg(512/511) = */ 0x00000b8e,
  96219. /* lg(1024/1023) = */ 0x000005c6,
  96220. /* lg(2048/2047) = */ 0x000002e3,
  96221. /* lg(4096/4095) = */ 0x00000171,
  96222. /* lg(8192/8191) = */ 0x000000b9,
  96223. /* lg(16384/16383) = */ 0x0000005c,
  96224. /* lg(32768/32767) = */ 0x0000002e
  96225. },
  96226. {
  96227. /*
  96228. * 24 fraction bits
  96229. */
  96230. /* undefined */ 0x00000000,
  96231. /* lg(2/1) = */ 0x01000000,
  96232. /* lg(4/3) = */ 0x006a3fe6,
  96233. /* lg(8/7) = */ 0x00315130,
  96234. /* lg(16/15) = */ 0x0017d605,
  96235. /* lg(32/31) = */ 0x000bb9ca,
  96236. /* lg(64/63) = */ 0x0005d0fc,
  96237. /* lg(128/127) = */ 0x0002e58f,
  96238. /* lg(256/255) = */ 0x0001720e,
  96239. /* lg(512/511) = */ 0x0000b8d8,
  96240. /* lg(1024/1023) = */ 0x00005c61,
  96241. /* lg(2048/2047) = */ 0x00002e2d,
  96242. /* lg(4096/4095) = */ 0x00001716,
  96243. /* lg(8192/8191) = */ 0x00000b8b,
  96244. /* lg(16384/16383) = */ 0x000005c5,
  96245. /* lg(32768/32767) = */ 0x000002e3
  96246. },
  96247. {
  96248. /*
  96249. * 28 fraction bits
  96250. */
  96251. /* undefined */ 0x00000000,
  96252. /* lg(2/1) = */ 0x10000000,
  96253. /* lg(4/3) = */ 0x06a3fe5c,
  96254. /* lg(8/7) = */ 0x03151301,
  96255. /* lg(16/15) = */ 0x017d6049,
  96256. /* lg(32/31) = */ 0x00bb9ca6,
  96257. /* lg(64/63) = */ 0x005d0fba,
  96258. /* lg(128/127) = */ 0x002e58f7,
  96259. /* lg(256/255) = */ 0x001720da,
  96260. /* lg(512/511) = */ 0x000b8d87,
  96261. /* lg(1024/1023) = */ 0x0005c60b,
  96262. /* lg(2048/2047) = */ 0x0002e2d7,
  96263. /* lg(4096/4095) = */ 0x00017160,
  96264. /* lg(8192/8191) = */ 0x0000b8ad,
  96265. /* lg(16384/16383) = */ 0x00005c56,
  96266. /* lg(32768/32767) = */ 0x00002e2b
  96267. }
  96268. };
  96269. #if 0
  96270. static const FLAC__uint64 log2_lookup_wide[] = {
  96271. {
  96272. /*
  96273. * 32 fraction bits
  96274. */
  96275. /* undefined */ 0x00000000,
  96276. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96277. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96278. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96279. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96280. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96281. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96282. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96283. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96284. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96285. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96286. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96287. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96288. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96289. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96290. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96291. },
  96292. {
  96293. /*
  96294. * 48 fraction bits
  96295. */
  96296. /* undefined */ 0x00000000,
  96297. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96298. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96299. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96300. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96301. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96302. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96303. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96304. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96305. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96306. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96307. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96308. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96309. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96310. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96311. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96312. }
  96313. };
  96314. #endif
  96315. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96316. {
  96317. const FLAC__uint32 ONE = (1u << fracbits);
  96318. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96319. FLAC__ASSERT(fracbits < 32);
  96320. FLAC__ASSERT((fracbits & 0x3) == 0);
  96321. if(x < ONE)
  96322. return 0;
  96323. if(precision > LOG2_LOOKUP_PRECISION)
  96324. precision = LOG2_LOOKUP_PRECISION;
  96325. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96326. {
  96327. FLAC__uint32 y = 0;
  96328. FLAC__uint32 z = x >> 1, k = 1;
  96329. while (x > ONE && k < precision) {
  96330. if (x - z >= ONE) {
  96331. x -= z;
  96332. z = x >> k;
  96333. y += table[k];
  96334. }
  96335. else {
  96336. z >>= 1;
  96337. k++;
  96338. }
  96339. }
  96340. return y;
  96341. }
  96342. }
  96343. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96344. #endif
  96345. /*** End of inlined file: float.c ***/
  96346. /*** Start of inlined file: format.c ***/
  96347. /*** Start of inlined file: juce_FlacHeader.h ***/
  96348. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96349. // tasks..
  96350. #define VERSION "1.2.1"
  96351. #define FLAC__NO_DLL 1
  96352. #if JUCE_MSVC
  96353. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96354. #endif
  96355. #if JUCE_MAC
  96356. #define FLAC__SYS_DARWIN 1
  96357. #endif
  96358. /*** End of inlined file: juce_FlacHeader.h ***/
  96359. #if JUCE_USE_FLAC
  96360. #if HAVE_CONFIG_H
  96361. # include <config.h>
  96362. #endif
  96363. #include <stdio.h>
  96364. #include <stdlib.h> /* for qsort() */
  96365. #include <string.h> /* for memset() */
  96366. #ifndef FLaC__INLINE
  96367. #define FLaC__INLINE
  96368. #endif
  96369. #ifdef min
  96370. #undef min
  96371. #endif
  96372. #define min(a,b) ((a)<(b)?(a):(b))
  96373. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96374. #ifdef _MSC_VER
  96375. #define FLAC__U64L(x) x
  96376. #else
  96377. #define FLAC__U64L(x) x##LLU
  96378. #endif
  96379. /* VERSION should come from configure */
  96380. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96381. ;
  96382. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96383. /* yet one more hack because of MSVC6: */
  96384. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96385. #else
  96386. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96387. #endif
  96388. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96389. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96390. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96391. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96392. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96393. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96394. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96395. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96396. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96397. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96398. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96399. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96400. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96401. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96402. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96403. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96404. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96405. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96406. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96407. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96408. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96409. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96410. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96411. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96412. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96413. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96414. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96415. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96416. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96417. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96418. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96419. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96420. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96421. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96422. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96423. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96424. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96425. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96426. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96427. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96428. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96429. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96430. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96431. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96432. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96433. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96434. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96435. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96436. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96437. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96438. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96439. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96440. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96441. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96442. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96443. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96444. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96445. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96446. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96447. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96448. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96449. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96450. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96451. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96452. "PARTITIONED_RICE",
  96453. "PARTITIONED_RICE2"
  96454. };
  96455. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96456. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96457. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96458. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96459. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96460. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96461. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96462. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96463. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96464. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96465. "CONSTANT",
  96466. "VERBATIM",
  96467. "FIXED",
  96468. "LPC"
  96469. };
  96470. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96471. "INDEPENDENT",
  96472. "LEFT_SIDE",
  96473. "RIGHT_SIDE",
  96474. "MID_SIDE"
  96475. };
  96476. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96477. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96478. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96479. };
  96480. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96481. "STREAMINFO",
  96482. "PADDING",
  96483. "APPLICATION",
  96484. "SEEKTABLE",
  96485. "VORBIS_COMMENT",
  96486. "CUESHEET",
  96487. "PICTURE"
  96488. };
  96489. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96490. "Other",
  96491. "32x32 pixels 'file icon' (PNG only)",
  96492. "Other file icon",
  96493. "Cover (front)",
  96494. "Cover (back)",
  96495. "Leaflet page",
  96496. "Media (e.g. label side of CD)",
  96497. "Lead artist/lead performer/soloist",
  96498. "Artist/performer",
  96499. "Conductor",
  96500. "Band/Orchestra",
  96501. "Composer",
  96502. "Lyricist/text writer",
  96503. "Recording Location",
  96504. "During recording",
  96505. "During performance",
  96506. "Movie/video screen capture",
  96507. "A bright coloured fish",
  96508. "Illustration",
  96509. "Band/artist logotype",
  96510. "Publisher/Studio logotype"
  96511. };
  96512. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96513. {
  96514. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96515. return false;
  96516. }
  96517. else
  96518. return true;
  96519. }
  96520. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96521. {
  96522. if(
  96523. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96524. (
  96525. sample_rate >= (1u << 16) &&
  96526. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96527. )
  96528. ) {
  96529. return false;
  96530. }
  96531. else
  96532. return true;
  96533. }
  96534. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96535. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96536. {
  96537. unsigned i;
  96538. FLAC__uint64 prev_sample_number = 0;
  96539. FLAC__bool got_prev = false;
  96540. FLAC__ASSERT(0 != seek_table);
  96541. for(i = 0; i < seek_table->num_points; i++) {
  96542. if(got_prev) {
  96543. if(
  96544. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96545. seek_table->points[i].sample_number <= prev_sample_number
  96546. )
  96547. return false;
  96548. }
  96549. prev_sample_number = seek_table->points[i].sample_number;
  96550. got_prev = true;
  96551. }
  96552. return true;
  96553. }
  96554. /* used as the sort predicate for qsort() */
  96555. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96556. {
  96557. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96558. if(l->sample_number == r->sample_number)
  96559. return 0;
  96560. else if(l->sample_number < r->sample_number)
  96561. return -1;
  96562. else
  96563. return 1;
  96564. }
  96565. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96566. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96567. {
  96568. unsigned i, j;
  96569. FLAC__bool first;
  96570. FLAC__ASSERT(0 != seek_table);
  96571. /* sort the seekpoints */
  96572. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96573. /* uniquify the seekpoints */
  96574. first = true;
  96575. for(i = j = 0; i < seek_table->num_points; i++) {
  96576. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96577. if(!first) {
  96578. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96579. continue;
  96580. }
  96581. }
  96582. first = false;
  96583. seek_table->points[j++] = seek_table->points[i];
  96584. }
  96585. for(i = j; i < seek_table->num_points; i++) {
  96586. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96587. seek_table->points[i].stream_offset = 0;
  96588. seek_table->points[i].frame_samples = 0;
  96589. }
  96590. return j;
  96591. }
  96592. /*
  96593. * also disallows non-shortest-form encodings, c.f.
  96594. * http://www.unicode.org/versions/corrigendum1.html
  96595. * and a more clear explanation at the end of this section:
  96596. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96597. */
  96598. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96599. {
  96600. FLAC__ASSERT(0 != utf8);
  96601. if ((utf8[0] & 0x80) == 0) {
  96602. return 1;
  96603. }
  96604. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96605. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96606. return 0;
  96607. return 2;
  96608. }
  96609. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96610. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96611. return 0;
  96612. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96613. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96614. return 0;
  96615. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96616. return 0;
  96617. return 3;
  96618. }
  96619. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96620. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96621. return 0;
  96622. return 4;
  96623. }
  96624. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96625. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96626. return 0;
  96627. return 5;
  96628. }
  96629. 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) {
  96630. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96631. return 0;
  96632. return 6;
  96633. }
  96634. else {
  96635. return 0;
  96636. }
  96637. }
  96638. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96639. {
  96640. char c;
  96641. for(c = *name; c; c = *(++name))
  96642. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96643. return false;
  96644. return true;
  96645. }
  96646. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96647. {
  96648. if(length == (unsigned)(-1)) {
  96649. while(*value) {
  96650. unsigned n = utf8len_(value);
  96651. if(n == 0)
  96652. return false;
  96653. value += n;
  96654. }
  96655. }
  96656. else {
  96657. const FLAC__byte *end = value + length;
  96658. while(value < end) {
  96659. unsigned n = utf8len_(value);
  96660. if(n == 0)
  96661. return false;
  96662. value += n;
  96663. }
  96664. if(value != end)
  96665. return false;
  96666. }
  96667. return true;
  96668. }
  96669. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96670. {
  96671. const FLAC__byte *s, *end;
  96672. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96673. if(*s < 0x20 || *s > 0x7D)
  96674. return false;
  96675. }
  96676. if(s == end)
  96677. return false;
  96678. s++; /* skip '=' */
  96679. while(s < end) {
  96680. unsigned n = utf8len_(s);
  96681. if(n == 0)
  96682. return false;
  96683. s += n;
  96684. }
  96685. if(s != end)
  96686. return false;
  96687. return true;
  96688. }
  96689. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96690. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96691. {
  96692. unsigned i, j;
  96693. if(check_cd_da_subset) {
  96694. if(cue_sheet->lead_in < 2 * 44100) {
  96695. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96696. return false;
  96697. }
  96698. if(cue_sheet->lead_in % 588 != 0) {
  96699. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96700. return false;
  96701. }
  96702. }
  96703. if(cue_sheet->num_tracks == 0) {
  96704. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96705. return false;
  96706. }
  96707. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96708. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96709. return false;
  96710. }
  96711. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96712. if(cue_sheet->tracks[i].number == 0) {
  96713. if(violation) *violation = "cue sheet may not have a track number 0";
  96714. return false;
  96715. }
  96716. if(check_cd_da_subset) {
  96717. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96718. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96719. return false;
  96720. }
  96721. }
  96722. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96723. if(violation) {
  96724. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96725. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96726. else
  96727. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96728. }
  96729. return false;
  96730. }
  96731. if(i < cue_sheet->num_tracks - 1) {
  96732. if(cue_sheet->tracks[i].num_indices == 0) {
  96733. if(violation) *violation = "cue sheet track must have at least one index point";
  96734. return false;
  96735. }
  96736. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96737. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96738. return false;
  96739. }
  96740. }
  96741. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96742. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96743. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96744. return false;
  96745. }
  96746. if(j > 0) {
  96747. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96748. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96749. return false;
  96750. }
  96751. }
  96752. }
  96753. }
  96754. return true;
  96755. }
  96756. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96757. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96758. {
  96759. char *p;
  96760. FLAC__byte *b;
  96761. for(p = picture->mime_type; *p; p++) {
  96762. if(*p < 0x20 || *p > 0x7e) {
  96763. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96764. return false;
  96765. }
  96766. }
  96767. for(b = picture->description; *b; ) {
  96768. unsigned n = utf8len_(b);
  96769. if(n == 0) {
  96770. if(violation) *violation = "description string must be valid UTF-8";
  96771. return false;
  96772. }
  96773. b += n;
  96774. }
  96775. return true;
  96776. }
  96777. /*
  96778. * These routines are private to libFLAC
  96779. */
  96780. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96781. {
  96782. return
  96783. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96784. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96785. blocksize,
  96786. predictor_order
  96787. );
  96788. }
  96789. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96790. {
  96791. unsigned max_rice_partition_order = 0;
  96792. while(!(blocksize & 1)) {
  96793. max_rice_partition_order++;
  96794. blocksize >>= 1;
  96795. }
  96796. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96797. }
  96798. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96799. {
  96800. unsigned max_rice_partition_order = limit;
  96801. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96802. max_rice_partition_order--;
  96803. FLAC__ASSERT(
  96804. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96805. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96806. );
  96807. return max_rice_partition_order;
  96808. }
  96809. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96810. {
  96811. FLAC__ASSERT(0 != object);
  96812. object->parameters = 0;
  96813. object->raw_bits = 0;
  96814. object->capacity_by_order = 0;
  96815. }
  96816. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96817. {
  96818. FLAC__ASSERT(0 != object);
  96819. if(0 != object->parameters)
  96820. free(object->parameters);
  96821. if(0 != object->raw_bits)
  96822. free(object->raw_bits);
  96823. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96824. }
  96825. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96826. {
  96827. FLAC__ASSERT(0 != object);
  96828. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96829. if(object->capacity_by_order < max_partition_order) {
  96830. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96831. return false;
  96832. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96833. return false;
  96834. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96835. object->capacity_by_order = max_partition_order;
  96836. }
  96837. return true;
  96838. }
  96839. #endif
  96840. /*** End of inlined file: format.c ***/
  96841. /*** Start of inlined file: lpc_flac.c ***/
  96842. /*** Start of inlined file: juce_FlacHeader.h ***/
  96843. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96844. // tasks..
  96845. #define VERSION "1.2.1"
  96846. #define FLAC__NO_DLL 1
  96847. #if JUCE_MSVC
  96848. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96849. #endif
  96850. #if JUCE_MAC
  96851. #define FLAC__SYS_DARWIN 1
  96852. #endif
  96853. /*** End of inlined file: juce_FlacHeader.h ***/
  96854. #if JUCE_USE_FLAC
  96855. #if HAVE_CONFIG_H
  96856. # include <config.h>
  96857. #endif
  96858. #include <math.h>
  96859. /*** Start of inlined file: lpc.h ***/
  96860. #ifndef FLAC__PRIVATE__LPC_H
  96861. #define FLAC__PRIVATE__LPC_H
  96862. #ifdef HAVE_CONFIG_H
  96863. #include <config.h>
  96864. #endif
  96865. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96866. /*
  96867. * FLAC__lpc_window_data()
  96868. * --------------------------------------------------------------------
  96869. * Applies the given window to the data.
  96870. * OPT: asm implementation
  96871. *
  96872. * IN in[0,data_len-1]
  96873. * IN window[0,data_len-1]
  96874. * OUT out[0,lag-1]
  96875. * IN data_len
  96876. */
  96877. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96878. /*
  96879. * FLAC__lpc_compute_autocorrelation()
  96880. * --------------------------------------------------------------------
  96881. * Compute the autocorrelation for lags between 0 and lag-1.
  96882. * Assumes data[] outside of [0,data_len-1] == 0.
  96883. * Asserts that lag > 0.
  96884. *
  96885. * IN data[0,data_len-1]
  96886. * IN data_len
  96887. * IN 0 < lag <= data_len
  96888. * OUT autoc[0,lag-1]
  96889. */
  96890. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96891. #ifndef FLAC__NO_ASM
  96892. # ifdef FLAC__CPU_IA32
  96893. # ifdef FLAC__HAS_NASM
  96894. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96895. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96896. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96897. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96898. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96899. # endif
  96900. # endif
  96901. #endif
  96902. /*
  96903. * FLAC__lpc_compute_lp_coefficients()
  96904. * --------------------------------------------------------------------
  96905. * Computes LP coefficients for orders 1..max_order.
  96906. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96907. * and there is no point in calculating a predictor.
  96908. *
  96909. * IN autoc[0,max_order] autocorrelation values
  96910. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96911. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96912. * *** IMPORTANT:
  96913. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96914. * OUT error[0,max_order-1] error for each order (more
  96915. * specifically, the variance of
  96916. * the error signal times # of
  96917. * samples in the signal)
  96918. *
  96919. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96920. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96921. * in lp_coeff[7][0,7], etc.
  96922. */
  96923. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96924. /*
  96925. * FLAC__lpc_quantize_coefficients()
  96926. * --------------------------------------------------------------------
  96927. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96928. * must be less than 32 (sizeof(FLAC__int32)*8).
  96929. *
  96930. * IN lp_coeff[0,order-1] LP coefficients
  96931. * IN order LP order
  96932. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96933. * desired precision (in bits, including sign
  96934. * bit) of largest coefficient
  96935. * OUT qlp_coeff[0,order-1] quantized coefficients
  96936. * OUT shift # of bits to shift right to get approximated
  96937. * LP coefficients. NOTE: could be negative.
  96938. * RETURN 0 => quantization OK
  96939. * 1 => coefficients require too much shifting for *shift to
  96940. * fit in the LPC subframe header. 'shift' is unset.
  96941. * 2 => coefficients are all zero, which is bad. 'shift' is
  96942. * unset.
  96943. */
  96944. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96945. /*
  96946. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96947. * --------------------------------------------------------------------
  96948. * Compute the residual signal obtained from sutracting the predicted
  96949. * signal from the original.
  96950. *
  96951. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96952. * IN data_len length of original signal
  96953. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96954. * IN order > 0 LP order
  96955. * IN lp_quantization quantization of LP coefficients in bits
  96956. * OUT residual[0,data_len-1] residual signal
  96957. */
  96958. 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[]);
  96959. 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[]);
  96960. #ifndef FLAC__NO_ASM
  96961. # ifdef FLAC__CPU_IA32
  96962. # ifdef FLAC__HAS_NASM
  96963. 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[]);
  96964. 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[]);
  96965. # endif
  96966. # endif
  96967. #endif
  96968. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96969. /*
  96970. * FLAC__lpc_restore_signal()
  96971. * --------------------------------------------------------------------
  96972. * Restore the original signal by summing the residual and the
  96973. * predictor.
  96974. *
  96975. * IN residual[0,data_len-1] residual signal
  96976. * IN data_len length of original signal
  96977. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96978. * IN order > 0 LP order
  96979. * IN lp_quantization quantization of LP coefficients in bits
  96980. * *** IMPORTANT: the caller must pass in the historical samples:
  96981. * IN data[-order,-1] previously-reconstructed historical samples
  96982. * OUT data[0,data_len-1] original signal
  96983. */
  96984. 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[]);
  96985. 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[]);
  96986. #ifndef FLAC__NO_ASM
  96987. # ifdef FLAC__CPU_IA32
  96988. # ifdef FLAC__HAS_NASM
  96989. 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[]);
  96990. 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[]);
  96991. # endif /* FLAC__HAS_NASM */
  96992. # elif defined FLAC__CPU_PPC
  96993. 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[]);
  96994. 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[]);
  96995. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96996. #endif /* FLAC__NO_ASM */
  96997. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96998. /*
  96999. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97000. * --------------------------------------------------------------------
  97001. * Compute the expected number of bits per residual signal sample
  97002. * based on the LP error (which is related to the residual variance).
  97003. *
  97004. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97005. * IN total_samples > 0 # of samples in residual signal
  97006. * RETURN expected bits per sample
  97007. */
  97008. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97009. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97010. /*
  97011. * FLAC__lpc_compute_best_order()
  97012. * --------------------------------------------------------------------
  97013. * Compute the best order from the array of signal errors returned
  97014. * during coefficient computation.
  97015. *
  97016. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97017. * IN max_order > 0 max LP order
  97018. * IN total_samples > 0 # of samples in residual signal
  97019. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97020. * (includes warmup sample size and quantized LP coefficient)
  97021. * RETURN [1,max_order] best order
  97022. */
  97023. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97024. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97025. #endif
  97026. /*** End of inlined file: lpc.h ***/
  97027. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97028. #include <stdio.h>
  97029. #endif
  97030. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97031. #ifndef M_LN2
  97032. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97033. #define M_LN2 0.69314718055994530942
  97034. #endif
  97035. /* OPT: #undef'ing this may improve the speed on some architectures */
  97036. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97037. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97038. {
  97039. unsigned i;
  97040. for(i = 0; i < data_len; i++)
  97041. out[i] = in[i] * window[i];
  97042. }
  97043. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97044. {
  97045. /* a readable, but slower, version */
  97046. #if 0
  97047. FLAC__real d;
  97048. unsigned i;
  97049. FLAC__ASSERT(lag > 0);
  97050. FLAC__ASSERT(lag <= data_len);
  97051. /*
  97052. * Technically we should subtract the mean first like so:
  97053. * for(i = 0; i < data_len; i++)
  97054. * data[i] -= mean;
  97055. * but it appears not to make enough of a difference to matter, and
  97056. * most signals are already closely centered around zero
  97057. */
  97058. while(lag--) {
  97059. for(i = lag, d = 0.0; i < data_len; i++)
  97060. d += data[i] * data[i - lag];
  97061. autoc[lag] = d;
  97062. }
  97063. #endif
  97064. /*
  97065. * this version tends to run faster because of better data locality
  97066. * ('data_len' is usually much larger than 'lag')
  97067. */
  97068. FLAC__real d;
  97069. unsigned sample, coeff;
  97070. const unsigned limit = data_len - lag;
  97071. FLAC__ASSERT(lag > 0);
  97072. FLAC__ASSERT(lag <= data_len);
  97073. for(coeff = 0; coeff < lag; coeff++)
  97074. autoc[coeff] = 0.0;
  97075. for(sample = 0; sample <= limit; sample++) {
  97076. d = data[sample];
  97077. for(coeff = 0; coeff < lag; coeff++)
  97078. autoc[coeff] += d * data[sample+coeff];
  97079. }
  97080. for(; sample < data_len; sample++) {
  97081. d = data[sample];
  97082. for(coeff = 0; coeff < data_len - sample; coeff++)
  97083. autoc[coeff] += d * data[sample+coeff];
  97084. }
  97085. }
  97086. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97087. {
  97088. unsigned i, j;
  97089. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97090. FLAC__ASSERT(0 != max_order);
  97091. FLAC__ASSERT(0 < *max_order);
  97092. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97093. FLAC__ASSERT(autoc[0] != 0.0);
  97094. err = autoc[0];
  97095. for(i = 0; i < *max_order; i++) {
  97096. /* Sum up this iteration's reflection coefficient. */
  97097. r = -autoc[i+1];
  97098. for(j = 0; j < i; j++)
  97099. r -= lpc[j] * autoc[i-j];
  97100. ref[i] = (r/=err);
  97101. /* Update LPC coefficients and total error. */
  97102. lpc[i]=r;
  97103. for(j = 0; j < (i>>1); j++) {
  97104. FLAC__double tmp = lpc[j];
  97105. lpc[j] += r * lpc[i-1-j];
  97106. lpc[i-1-j] += r * tmp;
  97107. }
  97108. if(i & 1)
  97109. lpc[j] += lpc[j] * r;
  97110. err *= (1.0 - r * r);
  97111. /* save this order */
  97112. for(j = 0; j <= i; j++)
  97113. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97114. error[i] = err;
  97115. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97116. if(err == 0.0) {
  97117. *max_order = i+1;
  97118. return;
  97119. }
  97120. }
  97121. }
  97122. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97123. {
  97124. unsigned i;
  97125. FLAC__double cmax;
  97126. FLAC__int32 qmax, qmin;
  97127. FLAC__ASSERT(precision > 0);
  97128. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97129. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97130. precision--;
  97131. qmax = 1 << precision;
  97132. qmin = -qmax;
  97133. qmax--;
  97134. /* calc cmax = max( |lp_coeff[i]| ) */
  97135. cmax = 0.0;
  97136. for(i = 0; i < order; i++) {
  97137. const FLAC__double d = fabs(lp_coeff[i]);
  97138. if(d > cmax)
  97139. cmax = d;
  97140. }
  97141. if(cmax <= 0.0) {
  97142. /* => coefficients are all 0, which means our constant-detect didn't work */
  97143. return 2;
  97144. }
  97145. else {
  97146. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97147. const int min_shiftlimit = -max_shiftlimit - 1;
  97148. int log2cmax;
  97149. (void)frexp(cmax, &log2cmax);
  97150. log2cmax--;
  97151. *shift = (int)precision - log2cmax - 1;
  97152. if(*shift > max_shiftlimit)
  97153. *shift = max_shiftlimit;
  97154. else if(*shift < min_shiftlimit)
  97155. return 1;
  97156. }
  97157. if(*shift >= 0) {
  97158. FLAC__double error = 0.0;
  97159. FLAC__int32 q;
  97160. for(i = 0; i < order; i++) {
  97161. error += lp_coeff[i] * (1 << *shift);
  97162. #if 1 /* unfortunately lround() is C99 */
  97163. if(error >= 0.0)
  97164. q = (FLAC__int32)(error + 0.5);
  97165. else
  97166. q = (FLAC__int32)(error - 0.5);
  97167. #else
  97168. q = lround(error);
  97169. #endif
  97170. #ifdef FLAC__OVERFLOW_DETECT
  97171. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97172. 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]);
  97173. else if(q < qmin)
  97174. 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]);
  97175. #endif
  97176. if(q > qmax)
  97177. q = qmax;
  97178. else if(q < qmin)
  97179. q = qmin;
  97180. error -= q;
  97181. qlp_coeff[i] = q;
  97182. }
  97183. }
  97184. /* negative shift is very rare but due to design flaw, negative shift is
  97185. * a NOP in the decoder, so it must be handled specially by scaling down
  97186. * coeffs
  97187. */
  97188. else {
  97189. const int nshift = -(*shift);
  97190. FLAC__double error = 0.0;
  97191. FLAC__int32 q;
  97192. #ifdef DEBUG
  97193. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97194. #endif
  97195. for(i = 0; i < order; i++) {
  97196. error += lp_coeff[i] / (1 << nshift);
  97197. #if 1 /* unfortunately lround() is C99 */
  97198. if(error >= 0.0)
  97199. q = (FLAC__int32)(error + 0.5);
  97200. else
  97201. q = (FLAC__int32)(error - 0.5);
  97202. #else
  97203. q = lround(error);
  97204. #endif
  97205. #ifdef FLAC__OVERFLOW_DETECT
  97206. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97207. 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]);
  97208. else if(q < qmin)
  97209. 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]);
  97210. #endif
  97211. if(q > qmax)
  97212. q = qmax;
  97213. else if(q < qmin)
  97214. q = qmin;
  97215. error -= q;
  97216. qlp_coeff[i] = q;
  97217. }
  97218. *shift = 0;
  97219. }
  97220. return 0;
  97221. }
  97222. 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[])
  97223. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97224. {
  97225. FLAC__int64 sumo;
  97226. unsigned i, j;
  97227. FLAC__int32 sum;
  97228. const FLAC__int32 *history;
  97229. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97230. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97231. for(i=0;i<order;i++)
  97232. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97233. fprintf(stderr,"\n");
  97234. #endif
  97235. FLAC__ASSERT(order > 0);
  97236. for(i = 0; i < data_len; i++) {
  97237. sumo = 0;
  97238. sum = 0;
  97239. history = data;
  97240. for(j = 0; j < order; j++) {
  97241. sum += qlp_coeff[j] * (*(--history));
  97242. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97243. #if defined _MSC_VER
  97244. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97245. 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);
  97246. #else
  97247. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97248. 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);
  97249. #endif
  97250. }
  97251. *(residual++) = *(data++) - (sum >> lp_quantization);
  97252. }
  97253. /* Here's a slower but clearer version:
  97254. for(i = 0; i < data_len; i++) {
  97255. sum = 0;
  97256. for(j = 0; j < order; j++)
  97257. sum += qlp_coeff[j] * data[i-j-1];
  97258. residual[i] = data[i] - (sum >> lp_quantization);
  97259. }
  97260. */
  97261. }
  97262. #else /* fully unrolled version for normal use */
  97263. {
  97264. int i;
  97265. FLAC__int32 sum;
  97266. FLAC__ASSERT(order > 0);
  97267. FLAC__ASSERT(order <= 32);
  97268. /*
  97269. * We do unique versions up to 12th order since that's the subset limit.
  97270. * Also they are roughly ordered to match frequency of occurrence to
  97271. * minimize branching.
  97272. */
  97273. if(order <= 12) {
  97274. if(order > 8) {
  97275. if(order > 10) {
  97276. if(order == 12) {
  97277. for(i = 0; i < (int)data_len; i++) {
  97278. sum = 0;
  97279. sum += qlp_coeff[11] * data[i-12];
  97280. sum += qlp_coeff[10] * data[i-11];
  97281. sum += qlp_coeff[9] * data[i-10];
  97282. sum += qlp_coeff[8] * data[i-9];
  97283. sum += qlp_coeff[7] * data[i-8];
  97284. sum += qlp_coeff[6] * data[i-7];
  97285. sum += qlp_coeff[5] * data[i-6];
  97286. sum += qlp_coeff[4] * data[i-5];
  97287. sum += qlp_coeff[3] * data[i-4];
  97288. sum += qlp_coeff[2] * data[i-3];
  97289. sum += qlp_coeff[1] * data[i-2];
  97290. sum += qlp_coeff[0] * data[i-1];
  97291. residual[i] = data[i] - (sum >> lp_quantization);
  97292. }
  97293. }
  97294. else { /* order == 11 */
  97295. for(i = 0; i < (int)data_len; i++) {
  97296. sum = 0;
  97297. sum += qlp_coeff[10] * data[i-11];
  97298. sum += qlp_coeff[9] * data[i-10];
  97299. sum += qlp_coeff[8] * data[i-9];
  97300. sum += qlp_coeff[7] * data[i-8];
  97301. sum += qlp_coeff[6] * data[i-7];
  97302. sum += qlp_coeff[5] * data[i-6];
  97303. sum += qlp_coeff[4] * data[i-5];
  97304. sum += qlp_coeff[3] * data[i-4];
  97305. sum += qlp_coeff[2] * data[i-3];
  97306. sum += qlp_coeff[1] * data[i-2];
  97307. sum += qlp_coeff[0] * data[i-1];
  97308. residual[i] = data[i] - (sum >> lp_quantization);
  97309. }
  97310. }
  97311. }
  97312. else {
  97313. if(order == 10) {
  97314. for(i = 0; i < (int)data_len; i++) {
  97315. sum = 0;
  97316. sum += qlp_coeff[9] * data[i-10];
  97317. sum += qlp_coeff[8] * data[i-9];
  97318. sum += qlp_coeff[7] * data[i-8];
  97319. sum += qlp_coeff[6] * data[i-7];
  97320. sum += qlp_coeff[5] * data[i-6];
  97321. sum += qlp_coeff[4] * data[i-5];
  97322. sum += qlp_coeff[3] * data[i-4];
  97323. sum += qlp_coeff[2] * data[i-3];
  97324. sum += qlp_coeff[1] * data[i-2];
  97325. sum += qlp_coeff[0] * data[i-1];
  97326. residual[i] = data[i] - (sum >> lp_quantization);
  97327. }
  97328. }
  97329. else { /* order == 9 */
  97330. for(i = 0; i < (int)data_len; i++) {
  97331. sum = 0;
  97332. sum += qlp_coeff[8] * data[i-9];
  97333. sum += qlp_coeff[7] * data[i-8];
  97334. sum += qlp_coeff[6] * data[i-7];
  97335. sum += qlp_coeff[5] * data[i-6];
  97336. sum += qlp_coeff[4] * data[i-5];
  97337. sum += qlp_coeff[3] * data[i-4];
  97338. sum += qlp_coeff[2] * data[i-3];
  97339. sum += qlp_coeff[1] * data[i-2];
  97340. sum += qlp_coeff[0] * data[i-1];
  97341. residual[i] = data[i] - (sum >> lp_quantization);
  97342. }
  97343. }
  97344. }
  97345. }
  97346. else if(order > 4) {
  97347. if(order > 6) {
  97348. if(order == 8) {
  97349. for(i = 0; i < (int)data_len; i++) {
  97350. sum = 0;
  97351. sum += qlp_coeff[7] * data[i-8];
  97352. sum += qlp_coeff[6] * data[i-7];
  97353. sum += qlp_coeff[5] * data[i-6];
  97354. sum += qlp_coeff[4] * data[i-5];
  97355. sum += qlp_coeff[3] * data[i-4];
  97356. sum += qlp_coeff[2] * data[i-3];
  97357. sum += qlp_coeff[1] * data[i-2];
  97358. sum += qlp_coeff[0] * data[i-1];
  97359. residual[i] = data[i] - (sum >> lp_quantization);
  97360. }
  97361. }
  97362. else { /* order == 7 */
  97363. for(i = 0; i < (int)data_len; i++) {
  97364. sum = 0;
  97365. sum += qlp_coeff[6] * data[i-7];
  97366. sum += qlp_coeff[5] * data[i-6];
  97367. sum += qlp_coeff[4] * data[i-5];
  97368. sum += qlp_coeff[3] * data[i-4];
  97369. sum += qlp_coeff[2] * data[i-3];
  97370. sum += qlp_coeff[1] * data[i-2];
  97371. sum += qlp_coeff[0] * data[i-1];
  97372. residual[i] = data[i] - (sum >> lp_quantization);
  97373. }
  97374. }
  97375. }
  97376. else {
  97377. if(order == 6) {
  97378. for(i = 0; i < (int)data_len; i++) {
  97379. sum = 0;
  97380. sum += qlp_coeff[5] * data[i-6];
  97381. sum += qlp_coeff[4] * data[i-5];
  97382. sum += qlp_coeff[3] * data[i-4];
  97383. sum += qlp_coeff[2] * data[i-3];
  97384. sum += qlp_coeff[1] * data[i-2];
  97385. sum += qlp_coeff[0] * data[i-1];
  97386. residual[i] = data[i] - (sum >> lp_quantization);
  97387. }
  97388. }
  97389. else { /* order == 5 */
  97390. for(i = 0; i < (int)data_len; i++) {
  97391. sum = 0;
  97392. sum += qlp_coeff[4] * data[i-5];
  97393. sum += qlp_coeff[3] * data[i-4];
  97394. sum += qlp_coeff[2] * data[i-3];
  97395. sum += qlp_coeff[1] * data[i-2];
  97396. sum += qlp_coeff[0] * data[i-1];
  97397. residual[i] = data[i] - (sum >> lp_quantization);
  97398. }
  97399. }
  97400. }
  97401. }
  97402. else {
  97403. if(order > 2) {
  97404. if(order == 4) {
  97405. for(i = 0; i < (int)data_len; i++) {
  97406. sum = 0;
  97407. sum += qlp_coeff[3] * data[i-4];
  97408. sum += qlp_coeff[2] * data[i-3];
  97409. sum += qlp_coeff[1] * data[i-2];
  97410. sum += qlp_coeff[0] * data[i-1];
  97411. residual[i] = data[i] - (sum >> lp_quantization);
  97412. }
  97413. }
  97414. else { /* order == 3 */
  97415. for(i = 0; i < (int)data_len; i++) {
  97416. sum = 0;
  97417. sum += qlp_coeff[2] * data[i-3];
  97418. sum += qlp_coeff[1] * data[i-2];
  97419. sum += qlp_coeff[0] * data[i-1];
  97420. residual[i] = data[i] - (sum >> lp_quantization);
  97421. }
  97422. }
  97423. }
  97424. else {
  97425. if(order == 2) {
  97426. for(i = 0; i < (int)data_len; i++) {
  97427. sum = 0;
  97428. sum += qlp_coeff[1] * data[i-2];
  97429. sum += qlp_coeff[0] * data[i-1];
  97430. residual[i] = data[i] - (sum >> lp_quantization);
  97431. }
  97432. }
  97433. else { /* order == 1 */
  97434. for(i = 0; i < (int)data_len; i++)
  97435. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97436. }
  97437. }
  97438. }
  97439. }
  97440. else { /* order > 12 */
  97441. for(i = 0; i < (int)data_len; i++) {
  97442. sum = 0;
  97443. switch(order) {
  97444. case 32: sum += qlp_coeff[31] * data[i-32];
  97445. case 31: sum += qlp_coeff[30] * data[i-31];
  97446. case 30: sum += qlp_coeff[29] * data[i-30];
  97447. case 29: sum += qlp_coeff[28] * data[i-29];
  97448. case 28: sum += qlp_coeff[27] * data[i-28];
  97449. case 27: sum += qlp_coeff[26] * data[i-27];
  97450. case 26: sum += qlp_coeff[25] * data[i-26];
  97451. case 25: sum += qlp_coeff[24] * data[i-25];
  97452. case 24: sum += qlp_coeff[23] * data[i-24];
  97453. case 23: sum += qlp_coeff[22] * data[i-23];
  97454. case 22: sum += qlp_coeff[21] * data[i-22];
  97455. case 21: sum += qlp_coeff[20] * data[i-21];
  97456. case 20: sum += qlp_coeff[19] * data[i-20];
  97457. case 19: sum += qlp_coeff[18] * data[i-19];
  97458. case 18: sum += qlp_coeff[17] * data[i-18];
  97459. case 17: sum += qlp_coeff[16] * data[i-17];
  97460. case 16: sum += qlp_coeff[15] * data[i-16];
  97461. case 15: sum += qlp_coeff[14] * data[i-15];
  97462. case 14: sum += qlp_coeff[13] * data[i-14];
  97463. case 13: sum += qlp_coeff[12] * data[i-13];
  97464. sum += qlp_coeff[11] * data[i-12];
  97465. sum += qlp_coeff[10] * data[i-11];
  97466. sum += qlp_coeff[ 9] * data[i-10];
  97467. sum += qlp_coeff[ 8] * data[i- 9];
  97468. sum += qlp_coeff[ 7] * data[i- 8];
  97469. sum += qlp_coeff[ 6] * data[i- 7];
  97470. sum += qlp_coeff[ 5] * data[i- 6];
  97471. sum += qlp_coeff[ 4] * data[i- 5];
  97472. sum += qlp_coeff[ 3] * data[i- 4];
  97473. sum += qlp_coeff[ 2] * data[i- 3];
  97474. sum += qlp_coeff[ 1] * data[i- 2];
  97475. sum += qlp_coeff[ 0] * data[i- 1];
  97476. }
  97477. residual[i] = data[i] - (sum >> lp_quantization);
  97478. }
  97479. }
  97480. }
  97481. #endif
  97482. 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[])
  97483. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97484. {
  97485. unsigned i, j;
  97486. FLAC__int64 sum;
  97487. const FLAC__int32 *history;
  97488. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97489. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97490. for(i=0;i<order;i++)
  97491. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97492. fprintf(stderr,"\n");
  97493. #endif
  97494. FLAC__ASSERT(order > 0);
  97495. for(i = 0; i < data_len; i++) {
  97496. sum = 0;
  97497. history = data;
  97498. for(j = 0; j < order; j++)
  97499. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97500. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97501. #if defined _MSC_VER
  97502. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97503. #else
  97504. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97505. #endif
  97506. break;
  97507. }
  97508. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97509. #if defined _MSC_VER
  97510. 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));
  97511. #else
  97512. 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)));
  97513. #endif
  97514. break;
  97515. }
  97516. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97517. }
  97518. }
  97519. #else /* fully unrolled version for normal use */
  97520. {
  97521. int i;
  97522. FLAC__int64 sum;
  97523. FLAC__ASSERT(order > 0);
  97524. FLAC__ASSERT(order <= 32);
  97525. /*
  97526. * We do unique versions up to 12th order since that's the subset limit.
  97527. * Also they are roughly ordered to match frequency of occurrence to
  97528. * minimize branching.
  97529. */
  97530. if(order <= 12) {
  97531. if(order > 8) {
  97532. if(order > 10) {
  97533. if(order == 12) {
  97534. for(i = 0; i < (int)data_len; i++) {
  97535. sum = 0;
  97536. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97537. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97538. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97539. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97540. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97541. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97542. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97543. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97544. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97545. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97546. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97547. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97548. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97549. }
  97550. }
  97551. else { /* order == 11 */
  97552. for(i = 0; i < (int)data_len; i++) {
  97553. sum = 0;
  97554. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97555. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97556. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97557. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97558. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97559. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97560. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97561. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97562. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97563. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97564. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97565. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97566. }
  97567. }
  97568. }
  97569. else {
  97570. if(order == 10) {
  97571. for(i = 0; i < (int)data_len; i++) {
  97572. sum = 0;
  97573. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97574. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97575. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97576. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97577. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97578. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97579. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97580. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97581. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97582. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97583. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97584. }
  97585. }
  97586. else { /* order == 9 */
  97587. for(i = 0; i < (int)data_len; i++) {
  97588. sum = 0;
  97589. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97590. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97591. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97592. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97593. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97594. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97595. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97596. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97597. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97598. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97599. }
  97600. }
  97601. }
  97602. }
  97603. else if(order > 4) {
  97604. if(order > 6) {
  97605. if(order == 8) {
  97606. for(i = 0; i < (int)data_len; i++) {
  97607. sum = 0;
  97608. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97609. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97610. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97611. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97612. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97613. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97614. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97615. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97616. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97617. }
  97618. }
  97619. else { /* order == 7 */
  97620. for(i = 0; i < (int)data_len; i++) {
  97621. sum = 0;
  97622. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97623. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97624. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97625. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97626. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97627. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97628. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97629. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97630. }
  97631. }
  97632. }
  97633. else {
  97634. if(order == 6) {
  97635. for(i = 0; i < (int)data_len; i++) {
  97636. sum = 0;
  97637. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97638. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97639. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97640. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97641. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97642. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97643. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97644. }
  97645. }
  97646. else { /* order == 5 */
  97647. for(i = 0; i < (int)data_len; i++) {
  97648. sum = 0;
  97649. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97650. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97651. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97652. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97653. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97654. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97655. }
  97656. }
  97657. }
  97658. }
  97659. else {
  97660. if(order > 2) {
  97661. if(order == 4) {
  97662. for(i = 0; i < (int)data_len; i++) {
  97663. sum = 0;
  97664. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97665. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97666. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97667. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97668. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97669. }
  97670. }
  97671. else { /* order == 3 */
  97672. for(i = 0; i < (int)data_len; i++) {
  97673. sum = 0;
  97674. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97675. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97676. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97677. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97678. }
  97679. }
  97680. }
  97681. else {
  97682. if(order == 2) {
  97683. for(i = 0; i < (int)data_len; i++) {
  97684. sum = 0;
  97685. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97686. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97687. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97688. }
  97689. }
  97690. else { /* order == 1 */
  97691. for(i = 0; i < (int)data_len; i++)
  97692. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97693. }
  97694. }
  97695. }
  97696. }
  97697. else { /* order > 12 */
  97698. for(i = 0; i < (int)data_len; i++) {
  97699. sum = 0;
  97700. switch(order) {
  97701. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97702. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97703. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97704. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97705. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97706. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97707. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97708. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97709. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97710. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97711. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97712. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97713. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97714. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97715. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97716. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97717. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97718. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97719. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97720. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97721. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97722. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97723. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97724. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97725. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97726. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97727. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97728. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97729. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97730. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97731. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97732. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97733. }
  97734. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97735. }
  97736. }
  97737. }
  97738. #endif
  97739. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97740. 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[])
  97741. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97742. {
  97743. FLAC__int64 sumo;
  97744. unsigned i, j;
  97745. FLAC__int32 sum;
  97746. const FLAC__int32 *r = residual, *history;
  97747. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97748. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97749. for(i=0;i<order;i++)
  97750. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97751. fprintf(stderr,"\n");
  97752. #endif
  97753. FLAC__ASSERT(order > 0);
  97754. for(i = 0; i < data_len; i++) {
  97755. sumo = 0;
  97756. sum = 0;
  97757. history = data;
  97758. for(j = 0; j < order; j++) {
  97759. sum += qlp_coeff[j] * (*(--history));
  97760. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97761. #if defined _MSC_VER
  97762. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97763. 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);
  97764. #else
  97765. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97766. 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);
  97767. #endif
  97768. }
  97769. *(data++) = *(r++) + (sum >> lp_quantization);
  97770. }
  97771. /* Here's a slower but clearer version:
  97772. for(i = 0; i < data_len; i++) {
  97773. sum = 0;
  97774. for(j = 0; j < order; j++)
  97775. sum += qlp_coeff[j] * data[i-j-1];
  97776. data[i] = residual[i] + (sum >> lp_quantization);
  97777. }
  97778. */
  97779. }
  97780. #else /* fully unrolled version for normal use */
  97781. {
  97782. int i;
  97783. FLAC__int32 sum;
  97784. FLAC__ASSERT(order > 0);
  97785. FLAC__ASSERT(order <= 32);
  97786. /*
  97787. * We do unique versions up to 12th order since that's the subset limit.
  97788. * Also they are roughly ordered to match frequency of occurrence to
  97789. * minimize branching.
  97790. */
  97791. if(order <= 12) {
  97792. if(order > 8) {
  97793. if(order > 10) {
  97794. if(order == 12) {
  97795. for(i = 0; i < (int)data_len; i++) {
  97796. sum = 0;
  97797. sum += qlp_coeff[11] * data[i-12];
  97798. sum += qlp_coeff[10] * data[i-11];
  97799. sum += qlp_coeff[9] * data[i-10];
  97800. sum += qlp_coeff[8] * data[i-9];
  97801. sum += qlp_coeff[7] * data[i-8];
  97802. sum += qlp_coeff[6] * data[i-7];
  97803. sum += qlp_coeff[5] * data[i-6];
  97804. sum += qlp_coeff[4] * data[i-5];
  97805. sum += qlp_coeff[3] * data[i-4];
  97806. sum += qlp_coeff[2] * data[i-3];
  97807. sum += qlp_coeff[1] * data[i-2];
  97808. sum += qlp_coeff[0] * data[i-1];
  97809. data[i] = residual[i] + (sum >> lp_quantization);
  97810. }
  97811. }
  97812. else { /* order == 11 */
  97813. for(i = 0; i < (int)data_len; i++) {
  97814. sum = 0;
  97815. sum += qlp_coeff[10] * data[i-11];
  97816. sum += qlp_coeff[9] * data[i-10];
  97817. sum += qlp_coeff[8] * data[i-9];
  97818. sum += qlp_coeff[7] * data[i-8];
  97819. sum += qlp_coeff[6] * data[i-7];
  97820. sum += qlp_coeff[5] * data[i-6];
  97821. sum += qlp_coeff[4] * data[i-5];
  97822. sum += qlp_coeff[3] * data[i-4];
  97823. sum += qlp_coeff[2] * data[i-3];
  97824. sum += qlp_coeff[1] * data[i-2];
  97825. sum += qlp_coeff[0] * data[i-1];
  97826. data[i] = residual[i] + (sum >> lp_quantization);
  97827. }
  97828. }
  97829. }
  97830. else {
  97831. if(order == 10) {
  97832. for(i = 0; i < (int)data_len; i++) {
  97833. sum = 0;
  97834. sum += qlp_coeff[9] * data[i-10];
  97835. sum += qlp_coeff[8] * data[i-9];
  97836. sum += qlp_coeff[7] * data[i-8];
  97837. sum += qlp_coeff[6] * data[i-7];
  97838. sum += qlp_coeff[5] * data[i-6];
  97839. sum += qlp_coeff[4] * data[i-5];
  97840. sum += qlp_coeff[3] * data[i-4];
  97841. sum += qlp_coeff[2] * data[i-3];
  97842. sum += qlp_coeff[1] * data[i-2];
  97843. sum += qlp_coeff[0] * data[i-1];
  97844. data[i] = residual[i] + (sum >> lp_quantization);
  97845. }
  97846. }
  97847. else { /* order == 9 */
  97848. for(i = 0; i < (int)data_len; i++) {
  97849. sum = 0;
  97850. sum += qlp_coeff[8] * data[i-9];
  97851. sum += qlp_coeff[7] * data[i-8];
  97852. sum += qlp_coeff[6] * data[i-7];
  97853. sum += qlp_coeff[5] * data[i-6];
  97854. sum += qlp_coeff[4] * data[i-5];
  97855. sum += qlp_coeff[3] * data[i-4];
  97856. sum += qlp_coeff[2] * data[i-3];
  97857. sum += qlp_coeff[1] * data[i-2];
  97858. sum += qlp_coeff[0] * data[i-1];
  97859. data[i] = residual[i] + (sum >> lp_quantization);
  97860. }
  97861. }
  97862. }
  97863. }
  97864. else if(order > 4) {
  97865. if(order > 6) {
  97866. if(order == 8) {
  97867. for(i = 0; i < (int)data_len; i++) {
  97868. sum = 0;
  97869. sum += qlp_coeff[7] * data[i-8];
  97870. sum += qlp_coeff[6] * data[i-7];
  97871. sum += qlp_coeff[5] * data[i-6];
  97872. sum += qlp_coeff[4] * data[i-5];
  97873. sum += qlp_coeff[3] * data[i-4];
  97874. sum += qlp_coeff[2] * data[i-3];
  97875. sum += qlp_coeff[1] * data[i-2];
  97876. sum += qlp_coeff[0] * data[i-1];
  97877. data[i] = residual[i] + (sum >> lp_quantization);
  97878. }
  97879. }
  97880. else { /* order == 7 */
  97881. for(i = 0; i < (int)data_len; i++) {
  97882. sum = 0;
  97883. sum += qlp_coeff[6] * data[i-7];
  97884. sum += qlp_coeff[5] * data[i-6];
  97885. sum += qlp_coeff[4] * data[i-5];
  97886. sum += qlp_coeff[3] * data[i-4];
  97887. sum += qlp_coeff[2] * data[i-3];
  97888. sum += qlp_coeff[1] * data[i-2];
  97889. sum += qlp_coeff[0] * data[i-1];
  97890. data[i] = residual[i] + (sum >> lp_quantization);
  97891. }
  97892. }
  97893. }
  97894. else {
  97895. if(order == 6) {
  97896. for(i = 0; i < (int)data_len; i++) {
  97897. sum = 0;
  97898. sum += qlp_coeff[5] * data[i-6];
  97899. sum += qlp_coeff[4] * data[i-5];
  97900. sum += qlp_coeff[3] * data[i-4];
  97901. sum += qlp_coeff[2] * data[i-3];
  97902. sum += qlp_coeff[1] * data[i-2];
  97903. sum += qlp_coeff[0] * data[i-1];
  97904. data[i] = residual[i] + (sum >> lp_quantization);
  97905. }
  97906. }
  97907. else { /* order == 5 */
  97908. for(i = 0; i < (int)data_len; i++) {
  97909. sum = 0;
  97910. sum += qlp_coeff[4] * data[i-5];
  97911. sum += qlp_coeff[3] * data[i-4];
  97912. sum += qlp_coeff[2] * data[i-3];
  97913. sum += qlp_coeff[1] * data[i-2];
  97914. sum += qlp_coeff[0] * data[i-1];
  97915. data[i] = residual[i] + (sum >> lp_quantization);
  97916. }
  97917. }
  97918. }
  97919. }
  97920. else {
  97921. if(order > 2) {
  97922. if(order == 4) {
  97923. for(i = 0; i < (int)data_len; i++) {
  97924. sum = 0;
  97925. sum += qlp_coeff[3] * data[i-4];
  97926. sum += qlp_coeff[2] * data[i-3];
  97927. sum += qlp_coeff[1] * data[i-2];
  97928. sum += qlp_coeff[0] * data[i-1];
  97929. data[i] = residual[i] + (sum >> lp_quantization);
  97930. }
  97931. }
  97932. else { /* order == 3 */
  97933. for(i = 0; i < (int)data_len; i++) {
  97934. sum = 0;
  97935. sum += qlp_coeff[2] * data[i-3];
  97936. sum += qlp_coeff[1] * data[i-2];
  97937. sum += qlp_coeff[0] * data[i-1];
  97938. data[i] = residual[i] + (sum >> lp_quantization);
  97939. }
  97940. }
  97941. }
  97942. else {
  97943. if(order == 2) {
  97944. for(i = 0; i < (int)data_len; i++) {
  97945. sum = 0;
  97946. sum += qlp_coeff[1] * data[i-2];
  97947. sum += qlp_coeff[0] * data[i-1];
  97948. data[i] = residual[i] + (sum >> lp_quantization);
  97949. }
  97950. }
  97951. else { /* order == 1 */
  97952. for(i = 0; i < (int)data_len; i++)
  97953. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97954. }
  97955. }
  97956. }
  97957. }
  97958. else { /* order > 12 */
  97959. for(i = 0; i < (int)data_len; i++) {
  97960. sum = 0;
  97961. switch(order) {
  97962. case 32: sum += qlp_coeff[31] * data[i-32];
  97963. case 31: sum += qlp_coeff[30] * data[i-31];
  97964. case 30: sum += qlp_coeff[29] * data[i-30];
  97965. case 29: sum += qlp_coeff[28] * data[i-29];
  97966. case 28: sum += qlp_coeff[27] * data[i-28];
  97967. case 27: sum += qlp_coeff[26] * data[i-27];
  97968. case 26: sum += qlp_coeff[25] * data[i-26];
  97969. case 25: sum += qlp_coeff[24] * data[i-25];
  97970. case 24: sum += qlp_coeff[23] * data[i-24];
  97971. case 23: sum += qlp_coeff[22] * data[i-23];
  97972. case 22: sum += qlp_coeff[21] * data[i-22];
  97973. case 21: sum += qlp_coeff[20] * data[i-21];
  97974. case 20: sum += qlp_coeff[19] * data[i-20];
  97975. case 19: sum += qlp_coeff[18] * data[i-19];
  97976. case 18: sum += qlp_coeff[17] * data[i-18];
  97977. case 17: sum += qlp_coeff[16] * data[i-17];
  97978. case 16: sum += qlp_coeff[15] * data[i-16];
  97979. case 15: sum += qlp_coeff[14] * data[i-15];
  97980. case 14: sum += qlp_coeff[13] * data[i-14];
  97981. case 13: sum += qlp_coeff[12] * data[i-13];
  97982. sum += qlp_coeff[11] * data[i-12];
  97983. sum += qlp_coeff[10] * data[i-11];
  97984. sum += qlp_coeff[ 9] * data[i-10];
  97985. sum += qlp_coeff[ 8] * data[i- 9];
  97986. sum += qlp_coeff[ 7] * data[i- 8];
  97987. sum += qlp_coeff[ 6] * data[i- 7];
  97988. sum += qlp_coeff[ 5] * data[i- 6];
  97989. sum += qlp_coeff[ 4] * data[i- 5];
  97990. sum += qlp_coeff[ 3] * data[i- 4];
  97991. sum += qlp_coeff[ 2] * data[i- 3];
  97992. sum += qlp_coeff[ 1] * data[i- 2];
  97993. sum += qlp_coeff[ 0] * data[i- 1];
  97994. }
  97995. data[i] = residual[i] + (sum >> lp_quantization);
  97996. }
  97997. }
  97998. }
  97999. #endif
  98000. 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[])
  98001. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98002. {
  98003. unsigned i, j;
  98004. FLAC__int64 sum;
  98005. const FLAC__int32 *r = residual, *history;
  98006. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98007. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98008. for(i=0;i<order;i++)
  98009. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98010. fprintf(stderr,"\n");
  98011. #endif
  98012. FLAC__ASSERT(order > 0);
  98013. for(i = 0; i < data_len; i++) {
  98014. sum = 0;
  98015. history = data;
  98016. for(j = 0; j < order; j++)
  98017. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98018. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98019. #ifdef _MSC_VER
  98020. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98021. #else
  98022. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98023. #endif
  98024. break;
  98025. }
  98026. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98027. #ifdef _MSC_VER
  98028. 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));
  98029. #else
  98030. 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)));
  98031. #endif
  98032. break;
  98033. }
  98034. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98035. }
  98036. }
  98037. #else /* fully unrolled version for normal use */
  98038. {
  98039. int i;
  98040. FLAC__int64 sum;
  98041. FLAC__ASSERT(order > 0);
  98042. FLAC__ASSERT(order <= 32);
  98043. /*
  98044. * We do unique versions up to 12th order since that's the subset limit.
  98045. * Also they are roughly ordered to match frequency of occurrence to
  98046. * minimize branching.
  98047. */
  98048. if(order <= 12) {
  98049. if(order > 8) {
  98050. if(order > 10) {
  98051. if(order == 12) {
  98052. for(i = 0; i < (int)data_len; i++) {
  98053. sum = 0;
  98054. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98055. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98056. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98057. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98058. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98059. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98060. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98061. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98062. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98063. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98064. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98065. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98066. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98067. }
  98068. }
  98069. else { /* order == 11 */
  98070. for(i = 0; i < (int)data_len; i++) {
  98071. sum = 0;
  98072. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98073. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98074. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98075. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98076. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98077. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98078. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98079. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98080. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98081. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98082. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98083. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98084. }
  98085. }
  98086. }
  98087. else {
  98088. if(order == 10) {
  98089. for(i = 0; i < (int)data_len; i++) {
  98090. sum = 0;
  98091. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98092. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98093. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98094. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98095. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98096. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98097. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98098. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98099. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98100. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98101. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98102. }
  98103. }
  98104. else { /* order == 9 */
  98105. for(i = 0; i < (int)data_len; i++) {
  98106. sum = 0;
  98107. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98108. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98109. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98110. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98111. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98112. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98113. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98114. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98115. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98116. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98117. }
  98118. }
  98119. }
  98120. }
  98121. else if(order > 4) {
  98122. if(order > 6) {
  98123. if(order == 8) {
  98124. for(i = 0; i < (int)data_len; i++) {
  98125. sum = 0;
  98126. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98127. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98128. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98129. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98130. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98131. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98132. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98133. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98134. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98135. }
  98136. }
  98137. else { /* order == 7 */
  98138. for(i = 0; i < (int)data_len; i++) {
  98139. sum = 0;
  98140. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98141. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98142. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98143. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98144. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98145. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98146. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98147. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98148. }
  98149. }
  98150. }
  98151. else {
  98152. if(order == 6) {
  98153. for(i = 0; i < (int)data_len; i++) {
  98154. sum = 0;
  98155. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98156. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98157. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98158. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98159. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98160. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98161. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98162. }
  98163. }
  98164. else { /* order == 5 */
  98165. for(i = 0; i < (int)data_len; i++) {
  98166. sum = 0;
  98167. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98168. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98169. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98170. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98171. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98172. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98173. }
  98174. }
  98175. }
  98176. }
  98177. else {
  98178. if(order > 2) {
  98179. if(order == 4) {
  98180. for(i = 0; i < (int)data_len; i++) {
  98181. sum = 0;
  98182. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98183. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98184. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98185. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98186. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98187. }
  98188. }
  98189. else { /* order == 3 */
  98190. for(i = 0; i < (int)data_len; i++) {
  98191. sum = 0;
  98192. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98193. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98194. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98195. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98196. }
  98197. }
  98198. }
  98199. else {
  98200. if(order == 2) {
  98201. for(i = 0; i < (int)data_len; i++) {
  98202. sum = 0;
  98203. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98204. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98205. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98206. }
  98207. }
  98208. else { /* order == 1 */
  98209. for(i = 0; i < (int)data_len; i++)
  98210. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98211. }
  98212. }
  98213. }
  98214. }
  98215. else { /* order > 12 */
  98216. for(i = 0; i < (int)data_len; i++) {
  98217. sum = 0;
  98218. switch(order) {
  98219. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98220. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98221. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98222. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98223. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98224. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98225. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98226. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98227. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98228. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98229. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98230. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98231. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98232. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98233. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98234. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98235. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98236. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98237. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98238. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98239. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98240. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98241. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98242. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98243. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98244. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98245. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98246. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98247. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98248. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98249. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98250. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98251. }
  98252. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98253. }
  98254. }
  98255. }
  98256. #endif
  98257. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98258. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98259. {
  98260. FLAC__double error_scale;
  98261. FLAC__ASSERT(total_samples > 0);
  98262. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98263. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98264. }
  98265. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98266. {
  98267. if(lpc_error > 0.0) {
  98268. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98269. if(bps >= 0.0)
  98270. return bps;
  98271. else
  98272. return 0.0;
  98273. }
  98274. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98275. return 1e32;
  98276. }
  98277. else {
  98278. return 0.0;
  98279. }
  98280. }
  98281. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98282. {
  98283. 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 */
  98284. FLAC__double bits, best_bits, error_scale;
  98285. FLAC__ASSERT(max_order > 0);
  98286. FLAC__ASSERT(total_samples > 0);
  98287. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98288. best_index = 0;
  98289. best_bits = (unsigned)(-1);
  98290. for(index = 0, order = 1; index < max_order; index++, order++) {
  98291. 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);
  98292. if(bits < best_bits) {
  98293. best_index = index;
  98294. best_bits = bits;
  98295. }
  98296. }
  98297. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98298. }
  98299. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98300. #endif
  98301. /*** End of inlined file: lpc_flac.c ***/
  98302. /*** Start of inlined file: md5.c ***/
  98303. /*** Start of inlined file: juce_FlacHeader.h ***/
  98304. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98305. // tasks..
  98306. #define VERSION "1.2.1"
  98307. #define FLAC__NO_DLL 1
  98308. #if JUCE_MSVC
  98309. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98310. #endif
  98311. #if JUCE_MAC
  98312. #define FLAC__SYS_DARWIN 1
  98313. #endif
  98314. /*** End of inlined file: juce_FlacHeader.h ***/
  98315. #if JUCE_USE_FLAC
  98316. #if HAVE_CONFIG_H
  98317. # include <config.h>
  98318. #endif
  98319. #include <stdlib.h> /* for malloc() */
  98320. #include <string.h> /* for memcpy() */
  98321. /*** Start of inlined file: md5.h ***/
  98322. #ifndef FLAC__PRIVATE__MD5_H
  98323. #define FLAC__PRIVATE__MD5_H
  98324. /*
  98325. * This is the header file for the MD5 message-digest algorithm.
  98326. * The algorithm is due to Ron Rivest. This code was
  98327. * written by Colin Plumb in 1993, no copyright is claimed.
  98328. * This code is in the public domain; do with it what you wish.
  98329. *
  98330. * Equivalent code is available from RSA Data Security, Inc.
  98331. * This code has been tested against that, and is equivalent,
  98332. * except that you don't need to include two pages of legalese
  98333. * with every copy.
  98334. *
  98335. * To compute the message digest of a chunk of bytes, declare an
  98336. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98337. * needed on buffers full of bytes, and then call MD5Final, which
  98338. * will fill a supplied 16-byte array with the digest.
  98339. *
  98340. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98341. * header definitions; now uses stuff from dpkg's config.h
  98342. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98343. * Still in the public domain.
  98344. *
  98345. * Josh Coalson: made some changes to integrate with libFLAC.
  98346. * Still in the public domain, with no warranty.
  98347. */
  98348. typedef struct {
  98349. FLAC__uint32 in[16];
  98350. FLAC__uint32 buf[4];
  98351. FLAC__uint32 bytes[2];
  98352. FLAC__byte *internal_buf;
  98353. size_t capacity;
  98354. } FLAC__MD5Context;
  98355. void FLAC__MD5Init(FLAC__MD5Context *context);
  98356. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98357. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98358. #endif
  98359. /*** End of inlined file: md5.h ***/
  98360. #ifndef FLaC__INLINE
  98361. #define FLaC__INLINE
  98362. #endif
  98363. /*
  98364. * This code implements the MD5 message-digest algorithm.
  98365. * The algorithm is due to Ron Rivest. This code was
  98366. * written by Colin Plumb in 1993, no copyright is claimed.
  98367. * This code is in the public domain; do with it what you wish.
  98368. *
  98369. * Equivalent code is available from RSA Data Security, Inc.
  98370. * This code has been tested against that, and is equivalent,
  98371. * except that you don't need to include two pages of legalese
  98372. * with every copy.
  98373. *
  98374. * To compute the message digest of a chunk of bytes, declare an
  98375. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98376. * needed on buffers full of bytes, and then call MD5Final, which
  98377. * will fill a supplied 16-byte array with the digest.
  98378. *
  98379. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98380. * definitions; now uses stuff from dpkg's config.h.
  98381. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98382. * Still in the public domain.
  98383. *
  98384. * Josh Coalson: made some changes to integrate with libFLAC.
  98385. * Still in the public domain.
  98386. */
  98387. /* The four core functions - F1 is optimized somewhat */
  98388. /* #define F1(x, y, z) (x & y | ~x & z) */
  98389. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98390. #define F2(x, y, z) F1(z, x, y)
  98391. #define F3(x, y, z) (x ^ y ^ z)
  98392. #define F4(x, y, z) (y ^ (x | ~z))
  98393. /* This is the central step in the MD5 algorithm. */
  98394. #define MD5STEP(f,w,x,y,z,in,s) \
  98395. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98396. /*
  98397. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98398. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98399. * the data and converts bytes into longwords for this routine.
  98400. */
  98401. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98402. {
  98403. register FLAC__uint32 a, b, c, d;
  98404. a = buf[0];
  98405. b = buf[1];
  98406. c = buf[2];
  98407. d = buf[3];
  98408. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98409. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98410. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98411. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98412. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98413. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98414. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98415. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98416. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98417. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98418. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98419. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98420. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98421. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98422. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98423. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98424. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98425. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98426. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98427. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98428. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98429. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98430. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98431. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98432. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98433. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98434. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98435. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98436. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98437. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98438. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98439. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98440. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98441. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98442. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98443. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98444. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98445. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98446. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98447. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98448. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98449. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98450. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98451. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98452. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98453. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98454. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98455. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98456. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98457. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98458. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98459. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98460. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98461. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98462. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98463. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98464. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98465. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98466. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98467. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98468. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98469. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98470. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98471. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98472. buf[0] += a;
  98473. buf[1] += b;
  98474. buf[2] += c;
  98475. buf[3] += d;
  98476. }
  98477. #if WORDS_BIGENDIAN
  98478. //@@@@@@ OPT: use bswap/intrinsics
  98479. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98480. {
  98481. register FLAC__uint32 x;
  98482. do {
  98483. x = *buf;
  98484. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98485. *buf++ = (x >> 16) | (x << 16);
  98486. } while (--words);
  98487. }
  98488. static void byteSwapX16(FLAC__uint32 *buf)
  98489. {
  98490. register FLAC__uint32 x;
  98491. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98492. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98493. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98494. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98495. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98496. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98497. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98498. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98499. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98500. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98501. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98502. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98503. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98504. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98505. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98506. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98507. }
  98508. #else
  98509. #define byteSwap(buf, words)
  98510. #define byteSwapX16(buf)
  98511. #endif
  98512. /*
  98513. * Update context to reflect the concatenation of another buffer full
  98514. * of bytes.
  98515. */
  98516. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98517. {
  98518. FLAC__uint32 t;
  98519. /* Update byte count */
  98520. t = ctx->bytes[0];
  98521. if ((ctx->bytes[0] = t + len) < t)
  98522. ctx->bytes[1]++; /* Carry from low to high */
  98523. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98524. if (t > len) {
  98525. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98526. return;
  98527. }
  98528. /* First chunk is an odd size */
  98529. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98530. byteSwapX16(ctx->in);
  98531. FLAC__MD5Transform(ctx->buf, ctx->in);
  98532. buf += t;
  98533. len -= t;
  98534. /* Process data in 64-byte chunks */
  98535. while (len >= 64) {
  98536. memcpy(ctx->in, buf, 64);
  98537. byteSwapX16(ctx->in);
  98538. FLAC__MD5Transform(ctx->buf, ctx->in);
  98539. buf += 64;
  98540. len -= 64;
  98541. }
  98542. /* Handle any remaining bytes of data. */
  98543. memcpy(ctx->in, buf, len);
  98544. }
  98545. /*
  98546. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98547. * initialization constants.
  98548. */
  98549. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98550. {
  98551. ctx->buf[0] = 0x67452301;
  98552. ctx->buf[1] = 0xefcdab89;
  98553. ctx->buf[2] = 0x98badcfe;
  98554. ctx->buf[3] = 0x10325476;
  98555. ctx->bytes[0] = 0;
  98556. ctx->bytes[1] = 0;
  98557. ctx->internal_buf = 0;
  98558. ctx->capacity = 0;
  98559. }
  98560. /*
  98561. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98562. * 1 0* (64-bit count of bits processed, MSB-first)
  98563. */
  98564. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98565. {
  98566. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98567. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98568. /* Set the first char of padding to 0x80. There is always room. */
  98569. *p++ = 0x80;
  98570. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98571. count = 56 - 1 - count;
  98572. if (count < 0) { /* Padding forces an extra block */
  98573. memset(p, 0, count + 8);
  98574. byteSwapX16(ctx->in);
  98575. FLAC__MD5Transform(ctx->buf, ctx->in);
  98576. p = (FLAC__byte *)ctx->in;
  98577. count = 56;
  98578. }
  98579. memset(p, 0, count);
  98580. byteSwap(ctx->in, 14);
  98581. /* Append length in bits and transform */
  98582. ctx->in[14] = ctx->bytes[0] << 3;
  98583. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98584. FLAC__MD5Transform(ctx->buf, ctx->in);
  98585. byteSwap(ctx->buf, 4);
  98586. memcpy(digest, ctx->buf, 16);
  98587. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98588. if(0 != ctx->internal_buf) {
  98589. free(ctx->internal_buf);
  98590. ctx->internal_buf = 0;
  98591. ctx->capacity = 0;
  98592. }
  98593. }
  98594. /*
  98595. * Convert the incoming audio signal to a byte stream
  98596. */
  98597. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98598. {
  98599. unsigned channel, sample;
  98600. register FLAC__int32 a_word;
  98601. register FLAC__byte *buf_ = buf;
  98602. #if WORDS_BIGENDIAN
  98603. #else
  98604. if(channels == 2 && bytes_per_sample == 2) {
  98605. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98606. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98607. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98608. *buf1_ = (FLAC__int16)signal[1][sample];
  98609. }
  98610. else if(channels == 1 && bytes_per_sample == 2) {
  98611. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98612. for(sample = 0; sample < samples; sample++)
  98613. *buf1_++ = (FLAC__int16)signal[0][sample];
  98614. }
  98615. else
  98616. #endif
  98617. if(bytes_per_sample == 2) {
  98618. if(channels == 2) {
  98619. for(sample = 0; sample < samples; sample++) {
  98620. a_word = signal[0][sample];
  98621. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98622. *buf_++ = (FLAC__byte)a_word;
  98623. a_word = signal[1][sample];
  98624. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98625. *buf_++ = (FLAC__byte)a_word;
  98626. }
  98627. }
  98628. else if(channels == 1) {
  98629. for(sample = 0; sample < samples; sample++) {
  98630. a_word = signal[0][sample];
  98631. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98632. *buf_++ = (FLAC__byte)a_word;
  98633. }
  98634. }
  98635. else {
  98636. for(sample = 0; sample < samples; sample++) {
  98637. for(channel = 0; channel < channels; channel++) {
  98638. a_word = signal[channel][sample];
  98639. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98640. *buf_++ = (FLAC__byte)a_word;
  98641. }
  98642. }
  98643. }
  98644. }
  98645. else if(bytes_per_sample == 3) {
  98646. if(channels == 2) {
  98647. for(sample = 0; sample < samples; sample++) {
  98648. a_word = signal[0][sample];
  98649. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98650. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98651. *buf_++ = (FLAC__byte)a_word;
  98652. a_word = signal[1][sample];
  98653. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98654. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98655. *buf_++ = (FLAC__byte)a_word;
  98656. }
  98657. }
  98658. else if(channels == 1) {
  98659. for(sample = 0; sample < samples; sample++) {
  98660. a_word = signal[0][sample];
  98661. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98662. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98663. *buf_++ = (FLAC__byte)a_word;
  98664. }
  98665. }
  98666. else {
  98667. for(sample = 0; sample < samples; sample++) {
  98668. for(channel = 0; channel < channels; channel++) {
  98669. a_word = signal[channel][sample];
  98670. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98671. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98672. *buf_++ = (FLAC__byte)a_word;
  98673. }
  98674. }
  98675. }
  98676. }
  98677. else if(bytes_per_sample == 1) {
  98678. if(channels == 2) {
  98679. for(sample = 0; sample < samples; sample++) {
  98680. a_word = signal[0][sample];
  98681. *buf_++ = (FLAC__byte)a_word;
  98682. a_word = signal[1][sample];
  98683. *buf_++ = (FLAC__byte)a_word;
  98684. }
  98685. }
  98686. else if(channels == 1) {
  98687. for(sample = 0; sample < samples; sample++) {
  98688. a_word = signal[0][sample];
  98689. *buf_++ = (FLAC__byte)a_word;
  98690. }
  98691. }
  98692. else {
  98693. for(sample = 0; sample < samples; sample++) {
  98694. for(channel = 0; channel < channels; channel++) {
  98695. a_word = signal[channel][sample];
  98696. *buf_++ = (FLAC__byte)a_word;
  98697. }
  98698. }
  98699. }
  98700. }
  98701. else { /* bytes_per_sample == 4, maybe optimize more later */
  98702. for(sample = 0; sample < samples; sample++) {
  98703. for(channel = 0; channel < channels; channel++) {
  98704. a_word = signal[channel][sample];
  98705. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98706. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98707. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98708. *buf_++ = (FLAC__byte)a_word;
  98709. }
  98710. }
  98711. }
  98712. }
  98713. /*
  98714. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98715. */
  98716. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98717. {
  98718. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98719. /* overflow check */
  98720. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98721. return false;
  98722. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98723. return false;
  98724. if(ctx->capacity < bytes_needed) {
  98725. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98726. if(0 == tmp) {
  98727. free(ctx->internal_buf);
  98728. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98729. return false;
  98730. }
  98731. ctx->internal_buf = tmp;
  98732. ctx->capacity = bytes_needed;
  98733. }
  98734. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98735. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98736. return true;
  98737. }
  98738. #endif
  98739. /*** End of inlined file: md5.c ***/
  98740. /*** Start of inlined file: memory.c ***/
  98741. /*** Start of inlined file: juce_FlacHeader.h ***/
  98742. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98743. // tasks..
  98744. #define VERSION "1.2.1"
  98745. #define FLAC__NO_DLL 1
  98746. #if JUCE_MSVC
  98747. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98748. #endif
  98749. #if JUCE_MAC
  98750. #define FLAC__SYS_DARWIN 1
  98751. #endif
  98752. /*** End of inlined file: juce_FlacHeader.h ***/
  98753. #if JUCE_USE_FLAC
  98754. #if HAVE_CONFIG_H
  98755. # include <config.h>
  98756. #endif
  98757. /*** Start of inlined file: memory.h ***/
  98758. #ifndef FLAC__PRIVATE__MEMORY_H
  98759. #define FLAC__PRIVATE__MEMORY_H
  98760. #ifdef HAVE_CONFIG_H
  98761. #include <config.h>
  98762. #endif
  98763. #include <stdlib.h> /* for size_t */
  98764. /* Returns the unaligned address returned by malloc.
  98765. * Use free() on this address to deallocate.
  98766. */
  98767. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98768. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98769. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98770. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98771. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98772. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98773. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98774. #endif
  98775. #endif
  98776. /*** End of inlined file: memory.h ***/
  98777. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98778. {
  98779. void *x;
  98780. FLAC__ASSERT(0 != aligned_address);
  98781. #ifdef FLAC__ALIGN_MALLOC_DATA
  98782. /* align on 32-byte (256-bit) boundary */
  98783. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98784. #ifdef SIZEOF_VOIDP
  98785. #if SIZEOF_VOIDP == 4
  98786. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98787. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98788. #elif SIZEOF_VOIDP == 8
  98789. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98790. #else
  98791. # error Unsupported sizeof(void*)
  98792. #endif
  98793. #else
  98794. /* there's got to be a better way to do this right for all archs */
  98795. if(sizeof(void*) == sizeof(unsigned))
  98796. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98797. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98798. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98799. else
  98800. return 0;
  98801. #endif
  98802. #else
  98803. x = safe_malloc_(bytes);
  98804. *aligned_address = x;
  98805. #endif
  98806. return x;
  98807. }
  98808. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98809. {
  98810. FLAC__int32 *pu; /* unaligned pointer */
  98811. union { /* union needed to comply with C99 pointer aliasing rules */
  98812. FLAC__int32 *pa; /* aligned pointer */
  98813. void *pv; /* aligned pointer alias */
  98814. } u;
  98815. FLAC__ASSERT(elements > 0);
  98816. FLAC__ASSERT(0 != unaligned_pointer);
  98817. FLAC__ASSERT(0 != aligned_pointer);
  98818. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98819. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98820. if(0 == pu) {
  98821. return false;
  98822. }
  98823. else {
  98824. if(*unaligned_pointer != 0)
  98825. free(*unaligned_pointer);
  98826. *unaligned_pointer = pu;
  98827. *aligned_pointer = u.pa;
  98828. return true;
  98829. }
  98830. }
  98831. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98832. {
  98833. FLAC__uint32 *pu; /* unaligned pointer */
  98834. union { /* union needed to comply with C99 pointer aliasing rules */
  98835. FLAC__uint32 *pa; /* aligned pointer */
  98836. void *pv; /* aligned pointer alias */
  98837. } u;
  98838. FLAC__ASSERT(elements > 0);
  98839. FLAC__ASSERT(0 != unaligned_pointer);
  98840. FLAC__ASSERT(0 != aligned_pointer);
  98841. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98842. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98843. if(0 == pu) {
  98844. return false;
  98845. }
  98846. else {
  98847. if(*unaligned_pointer != 0)
  98848. free(*unaligned_pointer);
  98849. *unaligned_pointer = pu;
  98850. *aligned_pointer = u.pa;
  98851. return true;
  98852. }
  98853. }
  98854. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98855. {
  98856. FLAC__uint64 *pu; /* unaligned pointer */
  98857. union { /* union needed to comply with C99 pointer aliasing rules */
  98858. FLAC__uint64 *pa; /* aligned pointer */
  98859. void *pv; /* aligned pointer alias */
  98860. } u;
  98861. FLAC__ASSERT(elements > 0);
  98862. FLAC__ASSERT(0 != unaligned_pointer);
  98863. FLAC__ASSERT(0 != aligned_pointer);
  98864. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98865. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98866. if(0 == pu) {
  98867. return false;
  98868. }
  98869. else {
  98870. if(*unaligned_pointer != 0)
  98871. free(*unaligned_pointer);
  98872. *unaligned_pointer = pu;
  98873. *aligned_pointer = u.pa;
  98874. return true;
  98875. }
  98876. }
  98877. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98878. {
  98879. unsigned *pu; /* unaligned pointer */
  98880. union { /* union needed to comply with C99 pointer aliasing rules */
  98881. unsigned *pa; /* aligned pointer */
  98882. void *pv; /* aligned pointer alias */
  98883. } u;
  98884. FLAC__ASSERT(elements > 0);
  98885. FLAC__ASSERT(0 != unaligned_pointer);
  98886. FLAC__ASSERT(0 != aligned_pointer);
  98887. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98888. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98889. if(0 == pu) {
  98890. return false;
  98891. }
  98892. else {
  98893. if(*unaligned_pointer != 0)
  98894. free(*unaligned_pointer);
  98895. *unaligned_pointer = pu;
  98896. *aligned_pointer = u.pa;
  98897. return true;
  98898. }
  98899. }
  98900. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98901. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98902. {
  98903. FLAC__real *pu; /* unaligned pointer */
  98904. union { /* union needed to comply with C99 pointer aliasing rules */
  98905. FLAC__real *pa; /* aligned pointer */
  98906. void *pv; /* aligned pointer alias */
  98907. } u;
  98908. FLAC__ASSERT(elements > 0);
  98909. FLAC__ASSERT(0 != unaligned_pointer);
  98910. FLAC__ASSERT(0 != aligned_pointer);
  98911. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98912. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98913. if(0 == pu) {
  98914. return false;
  98915. }
  98916. else {
  98917. if(*unaligned_pointer != 0)
  98918. free(*unaligned_pointer);
  98919. *unaligned_pointer = pu;
  98920. *aligned_pointer = u.pa;
  98921. return true;
  98922. }
  98923. }
  98924. #endif
  98925. #endif
  98926. /*** End of inlined file: memory.c ***/
  98927. /*** Start of inlined file: stream_decoder.c ***/
  98928. /*** Start of inlined file: juce_FlacHeader.h ***/
  98929. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98930. // tasks..
  98931. #define VERSION "1.2.1"
  98932. #define FLAC__NO_DLL 1
  98933. #if JUCE_MSVC
  98934. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98935. #endif
  98936. #if JUCE_MAC
  98937. #define FLAC__SYS_DARWIN 1
  98938. #endif
  98939. /*** End of inlined file: juce_FlacHeader.h ***/
  98940. #if JUCE_USE_FLAC
  98941. #if HAVE_CONFIG_H
  98942. # include <config.h>
  98943. #endif
  98944. #if defined _MSC_VER || defined __MINGW32__
  98945. #include <io.h> /* for _setmode() */
  98946. #include <fcntl.h> /* for _O_BINARY */
  98947. #endif
  98948. #if defined __CYGWIN__ || defined __EMX__
  98949. #include <io.h> /* for setmode(), O_BINARY */
  98950. #include <fcntl.h> /* for _O_BINARY */
  98951. #endif
  98952. #include <stdio.h>
  98953. #include <stdlib.h> /* for malloc() */
  98954. #include <string.h> /* for memset/memcpy() */
  98955. #include <sys/stat.h> /* for stat() */
  98956. #include <sys/types.h> /* for off_t */
  98957. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98958. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98959. #define fseeko fseek
  98960. #define ftello ftell
  98961. #endif
  98962. #endif
  98963. /*** Start of inlined file: stream_decoder.h ***/
  98964. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98965. #define FLAC__PROTECTED__STREAM_DECODER_H
  98966. #if FLAC__HAS_OGG
  98967. #include "include/private/ogg_decoder_aspect.h"
  98968. #endif
  98969. typedef struct FLAC__StreamDecoderProtected {
  98970. FLAC__StreamDecoderState state;
  98971. unsigned channels;
  98972. FLAC__ChannelAssignment channel_assignment;
  98973. unsigned bits_per_sample;
  98974. unsigned sample_rate; /* in Hz */
  98975. unsigned blocksize; /* in samples (per channel) */
  98976. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98977. #if FLAC__HAS_OGG
  98978. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98979. #endif
  98980. } FLAC__StreamDecoderProtected;
  98981. /*
  98982. * return the number of input bytes consumed
  98983. */
  98984. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98985. #endif
  98986. /*** End of inlined file: stream_decoder.h ***/
  98987. #ifdef max
  98988. #undef max
  98989. #endif
  98990. #define max(a,b) ((a)>(b)?(a):(b))
  98991. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98992. #ifdef _MSC_VER
  98993. #define FLAC__U64L(x) x
  98994. #else
  98995. #define FLAC__U64L(x) x##LLU
  98996. #endif
  98997. /* technically this should be in an "export.c" but this is convenient enough */
  98998. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98999. #if FLAC__HAS_OGG
  99000. 1
  99001. #else
  99002. 0
  99003. #endif
  99004. ;
  99005. /***********************************************************************
  99006. *
  99007. * Private static data
  99008. *
  99009. ***********************************************************************/
  99010. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99011. /***********************************************************************
  99012. *
  99013. * Private class method prototypes
  99014. *
  99015. ***********************************************************************/
  99016. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99017. static FILE *get_binary_stdin_(void);
  99018. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99019. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99020. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99021. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99022. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99023. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99024. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99025. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99026. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99027. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99028. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99029. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99030. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99031. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99032. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99033. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99034. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99035. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99036. 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);
  99037. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99038. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99039. #if FLAC__HAS_OGG
  99040. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99041. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99042. #endif
  99043. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99044. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99045. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99046. #if FLAC__HAS_OGG
  99047. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99048. #endif
  99049. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99050. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99051. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99052. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99053. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99054. /***********************************************************************
  99055. *
  99056. * Private class data
  99057. *
  99058. ***********************************************************************/
  99059. typedef struct FLAC__StreamDecoderPrivate {
  99060. #if FLAC__HAS_OGG
  99061. FLAC__bool is_ogg;
  99062. #endif
  99063. FLAC__StreamDecoderReadCallback read_callback;
  99064. FLAC__StreamDecoderSeekCallback seek_callback;
  99065. FLAC__StreamDecoderTellCallback tell_callback;
  99066. FLAC__StreamDecoderLengthCallback length_callback;
  99067. FLAC__StreamDecoderEofCallback eof_callback;
  99068. FLAC__StreamDecoderWriteCallback write_callback;
  99069. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99070. FLAC__StreamDecoderErrorCallback error_callback;
  99071. /* generic 32-bit datapath: */
  99072. 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[]);
  99073. /* generic 64-bit datapath: */
  99074. 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[]);
  99075. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99076. 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[]);
  99077. /* 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: */
  99078. 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[]);
  99079. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99080. void *client_data;
  99081. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99082. FLAC__BitReader *input;
  99083. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99084. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99085. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99086. unsigned output_capacity, output_channels;
  99087. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99088. FLAC__uint64 samples_decoded;
  99089. FLAC__bool has_stream_info, has_seek_table;
  99090. FLAC__StreamMetadata stream_info;
  99091. FLAC__StreamMetadata seek_table;
  99092. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99093. FLAC__byte *metadata_filter_ids;
  99094. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99095. FLAC__Frame frame;
  99096. FLAC__bool cached; /* true if there is a byte in lookahead */
  99097. FLAC__CPUInfo cpuinfo;
  99098. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99099. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99100. /* unaligned (original) pointers to allocated data */
  99101. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99102. 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 */
  99103. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99104. FLAC__bool is_seeking;
  99105. FLAC__MD5Context md5context;
  99106. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99107. /* (the rest of these are only used for seeking) */
  99108. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99109. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99110. FLAC__uint64 target_sample;
  99111. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99112. #if FLAC__HAS_OGG
  99113. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99114. #endif
  99115. } FLAC__StreamDecoderPrivate;
  99116. /***********************************************************************
  99117. *
  99118. * Public static class data
  99119. *
  99120. ***********************************************************************/
  99121. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99122. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99123. "FLAC__STREAM_DECODER_READ_METADATA",
  99124. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99125. "FLAC__STREAM_DECODER_READ_FRAME",
  99126. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99127. "FLAC__STREAM_DECODER_OGG_ERROR",
  99128. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99129. "FLAC__STREAM_DECODER_ABORTED",
  99130. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99131. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99132. };
  99133. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99134. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99135. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99136. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99137. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99138. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99139. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99140. };
  99141. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99142. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99143. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99144. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99145. };
  99146. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99147. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99148. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99149. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99150. };
  99151. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99152. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99153. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99154. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99155. };
  99156. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99157. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99158. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99159. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99160. };
  99161. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99162. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99163. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99164. };
  99165. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99166. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99167. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99168. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99169. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99170. };
  99171. /***********************************************************************
  99172. *
  99173. * Class constructor/destructor
  99174. *
  99175. ***********************************************************************/
  99176. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99177. {
  99178. FLAC__StreamDecoder *decoder;
  99179. unsigned i;
  99180. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99181. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99182. if(decoder == 0) {
  99183. return 0;
  99184. }
  99185. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99186. if(decoder->protected_ == 0) {
  99187. free(decoder);
  99188. return 0;
  99189. }
  99190. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99191. if(decoder->private_ == 0) {
  99192. free(decoder->protected_);
  99193. free(decoder);
  99194. return 0;
  99195. }
  99196. decoder->private_->input = FLAC__bitreader_new();
  99197. if(decoder->private_->input == 0) {
  99198. free(decoder->private_);
  99199. free(decoder->protected_);
  99200. free(decoder);
  99201. return 0;
  99202. }
  99203. decoder->private_->metadata_filter_ids_capacity = 16;
  99204. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99205. FLAC__bitreader_delete(decoder->private_->input);
  99206. free(decoder->private_);
  99207. free(decoder->protected_);
  99208. free(decoder);
  99209. return 0;
  99210. }
  99211. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99212. decoder->private_->output[i] = 0;
  99213. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99214. }
  99215. decoder->private_->output_capacity = 0;
  99216. decoder->private_->output_channels = 0;
  99217. decoder->private_->has_seek_table = false;
  99218. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99219. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99220. decoder->private_->file = 0;
  99221. set_defaults_dec(decoder);
  99222. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99223. return decoder;
  99224. }
  99225. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99226. {
  99227. unsigned i;
  99228. FLAC__ASSERT(0 != decoder);
  99229. FLAC__ASSERT(0 != decoder->protected_);
  99230. FLAC__ASSERT(0 != decoder->private_);
  99231. FLAC__ASSERT(0 != decoder->private_->input);
  99232. (void)FLAC__stream_decoder_finish(decoder);
  99233. if(0 != decoder->private_->metadata_filter_ids)
  99234. free(decoder->private_->metadata_filter_ids);
  99235. FLAC__bitreader_delete(decoder->private_->input);
  99236. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99237. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99238. free(decoder->private_);
  99239. free(decoder->protected_);
  99240. free(decoder);
  99241. }
  99242. /***********************************************************************
  99243. *
  99244. * Public class methods
  99245. *
  99246. ***********************************************************************/
  99247. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99248. FLAC__StreamDecoder *decoder,
  99249. FLAC__StreamDecoderReadCallback read_callback,
  99250. FLAC__StreamDecoderSeekCallback seek_callback,
  99251. FLAC__StreamDecoderTellCallback tell_callback,
  99252. FLAC__StreamDecoderLengthCallback length_callback,
  99253. FLAC__StreamDecoderEofCallback eof_callback,
  99254. FLAC__StreamDecoderWriteCallback write_callback,
  99255. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99256. FLAC__StreamDecoderErrorCallback error_callback,
  99257. void *client_data,
  99258. FLAC__bool is_ogg
  99259. )
  99260. {
  99261. FLAC__ASSERT(0 != decoder);
  99262. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99263. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99264. #if !FLAC__HAS_OGG
  99265. if(is_ogg)
  99266. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99267. #endif
  99268. if(
  99269. 0 == read_callback ||
  99270. 0 == write_callback ||
  99271. 0 == error_callback ||
  99272. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99273. )
  99274. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99275. #if FLAC__HAS_OGG
  99276. decoder->private_->is_ogg = is_ogg;
  99277. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99278. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99279. #endif
  99280. /*
  99281. * get the CPU info and set the function pointers
  99282. */
  99283. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99284. /* first default to the non-asm routines */
  99285. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99286. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99287. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99288. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99289. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99290. /* now override with asm where appropriate */
  99291. #ifndef FLAC__NO_ASM
  99292. if(decoder->private_->cpuinfo.use_asm) {
  99293. #ifdef FLAC__CPU_IA32
  99294. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99295. #ifdef FLAC__HAS_NASM
  99296. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99297. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99298. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99299. #endif
  99300. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99301. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99302. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99303. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99304. }
  99305. else {
  99306. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99307. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99308. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99309. }
  99310. #endif
  99311. #elif defined FLAC__CPU_PPC
  99312. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99313. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99314. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99315. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99316. }
  99317. #endif
  99318. }
  99319. #endif
  99320. /* from here on, errors are fatal */
  99321. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99322. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99323. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99324. }
  99325. decoder->private_->read_callback = read_callback;
  99326. decoder->private_->seek_callback = seek_callback;
  99327. decoder->private_->tell_callback = tell_callback;
  99328. decoder->private_->length_callback = length_callback;
  99329. decoder->private_->eof_callback = eof_callback;
  99330. decoder->private_->write_callback = write_callback;
  99331. decoder->private_->metadata_callback = metadata_callback;
  99332. decoder->private_->error_callback = error_callback;
  99333. decoder->private_->client_data = client_data;
  99334. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99335. decoder->private_->samples_decoded = 0;
  99336. decoder->private_->has_stream_info = false;
  99337. decoder->private_->cached = false;
  99338. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99339. decoder->private_->is_seeking = false;
  99340. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99341. if(!FLAC__stream_decoder_reset(decoder)) {
  99342. /* above call sets the state for us */
  99343. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99344. }
  99345. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99346. }
  99347. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99348. FLAC__StreamDecoder *decoder,
  99349. FLAC__StreamDecoderReadCallback read_callback,
  99350. FLAC__StreamDecoderSeekCallback seek_callback,
  99351. FLAC__StreamDecoderTellCallback tell_callback,
  99352. FLAC__StreamDecoderLengthCallback length_callback,
  99353. FLAC__StreamDecoderEofCallback eof_callback,
  99354. FLAC__StreamDecoderWriteCallback write_callback,
  99355. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99356. FLAC__StreamDecoderErrorCallback error_callback,
  99357. void *client_data
  99358. )
  99359. {
  99360. return init_stream_internal_dec(
  99361. decoder,
  99362. read_callback,
  99363. seek_callback,
  99364. tell_callback,
  99365. length_callback,
  99366. eof_callback,
  99367. write_callback,
  99368. metadata_callback,
  99369. error_callback,
  99370. client_data,
  99371. /*is_ogg=*/false
  99372. );
  99373. }
  99374. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99375. FLAC__StreamDecoder *decoder,
  99376. FLAC__StreamDecoderReadCallback read_callback,
  99377. FLAC__StreamDecoderSeekCallback seek_callback,
  99378. FLAC__StreamDecoderTellCallback tell_callback,
  99379. FLAC__StreamDecoderLengthCallback length_callback,
  99380. FLAC__StreamDecoderEofCallback eof_callback,
  99381. FLAC__StreamDecoderWriteCallback write_callback,
  99382. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99383. FLAC__StreamDecoderErrorCallback error_callback,
  99384. void *client_data
  99385. )
  99386. {
  99387. return init_stream_internal_dec(
  99388. decoder,
  99389. read_callback,
  99390. seek_callback,
  99391. tell_callback,
  99392. length_callback,
  99393. eof_callback,
  99394. write_callback,
  99395. metadata_callback,
  99396. error_callback,
  99397. client_data,
  99398. /*is_ogg=*/true
  99399. );
  99400. }
  99401. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99402. FLAC__StreamDecoder *decoder,
  99403. FILE *file,
  99404. FLAC__StreamDecoderWriteCallback write_callback,
  99405. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99406. FLAC__StreamDecoderErrorCallback error_callback,
  99407. void *client_data,
  99408. FLAC__bool is_ogg
  99409. )
  99410. {
  99411. FLAC__ASSERT(0 != decoder);
  99412. FLAC__ASSERT(0 != file);
  99413. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99414. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99415. if(0 == write_callback || 0 == error_callback)
  99416. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99417. /*
  99418. * To make sure that our file does not go unclosed after an error, we
  99419. * must assign the FILE pointer before any further error can occur in
  99420. * this routine.
  99421. */
  99422. if(file == stdin)
  99423. file = get_binary_stdin_(); /* just to be safe */
  99424. decoder->private_->file = file;
  99425. return init_stream_internal_dec(
  99426. decoder,
  99427. file_read_callback_dec,
  99428. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99429. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99430. decoder->private_->file == stdin? 0: file_length_callback_,
  99431. file_eof_callback_,
  99432. write_callback,
  99433. metadata_callback,
  99434. error_callback,
  99435. client_data,
  99436. is_ogg
  99437. );
  99438. }
  99439. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99440. FLAC__StreamDecoder *decoder,
  99441. FILE *file,
  99442. FLAC__StreamDecoderWriteCallback write_callback,
  99443. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99444. FLAC__StreamDecoderErrorCallback error_callback,
  99445. void *client_data
  99446. )
  99447. {
  99448. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99449. }
  99450. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99451. FLAC__StreamDecoder *decoder,
  99452. FILE *file,
  99453. FLAC__StreamDecoderWriteCallback write_callback,
  99454. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99455. FLAC__StreamDecoderErrorCallback error_callback,
  99456. void *client_data
  99457. )
  99458. {
  99459. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99460. }
  99461. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99462. FLAC__StreamDecoder *decoder,
  99463. const char *filename,
  99464. FLAC__StreamDecoderWriteCallback write_callback,
  99465. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99466. FLAC__StreamDecoderErrorCallback error_callback,
  99467. void *client_data,
  99468. FLAC__bool is_ogg
  99469. )
  99470. {
  99471. FILE *file;
  99472. FLAC__ASSERT(0 != decoder);
  99473. /*
  99474. * To make sure that our file does not go unclosed after an error, we
  99475. * have to do the same entrance checks here that are later performed
  99476. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99477. */
  99478. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99479. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99480. if(0 == write_callback || 0 == error_callback)
  99481. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99482. file = filename? fopen(filename, "rb") : stdin;
  99483. if(0 == file)
  99484. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99485. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99486. }
  99487. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99488. FLAC__StreamDecoder *decoder,
  99489. const char *filename,
  99490. FLAC__StreamDecoderWriteCallback write_callback,
  99491. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99492. FLAC__StreamDecoderErrorCallback error_callback,
  99493. void *client_data
  99494. )
  99495. {
  99496. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99497. }
  99498. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99499. FLAC__StreamDecoder *decoder,
  99500. const char *filename,
  99501. FLAC__StreamDecoderWriteCallback write_callback,
  99502. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99503. FLAC__StreamDecoderErrorCallback error_callback,
  99504. void *client_data
  99505. )
  99506. {
  99507. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99508. }
  99509. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99510. {
  99511. FLAC__bool md5_failed = false;
  99512. unsigned i;
  99513. FLAC__ASSERT(0 != decoder);
  99514. FLAC__ASSERT(0 != decoder->private_);
  99515. FLAC__ASSERT(0 != decoder->protected_);
  99516. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99517. return true;
  99518. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99519. * always call FLAC__MD5Final()
  99520. */
  99521. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99522. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99523. free(decoder->private_->seek_table.data.seek_table.points);
  99524. decoder->private_->seek_table.data.seek_table.points = 0;
  99525. decoder->private_->has_seek_table = false;
  99526. }
  99527. FLAC__bitreader_free(decoder->private_->input);
  99528. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99529. /* WATCHOUT:
  99530. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99531. * output arrays have a buffer of up to 3 zeroes in front
  99532. * (at negative indices) for alignment purposes; we use 4
  99533. * to keep the data well-aligned.
  99534. */
  99535. if(0 != decoder->private_->output[i]) {
  99536. free(decoder->private_->output[i]-4);
  99537. decoder->private_->output[i] = 0;
  99538. }
  99539. if(0 != decoder->private_->residual_unaligned[i]) {
  99540. free(decoder->private_->residual_unaligned[i]);
  99541. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99542. }
  99543. }
  99544. decoder->private_->output_capacity = 0;
  99545. decoder->private_->output_channels = 0;
  99546. #if FLAC__HAS_OGG
  99547. if(decoder->private_->is_ogg)
  99548. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99549. #endif
  99550. if(0 != decoder->private_->file) {
  99551. if(decoder->private_->file != stdin)
  99552. fclose(decoder->private_->file);
  99553. decoder->private_->file = 0;
  99554. }
  99555. if(decoder->private_->do_md5_checking) {
  99556. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99557. md5_failed = true;
  99558. }
  99559. decoder->private_->is_seeking = false;
  99560. set_defaults_dec(decoder);
  99561. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99562. return !md5_failed;
  99563. }
  99564. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99565. {
  99566. FLAC__ASSERT(0 != decoder);
  99567. FLAC__ASSERT(0 != decoder->private_);
  99568. FLAC__ASSERT(0 != decoder->protected_);
  99569. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99570. return false;
  99571. #if FLAC__HAS_OGG
  99572. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99573. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99574. return true;
  99575. #else
  99576. (void)value;
  99577. return false;
  99578. #endif
  99579. }
  99580. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99581. {
  99582. FLAC__ASSERT(0 != decoder);
  99583. FLAC__ASSERT(0 != decoder->protected_);
  99584. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99585. return false;
  99586. decoder->protected_->md5_checking = value;
  99587. return true;
  99588. }
  99589. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99590. {
  99591. FLAC__ASSERT(0 != decoder);
  99592. FLAC__ASSERT(0 != decoder->private_);
  99593. FLAC__ASSERT(0 != decoder->protected_);
  99594. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99595. /* double protection */
  99596. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99597. return false;
  99598. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99599. return false;
  99600. decoder->private_->metadata_filter[type] = true;
  99601. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99602. decoder->private_->metadata_filter_ids_count = 0;
  99603. return true;
  99604. }
  99605. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99606. {
  99607. FLAC__ASSERT(0 != decoder);
  99608. FLAC__ASSERT(0 != decoder->private_);
  99609. FLAC__ASSERT(0 != decoder->protected_);
  99610. FLAC__ASSERT(0 != id);
  99611. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99612. return false;
  99613. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99614. return true;
  99615. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99616. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99617. 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))) {
  99618. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99619. return false;
  99620. }
  99621. decoder->private_->metadata_filter_ids_capacity *= 2;
  99622. }
  99623. 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));
  99624. decoder->private_->metadata_filter_ids_count++;
  99625. return true;
  99626. }
  99627. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99628. {
  99629. unsigned i;
  99630. FLAC__ASSERT(0 != decoder);
  99631. FLAC__ASSERT(0 != decoder->private_);
  99632. FLAC__ASSERT(0 != decoder->protected_);
  99633. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99634. return false;
  99635. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99636. decoder->private_->metadata_filter[i] = true;
  99637. decoder->private_->metadata_filter_ids_count = 0;
  99638. return true;
  99639. }
  99640. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99641. {
  99642. FLAC__ASSERT(0 != decoder);
  99643. FLAC__ASSERT(0 != decoder->private_);
  99644. FLAC__ASSERT(0 != decoder->protected_);
  99645. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99646. /* double protection */
  99647. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99648. return false;
  99649. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99650. return false;
  99651. decoder->private_->metadata_filter[type] = false;
  99652. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99653. decoder->private_->metadata_filter_ids_count = 0;
  99654. return true;
  99655. }
  99656. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99657. {
  99658. FLAC__ASSERT(0 != decoder);
  99659. FLAC__ASSERT(0 != decoder->private_);
  99660. FLAC__ASSERT(0 != decoder->protected_);
  99661. FLAC__ASSERT(0 != id);
  99662. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99663. return false;
  99664. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99665. return true;
  99666. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99667. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99668. 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))) {
  99669. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99670. return false;
  99671. }
  99672. decoder->private_->metadata_filter_ids_capacity *= 2;
  99673. }
  99674. 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));
  99675. decoder->private_->metadata_filter_ids_count++;
  99676. return true;
  99677. }
  99678. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99679. {
  99680. FLAC__ASSERT(0 != decoder);
  99681. FLAC__ASSERT(0 != decoder->private_);
  99682. FLAC__ASSERT(0 != decoder->protected_);
  99683. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99684. return false;
  99685. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99686. decoder->private_->metadata_filter_ids_count = 0;
  99687. return true;
  99688. }
  99689. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99690. {
  99691. FLAC__ASSERT(0 != decoder);
  99692. FLAC__ASSERT(0 != decoder->protected_);
  99693. return decoder->protected_->state;
  99694. }
  99695. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99696. {
  99697. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99698. }
  99699. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99700. {
  99701. FLAC__ASSERT(0 != decoder);
  99702. FLAC__ASSERT(0 != decoder->protected_);
  99703. return decoder->protected_->md5_checking;
  99704. }
  99705. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99706. {
  99707. FLAC__ASSERT(0 != decoder);
  99708. FLAC__ASSERT(0 != decoder->protected_);
  99709. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99710. }
  99711. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99712. {
  99713. FLAC__ASSERT(0 != decoder);
  99714. FLAC__ASSERT(0 != decoder->protected_);
  99715. return decoder->protected_->channels;
  99716. }
  99717. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99718. {
  99719. FLAC__ASSERT(0 != decoder);
  99720. FLAC__ASSERT(0 != decoder->protected_);
  99721. return decoder->protected_->channel_assignment;
  99722. }
  99723. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99724. {
  99725. FLAC__ASSERT(0 != decoder);
  99726. FLAC__ASSERT(0 != decoder->protected_);
  99727. return decoder->protected_->bits_per_sample;
  99728. }
  99729. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99730. {
  99731. FLAC__ASSERT(0 != decoder);
  99732. FLAC__ASSERT(0 != decoder->protected_);
  99733. return decoder->protected_->sample_rate;
  99734. }
  99735. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99736. {
  99737. FLAC__ASSERT(0 != decoder);
  99738. FLAC__ASSERT(0 != decoder->protected_);
  99739. return decoder->protected_->blocksize;
  99740. }
  99741. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99742. {
  99743. FLAC__ASSERT(0 != decoder);
  99744. FLAC__ASSERT(0 != decoder->private_);
  99745. FLAC__ASSERT(0 != position);
  99746. #if FLAC__HAS_OGG
  99747. if(decoder->private_->is_ogg)
  99748. return false;
  99749. #endif
  99750. if(0 == decoder->private_->tell_callback)
  99751. return false;
  99752. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99753. return false;
  99754. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99755. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99756. return false;
  99757. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99758. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99759. return true;
  99760. }
  99761. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99762. {
  99763. FLAC__ASSERT(0 != decoder);
  99764. FLAC__ASSERT(0 != decoder->private_);
  99765. FLAC__ASSERT(0 != decoder->protected_);
  99766. decoder->private_->samples_decoded = 0;
  99767. decoder->private_->do_md5_checking = false;
  99768. #if FLAC__HAS_OGG
  99769. if(decoder->private_->is_ogg)
  99770. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99771. #endif
  99772. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99773. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99774. return false;
  99775. }
  99776. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99777. return true;
  99778. }
  99779. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99780. {
  99781. FLAC__ASSERT(0 != decoder);
  99782. FLAC__ASSERT(0 != decoder->private_);
  99783. FLAC__ASSERT(0 != decoder->protected_);
  99784. if(!FLAC__stream_decoder_flush(decoder)) {
  99785. /* above call sets the state for us */
  99786. return false;
  99787. }
  99788. #if FLAC__HAS_OGG
  99789. /*@@@ could go in !internal_reset_hack block below */
  99790. if(decoder->private_->is_ogg)
  99791. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99792. #endif
  99793. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99794. * (internal_reset_hack) don't try to rewind since we are already at
  99795. * the beginning of the stream and don't want to fail if the input is
  99796. * not seekable.
  99797. */
  99798. if(!decoder->private_->internal_reset_hack) {
  99799. if(decoder->private_->file == stdin)
  99800. return false; /* can't rewind stdin, reset fails */
  99801. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99802. return false; /* seekable and seek fails, reset fails */
  99803. }
  99804. else
  99805. decoder->private_->internal_reset_hack = false;
  99806. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99807. decoder->private_->has_stream_info = false;
  99808. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99809. free(decoder->private_->seek_table.data.seek_table.points);
  99810. decoder->private_->seek_table.data.seek_table.points = 0;
  99811. decoder->private_->has_seek_table = false;
  99812. }
  99813. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99814. /*
  99815. * This goes in reset() and not flush() because according to the spec, a
  99816. * fixed-blocksize stream must stay that way through the whole stream.
  99817. */
  99818. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99819. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99820. * is because md5 checking may be turned on to start and then turned off if
  99821. * a seek occurs. So we init the context here and finalize it in
  99822. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99823. * properly.
  99824. */
  99825. FLAC__MD5Init(&decoder->private_->md5context);
  99826. decoder->private_->first_frame_offset = 0;
  99827. decoder->private_->unparseable_frame_count = 0;
  99828. return true;
  99829. }
  99830. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99831. {
  99832. FLAC__bool got_a_frame;
  99833. FLAC__ASSERT(0 != decoder);
  99834. FLAC__ASSERT(0 != decoder->protected_);
  99835. while(1) {
  99836. switch(decoder->protected_->state) {
  99837. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99838. if(!find_metadata_(decoder))
  99839. return false; /* above function sets the status for us */
  99840. break;
  99841. case FLAC__STREAM_DECODER_READ_METADATA:
  99842. if(!read_metadata_(decoder))
  99843. return false; /* above function sets the status for us */
  99844. else
  99845. return true;
  99846. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99847. if(!frame_sync_(decoder))
  99848. return true; /* above function sets the status for us */
  99849. break;
  99850. case FLAC__STREAM_DECODER_READ_FRAME:
  99851. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99852. return false; /* above function sets the status for us */
  99853. if(got_a_frame)
  99854. return true; /* above function sets the status for us */
  99855. break;
  99856. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99857. case FLAC__STREAM_DECODER_ABORTED:
  99858. return true;
  99859. default:
  99860. FLAC__ASSERT(0);
  99861. return false;
  99862. }
  99863. }
  99864. }
  99865. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99866. {
  99867. FLAC__ASSERT(0 != decoder);
  99868. FLAC__ASSERT(0 != decoder->protected_);
  99869. while(1) {
  99870. switch(decoder->protected_->state) {
  99871. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99872. if(!find_metadata_(decoder))
  99873. return false; /* above function sets the status for us */
  99874. break;
  99875. case FLAC__STREAM_DECODER_READ_METADATA:
  99876. if(!read_metadata_(decoder))
  99877. return false; /* above function sets the status for us */
  99878. break;
  99879. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99880. case FLAC__STREAM_DECODER_READ_FRAME:
  99881. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99882. case FLAC__STREAM_DECODER_ABORTED:
  99883. return true;
  99884. default:
  99885. FLAC__ASSERT(0);
  99886. return false;
  99887. }
  99888. }
  99889. }
  99890. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99891. {
  99892. FLAC__bool dummy;
  99893. FLAC__ASSERT(0 != decoder);
  99894. FLAC__ASSERT(0 != decoder->protected_);
  99895. while(1) {
  99896. switch(decoder->protected_->state) {
  99897. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99898. if(!find_metadata_(decoder))
  99899. return false; /* above function sets the status for us */
  99900. break;
  99901. case FLAC__STREAM_DECODER_READ_METADATA:
  99902. if(!read_metadata_(decoder))
  99903. return false; /* above function sets the status for us */
  99904. break;
  99905. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99906. if(!frame_sync_(decoder))
  99907. return true; /* above function sets the status for us */
  99908. break;
  99909. case FLAC__STREAM_DECODER_READ_FRAME:
  99910. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99911. return false; /* above function sets the status for us */
  99912. break;
  99913. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99914. case FLAC__STREAM_DECODER_ABORTED:
  99915. return true;
  99916. default:
  99917. FLAC__ASSERT(0);
  99918. return false;
  99919. }
  99920. }
  99921. }
  99922. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99923. {
  99924. FLAC__bool got_a_frame;
  99925. FLAC__ASSERT(0 != decoder);
  99926. FLAC__ASSERT(0 != decoder->protected_);
  99927. while(1) {
  99928. switch(decoder->protected_->state) {
  99929. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99930. case FLAC__STREAM_DECODER_READ_METADATA:
  99931. return false; /* above function sets the status for us */
  99932. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99933. if(!frame_sync_(decoder))
  99934. return true; /* above function sets the status for us */
  99935. break;
  99936. case FLAC__STREAM_DECODER_READ_FRAME:
  99937. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99938. return false; /* above function sets the status for us */
  99939. if(got_a_frame)
  99940. return true; /* above function sets the status for us */
  99941. break;
  99942. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99943. case FLAC__STREAM_DECODER_ABORTED:
  99944. return true;
  99945. default:
  99946. FLAC__ASSERT(0);
  99947. return false;
  99948. }
  99949. }
  99950. }
  99951. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99952. {
  99953. FLAC__uint64 length;
  99954. FLAC__ASSERT(0 != decoder);
  99955. if(
  99956. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99957. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99958. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99959. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99960. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99961. )
  99962. return false;
  99963. if(0 == decoder->private_->seek_callback)
  99964. return false;
  99965. FLAC__ASSERT(decoder->private_->seek_callback);
  99966. FLAC__ASSERT(decoder->private_->tell_callback);
  99967. FLAC__ASSERT(decoder->private_->length_callback);
  99968. FLAC__ASSERT(decoder->private_->eof_callback);
  99969. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99970. return false;
  99971. decoder->private_->is_seeking = true;
  99972. /* turn off md5 checking if a seek is attempted */
  99973. decoder->private_->do_md5_checking = false;
  99974. /* 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) */
  99975. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99976. decoder->private_->is_seeking = false;
  99977. return false;
  99978. }
  99979. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99980. if(
  99981. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99982. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99983. ) {
  99984. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99985. /* above call sets the state for us */
  99986. decoder->private_->is_seeking = false;
  99987. return false;
  99988. }
  99989. /* check this again in case we didn't know total_samples the first time */
  99990. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99991. decoder->private_->is_seeking = false;
  99992. return false;
  99993. }
  99994. }
  99995. {
  99996. const FLAC__bool ok =
  99997. #if FLAC__HAS_OGG
  99998. decoder->private_->is_ogg?
  99999. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100000. #endif
  100001. seek_to_absolute_sample_(decoder, length, sample)
  100002. ;
  100003. decoder->private_->is_seeking = false;
  100004. return ok;
  100005. }
  100006. }
  100007. /***********************************************************************
  100008. *
  100009. * Protected class methods
  100010. *
  100011. ***********************************************************************/
  100012. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100013. {
  100014. FLAC__ASSERT(0 != decoder);
  100015. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100016. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100017. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100018. }
  100019. /***********************************************************************
  100020. *
  100021. * Private class methods
  100022. *
  100023. ***********************************************************************/
  100024. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100025. {
  100026. #if FLAC__HAS_OGG
  100027. decoder->private_->is_ogg = false;
  100028. #endif
  100029. decoder->private_->read_callback = 0;
  100030. decoder->private_->seek_callback = 0;
  100031. decoder->private_->tell_callback = 0;
  100032. decoder->private_->length_callback = 0;
  100033. decoder->private_->eof_callback = 0;
  100034. decoder->private_->write_callback = 0;
  100035. decoder->private_->metadata_callback = 0;
  100036. decoder->private_->error_callback = 0;
  100037. decoder->private_->client_data = 0;
  100038. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100039. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100040. decoder->private_->metadata_filter_ids_count = 0;
  100041. decoder->protected_->md5_checking = false;
  100042. #if FLAC__HAS_OGG
  100043. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100044. #endif
  100045. }
  100046. /*
  100047. * This will forcibly set stdin to binary mode (for OSes that require it)
  100048. */
  100049. FILE *get_binary_stdin_(void)
  100050. {
  100051. /* if something breaks here it is probably due to the presence or
  100052. * absence of an underscore before the identifiers 'setmode',
  100053. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100054. */
  100055. #if defined _MSC_VER || defined __MINGW32__
  100056. _setmode(_fileno(stdin), _O_BINARY);
  100057. #elif defined __CYGWIN__
  100058. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100059. setmode(_fileno(stdin), _O_BINARY);
  100060. #elif defined __EMX__
  100061. setmode(fileno(stdin), O_BINARY);
  100062. #endif
  100063. return stdin;
  100064. }
  100065. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100066. {
  100067. unsigned i;
  100068. FLAC__int32 *tmp;
  100069. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100070. return true;
  100071. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100072. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100073. if(0 != decoder->private_->output[i]) {
  100074. free(decoder->private_->output[i]-4);
  100075. decoder->private_->output[i] = 0;
  100076. }
  100077. if(0 != decoder->private_->residual_unaligned[i]) {
  100078. free(decoder->private_->residual_unaligned[i]);
  100079. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100080. }
  100081. }
  100082. for(i = 0; i < channels; i++) {
  100083. /* WATCHOUT:
  100084. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100085. * output arrays have a buffer of up to 3 zeroes in front
  100086. * (at negative indices) for alignment purposes; we use 4
  100087. * to keep the data well-aligned.
  100088. */
  100089. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100090. if(tmp == 0) {
  100091. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100092. return false;
  100093. }
  100094. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100095. decoder->private_->output[i] = tmp + 4;
  100096. /* WATCHOUT:
  100097. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100098. */
  100099. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100100. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100101. return false;
  100102. }
  100103. }
  100104. decoder->private_->output_capacity = size;
  100105. decoder->private_->output_channels = channels;
  100106. return true;
  100107. }
  100108. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100109. {
  100110. size_t i;
  100111. FLAC__ASSERT(0 != decoder);
  100112. FLAC__ASSERT(0 != decoder->private_);
  100113. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100114. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100115. return true;
  100116. return false;
  100117. }
  100118. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100119. {
  100120. FLAC__uint32 x;
  100121. unsigned i, id_;
  100122. FLAC__bool first = true;
  100123. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100124. for(i = id_ = 0; i < 4; ) {
  100125. if(decoder->private_->cached) {
  100126. x = (FLAC__uint32)decoder->private_->lookahead;
  100127. decoder->private_->cached = false;
  100128. }
  100129. else {
  100130. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100131. return false; /* read_callback_ sets the state for us */
  100132. }
  100133. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100134. first = true;
  100135. i++;
  100136. id_ = 0;
  100137. continue;
  100138. }
  100139. if(x == ID3V2_TAG_[id_]) {
  100140. id_++;
  100141. i = 0;
  100142. if(id_ == 3) {
  100143. if(!skip_id3v2_tag_(decoder))
  100144. return false; /* skip_id3v2_tag_ sets the state for us */
  100145. }
  100146. continue;
  100147. }
  100148. id_ = 0;
  100149. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100150. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100151. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100152. return false; /* read_callback_ sets the state for us */
  100153. /* 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 */
  100154. /* else we have to check if the second byte is the end of a sync code */
  100155. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100156. decoder->private_->lookahead = (FLAC__byte)x;
  100157. decoder->private_->cached = true;
  100158. }
  100159. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100160. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100161. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100162. return true;
  100163. }
  100164. }
  100165. i = 0;
  100166. if(first) {
  100167. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100168. first = false;
  100169. }
  100170. }
  100171. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100172. return true;
  100173. }
  100174. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100175. {
  100176. FLAC__bool is_last;
  100177. FLAC__uint32 i, x, type, length;
  100178. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100179. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100180. return false; /* read_callback_ sets the state for us */
  100181. is_last = x? true : false;
  100182. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100183. return false; /* read_callback_ sets the state for us */
  100184. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100185. return false; /* read_callback_ sets the state for us */
  100186. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100187. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100188. return false;
  100189. decoder->private_->has_stream_info = true;
  100190. 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))
  100191. decoder->private_->do_md5_checking = false;
  100192. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100193. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100194. }
  100195. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100196. if(!read_metadata_seektable_(decoder, is_last, length))
  100197. return false;
  100198. decoder->private_->has_seek_table = true;
  100199. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100200. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100201. }
  100202. else {
  100203. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100204. unsigned real_length = length;
  100205. FLAC__StreamMetadata block;
  100206. block.is_last = is_last;
  100207. block.type = (FLAC__MetadataType)type;
  100208. block.length = length;
  100209. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100210. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100211. return false; /* read_callback_ sets the state for us */
  100212. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100213. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100214. return false;
  100215. }
  100216. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100217. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100218. skip_it = !skip_it;
  100219. }
  100220. if(skip_it) {
  100221. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100222. return false; /* read_callback_ sets the state for us */
  100223. }
  100224. else {
  100225. switch(type) {
  100226. case FLAC__METADATA_TYPE_PADDING:
  100227. /* skip the padding bytes */
  100228. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100229. return false; /* read_callback_ sets the state for us */
  100230. break;
  100231. case FLAC__METADATA_TYPE_APPLICATION:
  100232. /* remember, we read the ID already */
  100233. if(real_length > 0) {
  100234. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100235. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100236. return false;
  100237. }
  100238. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100239. return false; /* read_callback_ sets the state for us */
  100240. }
  100241. else
  100242. block.data.application.data = 0;
  100243. break;
  100244. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100245. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100246. return false;
  100247. break;
  100248. case FLAC__METADATA_TYPE_CUESHEET:
  100249. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100250. return false;
  100251. break;
  100252. case FLAC__METADATA_TYPE_PICTURE:
  100253. if(!read_metadata_picture_(decoder, &block.data.picture))
  100254. return false;
  100255. break;
  100256. case FLAC__METADATA_TYPE_STREAMINFO:
  100257. case FLAC__METADATA_TYPE_SEEKTABLE:
  100258. FLAC__ASSERT(0);
  100259. break;
  100260. default:
  100261. if(real_length > 0) {
  100262. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100263. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100264. return false;
  100265. }
  100266. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100267. return false; /* read_callback_ sets the state for us */
  100268. }
  100269. else
  100270. block.data.unknown.data = 0;
  100271. break;
  100272. }
  100273. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100274. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100275. /* now we have to free any malloc()ed data in the block */
  100276. switch(type) {
  100277. case FLAC__METADATA_TYPE_PADDING:
  100278. break;
  100279. case FLAC__METADATA_TYPE_APPLICATION:
  100280. if(0 != block.data.application.data)
  100281. free(block.data.application.data);
  100282. break;
  100283. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100284. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100285. free(block.data.vorbis_comment.vendor_string.entry);
  100286. if(block.data.vorbis_comment.num_comments > 0)
  100287. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100288. if(0 != block.data.vorbis_comment.comments[i].entry)
  100289. free(block.data.vorbis_comment.comments[i].entry);
  100290. if(0 != block.data.vorbis_comment.comments)
  100291. free(block.data.vorbis_comment.comments);
  100292. break;
  100293. case FLAC__METADATA_TYPE_CUESHEET:
  100294. if(block.data.cue_sheet.num_tracks > 0)
  100295. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100296. if(0 != block.data.cue_sheet.tracks[i].indices)
  100297. free(block.data.cue_sheet.tracks[i].indices);
  100298. if(0 != block.data.cue_sheet.tracks)
  100299. free(block.data.cue_sheet.tracks);
  100300. break;
  100301. case FLAC__METADATA_TYPE_PICTURE:
  100302. if(0 != block.data.picture.mime_type)
  100303. free(block.data.picture.mime_type);
  100304. if(0 != block.data.picture.description)
  100305. free(block.data.picture.description);
  100306. if(0 != block.data.picture.data)
  100307. free(block.data.picture.data);
  100308. break;
  100309. case FLAC__METADATA_TYPE_STREAMINFO:
  100310. case FLAC__METADATA_TYPE_SEEKTABLE:
  100311. FLAC__ASSERT(0);
  100312. default:
  100313. if(0 != block.data.unknown.data)
  100314. free(block.data.unknown.data);
  100315. break;
  100316. }
  100317. }
  100318. }
  100319. if(is_last) {
  100320. /* if this fails, it's OK, it's just a hint for the seek routine */
  100321. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100322. decoder->private_->first_frame_offset = 0;
  100323. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100324. }
  100325. return true;
  100326. }
  100327. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100328. {
  100329. FLAC__uint32 x;
  100330. unsigned bits, used_bits = 0;
  100331. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100332. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100333. decoder->private_->stream_info.is_last = is_last;
  100334. decoder->private_->stream_info.length = length;
  100335. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100336. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100337. return false; /* read_callback_ sets the state for us */
  100338. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100339. used_bits += bits;
  100340. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100341. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100342. return false; /* read_callback_ sets the state for us */
  100343. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100344. used_bits += bits;
  100345. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100346. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100347. return false; /* read_callback_ sets the state for us */
  100348. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100349. used_bits += bits;
  100350. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100351. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100352. return false; /* read_callback_ sets the state for us */
  100353. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100354. used_bits += bits;
  100355. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100356. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100357. return false; /* read_callback_ sets the state for us */
  100358. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100359. used_bits += bits;
  100360. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100361. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100362. return false; /* read_callback_ sets the state for us */
  100363. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100364. used_bits += bits;
  100365. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100366. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100367. return false; /* read_callback_ sets the state for us */
  100368. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100369. used_bits += bits;
  100370. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100371. 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))
  100372. return false; /* read_callback_ sets the state for us */
  100373. used_bits += bits;
  100374. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100375. return false; /* read_callback_ sets the state for us */
  100376. used_bits += 16*8;
  100377. /* skip the rest of the block */
  100378. FLAC__ASSERT(used_bits % 8 == 0);
  100379. length -= (used_bits / 8);
  100380. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100381. return false; /* read_callback_ sets the state for us */
  100382. return true;
  100383. }
  100384. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100385. {
  100386. FLAC__uint32 i, x;
  100387. FLAC__uint64 xx;
  100388. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100389. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100390. decoder->private_->seek_table.is_last = is_last;
  100391. decoder->private_->seek_table.length = length;
  100392. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100393. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100394. 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)))) {
  100395. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100396. return false;
  100397. }
  100398. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100399. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100400. return false; /* read_callback_ sets the state for us */
  100401. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100402. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100403. return false; /* read_callback_ sets the state for us */
  100404. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100405. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100406. return false; /* read_callback_ sets the state for us */
  100407. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100408. }
  100409. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100410. /* if there is a partial point left, skip over it */
  100411. if(length > 0) {
  100412. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100413. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100414. return false; /* read_callback_ sets the state for us */
  100415. }
  100416. return true;
  100417. }
  100418. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100419. {
  100420. FLAC__uint32 i;
  100421. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100422. /* read vendor string */
  100423. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100424. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100425. return false; /* read_callback_ sets the state for us */
  100426. if(obj->vendor_string.length > 0) {
  100427. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100428. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100429. return false;
  100430. }
  100431. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100432. return false; /* read_callback_ sets the state for us */
  100433. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100434. }
  100435. else
  100436. obj->vendor_string.entry = 0;
  100437. /* read num comments */
  100438. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100439. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100440. return false; /* read_callback_ sets the state for us */
  100441. /* read comments */
  100442. if(obj->num_comments > 0) {
  100443. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100444. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100445. return false;
  100446. }
  100447. for(i = 0; i < obj->num_comments; i++) {
  100448. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100449. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100450. return false; /* read_callback_ sets the state for us */
  100451. if(obj->comments[i].length > 0) {
  100452. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100453. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100454. return false;
  100455. }
  100456. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100457. return false; /* read_callback_ sets the state for us */
  100458. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100459. }
  100460. else
  100461. obj->comments[i].entry = 0;
  100462. }
  100463. }
  100464. else {
  100465. obj->comments = 0;
  100466. }
  100467. return true;
  100468. }
  100469. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100470. {
  100471. FLAC__uint32 i, j, x;
  100472. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100473. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100474. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100475. 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))
  100476. return false; /* read_callback_ sets the state for us */
  100477. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100478. return false; /* read_callback_ sets the state for us */
  100479. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100480. return false; /* read_callback_ sets the state for us */
  100481. obj->is_cd = x? true : false;
  100482. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100483. return false; /* read_callback_ sets the state for us */
  100484. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100485. return false; /* read_callback_ sets the state for us */
  100486. obj->num_tracks = x;
  100487. if(obj->num_tracks > 0) {
  100488. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100489. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100490. return false;
  100491. }
  100492. for(i = 0; i < obj->num_tracks; i++) {
  100493. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100494. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100495. return false; /* read_callback_ sets the state for us */
  100496. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100497. return false; /* read_callback_ sets the state for us */
  100498. track->number = (FLAC__byte)x;
  100499. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100500. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100501. return false; /* read_callback_ sets the state for us */
  100502. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100503. return false; /* read_callback_ sets the state for us */
  100504. track->type = x;
  100505. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100506. return false; /* read_callback_ sets the state for us */
  100507. track->pre_emphasis = x;
  100508. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100509. return false; /* read_callback_ sets the state for us */
  100510. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100511. return false; /* read_callback_ sets the state for us */
  100512. track->num_indices = (FLAC__byte)x;
  100513. if(track->num_indices > 0) {
  100514. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100515. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100516. return false;
  100517. }
  100518. for(j = 0; j < track->num_indices; j++) {
  100519. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100520. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100521. return false; /* read_callback_ sets the state for us */
  100522. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100523. return false; /* read_callback_ sets the state for us */
  100524. index->number = (FLAC__byte)x;
  100525. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100526. return false; /* read_callback_ sets the state for us */
  100527. }
  100528. }
  100529. }
  100530. }
  100531. return true;
  100532. }
  100533. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100534. {
  100535. FLAC__uint32 x;
  100536. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100537. /* read type */
  100538. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100539. return false; /* read_callback_ sets the state for us */
  100540. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100541. /* read MIME type */
  100542. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100543. return false; /* read_callback_ sets the state for us */
  100544. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100545. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100546. return false;
  100547. }
  100548. if(x > 0) {
  100549. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100550. return false; /* read_callback_ sets the state for us */
  100551. }
  100552. obj->mime_type[x] = '\0';
  100553. /* read description */
  100554. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100555. return false; /* read_callback_ sets the state for us */
  100556. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100557. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100558. return false;
  100559. }
  100560. if(x > 0) {
  100561. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100562. return false; /* read_callback_ sets the state for us */
  100563. }
  100564. obj->description[x] = '\0';
  100565. /* read width */
  100566. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100567. return false; /* read_callback_ sets the state for us */
  100568. /* read height */
  100569. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100570. return false; /* read_callback_ sets the state for us */
  100571. /* read depth */
  100572. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100573. return false; /* read_callback_ sets the state for us */
  100574. /* read colors */
  100575. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100576. return false; /* read_callback_ sets the state for us */
  100577. /* read data */
  100578. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100579. return false; /* read_callback_ sets the state for us */
  100580. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100581. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100582. return false;
  100583. }
  100584. if(obj->data_length > 0) {
  100585. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100586. return false; /* read_callback_ sets the state for us */
  100587. }
  100588. return true;
  100589. }
  100590. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100591. {
  100592. FLAC__uint32 x;
  100593. unsigned i, skip;
  100594. /* skip the version and flags bytes */
  100595. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100596. return false; /* read_callback_ sets the state for us */
  100597. /* get the size (in bytes) to skip */
  100598. skip = 0;
  100599. for(i = 0; i < 4; i++) {
  100600. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100601. return false; /* read_callback_ sets the state for us */
  100602. skip <<= 7;
  100603. skip |= (x & 0x7f);
  100604. }
  100605. /* skip the rest of the tag */
  100606. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100607. return false; /* read_callback_ sets the state for us */
  100608. return true;
  100609. }
  100610. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100611. {
  100612. FLAC__uint32 x;
  100613. FLAC__bool first = true;
  100614. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100615. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100616. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100617. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100618. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100619. return true;
  100620. }
  100621. }
  100622. /* make sure we're byte aligned */
  100623. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100624. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100625. return false; /* read_callback_ sets the state for us */
  100626. }
  100627. while(1) {
  100628. if(decoder->private_->cached) {
  100629. x = (FLAC__uint32)decoder->private_->lookahead;
  100630. decoder->private_->cached = false;
  100631. }
  100632. else {
  100633. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100634. return false; /* read_callback_ sets the state for us */
  100635. }
  100636. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100637. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100638. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100639. return false; /* read_callback_ sets the state for us */
  100640. /* 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 */
  100641. /* else we have to check if the second byte is the end of a sync code */
  100642. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100643. decoder->private_->lookahead = (FLAC__byte)x;
  100644. decoder->private_->cached = true;
  100645. }
  100646. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100647. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100648. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100649. return true;
  100650. }
  100651. }
  100652. if(first) {
  100653. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100654. first = false;
  100655. }
  100656. }
  100657. return true;
  100658. }
  100659. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100660. {
  100661. unsigned channel;
  100662. unsigned i;
  100663. FLAC__int32 mid, side;
  100664. unsigned frame_crc; /* the one we calculate from the input stream */
  100665. FLAC__uint32 x;
  100666. *got_a_frame = false;
  100667. /* init the CRC */
  100668. frame_crc = 0;
  100669. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100670. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100671. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100672. if(!read_frame_header_(decoder))
  100673. return false;
  100674. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100675. return true;
  100676. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100677. return false;
  100678. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100679. /*
  100680. * first figure the correct bits-per-sample of the subframe
  100681. */
  100682. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100683. switch(decoder->private_->frame.header.channel_assignment) {
  100684. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100685. /* no adjustment needed */
  100686. break;
  100687. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100688. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100689. if(channel == 1)
  100690. bps++;
  100691. break;
  100692. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100693. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100694. if(channel == 0)
  100695. bps++;
  100696. break;
  100697. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100698. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100699. if(channel == 1)
  100700. bps++;
  100701. break;
  100702. default:
  100703. FLAC__ASSERT(0);
  100704. }
  100705. /*
  100706. * now read it
  100707. */
  100708. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100709. return false;
  100710. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100711. return true;
  100712. }
  100713. if(!read_zero_padding_(decoder))
  100714. return false;
  100715. 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) */
  100716. return true;
  100717. /*
  100718. * Read the frame CRC-16 from the footer and check
  100719. */
  100720. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100721. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100722. return false; /* read_callback_ sets the state for us */
  100723. if(frame_crc == x) {
  100724. if(do_full_decode) {
  100725. /* Undo any special channel coding */
  100726. switch(decoder->private_->frame.header.channel_assignment) {
  100727. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100728. /* do nothing */
  100729. break;
  100730. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100731. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100732. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100733. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100734. break;
  100735. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100736. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100737. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100738. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100739. break;
  100740. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100741. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100742. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100743. #if 1
  100744. mid = decoder->private_->output[0][i];
  100745. side = decoder->private_->output[1][i];
  100746. mid <<= 1;
  100747. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100748. decoder->private_->output[0][i] = (mid + side) >> 1;
  100749. decoder->private_->output[1][i] = (mid - side) >> 1;
  100750. #else
  100751. /* OPT: without 'side' temp variable */
  100752. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100753. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100754. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100755. #endif
  100756. }
  100757. break;
  100758. default:
  100759. FLAC__ASSERT(0);
  100760. break;
  100761. }
  100762. }
  100763. }
  100764. else {
  100765. /* Bad frame, emit error and zero the output signal */
  100766. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100767. if(do_full_decode) {
  100768. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100769. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100770. }
  100771. }
  100772. }
  100773. *got_a_frame = true;
  100774. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100775. if(decoder->private_->next_fixed_block_size)
  100776. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100777. /* put the latest values into the public section of the decoder instance */
  100778. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100779. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100780. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100781. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100782. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100783. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100784. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100785. /* write it */
  100786. if(do_full_decode) {
  100787. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100788. return false;
  100789. }
  100790. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100791. return true;
  100792. }
  100793. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100794. {
  100795. FLAC__uint32 x;
  100796. FLAC__uint64 xx;
  100797. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100798. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100799. unsigned raw_header_len;
  100800. FLAC__bool is_unparseable = false;
  100801. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100802. /* init the raw header with the saved bits from synchronization */
  100803. raw_header[0] = decoder->private_->header_warmup[0];
  100804. raw_header[1] = decoder->private_->header_warmup[1];
  100805. raw_header_len = 2;
  100806. /* check to make sure that reserved bit is 0 */
  100807. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100808. is_unparseable = true;
  100809. /*
  100810. * Note that along the way as we read the header, we look for a sync
  100811. * code inside. If we find one it would indicate that our original
  100812. * sync was bad since there cannot be a sync code in a valid header.
  100813. *
  100814. * Three kinds of things can go wrong when reading the frame header:
  100815. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100816. * If we don't find a sync code, it can end up looking like we read
  100817. * a valid but unparseable header, until getting to the frame header
  100818. * CRC. Even then we could get a false positive on the CRC.
  100819. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100820. * future encoder).
  100821. * 3) We may be on a damaged frame which appears valid but unparseable.
  100822. *
  100823. * For all these reasons, we try and read a complete frame header as
  100824. * long as it seems valid, even if unparseable, up until the frame
  100825. * header CRC.
  100826. */
  100827. /*
  100828. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100829. */
  100830. for(i = 0; i < 2; i++) {
  100831. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100832. return false; /* read_callback_ sets the state for us */
  100833. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100834. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100835. decoder->private_->lookahead = (FLAC__byte)x;
  100836. decoder->private_->cached = true;
  100837. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100838. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100839. return true;
  100840. }
  100841. raw_header[raw_header_len++] = (FLAC__byte)x;
  100842. }
  100843. switch(x = raw_header[2] >> 4) {
  100844. case 0:
  100845. is_unparseable = true;
  100846. break;
  100847. case 1:
  100848. decoder->private_->frame.header.blocksize = 192;
  100849. break;
  100850. case 2:
  100851. case 3:
  100852. case 4:
  100853. case 5:
  100854. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100855. break;
  100856. case 6:
  100857. case 7:
  100858. blocksize_hint = x;
  100859. break;
  100860. case 8:
  100861. case 9:
  100862. case 10:
  100863. case 11:
  100864. case 12:
  100865. case 13:
  100866. case 14:
  100867. case 15:
  100868. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100869. break;
  100870. default:
  100871. FLAC__ASSERT(0);
  100872. break;
  100873. }
  100874. switch(x = raw_header[2] & 0x0f) {
  100875. case 0:
  100876. if(decoder->private_->has_stream_info)
  100877. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100878. else
  100879. is_unparseable = true;
  100880. break;
  100881. case 1:
  100882. decoder->private_->frame.header.sample_rate = 88200;
  100883. break;
  100884. case 2:
  100885. decoder->private_->frame.header.sample_rate = 176400;
  100886. break;
  100887. case 3:
  100888. decoder->private_->frame.header.sample_rate = 192000;
  100889. break;
  100890. case 4:
  100891. decoder->private_->frame.header.sample_rate = 8000;
  100892. break;
  100893. case 5:
  100894. decoder->private_->frame.header.sample_rate = 16000;
  100895. break;
  100896. case 6:
  100897. decoder->private_->frame.header.sample_rate = 22050;
  100898. break;
  100899. case 7:
  100900. decoder->private_->frame.header.sample_rate = 24000;
  100901. break;
  100902. case 8:
  100903. decoder->private_->frame.header.sample_rate = 32000;
  100904. break;
  100905. case 9:
  100906. decoder->private_->frame.header.sample_rate = 44100;
  100907. break;
  100908. case 10:
  100909. decoder->private_->frame.header.sample_rate = 48000;
  100910. break;
  100911. case 11:
  100912. decoder->private_->frame.header.sample_rate = 96000;
  100913. break;
  100914. case 12:
  100915. case 13:
  100916. case 14:
  100917. sample_rate_hint = x;
  100918. break;
  100919. case 15:
  100920. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100921. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100922. return true;
  100923. default:
  100924. FLAC__ASSERT(0);
  100925. }
  100926. x = (unsigned)(raw_header[3] >> 4);
  100927. if(x & 8) {
  100928. decoder->private_->frame.header.channels = 2;
  100929. switch(x & 7) {
  100930. case 0:
  100931. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100932. break;
  100933. case 1:
  100934. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100935. break;
  100936. case 2:
  100937. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100938. break;
  100939. default:
  100940. is_unparseable = true;
  100941. break;
  100942. }
  100943. }
  100944. else {
  100945. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100946. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100947. }
  100948. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100949. case 0:
  100950. if(decoder->private_->has_stream_info)
  100951. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100952. else
  100953. is_unparseable = true;
  100954. break;
  100955. case 1:
  100956. decoder->private_->frame.header.bits_per_sample = 8;
  100957. break;
  100958. case 2:
  100959. decoder->private_->frame.header.bits_per_sample = 12;
  100960. break;
  100961. case 4:
  100962. decoder->private_->frame.header.bits_per_sample = 16;
  100963. break;
  100964. case 5:
  100965. decoder->private_->frame.header.bits_per_sample = 20;
  100966. break;
  100967. case 6:
  100968. decoder->private_->frame.header.bits_per_sample = 24;
  100969. break;
  100970. case 3:
  100971. case 7:
  100972. is_unparseable = true;
  100973. break;
  100974. default:
  100975. FLAC__ASSERT(0);
  100976. break;
  100977. }
  100978. /* check to make sure that reserved bit is 0 */
  100979. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100980. is_unparseable = true;
  100981. /* read the frame's starting sample number (or frame number as the case may be) */
  100982. if(
  100983. raw_header[1] & 0x01 ||
  100984. /*@@@ 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 */
  100985. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100986. ) { /* variable blocksize */
  100987. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100988. return false; /* read_callback_ sets the state for us */
  100989. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100990. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100991. decoder->private_->cached = true;
  100992. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100993. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100994. return true;
  100995. }
  100996. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100997. decoder->private_->frame.header.number.sample_number = xx;
  100998. }
  100999. else { /* fixed blocksize */
  101000. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101001. return false; /* read_callback_ sets the state for us */
  101002. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101003. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101004. decoder->private_->cached = true;
  101005. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101006. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101007. return true;
  101008. }
  101009. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101010. decoder->private_->frame.header.number.frame_number = x;
  101011. }
  101012. if(blocksize_hint) {
  101013. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101014. return false; /* read_callback_ sets the state for us */
  101015. raw_header[raw_header_len++] = (FLAC__byte)x;
  101016. if(blocksize_hint == 7) {
  101017. FLAC__uint32 _x;
  101018. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101019. return false; /* read_callback_ sets the state for us */
  101020. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101021. x = (x << 8) | _x;
  101022. }
  101023. decoder->private_->frame.header.blocksize = x+1;
  101024. }
  101025. if(sample_rate_hint) {
  101026. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101027. return false; /* read_callback_ sets the state for us */
  101028. raw_header[raw_header_len++] = (FLAC__byte)x;
  101029. if(sample_rate_hint != 12) {
  101030. FLAC__uint32 _x;
  101031. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101032. return false; /* read_callback_ sets the state for us */
  101033. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101034. x = (x << 8) | _x;
  101035. }
  101036. if(sample_rate_hint == 12)
  101037. decoder->private_->frame.header.sample_rate = x*1000;
  101038. else if(sample_rate_hint == 13)
  101039. decoder->private_->frame.header.sample_rate = x;
  101040. else
  101041. decoder->private_->frame.header.sample_rate = x*10;
  101042. }
  101043. /* read the CRC-8 byte */
  101044. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101045. return false; /* read_callback_ sets the state for us */
  101046. crc8 = (FLAC__byte)x;
  101047. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101048. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101049. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101050. return true;
  101051. }
  101052. /* calculate the sample number from the frame number if needed */
  101053. decoder->private_->next_fixed_block_size = 0;
  101054. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101055. x = decoder->private_->frame.header.number.frame_number;
  101056. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101057. if(decoder->private_->fixed_block_size)
  101058. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101059. else if(decoder->private_->has_stream_info) {
  101060. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101061. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101062. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101063. }
  101064. else
  101065. is_unparseable = true;
  101066. }
  101067. else if(x == 0) {
  101068. decoder->private_->frame.header.number.sample_number = 0;
  101069. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101070. }
  101071. else {
  101072. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101073. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101074. }
  101075. }
  101076. if(is_unparseable) {
  101077. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101078. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101079. return true;
  101080. }
  101081. return true;
  101082. }
  101083. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101084. {
  101085. FLAC__uint32 x;
  101086. FLAC__bool wasted_bits;
  101087. unsigned i;
  101088. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101089. return false; /* read_callback_ sets the state for us */
  101090. wasted_bits = (x & 1);
  101091. x &= 0xfe;
  101092. if(wasted_bits) {
  101093. unsigned u;
  101094. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101095. return false; /* read_callback_ sets the state for us */
  101096. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101097. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101098. }
  101099. else
  101100. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101101. /*
  101102. * Lots of magic numbers here
  101103. */
  101104. if(x & 0x80) {
  101105. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101106. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101107. return true;
  101108. }
  101109. else if(x == 0) {
  101110. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101111. return false;
  101112. }
  101113. else if(x == 2) {
  101114. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101115. return false;
  101116. }
  101117. else if(x < 16) {
  101118. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101119. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101120. return true;
  101121. }
  101122. else if(x <= 24) {
  101123. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101124. return false;
  101125. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101126. return true;
  101127. }
  101128. else if(x < 64) {
  101129. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101130. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101131. return true;
  101132. }
  101133. else {
  101134. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101135. return false;
  101136. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101137. return true;
  101138. }
  101139. if(wasted_bits && do_full_decode) {
  101140. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101141. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101142. decoder->private_->output[channel][i] <<= x;
  101143. }
  101144. return true;
  101145. }
  101146. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101147. {
  101148. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101149. FLAC__int32 x;
  101150. unsigned i;
  101151. FLAC__int32 *output = decoder->private_->output[channel];
  101152. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101153. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101154. return false; /* read_callback_ sets the state for us */
  101155. subframe->value = x;
  101156. /* decode the subframe */
  101157. if(do_full_decode) {
  101158. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101159. output[i] = x;
  101160. }
  101161. return true;
  101162. }
  101163. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101164. {
  101165. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101166. FLAC__int32 i32;
  101167. FLAC__uint32 u32;
  101168. unsigned u;
  101169. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101170. subframe->residual = decoder->private_->residual[channel];
  101171. subframe->order = order;
  101172. /* read warm-up samples */
  101173. for(u = 0; u < order; u++) {
  101174. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101175. return false; /* read_callback_ sets the state for us */
  101176. subframe->warmup[u] = i32;
  101177. }
  101178. /* read entropy coding method info */
  101179. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101180. return false; /* read_callback_ sets the state for us */
  101181. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101182. switch(subframe->entropy_coding_method.type) {
  101183. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101184. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101185. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101186. return false; /* read_callback_ sets the state for us */
  101187. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101188. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101189. break;
  101190. default:
  101191. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101192. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101193. return true;
  101194. }
  101195. /* read residual */
  101196. switch(subframe->entropy_coding_method.type) {
  101197. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101198. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101199. 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))
  101200. return false;
  101201. break;
  101202. default:
  101203. FLAC__ASSERT(0);
  101204. }
  101205. /* decode the subframe */
  101206. if(do_full_decode) {
  101207. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101208. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101209. }
  101210. return true;
  101211. }
  101212. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101213. {
  101214. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101215. FLAC__int32 i32;
  101216. FLAC__uint32 u32;
  101217. unsigned u;
  101218. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101219. subframe->residual = decoder->private_->residual[channel];
  101220. subframe->order = order;
  101221. /* read warm-up samples */
  101222. for(u = 0; u < order; u++) {
  101223. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101224. return false; /* read_callback_ sets the state for us */
  101225. subframe->warmup[u] = i32;
  101226. }
  101227. /* read qlp coeff precision */
  101228. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101229. return false; /* read_callback_ sets the state for us */
  101230. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101231. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101232. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101233. return true;
  101234. }
  101235. subframe->qlp_coeff_precision = u32+1;
  101236. /* read qlp shift */
  101237. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101238. return false; /* read_callback_ sets the state for us */
  101239. subframe->quantization_level = i32;
  101240. /* read quantized lp coefficiencts */
  101241. for(u = 0; u < order; u++) {
  101242. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101243. return false; /* read_callback_ sets the state for us */
  101244. subframe->qlp_coeff[u] = i32;
  101245. }
  101246. /* read entropy coding method info */
  101247. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101248. return false; /* read_callback_ sets the state for us */
  101249. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101250. switch(subframe->entropy_coding_method.type) {
  101251. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101252. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101253. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101254. return false; /* read_callback_ sets the state for us */
  101255. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101256. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101257. break;
  101258. default:
  101259. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101260. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101261. return true;
  101262. }
  101263. /* read residual */
  101264. switch(subframe->entropy_coding_method.type) {
  101265. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101266. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101267. 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))
  101268. return false;
  101269. break;
  101270. default:
  101271. FLAC__ASSERT(0);
  101272. }
  101273. /* decode the subframe */
  101274. if(do_full_decode) {
  101275. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101276. /*@@@@@@ technically not pessimistic enough, should be more like
  101277. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101278. */
  101279. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101280. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101281. if(order <= 8)
  101282. 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);
  101283. else
  101284. 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);
  101285. }
  101286. else
  101287. 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);
  101288. else
  101289. 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);
  101290. }
  101291. return true;
  101292. }
  101293. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101294. {
  101295. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101296. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101297. unsigned i;
  101298. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101299. subframe->data = residual;
  101300. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101301. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101302. return false; /* read_callback_ sets the state for us */
  101303. residual[i] = x;
  101304. }
  101305. /* decode the subframe */
  101306. if(do_full_decode)
  101307. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101308. return true;
  101309. }
  101310. 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)
  101311. {
  101312. FLAC__uint32 rice_parameter;
  101313. int i;
  101314. unsigned partition, sample, u;
  101315. const unsigned partitions = 1u << partition_order;
  101316. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101317. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101318. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101319. /* sanity checks */
  101320. if(partition_order == 0) {
  101321. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101322. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101323. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101324. return true;
  101325. }
  101326. }
  101327. else {
  101328. if(partition_samples < predictor_order) {
  101329. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101330. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101331. return true;
  101332. }
  101333. }
  101334. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101335. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101336. return false;
  101337. }
  101338. sample = 0;
  101339. for(partition = 0; partition < partitions; partition++) {
  101340. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101341. return false; /* read_callback_ sets the state for us */
  101342. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101343. if(rice_parameter < pesc) {
  101344. partitioned_rice_contents->raw_bits[partition] = 0;
  101345. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101346. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101347. return false; /* read_callback_ sets the state for us */
  101348. sample += u;
  101349. }
  101350. else {
  101351. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101352. return false; /* read_callback_ sets the state for us */
  101353. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101354. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101355. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101356. return false; /* read_callback_ sets the state for us */
  101357. residual[sample] = i;
  101358. }
  101359. }
  101360. }
  101361. return true;
  101362. }
  101363. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101364. {
  101365. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101366. FLAC__uint32 zero = 0;
  101367. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101368. return false; /* read_callback_ sets the state for us */
  101369. if(zero != 0) {
  101370. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101371. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101372. }
  101373. }
  101374. return true;
  101375. }
  101376. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101377. {
  101378. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101379. if(
  101380. #if FLAC__HAS_OGG
  101381. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101382. !decoder->private_->is_ogg &&
  101383. #endif
  101384. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101385. ) {
  101386. *bytes = 0;
  101387. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101388. return false;
  101389. }
  101390. else if(*bytes > 0) {
  101391. /* While seeking, it is possible for our seek to land in the
  101392. * middle of audio data that looks exactly like a frame header
  101393. * from a future version of an encoder. When that happens, our
  101394. * error callback will get an
  101395. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101396. * unparseable_frame_count. But there is a remote possibility
  101397. * that it is properly synced at such a "future-codec frame",
  101398. * so to make sure, we wait to see many "unparseable" errors in
  101399. * a row before bailing out.
  101400. */
  101401. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101402. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101403. return false;
  101404. }
  101405. else {
  101406. const FLAC__StreamDecoderReadStatus status =
  101407. #if FLAC__HAS_OGG
  101408. decoder->private_->is_ogg?
  101409. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101410. #endif
  101411. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101412. ;
  101413. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101414. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101415. return false;
  101416. }
  101417. else if(*bytes == 0) {
  101418. if(
  101419. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101420. (
  101421. #if FLAC__HAS_OGG
  101422. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101423. !decoder->private_->is_ogg &&
  101424. #endif
  101425. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101426. )
  101427. ) {
  101428. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101429. return false;
  101430. }
  101431. else
  101432. return true;
  101433. }
  101434. else
  101435. return true;
  101436. }
  101437. }
  101438. else {
  101439. /* abort to avoid a deadlock */
  101440. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101441. return false;
  101442. }
  101443. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101444. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101445. * and at the same time hit the end of the stream (for example, seeking
  101446. * to a point that is after the beginning of the last Ogg page). There
  101447. * is no way to report an Ogg sync loss through the callbacks (see note
  101448. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101449. * So to keep the decoder from stopping at this point we gate the call
  101450. * to the eof_callback and let the Ogg decoder aspect set the
  101451. * end-of-stream state when it is needed.
  101452. */
  101453. }
  101454. #if FLAC__HAS_OGG
  101455. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101456. {
  101457. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101458. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101459. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101460. /* we don't really have a way to handle lost sync via read
  101461. * callback so we'll let it pass and let the underlying
  101462. * FLAC decoder catch the error
  101463. */
  101464. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101465. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101466. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101467. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101468. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101469. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101470. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101471. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101472. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101473. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101474. default:
  101475. FLAC__ASSERT(0);
  101476. /* double protection */
  101477. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101478. }
  101479. }
  101480. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101481. {
  101482. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101483. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101484. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101485. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101486. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101487. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101488. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101489. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101490. default:
  101491. /* double protection: */
  101492. FLAC__ASSERT(0);
  101493. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101494. }
  101495. }
  101496. #endif
  101497. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101498. {
  101499. if(decoder->private_->is_seeking) {
  101500. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101501. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101502. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101503. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101504. #if FLAC__HAS_OGG
  101505. decoder->private_->got_a_frame = true;
  101506. #endif
  101507. decoder->private_->last_frame = *frame; /* save the frame */
  101508. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101509. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101510. /* kick out of seek mode */
  101511. decoder->private_->is_seeking = false;
  101512. /* shift out the samples before target_sample */
  101513. if(delta > 0) {
  101514. unsigned channel;
  101515. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101516. for(channel = 0; channel < frame->header.channels; channel++)
  101517. newbuffer[channel] = buffer[channel] + delta;
  101518. decoder->private_->last_frame.header.blocksize -= delta;
  101519. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101520. /* write the relevant samples */
  101521. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101522. }
  101523. else {
  101524. /* write the relevant samples */
  101525. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101526. }
  101527. }
  101528. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101529. }
  101530. /*
  101531. * If we never got STREAMINFO, turn off MD5 checking to save
  101532. * cycles since we don't have a sum to compare to anyway
  101533. */
  101534. if(!decoder->private_->has_stream_info)
  101535. decoder->private_->do_md5_checking = false;
  101536. if(decoder->private_->do_md5_checking) {
  101537. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101538. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101539. }
  101540. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101541. }
  101542. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101543. {
  101544. if(!decoder->private_->is_seeking)
  101545. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101546. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101547. decoder->private_->unparseable_frame_count++;
  101548. }
  101549. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101550. {
  101551. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101552. FLAC__int64 pos = -1;
  101553. int i;
  101554. unsigned approx_bytes_per_frame;
  101555. FLAC__bool first_seek = true;
  101556. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101557. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101558. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101559. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101560. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101561. /* take these from the current frame in case they've changed mid-stream */
  101562. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101563. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101564. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101565. /* use values from stream info if we didn't decode a frame */
  101566. if(channels == 0)
  101567. channels = decoder->private_->stream_info.data.stream_info.channels;
  101568. if(bps == 0)
  101569. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101570. /* we are just guessing here */
  101571. if(max_framesize > 0)
  101572. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101573. /*
  101574. * Check if it's a known fixed-blocksize stream. Note that though
  101575. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101576. * never get a STREAMINFO block when decoding so the value of
  101577. * min_blocksize might be zero.
  101578. */
  101579. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101580. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101581. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101582. }
  101583. else
  101584. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101585. /*
  101586. * First, we set an upper and lower bound on where in the
  101587. * stream we will search. For now we assume the worst case
  101588. * scenario, which is our best guess at the beginning of
  101589. * the first frame and end of the stream.
  101590. */
  101591. lower_bound = first_frame_offset;
  101592. lower_bound_sample = 0;
  101593. upper_bound = stream_length;
  101594. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101595. /*
  101596. * Now we refine the bounds if we have a seektable with
  101597. * suitable points. Note that according to the spec they
  101598. * must be ordered by ascending sample number.
  101599. *
  101600. * Note: to protect against invalid seek tables we will ignore points
  101601. * that have frame_samples==0 or sample_number>=total_samples
  101602. */
  101603. if(seek_table) {
  101604. FLAC__uint64 new_lower_bound = lower_bound;
  101605. FLAC__uint64 new_upper_bound = upper_bound;
  101606. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101607. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101608. /* find the closest seek point <= target_sample, if it exists */
  101609. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101610. if(
  101611. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101612. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101613. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101614. seek_table->points[i].sample_number <= target_sample
  101615. )
  101616. break;
  101617. }
  101618. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101619. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101620. new_lower_bound_sample = seek_table->points[i].sample_number;
  101621. }
  101622. /* find the closest seek point > target_sample, if it exists */
  101623. for(i = 0; i < (int)seek_table->num_points; i++) {
  101624. if(
  101625. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101626. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101627. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101628. seek_table->points[i].sample_number > target_sample
  101629. )
  101630. break;
  101631. }
  101632. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101633. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101634. new_upper_bound_sample = seek_table->points[i].sample_number;
  101635. }
  101636. /* final protection against unsorted seek tables; keep original values if bogus */
  101637. if(new_upper_bound >= new_lower_bound) {
  101638. lower_bound = new_lower_bound;
  101639. upper_bound = new_upper_bound;
  101640. lower_bound_sample = new_lower_bound_sample;
  101641. upper_bound_sample = new_upper_bound_sample;
  101642. }
  101643. }
  101644. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101645. /* there are 2 insidious ways that the following equality occurs, which
  101646. * we need to fix:
  101647. * 1) total_samples is 0 (unknown) and target_sample is 0
  101648. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101649. * exactly equal to the last seek point in the seek table; this
  101650. * means there is no seek point above it, and upper_bound_samples
  101651. * remains equal to the estimate (of target_samples) we made above
  101652. * in either case it does not hurt to move upper_bound_sample up by 1
  101653. */
  101654. if(upper_bound_sample == lower_bound_sample)
  101655. upper_bound_sample++;
  101656. decoder->private_->target_sample = target_sample;
  101657. while(1) {
  101658. /* check if the bounds are still ok */
  101659. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101660. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101661. return false;
  101662. }
  101663. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101664. #if defined _MSC_VER || defined __MINGW32__
  101665. /* with VC++ you have to spoon feed it the casting */
  101666. 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;
  101667. #else
  101668. 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;
  101669. #endif
  101670. #else
  101671. /* a little less accurate: */
  101672. if(upper_bound - lower_bound < 0xffffffff)
  101673. 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;
  101674. else /* @@@ WATCHOUT, ~2TB limit */
  101675. 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;
  101676. #endif
  101677. if(pos >= (FLAC__int64)upper_bound)
  101678. pos = (FLAC__int64)upper_bound - 1;
  101679. if(pos < (FLAC__int64)lower_bound)
  101680. pos = (FLAC__int64)lower_bound;
  101681. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101682. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101683. return false;
  101684. }
  101685. if(!FLAC__stream_decoder_flush(decoder)) {
  101686. /* above call sets the state for us */
  101687. return false;
  101688. }
  101689. /* Now we need to get a frame. First we need to reset our
  101690. * unparseable_frame_count; if we get too many unparseable
  101691. * frames in a row, the read callback will return
  101692. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101693. * FLAC__stream_decoder_process_single() to return false.
  101694. */
  101695. decoder->private_->unparseable_frame_count = 0;
  101696. if(!FLAC__stream_decoder_process_single(decoder)) {
  101697. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101698. return false;
  101699. }
  101700. /* our write callback will change the state when it gets to the target frame */
  101701. /* 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 */
  101702. #if 0
  101703. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101704. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101705. break;
  101706. #endif
  101707. if(!decoder->private_->is_seeking)
  101708. break;
  101709. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101710. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101711. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101712. if (pos == (FLAC__int64)lower_bound) {
  101713. /* can't move back any more than the first frame, something is fatally wrong */
  101714. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101715. return false;
  101716. }
  101717. /* our last move backwards wasn't big enough, try again */
  101718. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101719. continue;
  101720. }
  101721. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101722. first_seek = false;
  101723. /* make sure we are not seeking in corrupted stream */
  101724. if (this_frame_sample < lower_bound_sample) {
  101725. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101726. return false;
  101727. }
  101728. /* we need to narrow the search */
  101729. if(target_sample < this_frame_sample) {
  101730. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101731. /*@@@@@@ what will decode position be if at end of stream? */
  101732. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101733. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101734. return false;
  101735. }
  101736. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101737. }
  101738. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101739. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101740. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101741. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101742. return false;
  101743. }
  101744. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101745. }
  101746. }
  101747. return true;
  101748. }
  101749. #if FLAC__HAS_OGG
  101750. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101751. {
  101752. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101753. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101754. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101755. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101756. FLAC__bool did_a_seek;
  101757. unsigned iteration = 0;
  101758. /* In the first iterations, we will calculate the target byte position
  101759. * by the distance from the target sample to left_sample and
  101760. * right_sample (let's call it "proportional search"). After that, we
  101761. * will switch to binary search.
  101762. */
  101763. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101764. /* We will switch to a linear search once our current sample is less
  101765. * than this number of samples ahead of the target sample
  101766. */
  101767. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101768. /* If the total number of samples is unknown, use a large value, and
  101769. * force binary search immediately.
  101770. */
  101771. if(right_sample == 0) {
  101772. right_sample = (FLAC__uint64)(-1);
  101773. BINARY_SEARCH_AFTER_ITERATION = 0;
  101774. }
  101775. decoder->private_->target_sample = target_sample;
  101776. for( ; ; iteration++) {
  101777. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101778. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101779. pos = (right_pos + left_pos) / 2;
  101780. }
  101781. else {
  101782. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101783. #if defined _MSC_VER || defined __MINGW32__
  101784. /* with MSVC you have to spoon feed it the casting */
  101785. 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));
  101786. #else
  101787. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101788. #endif
  101789. #else
  101790. /* a little less accurate: */
  101791. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101792. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101793. else /* @@@ WATCHOUT, ~2TB limit */
  101794. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101795. #endif
  101796. /* @@@ TODO: might want to limit pos to some distance
  101797. * before EOF, to make sure we land before the last frame,
  101798. * thereby getting a this_frame_sample and so having a better
  101799. * estimate.
  101800. */
  101801. }
  101802. /* physical seek */
  101803. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101804. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101805. return false;
  101806. }
  101807. if(!FLAC__stream_decoder_flush(decoder)) {
  101808. /* above call sets the state for us */
  101809. return false;
  101810. }
  101811. did_a_seek = true;
  101812. }
  101813. else
  101814. did_a_seek = false;
  101815. decoder->private_->got_a_frame = false;
  101816. if(!FLAC__stream_decoder_process_single(decoder)) {
  101817. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101818. return false;
  101819. }
  101820. if(!decoder->private_->got_a_frame) {
  101821. if(did_a_seek) {
  101822. /* this can happen if we seek to a point after the last frame; we drop
  101823. * to binary search right away in this case to avoid any wasted
  101824. * iterations of proportional search.
  101825. */
  101826. right_pos = pos;
  101827. BINARY_SEARCH_AFTER_ITERATION = 0;
  101828. }
  101829. else {
  101830. /* this can probably only happen if total_samples is unknown and the
  101831. * target_sample is past the end of the stream
  101832. */
  101833. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101834. return false;
  101835. }
  101836. }
  101837. /* our write callback will change the state when it gets to the target frame */
  101838. else if(!decoder->private_->is_seeking) {
  101839. break;
  101840. }
  101841. else {
  101842. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101843. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101844. if (did_a_seek) {
  101845. if (this_frame_sample <= target_sample) {
  101846. /* The 'equal' case should not happen, since
  101847. * FLAC__stream_decoder_process_single()
  101848. * should recognize that it has hit the
  101849. * target sample and we would exit through
  101850. * the 'break' above.
  101851. */
  101852. FLAC__ASSERT(this_frame_sample != target_sample);
  101853. left_sample = this_frame_sample;
  101854. /* sanity check to avoid infinite loop */
  101855. if (left_pos == pos) {
  101856. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101857. return false;
  101858. }
  101859. left_pos = pos;
  101860. }
  101861. else if(this_frame_sample > target_sample) {
  101862. right_sample = this_frame_sample;
  101863. /* sanity check to avoid infinite loop */
  101864. if (right_pos == pos) {
  101865. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101866. return false;
  101867. }
  101868. right_pos = pos;
  101869. }
  101870. }
  101871. }
  101872. }
  101873. return true;
  101874. }
  101875. #endif
  101876. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101877. {
  101878. (void)client_data;
  101879. if(*bytes > 0) {
  101880. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101881. if(ferror(decoder->private_->file))
  101882. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101883. else if(*bytes == 0)
  101884. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101885. else
  101886. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101887. }
  101888. else
  101889. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101890. }
  101891. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101892. {
  101893. (void)client_data;
  101894. if(decoder->private_->file == stdin)
  101895. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101896. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101897. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101898. else
  101899. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101900. }
  101901. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101902. {
  101903. off_t pos;
  101904. (void)client_data;
  101905. if(decoder->private_->file == stdin)
  101906. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101907. else if((pos = ftello(decoder->private_->file)) < 0)
  101908. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101909. else {
  101910. *absolute_byte_offset = (FLAC__uint64)pos;
  101911. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101912. }
  101913. }
  101914. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101915. {
  101916. struct stat filestats;
  101917. (void)client_data;
  101918. if(decoder->private_->file == stdin)
  101919. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101920. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101921. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101922. else {
  101923. *stream_length = (FLAC__uint64)filestats.st_size;
  101924. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101925. }
  101926. }
  101927. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101928. {
  101929. (void)client_data;
  101930. return feof(decoder->private_->file)? true : false;
  101931. }
  101932. #endif
  101933. /*** End of inlined file: stream_decoder.c ***/
  101934. /*** Start of inlined file: stream_encoder.c ***/
  101935. /*** Start of inlined file: juce_FlacHeader.h ***/
  101936. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101937. // tasks..
  101938. #define VERSION "1.2.1"
  101939. #define FLAC__NO_DLL 1
  101940. #if JUCE_MSVC
  101941. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101942. #endif
  101943. #if JUCE_MAC
  101944. #define FLAC__SYS_DARWIN 1
  101945. #endif
  101946. /*** End of inlined file: juce_FlacHeader.h ***/
  101947. #if JUCE_USE_FLAC
  101948. #if HAVE_CONFIG_H
  101949. # include <config.h>
  101950. #endif
  101951. #if defined _MSC_VER || defined __MINGW32__
  101952. #include <io.h> /* for _setmode() */
  101953. #include <fcntl.h> /* for _O_BINARY */
  101954. #endif
  101955. #if defined __CYGWIN__ || defined __EMX__
  101956. #include <io.h> /* for setmode(), O_BINARY */
  101957. #include <fcntl.h> /* for _O_BINARY */
  101958. #endif
  101959. #include <limits.h>
  101960. #include <stdio.h>
  101961. #include <stdlib.h> /* for malloc() */
  101962. #include <string.h> /* for memcpy() */
  101963. #include <sys/types.h> /* for off_t */
  101964. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101965. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101966. #define fseeko fseek
  101967. #define ftello ftell
  101968. #endif
  101969. #endif
  101970. /*** Start of inlined file: stream_encoder.h ***/
  101971. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101972. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101973. #if FLAC__HAS_OGG
  101974. #include "private/ogg_encoder_aspect.h"
  101975. #endif
  101976. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101977. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101978. typedef enum {
  101979. FLAC__APODIZATION_BARTLETT,
  101980. FLAC__APODIZATION_BARTLETT_HANN,
  101981. FLAC__APODIZATION_BLACKMAN,
  101982. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101983. FLAC__APODIZATION_CONNES,
  101984. FLAC__APODIZATION_FLATTOP,
  101985. FLAC__APODIZATION_GAUSS,
  101986. FLAC__APODIZATION_HAMMING,
  101987. FLAC__APODIZATION_HANN,
  101988. FLAC__APODIZATION_KAISER_BESSEL,
  101989. FLAC__APODIZATION_NUTTALL,
  101990. FLAC__APODIZATION_RECTANGLE,
  101991. FLAC__APODIZATION_TRIANGLE,
  101992. FLAC__APODIZATION_TUKEY,
  101993. FLAC__APODIZATION_WELCH
  101994. } FLAC__ApodizationFunction;
  101995. typedef struct {
  101996. FLAC__ApodizationFunction type;
  101997. union {
  101998. struct {
  101999. FLAC__real stddev;
  102000. } gauss;
  102001. struct {
  102002. FLAC__real p;
  102003. } tukey;
  102004. } parameters;
  102005. } FLAC__ApodizationSpecification;
  102006. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102007. typedef struct FLAC__StreamEncoderProtected {
  102008. FLAC__StreamEncoderState state;
  102009. FLAC__bool verify;
  102010. FLAC__bool streamable_subset;
  102011. FLAC__bool do_md5;
  102012. FLAC__bool do_mid_side_stereo;
  102013. FLAC__bool loose_mid_side_stereo;
  102014. unsigned channels;
  102015. unsigned bits_per_sample;
  102016. unsigned sample_rate;
  102017. unsigned blocksize;
  102018. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102019. unsigned num_apodizations;
  102020. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102021. #endif
  102022. unsigned max_lpc_order;
  102023. unsigned qlp_coeff_precision;
  102024. FLAC__bool do_qlp_coeff_prec_search;
  102025. FLAC__bool do_exhaustive_model_search;
  102026. FLAC__bool do_escape_coding;
  102027. unsigned min_residual_partition_order;
  102028. unsigned max_residual_partition_order;
  102029. unsigned rice_parameter_search_dist;
  102030. FLAC__uint64 total_samples_estimate;
  102031. FLAC__StreamMetadata **metadata;
  102032. unsigned num_metadata_blocks;
  102033. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102034. #if FLAC__HAS_OGG
  102035. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102036. #endif
  102037. } FLAC__StreamEncoderProtected;
  102038. #endif
  102039. /*** End of inlined file: stream_encoder.h ***/
  102040. #if FLAC__HAS_OGG
  102041. #include "include/private/ogg_helper.h"
  102042. #include "include/private/ogg_mapping.h"
  102043. #endif
  102044. /*** Start of inlined file: stream_encoder_framing.h ***/
  102045. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102046. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102047. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102048. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102049. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102050. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102051. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102052. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102053. #endif
  102054. /*** End of inlined file: stream_encoder_framing.h ***/
  102055. /*** Start of inlined file: window.h ***/
  102056. #ifndef FLAC__PRIVATE__WINDOW_H
  102057. #define FLAC__PRIVATE__WINDOW_H
  102058. #ifdef HAVE_CONFIG_H
  102059. #include <config.h>
  102060. #endif
  102061. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102062. /*
  102063. * FLAC__window_*()
  102064. * --------------------------------------------------------------------
  102065. * Calculates window coefficients according to different apodization
  102066. * functions.
  102067. *
  102068. * OUT window[0,L-1]
  102069. * IN L (number of points in window)
  102070. */
  102071. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102072. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102073. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102074. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102075. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102076. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102077. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102078. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102079. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102080. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102081. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102082. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102083. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102084. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102085. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102086. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102087. #endif
  102088. /*** End of inlined file: window.h ***/
  102089. #ifndef FLaC__INLINE
  102090. #define FLaC__INLINE
  102091. #endif
  102092. #ifdef min
  102093. #undef min
  102094. #endif
  102095. #define min(x,y) ((x)<(y)?(x):(y))
  102096. #ifdef max
  102097. #undef max
  102098. #endif
  102099. #define max(x,y) ((x)>(y)?(x):(y))
  102100. /* Exact Rice codeword length calculation is off by default. The simple
  102101. * (and fast) estimation (of how many bits a residual value will be
  102102. * encoded with) in this encoder is very good, almost always yielding
  102103. * compression within 0.1% of exact calculation.
  102104. */
  102105. #undef EXACT_RICE_BITS_CALCULATION
  102106. /* Rice parameter searching is off by default. The simple (and fast)
  102107. * parameter estimation in this encoder is very good, almost always
  102108. * yielding compression within 0.1% of the optimal parameters.
  102109. */
  102110. #undef ENABLE_RICE_PARAMETER_SEARCH
  102111. typedef struct {
  102112. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102113. unsigned size; /* of each data[] in samples */
  102114. unsigned tail;
  102115. } verify_input_fifo;
  102116. typedef struct {
  102117. const FLAC__byte *data;
  102118. unsigned capacity;
  102119. unsigned bytes;
  102120. } verify_output;
  102121. typedef enum {
  102122. ENCODER_IN_MAGIC = 0,
  102123. ENCODER_IN_METADATA = 1,
  102124. ENCODER_IN_AUDIO = 2
  102125. } EncoderStateHint;
  102126. static struct CompressionLevels {
  102127. FLAC__bool do_mid_side_stereo;
  102128. FLAC__bool loose_mid_side_stereo;
  102129. unsigned max_lpc_order;
  102130. unsigned qlp_coeff_precision;
  102131. FLAC__bool do_qlp_coeff_prec_search;
  102132. FLAC__bool do_escape_coding;
  102133. FLAC__bool do_exhaustive_model_search;
  102134. unsigned min_residual_partition_order;
  102135. unsigned max_residual_partition_order;
  102136. unsigned rice_parameter_search_dist;
  102137. } compression_levels_[] = {
  102138. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102139. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102140. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102141. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102142. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102143. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102144. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102145. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102146. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102147. };
  102148. /***********************************************************************
  102149. *
  102150. * Private class method prototypes
  102151. *
  102152. ***********************************************************************/
  102153. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102154. static void free_(FLAC__StreamEncoder *encoder);
  102155. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102156. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102157. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102158. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102159. #if FLAC__HAS_OGG
  102160. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102161. #endif
  102162. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102163. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102164. static FLAC__bool process_subframe_(
  102165. FLAC__StreamEncoder *encoder,
  102166. unsigned min_partition_order,
  102167. unsigned max_partition_order,
  102168. const FLAC__FrameHeader *frame_header,
  102169. unsigned subframe_bps,
  102170. const FLAC__int32 integer_signal[],
  102171. FLAC__Subframe *subframe[2],
  102172. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102173. FLAC__int32 *residual[2],
  102174. unsigned *best_subframe,
  102175. unsigned *best_bits
  102176. );
  102177. static FLAC__bool add_subframe_(
  102178. FLAC__StreamEncoder *encoder,
  102179. unsigned blocksize,
  102180. unsigned subframe_bps,
  102181. const FLAC__Subframe *subframe,
  102182. FLAC__BitWriter *frame
  102183. );
  102184. static unsigned evaluate_constant_subframe_(
  102185. FLAC__StreamEncoder *encoder,
  102186. const FLAC__int32 signal,
  102187. unsigned blocksize,
  102188. unsigned subframe_bps,
  102189. FLAC__Subframe *subframe
  102190. );
  102191. static unsigned evaluate_fixed_subframe_(
  102192. FLAC__StreamEncoder *encoder,
  102193. const FLAC__int32 signal[],
  102194. FLAC__int32 residual[],
  102195. FLAC__uint64 abs_residual_partition_sums[],
  102196. unsigned raw_bits_per_partition[],
  102197. unsigned blocksize,
  102198. unsigned subframe_bps,
  102199. unsigned order,
  102200. unsigned rice_parameter,
  102201. unsigned rice_parameter_limit,
  102202. unsigned min_partition_order,
  102203. unsigned max_partition_order,
  102204. FLAC__bool do_escape_coding,
  102205. unsigned rice_parameter_search_dist,
  102206. FLAC__Subframe *subframe,
  102207. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102208. );
  102209. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102210. static unsigned evaluate_lpc_subframe_(
  102211. FLAC__StreamEncoder *encoder,
  102212. const FLAC__int32 signal[],
  102213. FLAC__int32 residual[],
  102214. FLAC__uint64 abs_residual_partition_sums[],
  102215. unsigned raw_bits_per_partition[],
  102216. const FLAC__real lp_coeff[],
  102217. unsigned blocksize,
  102218. unsigned subframe_bps,
  102219. unsigned order,
  102220. unsigned qlp_coeff_precision,
  102221. unsigned rice_parameter,
  102222. unsigned rice_parameter_limit,
  102223. unsigned min_partition_order,
  102224. unsigned max_partition_order,
  102225. FLAC__bool do_escape_coding,
  102226. unsigned rice_parameter_search_dist,
  102227. FLAC__Subframe *subframe,
  102228. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102229. );
  102230. #endif
  102231. static unsigned evaluate_verbatim_subframe_(
  102232. FLAC__StreamEncoder *encoder,
  102233. const FLAC__int32 signal[],
  102234. unsigned blocksize,
  102235. unsigned subframe_bps,
  102236. FLAC__Subframe *subframe
  102237. );
  102238. static unsigned find_best_partition_order_(
  102239. struct FLAC__StreamEncoderPrivate *private_,
  102240. const FLAC__int32 residual[],
  102241. FLAC__uint64 abs_residual_partition_sums[],
  102242. unsigned raw_bits_per_partition[],
  102243. unsigned residual_samples,
  102244. unsigned predictor_order,
  102245. unsigned rice_parameter,
  102246. unsigned rice_parameter_limit,
  102247. unsigned min_partition_order,
  102248. unsigned max_partition_order,
  102249. unsigned bps,
  102250. FLAC__bool do_escape_coding,
  102251. unsigned rice_parameter_search_dist,
  102252. FLAC__EntropyCodingMethod *best_ecm
  102253. );
  102254. static void precompute_partition_info_sums_(
  102255. const FLAC__int32 residual[],
  102256. FLAC__uint64 abs_residual_partition_sums[],
  102257. unsigned residual_samples,
  102258. unsigned predictor_order,
  102259. unsigned min_partition_order,
  102260. unsigned max_partition_order,
  102261. unsigned bps
  102262. );
  102263. static void precompute_partition_info_escapes_(
  102264. const FLAC__int32 residual[],
  102265. unsigned raw_bits_per_partition[],
  102266. unsigned residual_samples,
  102267. unsigned predictor_order,
  102268. unsigned min_partition_order,
  102269. unsigned max_partition_order
  102270. );
  102271. static FLAC__bool set_partitioned_rice_(
  102272. #ifdef EXACT_RICE_BITS_CALCULATION
  102273. const FLAC__int32 residual[],
  102274. #endif
  102275. const FLAC__uint64 abs_residual_partition_sums[],
  102276. const unsigned raw_bits_per_partition[],
  102277. const unsigned residual_samples,
  102278. const unsigned predictor_order,
  102279. const unsigned suggested_rice_parameter,
  102280. const unsigned rice_parameter_limit,
  102281. const unsigned rice_parameter_search_dist,
  102282. const unsigned partition_order,
  102283. const FLAC__bool search_for_escapes,
  102284. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102285. unsigned *bits
  102286. );
  102287. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102288. /* verify-related routines: */
  102289. static void append_to_verify_fifo_(
  102290. verify_input_fifo *fifo,
  102291. const FLAC__int32 * const input[],
  102292. unsigned input_offset,
  102293. unsigned channels,
  102294. unsigned wide_samples
  102295. );
  102296. static void append_to_verify_fifo_interleaved_(
  102297. verify_input_fifo *fifo,
  102298. const FLAC__int32 input[],
  102299. unsigned input_offset,
  102300. unsigned channels,
  102301. unsigned wide_samples
  102302. );
  102303. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102304. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102305. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102306. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102307. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102308. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102309. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102310. 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);
  102311. static FILE *get_binary_stdout_(void);
  102312. /***********************************************************************
  102313. *
  102314. * Private class data
  102315. *
  102316. ***********************************************************************/
  102317. typedef struct FLAC__StreamEncoderPrivate {
  102318. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102319. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102320. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102321. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102322. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102323. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102324. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102325. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102326. #endif
  102327. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102328. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102329. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102330. FLAC__int32 *residual_workspace_mid_side[2][2];
  102331. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102332. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102333. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102334. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102335. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102336. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102337. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102338. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102339. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102340. unsigned best_subframe_mid_side[2];
  102341. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102342. unsigned best_subframe_bits_mid_side[2];
  102343. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102344. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102345. FLAC__BitWriter *frame; /* the current frame being worked on */
  102346. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102347. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102348. FLAC__ChannelAssignment last_channel_assignment;
  102349. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102350. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102351. unsigned current_sample_number;
  102352. unsigned current_frame_number;
  102353. FLAC__MD5Context md5context;
  102354. FLAC__CPUInfo cpuinfo;
  102355. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102356. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102357. #else
  102358. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102359. #endif
  102360. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102361. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102362. 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[]);
  102363. 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[]);
  102364. 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[]);
  102365. #endif
  102366. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102367. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102368. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102369. FLAC__bool disable_constant_subframes;
  102370. FLAC__bool disable_fixed_subframes;
  102371. FLAC__bool disable_verbatim_subframes;
  102372. #if FLAC__HAS_OGG
  102373. FLAC__bool is_ogg;
  102374. #endif
  102375. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102376. FLAC__StreamEncoderSeekCallback seek_callback;
  102377. FLAC__StreamEncoderTellCallback tell_callback;
  102378. FLAC__StreamEncoderWriteCallback write_callback;
  102379. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102380. FLAC__StreamEncoderProgressCallback progress_callback;
  102381. void *client_data;
  102382. unsigned first_seekpoint_to_check;
  102383. FILE *file; /* only used when encoding to a file */
  102384. FLAC__uint64 bytes_written;
  102385. FLAC__uint64 samples_written;
  102386. unsigned frames_written;
  102387. unsigned total_frames_estimate;
  102388. /* unaligned (original) pointers to allocated data */
  102389. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102390. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102391. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102392. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102393. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102394. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102395. FLAC__real *windowed_signal_unaligned;
  102396. #endif
  102397. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102398. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102399. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102400. unsigned *raw_bits_per_partition_unaligned;
  102401. /*
  102402. * These fields have been moved here from private function local
  102403. * declarations merely to save stack space during encoding.
  102404. */
  102405. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102406. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102407. #endif
  102408. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102409. /*
  102410. * The data for the verify section
  102411. */
  102412. struct {
  102413. FLAC__StreamDecoder *decoder;
  102414. EncoderStateHint state_hint;
  102415. FLAC__bool needs_magic_hack;
  102416. verify_input_fifo input_fifo;
  102417. verify_output output;
  102418. struct {
  102419. FLAC__uint64 absolute_sample;
  102420. unsigned frame_number;
  102421. unsigned channel;
  102422. unsigned sample;
  102423. FLAC__int32 expected;
  102424. FLAC__int32 got;
  102425. } error_stats;
  102426. } verify;
  102427. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102428. } FLAC__StreamEncoderPrivate;
  102429. /***********************************************************************
  102430. *
  102431. * Public static class data
  102432. *
  102433. ***********************************************************************/
  102434. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102435. "FLAC__STREAM_ENCODER_OK",
  102436. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102437. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102438. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102439. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102440. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102441. "FLAC__STREAM_ENCODER_IO_ERROR",
  102442. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102443. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102444. };
  102445. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102446. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102447. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102448. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102449. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102450. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102451. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102452. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102453. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102454. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102455. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102456. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102457. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102458. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102459. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102460. };
  102461. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102462. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102463. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102464. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102465. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102466. };
  102467. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102468. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102469. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102470. };
  102471. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102472. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102473. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102474. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102475. };
  102476. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102477. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102478. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102479. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102480. };
  102481. /* Number of samples that will be overread to watch for end of stream. By
  102482. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102483. * always try to read blocksize+1 samples before encoding a block, so that
  102484. * even if the stream has a total sample count that is an integral multiple
  102485. * of the blocksize, we will still notice when we are encoding the last
  102486. * block. This is needed, for example, to correctly set the end-of-stream
  102487. * marker in Ogg FLAC.
  102488. *
  102489. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102490. * not really any reason to change it.
  102491. */
  102492. static const unsigned OVERREAD_ = 1;
  102493. /***********************************************************************
  102494. *
  102495. * Class constructor/destructor
  102496. *
  102497. */
  102498. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102499. {
  102500. FLAC__StreamEncoder *encoder;
  102501. unsigned i;
  102502. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102503. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102504. if(encoder == 0) {
  102505. return 0;
  102506. }
  102507. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102508. if(encoder->protected_ == 0) {
  102509. free(encoder);
  102510. return 0;
  102511. }
  102512. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102513. if(encoder->private_ == 0) {
  102514. free(encoder->protected_);
  102515. free(encoder);
  102516. return 0;
  102517. }
  102518. encoder->private_->frame = FLAC__bitwriter_new();
  102519. if(encoder->private_->frame == 0) {
  102520. free(encoder->private_);
  102521. free(encoder->protected_);
  102522. free(encoder);
  102523. return 0;
  102524. }
  102525. encoder->private_->file = 0;
  102526. set_defaults_enc(encoder);
  102527. encoder->private_->is_being_deleted = false;
  102528. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102529. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102530. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102531. }
  102532. for(i = 0; i < 2; i++) {
  102533. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102534. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102535. }
  102536. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102537. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102538. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102539. }
  102540. for(i = 0; i < 2; i++) {
  102541. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102542. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102543. }
  102544. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102545. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102546. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102547. }
  102548. for(i = 0; i < 2; i++) {
  102549. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102550. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102551. }
  102552. for(i = 0; i < 2; i++)
  102553. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102554. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102555. return encoder;
  102556. }
  102557. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102558. {
  102559. unsigned i;
  102560. FLAC__ASSERT(0 != encoder);
  102561. FLAC__ASSERT(0 != encoder->protected_);
  102562. FLAC__ASSERT(0 != encoder->private_);
  102563. FLAC__ASSERT(0 != encoder->private_->frame);
  102564. encoder->private_->is_being_deleted = true;
  102565. (void)FLAC__stream_encoder_finish(encoder);
  102566. if(0 != encoder->private_->verify.decoder)
  102567. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102568. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102569. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102570. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102571. }
  102572. for(i = 0; i < 2; i++) {
  102573. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102574. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102575. }
  102576. for(i = 0; i < 2; i++)
  102577. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102578. FLAC__bitwriter_delete(encoder->private_->frame);
  102579. free(encoder->private_);
  102580. free(encoder->protected_);
  102581. free(encoder);
  102582. }
  102583. /***********************************************************************
  102584. *
  102585. * Public class methods
  102586. *
  102587. ***********************************************************************/
  102588. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102589. FLAC__StreamEncoder *encoder,
  102590. FLAC__StreamEncoderReadCallback read_callback,
  102591. FLAC__StreamEncoderWriteCallback write_callback,
  102592. FLAC__StreamEncoderSeekCallback seek_callback,
  102593. FLAC__StreamEncoderTellCallback tell_callback,
  102594. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102595. void *client_data,
  102596. FLAC__bool is_ogg
  102597. )
  102598. {
  102599. unsigned i;
  102600. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102601. FLAC__ASSERT(0 != encoder);
  102602. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102603. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102604. #if !FLAC__HAS_OGG
  102605. if(is_ogg)
  102606. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102607. #endif
  102608. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102609. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102610. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102611. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102612. if(encoder->protected_->channels != 2) {
  102613. encoder->protected_->do_mid_side_stereo = false;
  102614. encoder->protected_->loose_mid_side_stereo = false;
  102615. }
  102616. else if(!encoder->protected_->do_mid_side_stereo)
  102617. encoder->protected_->loose_mid_side_stereo = false;
  102618. if(encoder->protected_->bits_per_sample >= 32)
  102619. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102620. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102621. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102622. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102623. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102624. if(encoder->protected_->blocksize == 0) {
  102625. if(encoder->protected_->max_lpc_order == 0)
  102626. encoder->protected_->blocksize = 1152;
  102627. else
  102628. encoder->protected_->blocksize = 4096;
  102629. }
  102630. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102631. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102632. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102633. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102634. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102635. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102636. if(encoder->protected_->qlp_coeff_precision == 0) {
  102637. if(encoder->protected_->bits_per_sample < 16) {
  102638. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102639. /* @@@ until then we'll make a guess */
  102640. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102641. }
  102642. else if(encoder->protected_->bits_per_sample == 16) {
  102643. if(encoder->protected_->blocksize <= 192)
  102644. encoder->protected_->qlp_coeff_precision = 7;
  102645. else if(encoder->protected_->blocksize <= 384)
  102646. encoder->protected_->qlp_coeff_precision = 8;
  102647. else if(encoder->protected_->blocksize <= 576)
  102648. encoder->protected_->qlp_coeff_precision = 9;
  102649. else if(encoder->protected_->blocksize <= 1152)
  102650. encoder->protected_->qlp_coeff_precision = 10;
  102651. else if(encoder->protected_->blocksize <= 2304)
  102652. encoder->protected_->qlp_coeff_precision = 11;
  102653. else if(encoder->protected_->blocksize <= 4608)
  102654. encoder->protected_->qlp_coeff_precision = 12;
  102655. else
  102656. encoder->protected_->qlp_coeff_precision = 13;
  102657. }
  102658. else {
  102659. if(encoder->protected_->blocksize <= 384)
  102660. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102661. else if(encoder->protected_->blocksize <= 1152)
  102662. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102663. else
  102664. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102665. }
  102666. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102667. }
  102668. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102669. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102670. if(encoder->protected_->streamable_subset) {
  102671. if(
  102672. encoder->protected_->blocksize != 192 &&
  102673. encoder->protected_->blocksize != 576 &&
  102674. encoder->protected_->blocksize != 1152 &&
  102675. encoder->protected_->blocksize != 2304 &&
  102676. encoder->protected_->blocksize != 4608 &&
  102677. encoder->protected_->blocksize != 256 &&
  102678. encoder->protected_->blocksize != 512 &&
  102679. encoder->protected_->blocksize != 1024 &&
  102680. encoder->protected_->blocksize != 2048 &&
  102681. encoder->protected_->blocksize != 4096 &&
  102682. encoder->protected_->blocksize != 8192 &&
  102683. encoder->protected_->blocksize != 16384
  102684. )
  102685. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102686. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102687. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102688. if(
  102689. encoder->protected_->bits_per_sample != 8 &&
  102690. encoder->protected_->bits_per_sample != 12 &&
  102691. encoder->protected_->bits_per_sample != 16 &&
  102692. encoder->protected_->bits_per_sample != 20 &&
  102693. encoder->protected_->bits_per_sample != 24
  102694. )
  102695. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102696. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102697. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102698. if(
  102699. encoder->protected_->sample_rate <= 48000 &&
  102700. (
  102701. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102702. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102703. )
  102704. ) {
  102705. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102706. }
  102707. }
  102708. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102709. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102710. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102711. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102712. #if FLAC__HAS_OGG
  102713. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102714. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102715. unsigned i;
  102716. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102717. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102718. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102719. for( ; i > 0; i--)
  102720. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102721. encoder->protected_->metadata[0] = vc;
  102722. break;
  102723. }
  102724. }
  102725. }
  102726. #endif
  102727. /* keep track of any SEEKTABLE block */
  102728. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102729. unsigned i;
  102730. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102731. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102732. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102733. break; /* take only the first one */
  102734. }
  102735. }
  102736. }
  102737. /* validate metadata */
  102738. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102739. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102740. metadata_has_seektable = false;
  102741. metadata_has_vorbis_comment = false;
  102742. metadata_picture_has_type1 = false;
  102743. metadata_picture_has_type2 = false;
  102744. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102745. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102746. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102747. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102748. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102749. if(metadata_has_seektable) /* only one is allowed */
  102750. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102751. metadata_has_seektable = true;
  102752. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102753. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102754. }
  102755. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102756. if(metadata_has_vorbis_comment) /* only one is allowed */
  102757. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102758. metadata_has_vorbis_comment = true;
  102759. }
  102760. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102761. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102762. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102763. }
  102764. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102765. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102766. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102767. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102768. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102769. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102770. metadata_picture_has_type1 = true;
  102771. /* standard icon must be 32x32 pixel PNG */
  102772. if(
  102773. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102774. (
  102775. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102776. m->data.picture.width != 32 ||
  102777. m->data.picture.height != 32
  102778. )
  102779. )
  102780. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102781. }
  102782. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102783. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102784. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102785. metadata_picture_has_type2 = true;
  102786. }
  102787. }
  102788. }
  102789. encoder->private_->input_capacity = 0;
  102790. for(i = 0; i < encoder->protected_->channels; i++) {
  102791. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102792. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102793. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102794. #endif
  102795. }
  102796. for(i = 0; i < 2; i++) {
  102797. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102798. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102799. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102800. #endif
  102801. }
  102802. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102803. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102804. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102805. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102806. #endif
  102807. for(i = 0; i < encoder->protected_->channels; i++) {
  102808. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102809. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102810. encoder->private_->best_subframe[i] = 0;
  102811. }
  102812. for(i = 0; i < 2; i++) {
  102813. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102814. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102815. encoder->private_->best_subframe_mid_side[i] = 0;
  102816. }
  102817. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102818. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102819. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102820. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102821. #else
  102822. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102823. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102824. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102825. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102826. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102827. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102828. 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);
  102829. #endif
  102830. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102831. encoder->private_->loose_mid_side_stereo_frames = 1;
  102832. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102833. encoder->private_->current_sample_number = 0;
  102834. encoder->private_->current_frame_number = 0;
  102835. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102836. 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? */
  102837. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102838. /*
  102839. * get the CPU info and set the function pointers
  102840. */
  102841. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102842. /* first default to the non-asm routines */
  102843. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102844. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102845. #endif
  102846. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102847. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102848. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102849. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102850. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102851. #endif
  102852. /* now override with asm where appropriate */
  102853. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102854. # ifndef FLAC__NO_ASM
  102855. if(encoder->private_->cpuinfo.use_asm) {
  102856. # ifdef FLAC__CPU_IA32
  102857. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102858. # ifdef FLAC__HAS_NASM
  102859. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102860. if(encoder->protected_->max_lpc_order < 4)
  102861. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102862. else if(encoder->protected_->max_lpc_order < 8)
  102863. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102864. else if(encoder->protected_->max_lpc_order < 12)
  102865. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102866. else
  102867. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102868. }
  102869. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102870. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102871. else
  102872. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102873. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102874. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102875. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102876. }
  102877. else {
  102878. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102879. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102880. }
  102881. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102882. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102883. # endif /* FLAC__HAS_NASM */
  102884. # endif /* FLAC__CPU_IA32 */
  102885. }
  102886. # endif /* !FLAC__NO_ASM */
  102887. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102888. /* finally override based on wide-ness if necessary */
  102889. if(encoder->private_->use_wide_by_block) {
  102890. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102891. }
  102892. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102893. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102894. #if FLAC__HAS_OGG
  102895. encoder->private_->is_ogg = is_ogg;
  102896. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102897. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102898. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102899. }
  102900. #endif
  102901. encoder->private_->read_callback = read_callback;
  102902. encoder->private_->write_callback = write_callback;
  102903. encoder->private_->seek_callback = seek_callback;
  102904. encoder->private_->tell_callback = tell_callback;
  102905. encoder->private_->metadata_callback = metadata_callback;
  102906. encoder->private_->client_data = client_data;
  102907. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102908. /* the above function sets the state for us in case of an error */
  102909. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102910. }
  102911. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102912. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102913. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102914. }
  102915. /*
  102916. * Set up the verify stuff if necessary
  102917. */
  102918. if(encoder->protected_->verify) {
  102919. /*
  102920. * First, set up the fifo which will hold the
  102921. * original signal to compare against
  102922. */
  102923. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102924. for(i = 0; i < encoder->protected_->channels; i++) {
  102925. 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))) {
  102926. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102927. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102928. }
  102929. }
  102930. encoder->private_->verify.input_fifo.tail = 0;
  102931. /*
  102932. * Now set up a stream decoder for verification
  102933. */
  102934. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102935. if(0 == encoder->private_->verify.decoder) {
  102936. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102937. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102938. }
  102939. 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) {
  102940. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102941. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102942. }
  102943. }
  102944. encoder->private_->verify.error_stats.absolute_sample = 0;
  102945. encoder->private_->verify.error_stats.frame_number = 0;
  102946. encoder->private_->verify.error_stats.channel = 0;
  102947. encoder->private_->verify.error_stats.sample = 0;
  102948. encoder->private_->verify.error_stats.expected = 0;
  102949. encoder->private_->verify.error_stats.got = 0;
  102950. /*
  102951. * These must be done before we write any metadata, because that
  102952. * calls the write_callback, which uses these values.
  102953. */
  102954. encoder->private_->first_seekpoint_to_check = 0;
  102955. encoder->private_->samples_written = 0;
  102956. encoder->protected_->streaminfo_offset = 0;
  102957. encoder->protected_->seektable_offset = 0;
  102958. encoder->protected_->audio_offset = 0;
  102959. /*
  102960. * write the stream header
  102961. */
  102962. if(encoder->protected_->verify)
  102963. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102964. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102965. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102966. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102967. }
  102968. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102969. /* the above function sets the state for us in case of an error */
  102970. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102971. }
  102972. /*
  102973. * write the STREAMINFO metadata block
  102974. */
  102975. if(encoder->protected_->verify)
  102976. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102977. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102978. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102979. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102980. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102981. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102982. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102983. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102984. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102985. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102986. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102987. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102988. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102989. if(encoder->protected_->do_md5)
  102990. FLAC__MD5Init(&encoder->private_->md5context);
  102991. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102992. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102993. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102994. }
  102995. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102996. /* the above function sets the state for us in case of an error */
  102997. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102998. }
  102999. /*
  103000. * Now that the STREAMINFO block is written, we can init this to an
  103001. * absurdly-high value...
  103002. */
  103003. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103004. /* ... and clear this to 0 */
  103005. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103006. /*
  103007. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103008. * if not, we will write an empty one (FLAC__add_metadata_block()
  103009. * automatically supplies the vendor string).
  103010. *
  103011. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103012. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103013. * true it will have already insured that the metadata list is properly
  103014. * ordered.)
  103015. */
  103016. if(!metadata_has_vorbis_comment) {
  103017. FLAC__StreamMetadata vorbis_comment;
  103018. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103019. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103020. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103021. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103022. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103023. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103024. vorbis_comment.data.vorbis_comment.comments = 0;
  103025. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103026. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103027. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103028. }
  103029. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103030. /* the above function sets the state for us in case of an error */
  103031. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103032. }
  103033. }
  103034. /*
  103035. * write the user's metadata blocks
  103036. */
  103037. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103038. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103039. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103040. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103041. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103042. }
  103043. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103044. /* the above function sets the state for us in case of an error */
  103045. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103046. }
  103047. }
  103048. /* now that all the metadata is written, we save the stream offset */
  103049. 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 */
  103050. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103051. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103052. }
  103053. if(encoder->protected_->verify)
  103054. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103055. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103056. }
  103057. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103058. FLAC__StreamEncoder *encoder,
  103059. FLAC__StreamEncoderWriteCallback write_callback,
  103060. FLAC__StreamEncoderSeekCallback seek_callback,
  103061. FLAC__StreamEncoderTellCallback tell_callback,
  103062. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103063. void *client_data
  103064. )
  103065. {
  103066. return init_stream_internal_enc(
  103067. encoder,
  103068. /*read_callback=*/0,
  103069. write_callback,
  103070. seek_callback,
  103071. tell_callback,
  103072. metadata_callback,
  103073. client_data,
  103074. /*is_ogg=*/false
  103075. );
  103076. }
  103077. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103078. FLAC__StreamEncoder *encoder,
  103079. FLAC__StreamEncoderReadCallback read_callback,
  103080. FLAC__StreamEncoderWriteCallback write_callback,
  103081. FLAC__StreamEncoderSeekCallback seek_callback,
  103082. FLAC__StreamEncoderTellCallback tell_callback,
  103083. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103084. void *client_data
  103085. )
  103086. {
  103087. return init_stream_internal_enc(
  103088. encoder,
  103089. read_callback,
  103090. write_callback,
  103091. seek_callback,
  103092. tell_callback,
  103093. metadata_callback,
  103094. client_data,
  103095. /*is_ogg=*/true
  103096. );
  103097. }
  103098. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103099. FLAC__StreamEncoder *encoder,
  103100. FILE *file,
  103101. FLAC__StreamEncoderProgressCallback progress_callback,
  103102. void *client_data,
  103103. FLAC__bool is_ogg
  103104. )
  103105. {
  103106. FLAC__StreamEncoderInitStatus init_status;
  103107. FLAC__ASSERT(0 != encoder);
  103108. FLAC__ASSERT(0 != file);
  103109. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103110. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103111. /* double protection */
  103112. if(file == 0) {
  103113. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103114. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103115. }
  103116. /*
  103117. * To make sure that our file does not go unclosed after an error, we
  103118. * must assign the FILE pointer before any further error can occur in
  103119. * this routine.
  103120. */
  103121. if(file == stdout)
  103122. file = get_binary_stdout_(); /* just to be safe */
  103123. encoder->private_->file = file;
  103124. encoder->private_->progress_callback = progress_callback;
  103125. encoder->private_->bytes_written = 0;
  103126. encoder->private_->samples_written = 0;
  103127. encoder->private_->frames_written = 0;
  103128. init_status = init_stream_internal_enc(
  103129. encoder,
  103130. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103131. file_write_callback_,
  103132. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103133. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103134. /*metadata_callback=*/0,
  103135. client_data,
  103136. is_ogg
  103137. );
  103138. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103139. /* the above function sets the state for us in case of an error */
  103140. return init_status;
  103141. }
  103142. {
  103143. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103144. FLAC__ASSERT(blocksize != 0);
  103145. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103146. }
  103147. return init_status;
  103148. }
  103149. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103150. FLAC__StreamEncoder *encoder,
  103151. FILE *file,
  103152. FLAC__StreamEncoderProgressCallback progress_callback,
  103153. void *client_data
  103154. )
  103155. {
  103156. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103157. }
  103158. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103159. FLAC__StreamEncoder *encoder,
  103160. FILE *file,
  103161. FLAC__StreamEncoderProgressCallback progress_callback,
  103162. void *client_data
  103163. )
  103164. {
  103165. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103166. }
  103167. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103168. FLAC__StreamEncoder *encoder,
  103169. const char *filename,
  103170. FLAC__StreamEncoderProgressCallback progress_callback,
  103171. void *client_data,
  103172. FLAC__bool is_ogg
  103173. )
  103174. {
  103175. FILE *file;
  103176. FLAC__ASSERT(0 != encoder);
  103177. /*
  103178. * To make sure that our file does not go unclosed after an error, we
  103179. * have to do the same entrance checks here that are later performed
  103180. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103181. */
  103182. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103183. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103184. file = filename? fopen(filename, "w+b") : stdout;
  103185. if(file == 0) {
  103186. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103187. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103188. }
  103189. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103190. }
  103191. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103192. FLAC__StreamEncoder *encoder,
  103193. const char *filename,
  103194. FLAC__StreamEncoderProgressCallback progress_callback,
  103195. void *client_data
  103196. )
  103197. {
  103198. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103199. }
  103200. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103201. FLAC__StreamEncoder *encoder,
  103202. const char *filename,
  103203. FLAC__StreamEncoderProgressCallback progress_callback,
  103204. void *client_data
  103205. )
  103206. {
  103207. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103208. }
  103209. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103210. {
  103211. FLAC__bool error = false;
  103212. FLAC__ASSERT(0 != encoder);
  103213. FLAC__ASSERT(0 != encoder->private_);
  103214. FLAC__ASSERT(0 != encoder->protected_);
  103215. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103216. return true;
  103217. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103218. if(encoder->private_->current_sample_number != 0) {
  103219. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103220. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103221. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103222. error = true;
  103223. }
  103224. }
  103225. if(encoder->protected_->do_md5)
  103226. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103227. if(!encoder->private_->is_being_deleted) {
  103228. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103229. if(encoder->private_->seek_callback) {
  103230. #if FLAC__HAS_OGG
  103231. if(encoder->private_->is_ogg)
  103232. update_ogg_metadata_(encoder);
  103233. else
  103234. #endif
  103235. update_metadata_(encoder);
  103236. /* check if an error occurred while updating metadata */
  103237. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103238. error = true;
  103239. }
  103240. if(encoder->private_->metadata_callback)
  103241. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103242. }
  103243. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103244. if(!error)
  103245. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103246. error = true;
  103247. }
  103248. }
  103249. if(0 != encoder->private_->file) {
  103250. if(encoder->private_->file != stdout)
  103251. fclose(encoder->private_->file);
  103252. encoder->private_->file = 0;
  103253. }
  103254. #if FLAC__HAS_OGG
  103255. if(encoder->private_->is_ogg)
  103256. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103257. #endif
  103258. free_(encoder);
  103259. set_defaults_enc(encoder);
  103260. if(!error)
  103261. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103262. return !error;
  103263. }
  103264. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103265. {
  103266. FLAC__ASSERT(0 != encoder);
  103267. FLAC__ASSERT(0 != encoder->private_);
  103268. FLAC__ASSERT(0 != encoder->protected_);
  103269. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103270. return false;
  103271. #if FLAC__HAS_OGG
  103272. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103273. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103274. return true;
  103275. #else
  103276. (void)value;
  103277. return false;
  103278. #endif
  103279. }
  103280. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103281. {
  103282. FLAC__ASSERT(0 != encoder);
  103283. FLAC__ASSERT(0 != encoder->private_);
  103284. FLAC__ASSERT(0 != encoder->protected_);
  103285. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103286. return false;
  103287. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103288. encoder->protected_->verify = value;
  103289. #endif
  103290. return true;
  103291. }
  103292. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103293. {
  103294. FLAC__ASSERT(0 != encoder);
  103295. FLAC__ASSERT(0 != encoder->private_);
  103296. FLAC__ASSERT(0 != encoder->protected_);
  103297. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103298. return false;
  103299. encoder->protected_->streamable_subset = value;
  103300. return true;
  103301. }
  103302. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103303. {
  103304. FLAC__ASSERT(0 != encoder);
  103305. FLAC__ASSERT(0 != encoder->private_);
  103306. FLAC__ASSERT(0 != encoder->protected_);
  103307. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103308. return false;
  103309. encoder->protected_->do_md5 = value;
  103310. return true;
  103311. }
  103312. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103313. {
  103314. FLAC__ASSERT(0 != encoder);
  103315. FLAC__ASSERT(0 != encoder->private_);
  103316. FLAC__ASSERT(0 != encoder->protected_);
  103317. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103318. return false;
  103319. encoder->protected_->channels = value;
  103320. return true;
  103321. }
  103322. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103323. {
  103324. FLAC__ASSERT(0 != encoder);
  103325. FLAC__ASSERT(0 != encoder->private_);
  103326. FLAC__ASSERT(0 != encoder->protected_);
  103327. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103328. return false;
  103329. encoder->protected_->bits_per_sample = value;
  103330. return true;
  103331. }
  103332. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103333. {
  103334. FLAC__ASSERT(0 != encoder);
  103335. FLAC__ASSERT(0 != encoder->private_);
  103336. FLAC__ASSERT(0 != encoder->protected_);
  103337. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103338. return false;
  103339. encoder->protected_->sample_rate = value;
  103340. return true;
  103341. }
  103342. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103343. {
  103344. FLAC__bool ok = true;
  103345. FLAC__ASSERT(0 != encoder);
  103346. FLAC__ASSERT(0 != encoder->private_);
  103347. FLAC__ASSERT(0 != encoder->protected_);
  103348. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103349. return false;
  103350. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103351. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103352. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103353. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103354. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103355. #if 0
  103356. /* was: */
  103357. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103358. /* but it's too hard to specify the string in a locale-specific way */
  103359. #else
  103360. encoder->protected_->num_apodizations = 1;
  103361. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103362. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103363. #endif
  103364. #endif
  103365. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103366. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103367. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103368. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103369. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103370. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103371. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103372. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103373. return ok;
  103374. }
  103375. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103376. {
  103377. FLAC__ASSERT(0 != encoder);
  103378. FLAC__ASSERT(0 != encoder->private_);
  103379. FLAC__ASSERT(0 != encoder->protected_);
  103380. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103381. return false;
  103382. encoder->protected_->blocksize = value;
  103383. return true;
  103384. }
  103385. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103386. {
  103387. FLAC__ASSERT(0 != encoder);
  103388. FLAC__ASSERT(0 != encoder->private_);
  103389. FLAC__ASSERT(0 != encoder->protected_);
  103390. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103391. return false;
  103392. encoder->protected_->do_mid_side_stereo = value;
  103393. return true;
  103394. }
  103395. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103396. {
  103397. FLAC__ASSERT(0 != encoder);
  103398. FLAC__ASSERT(0 != encoder->private_);
  103399. FLAC__ASSERT(0 != encoder->protected_);
  103400. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103401. return false;
  103402. encoder->protected_->loose_mid_side_stereo = value;
  103403. return true;
  103404. }
  103405. /*@@@@add to tests*/
  103406. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103407. {
  103408. FLAC__ASSERT(0 != encoder);
  103409. FLAC__ASSERT(0 != encoder->private_);
  103410. FLAC__ASSERT(0 != encoder->protected_);
  103411. FLAC__ASSERT(0 != specification);
  103412. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103413. return false;
  103414. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103415. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103416. #else
  103417. encoder->protected_->num_apodizations = 0;
  103418. while(1) {
  103419. const char *s = strchr(specification, ';');
  103420. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103421. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103422. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103423. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103424. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103425. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103426. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103427. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103428. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103429. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103430. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103431. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103432. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103433. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103434. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103435. if (stddev > 0.0 && stddev <= 0.5) {
  103436. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103437. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103438. }
  103439. }
  103440. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103441. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103442. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103443. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103444. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103445. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103446. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103447. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103448. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103449. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103450. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103451. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103452. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103453. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103454. if (p >= 0.0 && p <= 1.0) {
  103455. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103456. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103457. }
  103458. }
  103459. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103460. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103461. if (encoder->protected_->num_apodizations == 32)
  103462. break;
  103463. if (s)
  103464. specification = s+1;
  103465. else
  103466. break;
  103467. }
  103468. if(encoder->protected_->num_apodizations == 0) {
  103469. encoder->protected_->num_apodizations = 1;
  103470. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103471. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103472. }
  103473. #endif
  103474. return true;
  103475. }
  103476. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103477. {
  103478. FLAC__ASSERT(0 != encoder);
  103479. FLAC__ASSERT(0 != encoder->private_);
  103480. FLAC__ASSERT(0 != encoder->protected_);
  103481. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103482. return false;
  103483. encoder->protected_->max_lpc_order = value;
  103484. return true;
  103485. }
  103486. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103487. {
  103488. FLAC__ASSERT(0 != encoder);
  103489. FLAC__ASSERT(0 != encoder->private_);
  103490. FLAC__ASSERT(0 != encoder->protected_);
  103491. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103492. return false;
  103493. encoder->protected_->qlp_coeff_precision = value;
  103494. return true;
  103495. }
  103496. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103497. {
  103498. FLAC__ASSERT(0 != encoder);
  103499. FLAC__ASSERT(0 != encoder->private_);
  103500. FLAC__ASSERT(0 != encoder->protected_);
  103501. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103502. return false;
  103503. encoder->protected_->do_qlp_coeff_prec_search = value;
  103504. return true;
  103505. }
  103506. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103507. {
  103508. FLAC__ASSERT(0 != encoder);
  103509. FLAC__ASSERT(0 != encoder->private_);
  103510. FLAC__ASSERT(0 != encoder->protected_);
  103511. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103512. return false;
  103513. #if 0
  103514. /*@@@ deprecated: */
  103515. encoder->protected_->do_escape_coding = value;
  103516. #else
  103517. (void)value;
  103518. #endif
  103519. return true;
  103520. }
  103521. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103522. {
  103523. FLAC__ASSERT(0 != encoder);
  103524. FLAC__ASSERT(0 != encoder->private_);
  103525. FLAC__ASSERT(0 != encoder->protected_);
  103526. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103527. return false;
  103528. encoder->protected_->do_exhaustive_model_search = value;
  103529. return true;
  103530. }
  103531. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103532. {
  103533. FLAC__ASSERT(0 != encoder);
  103534. FLAC__ASSERT(0 != encoder->private_);
  103535. FLAC__ASSERT(0 != encoder->protected_);
  103536. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103537. return false;
  103538. encoder->protected_->min_residual_partition_order = value;
  103539. return true;
  103540. }
  103541. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103542. {
  103543. FLAC__ASSERT(0 != encoder);
  103544. FLAC__ASSERT(0 != encoder->private_);
  103545. FLAC__ASSERT(0 != encoder->protected_);
  103546. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103547. return false;
  103548. encoder->protected_->max_residual_partition_order = value;
  103549. return true;
  103550. }
  103551. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103552. {
  103553. FLAC__ASSERT(0 != encoder);
  103554. FLAC__ASSERT(0 != encoder->private_);
  103555. FLAC__ASSERT(0 != encoder->protected_);
  103556. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103557. return false;
  103558. #if 0
  103559. /*@@@ deprecated: */
  103560. encoder->protected_->rice_parameter_search_dist = value;
  103561. #else
  103562. (void)value;
  103563. #endif
  103564. return true;
  103565. }
  103566. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103567. {
  103568. FLAC__ASSERT(0 != encoder);
  103569. FLAC__ASSERT(0 != encoder->private_);
  103570. FLAC__ASSERT(0 != encoder->protected_);
  103571. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103572. return false;
  103573. encoder->protected_->total_samples_estimate = value;
  103574. return true;
  103575. }
  103576. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103577. {
  103578. FLAC__ASSERT(0 != encoder);
  103579. FLAC__ASSERT(0 != encoder->private_);
  103580. FLAC__ASSERT(0 != encoder->protected_);
  103581. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103582. return false;
  103583. if(0 == metadata)
  103584. num_blocks = 0;
  103585. if(0 == num_blocks)
  103586. metadata = 0;
  103587. /* realloc() does not do exactly what we want so... */
  103588. if(encoder->protected_->metadata) {
  103589. free(encoder->protected_->metadata);
  103590. encoder->protected_->metadata = 0;
  103591. encoder->protected_->num_metadata_blocks = 0;
  103592. }
  103593. if(num_blocks) {
  103594. FLAC__StreamMetadata **m;
  103595. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103596. return false;
  103597. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103598. encoder->protected_->metadata = m;
  103599. encoder->protected_->num_metadata_blocks = num_blocks;
  103600. }
  103601. #if FLAC__HAS_OGG
  103602. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103603. return false;
  103604. #endif
  103605. return true;
  103606. }
  103607. /*
  103608. * These three functions are not static, but not publically exposed in
  103609. * include/FLAC/ either. They are used by the test suite.
  103610. */
  103611. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103612. {
  103613. FLAC__ASSERT(0 != encoder);
  103614. FLAC__ASSERT(0 != encoder->private_);
  103615. FLAC__ASSERT(0 != encoder->protected_);
  103616. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103617. return false;
  103618. encoder->private_->disable_constant_subframes = value;
  103619. return true;
  103620. }
  103621. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103622. {
  103623. FLAC__ASSERT(0 != encoder);
  103624. FLAC__ASSERT(0 != encoder->private_);
  103625. FLAC__ASSERT(0 != encoder->protected_);
  103626. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103627. return false;
  103628. encoder->private_->disable_fixed_subframes = value;
  103629. return true;
  103630. }
  103631. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103632. {
  103633. FLAC__ASSERT(0 != encoder);
  103634. FLAC__ASSERT(0 != encoder->private_);
  103635. FLAC__ASSERT(0 != encoder->protected_);
  103636. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103637. return false;
  103638. encoder->private_->disable_verbatim_subframes = value;
  103639. return true;
  103640. }
  103641. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103642. {
  103643. FLAC__ASSERT(0 != encoder);
  103644. FLAC__ASSERT(0 != encoder->private_);
  103645. FLAC__ASSERT(0 != encoder->protected_);
  103646. return encoder->protected_->state;
  103647. }
  103648. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103649. {
  103650. FLAC__ASSERT(0 != encoder);
  103651. FLAC__ASSERT(0 != encoder->private_);
  103652. FLAC__ASSERT(0 != encoder->protected_);
  103653. if(encoder->protected_->verify)
  103654. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103655. else
  103656. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103657. }
  103658. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103659. {
  103660. FLAC__ASSERT(0 != encoder);
  103661. FLAC__ASSERT(0 != encoder->private_);
  103662. FLAC__ASSERT(0 != encoder->protected_);
  103663. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103664. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103665. else
  103666. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103667. }
  103668. 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)
  103669. {
  103670. FLAC__ASSERT(0 != encoder);
  103671. FLAC__ASSERT(0 != encoder->private_);
  103672. FLAC__ASSERT(0 != encoder->protected_);
  103673. if(0 != absolute_sample)
  103674. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103675. if(0 != frame_number)
  103676. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103677. if(0 != channel)
  103678. *channel = encoder->private_->verify.error_stats.channel;
  103679. if(0 != sample)
  103680. *sample = encoder->private_->verify.error_stats.sample;
  103681. if(0 != expected)
  103682. *expected = encoder->private_->verify.error_stats.expected;
  103683. if(0 != got)
  103684. *got = encoder->private_->verify.error_stats.got;
  103685. }
  103686. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103687. {
  103688. FLAC__ASSERT(0 != encoder);
  103689. FLAC__ASSERT(0 != encoder->private_);
  103690. FLAC__ASSERT(0 != encoder->protected_);
  103691. return encoder->protected_->verify;
  103692. }
  103693. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103694. {
  103695. FLAC__ASSERT(0 != encoder);
  103696. FLAC__ASSERT(0 != encoder->private_);
  103697. FLAC__ASSERT(0 != encoder->protected_);
  103698. return encoder->protected_->streamable_subset;
  103699. }
  103700. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103701. {
  103702. FLAC__ASSERT(0 != encoder);
  103703. FLAC__ASSERT(0 != encoder->private_);
  103704. FLAC__ASSERT(0 != encoder->protected_);
  103705. return encoder->protected_->do_md5;
  103706. }
  103707. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103708. {
  103709. FLAC__ASSERT(0 != encoder);
  103710. FLAC__ASSERT(0 != encoder->private_);
  103711. FLAC__ASSERT(0 != encoder->protected_);
  103712. return encoder->protected_->channels;
  103713. }
  103714. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103715. {
  103716. FLAC__ASSERT(0 != encoder);
  103717. FLAC__ASSERT(0 != encoder->private_);
  103718. FLAC__ASSERT(0 != encoder->protected_);
  103719. return encoder->protected_->bits_per_sample;
  103720. }
  103721. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103722. {
  103723. FLAC__ASSERT(0 != encoder);
  103724. FLAC__ASSERT(0 != encoder->private_);
  103725. FLAC__ASSERT(0 != encoder->protected_);
  103726. return encoder->protected_->sample_rate;
  103727. }
  103728. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103729. {
  103730. FLAC__ASSERT(0 != encoder);
  103731. FLAC__ASSERT(0 != encoder->private_);
  103732. FLAC__ASSERT(0 != encoder->protected_);
  103733. return encoder->protected_->blocksize;
  103734. }
  103735. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103736. {
  103737. FLAC__ASSERT(0 != encoder);
  103738. FLAC__ASSERT(0 != encoder->private_);
  103739. FLAC__ASSERT(0 != encoder->protected_);
  103740. return encoder->protected_->do_mid_side_stereo;
  103741. }
  103742. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103743. {
  103744. FLAC__ASSERT(0 != encoder);
  103745. FLAC__ASSERT(0 != encoder->private_);
  103746. FLAC__ASSERT(0 != encoder->protected_);
  103747. return encoder->protected_->loose_mid_side_stereo;
  103748. }
  103749. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103750. {
  103751. FLAC__ASSERT(0 != encoder);
  103752. FLAC__ASSERT(0 != encoder->private_);
  103753. FLAC__ASSERT(0 != encoder->protected_);
  103754. return encoder->protected_->max_lpc_order;
  103755. }
  103756. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103757. {
  103758. FLAC__ASSERT(0 != encoder);
  103759. FLAC__ASSERT(0 != encoder->private_);
  103760. FLAC__ASSERT(0 != encoder->protected_);
  103761. return encoder->protected_->qlp_coeff_precision;
  103762. }
  103763. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103764. {
  103765. FLAC__ASSERT(0 != encoder);
  103766. FLAC__ASSERT(0 != encoder->private_);
  103767. FLAC__ASSERT(0 != encoder->protected_);
  103768. return encoder->protected_->do_qlp_coeff_prec_search;
  103769. }
  103770. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103771. {
  103772. FLAC__ASSERT(0 != encoder);
  103773. FLAC__ASSERT(0 != encoder->private_);
  103774. FLAC__ASSERT(0 != encoder->protected_);
  103775. return encoder->protected_->do_escape_coding;
  103776. }
  103777. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103778. {
  103779. FLAC__ASSERT(0 != encoder);
  103780. FLAC__ASSERT(0 != encoder->private_);
  103781. FLAC__ASSERT(0 != encoder->protected_);
  103782. return encoder->protected_->do_exhaustive_model_search;
  103783. }
  103784. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103785. {
  103786. FLAC__ASSERT(0 != encoder);
  103787. FLAC__ASSERT(0 != encoder->private_);
  103788. FLAC__ASSERT(0 != encoder->protected_);
  103789. return encoder->protected_->min_residual_partition_order;
  103790. }
  103791. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103792. {
  103793. FLAC__ASSERT(0 != encoder);
  103794. FLAC__ASSERT(0 != encoder->private_);
  103795. FLAC__ASSERT(0 != encoder->protected_);
  103796. return encoder->protected_->max_residual_partition_order;
  103797. }
  103798. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103799. {
  103800. FLAC__ASSERT(0 != encoder);
  103801. FLAC__ASSERT(0 != encoder->private_);
  103802. FLAC__ASSERT(0 != encoder->protected_);
  103803. return encoder->protected_->rice_parameter_search_dist;
  103804. }
  103805. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103806. {
  103807. FLAC__ASSERT(0 != encoder);
  103808. FLAC__ASSERT(0 != encoder->private_);
  103809. FLAC__ASSERT(0 != encoder->protected_);
  103810. return encoder->protected_->total_samples_estimate;
  103811. }
  103812. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103813. {
  103814. unsigned i, j = 0, channel;
  103815. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103816. FLAC__ASSERT(0 != encoder);
  103817. FLAC__ASSERT(0 != encoder->private_);
  103818. FLAC__ASSERT(0 != encoder->protected_);
  103819. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103820. do {
  103821. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103822. if(encoder->protected_->verify)
  103823. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103824. for(channel = 0; channel < channels; channel++)
  103825. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103826. if(encoder->protected_->do_mid_side_stereo) {
  103827. FLAC__ASSERT(channels == 2);
  103828. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103829. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103830. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103831. 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' ! */
  103832. }
  103833. }
  103834. else
  103835. j += n;
  103836. encoder->private_->current_sample_number += n;
  103837. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103838. if(encoder->private_->current_sample_number > blocksize) {
  103839. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103840. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103841. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103842. return false;
  103843. /* move unprocessed overread samples to beginnings of arrays */
  103844. for(channel = 0; channel < channels; channel++)
  103845. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103846. if(encoder->protected_->do_mid_side_stereo) {
  103847. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103848. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103849. }
  103850. encoder->private_->current_sample_number = 1;
  103851. }
  103852. } while(j < samples);
  103853. return true;
  103854. }
  103855. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103856. {
  103857. unsigned i, j, k, channel;
  103858. FLAC__int32 x, mid, side;
  103859. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103860. FLAC__ASSERT(0 != encoder);
  103861. FLAC__ASSERT(0 != encoder->private_);
  103862. FLAC__ASSERT(0 != encoder->protected_);
  103863. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103864. j = k = 0;
  103865. /*
  103866. * we have several flavors of the same basic loop, optimized for
  103867. * different conditions:
  103868. */
  103869. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103870. /*
  103871. * stereo coding: unroll channel loop
  103872. */
  103873. do {
  103874. if(encoder->protected_->verify)
  103875. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103876. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103877. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103878. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103879. x = buffer[k++];
  103880. encoder->private_->integer_signal[1][i] = x;
  103881. mid += x;
  103882. side -= x;
  103883. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103884. encoder->private_->integer_signal_mid_side[1][i] = side;
  103885. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103886. }
  103887. encoder->private_->current_sample_number = i;
  103888. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103889. if(i > blocksize) {
  103890. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103891. return false;
  103892. /* move unprocessed overread samples to beginnings of arrays */
  103893. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103894. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103895. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103896. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103897. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103898. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103899. encoder->private_->current_sample_number = 1;
  103900. }
  103901. } while(j < samples);
  103902. }
  103903. else {
  103904. /*
  103905. * independent channel coding: buffer each channel in inner loop
  103906. */
  103907. do {
  103908. if(encoder->protected_->verify)
  103909. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103910. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103911. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103912. for(channel = 0; channel < channels; channel++)
  103913. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103914. }
  103915. encoder->private_->current_sample_number = i;
  103916. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103917. if(i > blocksize) {
  103918. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103919. return false;
  103920. /* move unprocessed overread samples to beginnings of arrays */
  103921. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103922. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103923. for(channel = 0; channel < channels; channel++)
  103924. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103925. encoder->private_->current_sample_number = 1;
  103926. }
  103927. } while(j < samples);
  103928. }
  103929. return true;
  103930. }
  103931. /***********************************************************************
  103932. *
  103933. * Private class methods
  103934. *
  103935. ***********************************************************************/
  103936. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103937. {
  103938. FLAC__ASSERT(0 != encoder);
  103939. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103940. encoder->protected_->verify = true;
  103941. #else
  103942. encoder->protected_->verify = false;
  103943. #endif
  103944. encoder->protected_->streamable_subset = true;
  103945. encoder->protected_->do_md5 = true;
  103946. encoder->protected_->do_mid_side_stereo = false;
  103947. encoder->protected_->loose_mid_side_stereo = false;
  103948. encoder->protected_->channels = 2;
  103949. encoder->protected_->bits_per_sample = 16;
  103950. encoder->protected_->sample_rate = 44100;
  103951. encoder->protected_->blocksize = 0;
  103952. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103953. encoder->protected_->num_apodizations = 1;
  103954. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103955. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103956. #endif
  103957. encoder->protected_->max_lpc_order = 0;
  103958. encoder->protected_->qlp_coeff_precision = 0;
  103959. encoder->protected_->do_qlp_coeff_prec_search = false;
  103960. encoder->protected_->do_exhaustive_model_search = false;
  103961. encoder->protected_->do_escape_coding = false;
  103962. encoder->protected_->min_residual_partition_order = 0;
  103963. encoder->protected_->max_residual_partition_order = 0;
  103964. encoder->protected_->rice_parameter_search_dist = 0;
  103965. encoder->protected_->total_samples_estimate = 0;
  103966. encoder->protected_->metadata = 0;
  103967. encoder->protected_->num_metadata_blocks = 0;
  103968. encoder->private_->seek_table = 0;
  103969. encoder->private_->disable_constant_subframes = false;
  103970. encoder->private_->disable_fixed_subframes = false;
  103971. encoder->private_->disable_verbatim_subframes = false;
  103972. #if FLAC__HAS_OGG
  103973. encoder->private_->is_ogg = false;
  103974. #endif
  103975. encoder->private_->read_callback = 0;
  103976. encoder->private_->write_callback = 0;
  103977. encoder->private_->seek_callback = 0;
  103978. encoder->private_->tell_callback = 0;
  103979. encoder->private_->metadata_callback = 0;
  103980. encoder->private_->progress_callback = 0;
  103981. encoder->private_->client_data = 0;
  103982. #if FLAC__HAS_OGG
  103983. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103984. #endif
  103985. }
  103986. void free_(FLAC__StreamEncoder *encoder)
  103987. {
  103988. unsigned i, channel;
  103989. FLAC__ASSERT(0 != encoder);
  103990. if(encoder->protected_->metadata) {
  103991. free(encoder->protected_->metadata);
  103992. encoder->protected_->metadata = 0;
  103993. encoder->protected_->num_metadata_blocks = 0;
  103994. }
  103995. for(i = 0; i < encoder->protected_->channels; i++) {
  103996. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103997. free(encoder->private_->integer_signal_unaligned[i]);
  103998. encoder->private_->integer_signal_unaligned[i] = 0;
  103999. }
  104000. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104001. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104002. free(encoder->private_->real_signal_unaligned[i]);
  104003. encoder->private_->real_signal_unaligned[i] = 0;
  104004. }
  104005. #endif
  104006. }
  104007. for(i = 0; i < 2; i++) {
  104008. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104009. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104010. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104011. }
  104012. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104013. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104014. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104015. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104016. }
  104017. #endif
  104018. }
  104019. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104020. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104021. if(0 != encoder->private_->window_unaligned[i]) {
  104022. free(encoder->private_->window_unaligned[i]);
  104023. encoder->private_->window_unaligned[i] = 0;
  104024. }
  104025. }
  104026. if(0 != encoder->private_->windowed_signal_unaligned) {
  104027. free(encoder->private_->windowed_signal_unaligned);
  104028. encoder->private_->windowed_signal_unaligned = 0;
  104029. }
  104030. #endif
  104031. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104032. for(i = 0; i < 2; i++) {
  104033. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104034. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104035. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104036. }
  104037. }
  104038. }
  104039. for(channel = 0; channel < 2; channel++) {
  104040. for(i = 0; i < 2; i++) {
  104041. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104042. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104043. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104044. }
  104045. }
  104046. }
  104047. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104048. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104049. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104050. }
  104051. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104052. free(encoder->private_->raw_bits_per_partition_unaligned);
  104053. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104054. }
  104055. if(encoder->protected_->verify) {
  104056. for(i = 0; i < encoder->protected_->channels; i++) {
  104057. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104058. free(encoder->private_->verify.input_fifo.data[i]);
  104059. encoder->private_->verify.input_fifo.data[i] = 0;
  104060. }
  104061. }
  104062. }
  104063. FLAC__bitwriter_free(encoder->private_->frame);
  104064. }
  104065. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104066. {
  104067. FLAC__bool ok;
  104068. unsigned i, channel;
  104069. FLAC__ASSERT(new_blocksize > 0);
  104070. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104071. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104072. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104073. if(new_blocksize <= encoder->private_->input_capacity)
  104074. return true;
  104075. ok = true;
  104076. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104077. * requires that the input arrays (in our case the integer signals)
  104078. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104079. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104080. */
  104081. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104082. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104083. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104084. encoder->private_->integer_signal[i] += 4;
  104085. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104086. #if 0 /* @@@ currently unused */
  104087. if(encoder->protected_->max_lpc_order > 0)
  104088. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104089. #endif
  104090. #endif
  104091. }
  104092. for(i = 0; ok && i < 2; i++) {
  104093. 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]);
  104094. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104095. encoder->private_->integer_signal_mid_side[i] += 4;
  104096. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104097. #if 0 /* @@@ currently unused */
  104098. if(encoder->protected_->max_lpc_order > 0)
  104099. 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]);
  104100. #endif
  104101. #endif
  104102. }
  104103. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104104. if(ok && encoder->protected_->max_lpc_order > 0) {
  104105. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104106. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104107. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104108. }
  104109. #endif
  104110. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104111. for(i = 0; ok && i < 2; i++) {
  104112. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104113. }
  104114. }
  104115. for(channel = 0; ok && channel < 2; channel++) {
  104116. for(i = 0; ok && i < 2; i++) {
  104117. 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]);
  104118. }
  104119. }
  104120. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104121. /*@@@ 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) */
  104122. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104123. if(encoder->protected_->do_escape_coding)
  104124. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104125. /* now adjust the windows if the blocksize has changed */
  104126. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104127. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104128. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104129. switch(encoder->protected_->apodizations[i].type) {
  104130. case FLAC__APODIZATION_BARTLETT:
  104131. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104132. break;
  104133. case FLAC__APODIZATION_BARTLETT_HANN:
  104134. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104135. break;
  104136. case FLAC__APODIZATION_BLACKMAN:
  104137. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104138. break;
  104139. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104140. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104141. break;
  104142. case FLAC__APODIZATION_CONNES:
  104143. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104144. break;
  104145. case FLAC__APODIZATION_FLATTOP:
  104146. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104147. break;
  104148. case FLAC__APODIZATION_GAUSS:
  104149. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104150. break;
  104151. case FLAC__APODIZATION_HAMMING:
  104152. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104153. break;
  104154. case FLAC__APODIZATION_HANN:
  104155. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104156. break;
  104157. case FLAC__APODIZATION_KAISER_BESSEL:
  104158. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104159. break;
  104160. case FLAC__APODIZATION_NUTTALL:
  104161. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104162. break;
  104163. case FLAC__APODIZATION_RECTANGLE:
  104164. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104165. break;
  104166. case FLAC__APODIZATION_TRIANGLE:
  104167. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104168. break;
  104169. case FLAC__APODIZATION_TUKEY:
  104170. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104171. break;
  104172. case FLAC__APODIZATION_WELCH:
  104173. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104174. break;
  104175. default:
  104176. FLAC__ASSERT(0);
  104177. /* double protection */
  104178. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104179. break;
  104180. }
  104181. }
  104182. }
  104183. #endif
  104184. if(ok)
  104185. encoder->private_->input_capacity = new_blocksize;
  104186. else
  104187. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104188. return ok;
  104189. }
  104190. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104191. {
  104192. const FLAC__byte *buffer;
  104193. size_t bytes;
  104194. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104195. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104196. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104197. return false;
  104198. }
  104199. if(encoder->protected_->verify) {
  104200. encoder->private_->verify.output.data = buffer;
  104201. encoder->private_->verify.output.bytes = bytes;
  104202. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104203. encoder->private_->verify.needs_magic_hack = true;
  104204. }
  104205. else {
  104206. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104207. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104208. FLAC__bitwriter_clear(encoder->private_->frame);
  104209. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104210. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104211. return false;
  104212. }
  104213. }
  104214. }
  104215. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104216. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104217. FLAC__bitwriter_clear(encoder->private_->frame);
  104218. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104219. return false;
  104220. }
  104221. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104222. FLAC__bitwriter_clear(encoder->private_->frame);
  104223. if(samples > 0) {
  104224. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104225. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104226. }
  104227. return true;
  104228. }
  104229. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104230. {
  104231. FLAC__StreamEncoderWriteStatus status;
  104232. FLAC__uint64 output_position = 0;
  104233. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104234. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104235. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104236. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104237. }
  104238. /*
  104239. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104240. */
  104241. if(samples == 0) {
  104242. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104243. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104244. encoder->protected_->streaminfo_offset = output_position;
  104245. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104246. encoder->protected_->seektable_offset = output_position;
  104247. }
  104248. /*
  104249. * Mark the current seek point if hit (if audio_offset == 0 that
  104250. * means we're still writing metadata and haven't hit the first
  104251. * frame yet)
  104252. */
  104253. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104254. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104255. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104256. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104257. FLAC__uint64 test_sample;
  104258. unsigned i;
  104259. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104260. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104261. if(test_sample > frame_last_sample) {
  104262. break;
  104263. }
  104264. else if(test_sample >= frame_first_sample) {
  104265. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104266. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104267. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104268. encoder->private_->first_seekpoint_to_check++;
  104269. /* DO NOT: "break;" and here's why:
  104270. * The seektable template may contain more than one target
  104271. * sample for any given frame; we will keep looping, generating
  104272. * duplicate seekpoints for them, and we'll clean it up later,
  104273. * just before writing the seektable back to the metadata.
  104274. */
  104275. }
  104276. else {
  104277. encoder->private_->first_seekpoint_to_check++;
  104278. }
  104279. }
  104280. }
  104281. #if FLAC__HAS_OGG
  104282. if(encoder->private_->is_ogg) {
  104283. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104284. &encoder->protected_->ogg_encoder_aspect,
  104285. buffer,
  104286. bytes,
  104287. samples,
  104288. encoder->private_->current_frame_number,
  104289. is_last_block,
  104290. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104291. encoder,
  104292. encoder->private_->client_data
  104293. );
  104294. }
  104295. else
  104296. #endif
  104297. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104298. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104299. encoder->private_->bytes_written += bytes;
  104300. encoder->private_->samples_written += samples;
  104301. /* we keep a high watermark on the number of frames written because
  104302. * when the encoder goes back to write metadata, 'current_frame'
  104303. * will drop back to 0.
  104304. */
  104305. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104306. }
  104307. else
  104308. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104309. return status;
  104310. }
  104311. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104312. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104313. {
  104314. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104315. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104316. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104317. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104318. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104319. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104320. FLAC__StreamEncoderSeekStatus seek_status;
  104321. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104322. /* All this is based on intimate knowledge of the stream header
  104323. * layout, but a change to the header format that would break this
  104324. * would also break all streams encoded in the previous format.
  104325. */
  104326. /*
  104327. * Write MD5 signature
  104328. */
  104329. {
  104330. const unsigned md5_offset =
  104331. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104332. (
  104333. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104334. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104335. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104336. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104337. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104338. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104339. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104340. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104341. ) / 8;
  104342. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104343. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104344. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104345. return;
  104346. }
  104347. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104348. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104349. return;
  104350. }
  104351. }
  104352. /*
  104353. * Write total samples
  104354. */
  104355. {
  104356. const unsigned total_samples_byte_offset =
  104357. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104358. (
  104359. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104360. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104361. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104362. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104363. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104364. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104365. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104366. - 4
  104367. ) / 8;
  104368. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104369. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104370. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104371. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104372. b[4] = (FLAC__byte)(samples & 0xFF);
  104373. 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) {
  104374. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104375. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104376. return;
  104377. }
  104378. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104379. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104380. return;
  104381. }
  104382. }
  104383. /*
  104384. * Write min/max framesize
  104385. */
  104386. {
  104387. const unsigned min_framesize_offset =
  104388. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104389. (
  104390. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104391. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104392. ) / 8;
  104393. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104394. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104395. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104396. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104397. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104398. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104399. 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) {
  104400. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104401. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104402. return;
  104403. }
  104404. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104405. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104406. return;
  104407. }
  104408. }
  104409. /*
  104410. * Write seektable
  104411. */
  104412. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104413. unsigned i;
  104414. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104415. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104416. 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) {
  104417. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104418. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104419. return;
  104420. }
  104421. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104422. FLAC__uint64 xx;
  104423. unsigned x;
  104424. xx = encoder->private_->seek_table->points[i].sample_number;
  104425. b[7] = (FLAC__byte)xx; xx >>= 8;
  104426. b[6] = (FLAC__byte)xx; xx >>= 8;
  104427. b[5] = (FLAC__byte)xx; xx >>= 8;
  104428. b[4] = (FLAC__byte)xx; xx >>= 8;
  104429. b[3] = (FLAC__byte)xx; xx >>= 8;
  104430. b[2] = (FLAC__byte)xx; xx >>= 8;
  104431. b[1] = (FLAC__byte)xx; xx >>= 8;
  104432. b[0] = (FLAC__byte)xx; xx >>= 8;
  104433. xx = encoder->private_->seek_table->points[i].stream_offset;
  104434. b[15] = (FLAC__byte)xx; xx >>= 8;
  104435. b[14] = (FLAC__byte)xx; xx >>= 8;
  104436. b[13] = (FLAC__byte)xx; xx >>= 8;
  104437. b[12] = (FLAC__byte)xx; xx >>= 8;
  104438. b[11] = (FLAC__byte)xx; xx >>= 8;
  104439. b[10] = (FLAC__byte)xx; xx >>= 8;
  104440. b[9] = (FLAC__byte)xx; xx >>= 8;
  104441. b[8] = (FLAC__byte)xx; xx >>= 8;
  104442. x = encoder->private_->seek_table->points[i].frame_samples;
  104443. b[17] = (FLAC__byte)x; x >>= 8;
  104444. b[16] = (FLAC__byte)x; x >>= 8;
  104445. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104446. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104447. return;
  104448. }
  104449. }
  104450. }
  104451. }
  104452. #if FLAC__HAS_OGG
  104453. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104454. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104455. {
  104456. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104457. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104458. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104459. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104460. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104461. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104462. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104463. FLAC__STREAM_SYNC_LENGTH
  104464. ;
  104465. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104466. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104467. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104468. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104469. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104470. ogg_page page;
  104471. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104472. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104473. /* Pre-check that client supports seeking, since we don't want the
  104474. * ogg_helper code to ever have to deal with this condition.
  104475. */
  104476. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104477. return;
  104478. /* All this is based on intimate knowledge of the stream header
  104479. * layout, but a change to the header format that would break this
  104480. * would also break all streams encoded in the previous format.
  104481. */
  104482. /**
  104483. ** Write STREAMINFO stats
  104484. **/
  104485. simple_ogg_page__init(&page);
  104486. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104487. simple_ogg_page__clear(&page);
  104488. return; /* state already set */
  104489. }
  104490. /*
  104491. * Write MD5 signature
  104492. */
  104493. {
  104494. const unsigned md5_offset =
  104495. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104496. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104497. (
  104498. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104499. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104500. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104501. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104502. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104503. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104504. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104505. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104506. ) / 8;
  104507. if(md5_offset + 16 > (unsigned)page.body_len) {
  104508. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104509. simple_ogg_page__clear(&page);
  104510. return;
  104511. }
  104512. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104513. }
  104514. /*
  104515. * Write total samples
  104516. */
  104517. {
  104518. const unsigned total_samples_byte_offset =
  104519. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104520. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104521. (
  104522. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104523. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104524. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104525. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104526. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104527. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104528. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104529. - 4
  104530. ) / 8;
  104531. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104532. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104533. simple_ogg_page__clear(&page);
  104534. return;
  104535. }
  104536. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104537. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104538. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104539. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104540. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104541. b[4] = (FLAC__byte)(samples & 0xFF);
  104542. memcpy(page.body + total_samples_byte_offset, b, 5);
  104543. }
  104544. /*
  104545. * Write min/max framesize
  104546. */
  104547. {
  104548. const unsigned min_framesize_offset =
  104549. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104550. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104551. (
  104552. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104553. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104554. ) / 8;
  104555. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104556. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104557. simple_ogg_page__clear(&page);
  104558. return;
  104559. }
  104560. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104561. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104562. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104563. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104564. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104565. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104566. memcpy(page.body + min_framesize_offset, b, 6);
  104567. }
  104568. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104569. simple_ogg_page__clear(&page);
  104570. return; /* state already set */
  104571. }
  104572. simple_ogg_page__clear(&page);
  104573. /*
  104574. * Write seektable
  104575. */
  104576. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104577. unsigned i;
  104578. FLAC__byte *p;
  104579. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104580. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104581. simple_ogg_page__init(&page);
  104582. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104583. simple_ogg_page__clear(&page);
  104584. return; /* state already set */
  104585. }
  104586. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104587. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104588. simple_ogg_page__clear(&page);
  104589. return;
  104590. }
  104591. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104592. FLAC__uint64 xx;
  104593. unsigned x;
  104594. xx = encoder->private_->seek_table->points[i].sample_number;
  104595. b[7] = (FLAC__byte)xx; xx >>= 8;
  104596. b[6] = (FLAC__byte)xx; xx >>= 8;
  104597. b[5] = (FLAC__byte)xx; xx >>= 8;
  104598. b[4] = (FLAC__byte)xx; xx >>= 8;
  104599. b[3] = (FLAC__byte)xx; xx >>= 8;
  104600. b[2] = (FLAC__byte)xx; xx >>= 8;
  104601. b[1] = (FLAC__byte)xx; xx >>= 8;
  104602. b[0] = (FLAC__byte)xx; xx >>= 8;
  104603. xx = encoder->private_->seek_table->points[i].stream_offset;
  104604. b[15] = (FLAC__byte)xx; xx >>= 8;
  104605. b[14] = (FLAC__byte)xx; xx >>= 8;
  104606. b[13] = (FLAC__byte)xx; xx >>= 8;
  104607. b[12] = (FLAC__byte)xx; xx >>= 8;
  104608. b[11] = (FLAC__byte)xx; xx >>= 8;
  104609. b[10] = (FLAC__byte)xx; xx >>= 8;
  104610. b[9] = (FLAC__byte)xx; xx >>= 8;
  104611. b[8] = (FLAC__byte)xx; xx >>= 8;
  104612. x = encoder->private_->seek_table->points[i].frame_samples;
  104613. b[17] = (FLAC__byte)x; x >>= 8;
  104614. b[16] = (FLAC__byte)x; x >>= 8;
  104615. memcpy(p, b, 18);
  104616. }
  104617. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104618. simple_ogg_page__clear(&page);
  104619. return; /* state already set */
  104620. }
  104621. simple_ogg_page__clear(&page);
  104622. }
  104623. }
  104624. #endif
  104625. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104626. {
  104627. FLAC__uint16 crc;
  104628. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104629. /*
  104630. * Accumulate raw signal to the MD5 signature
  104631. */
  104632. 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)) {
  104633. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104634. return false;
  104635. }
  104636. /*
  104637. * Process the frame header and subframes into the frame bitbuffer
  104638. */
  104639. if(!process_subframes_(encoder, is_fractional_block)) {
  104640. /* the above function sets the state for us in case of an error */
  104641. return false;
  104642. }
  104643. /*
  104644. * Zero-pad the frame to a byte_boundary
  104645. */
  104646. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104647. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104648. return false;
  104649. }
  104650. /*
  104651. * CRC-16 the whole thing
  104652. */
  104653. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104654. if(
  104655. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104656. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104657. ) {
  104658. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104659. return false;
  104660. }
  104661. /*
  104662. * Write it
  104663. */
  104664. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104665. /* the above function sets the state for us in case of an error */
  104666. return false;
  104667. }
  104668. /*
  104669. * Get ready for the next frame
  104670. */
  104671. encoder->private_->current_sample_number = 0;
  104672. encoder->private_->current_frame_number++;
  104673. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104674. return true;
  104675. }
  104676. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104677. {
  104678. FLAC__FrameHeader frame_header;
  104679. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104680. FLAC__bool do_independent, do_mid_side;
  104681. /*
  104682. * Calculate the min,max Rice partition orders
  104683. */
  104684. if(is_fractional_block) {
  104685. max_partition_order = 0;
  104686. }
  104687. else {
  104688. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104689. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104690. }
  104691. min_partition_order = min(min_partition_order, max_partition_order);
  104692. /*
  104693. * Setup the frame
  104694. */
  104695. frame_header.blocksize = encoder->protected_->blocksize;
  104696. frame_header.sample_rate = encoder->protected_->sample_rate;
  104697. frame_header.channels = encoder->protected_->channels;
  104698. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104699. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104700. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104701. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104702. /*
  104703. * Figure out what channel assignments to try
  104704. */
  104705. if(encoder->protected_->do_mid_side_stereo) {
  104706. if(encoder->protected_->loose_mid_side_stereo) {
  104707. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104708. do_independent = true;
  104709. do_mid_side = true;
  104710. }
  104711. else {
  104712. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104713. do_mid_side = !do_independent;
  104714. }
  104715. }
  104716. else {
  104717. do_independent = true;
  104718. do_mid_side = true;
  104719. }
  104720. }
  104721. else {
  104722. do_independent = true;
  104723. do_mid_side = false;
  104724. }
  104725. FLAC__ASSERT(do_independent || do_mid_side);
  104726. /*
  104727. * Check for wasted bits; set effective bps for each subframe
  104728. */
  104729. if(do_independent) {
  104730. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104731. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104732. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104733. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104734. }
  104735. }
  104736. if(do_mid_side) {
  104737. FLAC__ASSERT(encoder->protected_->channels == 2);
  104738. for(channel = 0; channel < 2; channel++) {
  104739. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104740. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104741. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104742. }
  104743. }
  104744. /*
  104745. * First do a normal encoding pass of each independent channel
  104746. */
  104747. if(do_independent) {
  104748. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104749. if(!
  104750. process_subframe_(
  104751. encoder,
  104752. min_partition_order,
  104753. max_partition_order,
  104754. &frame_header,
  104755. encoder->private_->subframe_bps[channel],
  104756. encoder->private_->integer_signal[channel],
  104757. encoder->private_->subframe_workspace_ptr[channel],
  104758. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104759. encoder->private_->residual_workspace[channel],
  104760. encoder->private_->best_subframe+channel,
  104761. encoder->private_->best_subframe_bits+channel
  104762. )
  104763. )
  104764. return false;
  104765. }
  104766. }
  104767. /*
  104768. * Now do mid and side channels if requested
  104769. */
  104770. if(do_mid_side) {
  104771. FLAC__ASSERT(encoder->protected_->channels == 2);
  104772. for(channel = 0; channel < 2; channel++) {
  104773. if(!
  104774. process_subframe_(
  104775. encoder,
  104776. min_partition_order,
  104777. max_partition_order,
  104778. &frame_header,
  104779. encoder->private_->subframe_bps_mid_side[channel],
  104780. encoder->private_->integer_signal_mid_side[channel],
  104781. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104782. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104783. encoder->private_->residual_workspace_mid_side[channel],
  104784. encoder->private_->best_subframe_mid_side+channel,
  104785. encoder->private_->best_subframe_bits_mid_side+channel
  104786. )
  104787. )
  104788. return false;
  104789. }
  104790. }
  104791. /*
  104792. * Compose the frame bitbuffer
  104793. */
  104794. if(do_mid_side) {
  104795. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104796. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104797. FLAC__ChannelAssignment channel_assignment;
  104798. FLAC__ASSERT(encoder->protected_->channels == 2);
  104799. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104800. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104801. }
  104802. else {
  104803. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104804. unsigned min_bits;
  104805. int ca;
  104806. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104807. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104808. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104809. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104810. FLAC__ASSERT(do_independent && do_mid_side);
  104811. /* We have to figure out which channel assignent results in the smallest frame */
  104812. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104813. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104814. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104815. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104816. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104817. min_bits = bits[channel_assignment];
  104818. for(ca = 1; ca <= 3; ca++) {
  104819. if(bits[ca] < min_bits) {
  104820. min_bits = bits[ca];
  104821. channel_assignment = (FLAC__ChannelAssignment)ca;
  104822. }
  104823. }
  104824. }
  104825. frame_header.channel_assignment = channel_assignment;
  104826. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104827. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104828. return false;
  104829. }
  104830. switch(channel_assignment) {
  104831. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104832. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104833. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104834. break;
  104835. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104836. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104837. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104838. break;
  104839. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104840. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104841. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104842. break;
  104843. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104844. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104845. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104846. break;
  104847. default:
  104848. FLAC__ASSERT(0);
  104849. }
  104850. switch(channel_assignment) {
  104851. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104852. left_bps = encoder->private_->subframe_bps [0];
  104853. right_bps = encoder->private_->subframe_bps [1];
  104854. break;
  104855. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104856. left_bps = encoder->private_->subframe_bps [0];
  104857. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104858. break;
  104859. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104860. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104861. right_bps = encoder->private_->subframe_bps [1];
  104862. break;
  104863. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104864. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104865. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104866. break;
  104867. default:
  104868. FLAC__ASSERT(0);
  104869. }
  104870. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104871. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104872. return false;
  104873. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104874. return false;
  104875. }
  104876. else {
  104877. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104878. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104879. return false;
  104880. }
  104881. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104882. 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)) {
  104883. /* the above function sets the state for us in case of an error */
  104884. return false;
  104885. }
  104886. }
  104887. }
  104888. if(encoder->protected_->loose_mid_side_stereo) {
  104889. encoder->private_->loose_mid_side_stereo_frame_count++;
  104890. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104891. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104892. }
  104893. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104894. return true;
  104895. }
  104896. FLAC__bool process_subframe_(
  104897. FLAC__StreamEncoder *encoder,
  104898. unsigned min_partition_order,
  104899. unsigned max_partition_order,
  104900. const FLAC__FrameHeader *frame_header,
  104901. unsigned subframe_bps,
  104902. const FLAC__int32 integer_signal[],
  104903. FLAC__Subframe *subframe[2],
  104904. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104905. FLAC__int32 *residual[2],
  104906. unsigned *best_subframe,
  104907. unsigned *best_bits
  104908. )
  104909. {
  104910. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104911. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104912. #else
  104913. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104914. #endif
  104915. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104916. FLAC__double lpc_residual_bits_per_sample;
  104917. 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 */
  104918. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104919. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104920. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104921. #endif
  104922. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104923. unsigned rice_parameter;
  104924. unsigned _candidate_bits, _best_bits;
  104925. unsigned _best_subframe;
  104926. /* only use RICE2 partitions if stream bps > 16 */
  104927. 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;
  104928. FLAC__ASSERT(frame_header->blocksize > 0);
  104929. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104930. _best_subframe = 0;
  104931. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104932. _best_bits = UINT_MAX;
  104933. else
  104934. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104935. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104936. unsigned signal_is_constant = false;
  104937. 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);
  104938. /* check for constant subframe */
  104939. if(
  104940. !encoder->private_->disable_constant_subframes &&
  104941. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104942. fixed_residual_bits_per_sample[1] == 0.0
  104943. #else
  104944. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104945. #endif
  104946. ) {
  104947. /* the above means it's possible all samples are the same value; now double-check it: */
  104948. unsigned i;
  104949. signal_is_constant = true;
  104950. for(i = 1; i < frame_header->blocksize; i++) {
  104951. if(integer_signal[0] != integer_signal[i]) {
  104952. signal_is_constant = false;
  104953. break;
  104954. }
  104955. }
  104956. }
  104957. if(signal_is_constant) {
  104958. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104959. if(_candidate_bits < _best_bits) {
  104960. _best_subframe = !_best_subframe;
  104961. _best_bits = _candidate_bits;
  104962. }
  104963. }
  104964. else {
  104965. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104966. /* encode fixed */
  104967. if(encoder->protected_->do_exhaustive_model_search) {
  104968. min_fixed_order = 0;
  104969. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104970. }
  104971. else {
  104972. min_fixed_order = max_fixed_order = guess_fixed_order;
  104973. }
  104974. if(max_fixed_order >= frame_header->blocksize)
  104975. max_fixed_order = frame_header->blocksize - 1;
  104976. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104977. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104978. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104979. continue; /* don't even try */
  104980. 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 */
  104981. #else
  104982. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104983. continue; /* don't even try */
  104984. 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 */
  104985. #endif
  104986. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104987. if(rice_parameter >= rice_parameter_limit) {
  104988. #ifdef DEBUG_VERBOSE
  104989. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104990. #endif
  104991. rice_parameter = rice_parameter_limit - 1;
  104992. }
  104993. _candidate_bits =
  104994. evaluate_fixed_subframe_(
  104995. encoder,
  104996. integer_signal,
  104997. residual[!_best_subframe],
  104998. encoder->private_->abs_residual_partition_sums,
  104999. encoder->private_->raw_bits_per_partition,
  105000. frame_header->blocksize,
  105001. subframe_bps,
  105002. fixed_order,
  105003. rice_parameter,
  105004. rice_parameter_limit,
  105005. min_partition_order,
  105006. max_partition_order,
  105007. encoder->protected_->do_escape_coding,
  105008. encoder->protected_->rice_parameter_search_dist,
  105009. subframe[!_best_subframe],
  105010. partitioned_rice_contents[!_best_subframe]
  105011. );
  105012. if(_candidate_bits < _best_bits) {
  105013. _best_subframe = !_best_subframe;
  105014. _best_bits = _candidate_bits;
  105015. }
  105016. }
  105017. }
  105018. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105019. /* encode lpc */
  105020. if(encoder->protected_->max_lpc_order > 0) {
  105021. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105022. max_lpc_order = frame_header->blocksize-1;
  105023. else
  105024. max_lpc_order = encoder->protected_->max_lpc_order;
  105025. if(max_lpc_order > 0) {
  105026. unsigned a;
  105027. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105028. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105029. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105030. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105031. if(autoc[0] != 0.0) {
  105032. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105033. if(encoder->protected_->do_exhaustive_model_search) {
  105034. min_lpc_order = 1;
  105035. }
  105036. else {
  105037. const unsigned guess_lpc_order =
  105038. FLAC__lpc_compute_best_order(
  105039. lpc_error,
  105040. max_lpc_order,
  105041. frame_header->blocksize,
  105042. subframe_bps + (
  105043. encoder->protected_->do_qlp_coeff_prec_search?
  105044. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105045. encoder->protected_->qlp_coeff_precision
  105046. )
  105047. );
  105048. min_lpc_order = max_lpc_order = guess_lpc_order;
  105049. }
  105050. if(max_lpc_order >= frame_header->blocksize)
  105051. max_lpc_order = frame_header->blocksize - 1;
  105052. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105053. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105054. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105055. continue; /* don't even try */
  105056. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105057. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105058. if(rice_parameter >= rice_parameter_limit) {
  105059. #ifdef DEBUG_VERBOSE
  105060. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105061. #endif
  105062. rice_parameter = rice_parameter_limit - 1;
  105063. }
  105064. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105065. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105066. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105067. if(subframe_bps <= 17) {
  105068. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105069. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105070. }
  105071. else
  105072. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105073. }
  105074. else {
  105075. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105076. }
  105077. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105078. _candidate_bits =
  105079. evaluate_lpc_subframe_(
  105080. encoder,
  105081. integer_signal,
  105082. residual[!_best_subframe],
  105083. encoder->private_->abs_residual_partition_sums,
  105084. encoder->private_->raw_bits_per_partition,
  105085. encoder->private_->lp_coeff[lpc_order-1],
  105086. frame_header->blocksize,
  105087. subframe_bps,
  105088. lpc_order,
  105089. qlp_coeff_precision,
  105090. rice_parameter,
  105091. rice_parameter_limit,
  105092. min_partition_order,
  105093. max_partition_order,
  105094. encoder->protected_->do_escape_coding,
  105095. encoder->protected_->rice_parameter_search_dist,
  105096. subframe[!_best_subframe],
  105097. partitioned_rice_contents[!_best_subframe]
  105098. );
  105099. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105100. if(_candidate_bits < _best_bits) {
  105101. _best_subframe = !_best_subframe;
  105102. _best_bits = _candidate_bits;
  105103. }
  105104. }
  105105. }
  105106. }
  105107. }
  105108. }
  105109. }
  105110. }
  105111. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105112. }
  105113. }
  105114. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105115. if(_best_bits == UINT_MAX) {
  105116. FLAC__ASSERT(_best_subframe == 0);
  105117. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105118. }
  105119. *best_subframe = _best_subframe;
  105120. *best_bits = _best_bits;
  105121. return true;
  105122. }
  105123. FLAC__bool add_subframe_(
  105124. FLAC__StreamEncoder *encoder,
  105125. unsigned blocksize,
  105126. unsigned subframe_bps,
  105127. const FLAC__Subframe *subframe,
  105128. FLAC__BitWriter *frame
  105129. )
  105130. {
  105131. switch(subframe->type) {
  105132. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105133. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105134. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105135. return false;
  105136. }
  105137. break;
  105138. case FLAC__SUBFRAME_TYPE_FIXED:
  105139. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105140. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105141. return false;
  105142. }
  105143. break;
  105144. case FLAC__SUBFRAME_TYPE_LPC:
  105145. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105146. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105147. return false;
  105148. }
  105149. break;
  105150. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105151. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105152. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105153. return false;
  105154. }
  105155. break;
  105156. default:
  105157. FLAC__ASSERT(0);
  105158. }
  105159. return true;
  105160. }
  105161. #define SPOTCHECK_ESTIMATE 0
  105162. #if SPOTCHECK_ESTIMATE
  105163. static void spotcheck_subframe_estimate_(
  105164. FLAC__StreamEncoder *encoder,
  105165. unsigned blocksize,
  105166. unsigned subframe_bps,
  105167. const FLAC__Subframe *subframe,
  105168. unsigned estimate
  105169. )
  105170. {
  105171. FLAC__bool ret;
  105172. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105173. if(frame == 0) {
  105174. fprintf(stderr, "EST: can't allocate frame\n");
  105175. return;
  105176. }
  105177. if(!FLAC__bitwriter_init(frame)) {
  105178. fprintf(stderr, "EST: can't init frame\n");
  105179. return;
  105180. }
  105181. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105182. FLAC__ASSERT(ret);
  105183. {
  105184. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105185. if(estimate != actual)
  105186. 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);
  105187. }
  105188. FLAC__bitwriter_delete(frame);
  105189. }
  105190. #endif
  105191. unsigned evaluate_constant_subframe_(
  105192. FLAC__StreamEncoder *encoder,
  105193. const FLAC__int32 signal,
  105194. unsigned blocksize,
  105195. unsigned subframe_bps,
  105196. FLAC__Subframe *subframe
  105197. )
  105198. {
  105199. unsigned estimate;
  105200. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105201. subframe->data.constant.value = signal;
  105202. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105203. #if SPOTCHECK_ESTIMATE
  105204. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105205. #else
  105206. (void)encoder, (void)blocksize;
  105207. #endif
  105208. return estimate;
  105209. }
  105210. unsigned evaluate_fixed_subframe_(
  105211. FLAC__StreamEncoder *encoder,
  105212. const FLAC__int32 signal[],
  105213. FLAC__int32 residual[],
  105214. FLAC__uint64 abs_residual_partition_sums[],
  105215. unsigned raw_bits_per_partition[],
  105216. unsigned blocksize,
  105217. unsigned subframe_bps,
  105218. unsigned order,
  105219. unsigned rice_parameter,
  105220. unsigned rice_parameter_limit,
  105221. unsigned min_partition_order,
  105222. unsigned max_partition_order,
  105223. FLAC__bool do_escape_coding,
  105224. unsigned rice_parameter_search_dist,
  105225. FLAC__Subframe *subframe,
  105226. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105227. )
  105228. {
  105229. unsigned i, residual_bits, estimate;
  105230. const unsigned residual_samples = blocksize - order;
  105231. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105232. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105233. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105234. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105235. subframe->data.fixed.residual = residual;
  105236. residual_bits =
  105237. find_best_partition_order_(
  105238. encoder->private_,
  105239. residual,
  105240. abs_residual_partition_sums,
  105241. raw_bits_per_partition,
  105242. residual_samples,
  105243. order,
  105244. rice_parameter,
  105245. rice_parameter_limit,
  105246. min_partition_order,
  105247. max_partition_order,
  105248. subframe_bps,
  105249. do_escape_coding,
  105250. rice_parameter_search_dist,
  105251. &subframe->data.fixed.entropy_coding_method
  105252. );
  105253. subframe->data.fixed.order = order;
  105254. for(i = 0; i < order; i++)
  105255. subframe->data.fixed.warmup[i] = signal[i];
  105256. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105257. #if SPOTCHECK_ESTIMATE
  105258. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105259. #endif
  105260. return estimate;
  105261. }
  105262. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105263. unsigned evaluate_lpc_subframe_(
  105264. FLAC__StreamEncoder *encoder,
  105265. const FLAC__int32 signal[],
  105266. FLAC__int32 residual[],
  105267. FLAC__uint64 abs_residual_partition_sums[],
  105268. unsigned raw_bits_per_partition[],
  105269. const FLAC__real lp_coeff[],
  105270. unsigned blocksize,
  105271. unsigned subframe_bps,
  105272. unsigned order,
  105273. unsigned qlp_coeff_precision,
  105274. unsigned rice_parameter,
  105275. unsigned rice_parameter_limit,
  105276. unsigned min_partition_order,
  105277. unsigned max_partition_order,
  105278. FLAC__bool do_escape_coding,
  105279. unsigned rice_parameter_search_dist,
  105280. FLAC__Subframe *subframe,
  105281. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105282. )
  105283. {
  105284. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105285. unsigned i, residual_bits, estimate;
  105286. int quantization, ret;
  105287. const unsigned residual_samples = blocksize - order;
  105288. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105289. if(subframe_bps <= 16) {
  105290. FLAC__ASSERT(order > 0);
  105291. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105292. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105293. }
  105294. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105295. if(ret != 0)
  105296. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105297. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105298. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105299. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105300. else
  105301. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105302. else
  105303. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105304. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105305. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105306. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105307. subframe->data.lpc.residual = residual;
  105308. residual_bits =
  105309. find_best_partition_order_(
  105310. encoder->private_,
  105311. residual,
  105312. abs_residual_partition_sums,
  105313. raw_bits_per_partition,
  105314. residual_samples,
  105315. order,
  105316. rice_parameter,
  105317. rice_parameter_limit,
  105318. min_partition_order,
  105319. max_partition_order,
  105320. subframe_bps,
  105321. do_escape_coding,
  105322. rice_parameter_search_dist,
  105323. &subframe->data.lpc.entropy_coding_method
  105324. );
  105325. subframe->data.lpc.order = order;
  105326. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105327. subframe->data.lpc.quantization_level = quantization;
  105328. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105329. for(i = 0; i < order; i++)
  105330. subframe->data.lpc.warmup[i] = signal[i];
  105331. 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;
  105332. #if SPOTCHECK_ESTIMATE
  105333. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105334. #endif
  105335. return estimate;
  105336. }
  105337. #endif
  105338. unsigned evaluate_verbatim_subframe_(
  105339. FLAC__StreamEncoder *encoder,
  105340. const FLAC__int32 signal[],
  105341. unsigned blocksize,
  105342. unsigned subframe_bps,
  105343. FLAC__Subframe *subframe
  105344. )
  105345. {
  105346. unsigned estimate;
  105347. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105348. subframe->data.verbatim.data = signal;
  105349. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105350. #if SPOTCHECK_ESTIMATE
  105351. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105352. #else
  105353. (void)encoder;
  105354. #endif
  105355. return estimate;
  105356. }
  105357. unsigned find_best_partition_order_(
  105358. FLAC__StreamEncoderPrivate *private_,
  105359. const FLAC__int32 residual[],
  105360. FLAC__uint64 abs_residual_partition_sums[],
  105361. unsigned raw_bits_per_partition[],
  105362. unsigned residual_samples,
  105363. unsigned predictor_order,
  105364. unsigned rice_parameter,
  105365. unsigned rice_parameter_limit,
  105366. unsigned min_partition_order,
  105367. unsigned max_partition_order,
  105368. unsigned bps,
  105369. FLAC__bool do_escape_coding,
  105370. unsigned rice_parameter_search_dist,
  105371. FLAC__EntropyCodingMethod *best_ecm
  105372. )
  105373. {
  105374. unsigned residual_bits, best_residual_bits = 0;
  105375. unsigned best_parameters_index = 0;
  105376. unsigned best_partition_order = 0;
  105377. const unsigned blocksize = residual_samples + predictor_order;
  105378. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105379. min_partition_order = min(min_partition_order, max_partition_order);
  105380. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105381. if(do_escape_coding)
  105382. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105383. {
  105384. int partition_order;
  105385. unsigned sum;
  105386. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105387. if(!
  105388. set_partitioned_rice_(
  105389. #ifdef EXACT_RICE_BITS_CALCULATION
  105390. residual,
  105391. #endif
  105392. abs_residual_partition_sums+sum,
  105393. raw_bits_per_partition+sum,
  105394. residual_samples,
  105395. predictor_order,
  105396. rice_parameter,
  105397. rice_parameter_limit,
  105398. rice_parameter_search_dist,
  105399. (unsigned)partition_order,
  105400. do_escape_coding,
  105401. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105402. &residual_bits
  105403. )
  105404. )
  105405. {
  105406. FLAC__ASSERT(best_residual_bits != 0);
  105407. break;
  105408. }
  105409. sum += 1u << partition_order;
  105410. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105411. best_residual_bits = residual_bits;
  105412. best_parameters_index = !best_parameters_index;
  105413. best_partition_order = partition_order;
  105414. }
  105415. }
  105416. }
  105417. best_ecm->data.partitioned_rice.order = best_partition_order;
  105418. {
  105419. /*
  105420. * We are allowed to de-const the pointer based on our special
  105421. * knowledge; it is const to the outside world.
  105422. */
  105423. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105424. unsigned partition;
  105425. /* save best parameters and raw_bits */
  105426. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105427. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105428. if(do_escape_coding)
  105429. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105430. /*
  105431. * Now need to check if the type should be changed to
  105432. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105433. * size of the rice parameters.
  105434. */
  105435. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105436. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105437. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105438. break;
  105439. }
  105440. }
  105441. }
  105442. return best_residual_bits;
  105443. }
  105444. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105445. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105446. const FLAC__int32 residual[],
  105447. FLAC__uint64 abs_residual_partition_sums[],
  105448. unsigned blocksize,
  105449. unsigned predictor_order,
  105450. unsigned min_partition_order,
  105451. unsigned max_partition_order
  105452. );
  105453. #endif
  105454. void precompute_partition_info_sums_(
  105455. const FLAC__int32 residual[],
  105456. FLAC__uint64 abs_residual_partition_sums[],
  105457. unsigned residual_samples,
  105458. unsigned predictor_order,
  105459. unsigned min_partition_order,
  105460. unsigned max_partition_order,
  105461. unsigned bps
  105462. )
  105463. {
  105464. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105465. unsigned partitions = 1u << max_partition_order;
  105466. FLAC__ASSERT(default_partition_samples > predictor_order);
  105467. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105468. /* slightly pessimistic but still catches all common cases */
  105469. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105470. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105471. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105472. return;
  105473. }
  105474. #endif
  105475. /* first do max_partition_order */
  105476. {
  105477. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105478. /* slightly pessimistic but still catches all common cases */
  105479. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105480. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105481. FLAC__uint32 abs_residual_partition_sum;
  105482. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105483. end += default_partition_samples;
  105484. abs_residual_partition_sum = 0;
  105485. for( ; residual_sample < end; residual_sample++)
  105486. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105487. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105488. }
  105489. }
  105490. else { /* have to pessimistically use 64 bits for accumulator */
  105491. FLAC__uint64 abs_residual_partition_sum;
  105492. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105493. end += default_partition_samples;
  105494. abs_residual_partition_sum = 0;
  105495. for( ; residual_sample < end; residual_sample++)
  105496. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105497. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105498. }
  105499. }
  105500. }
  105501. /* now merge partitions for lower orders */
  105502. {
  105503. unsigned from_partition = 0, to_partition = partitions;
  105504. int partition_order;
  105505. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105506. unsigned i;
  105507. partitions >>= 1;
  105508. for(i = 0; i < partitions; i++) {
  105509. abs_residual_partition_sums[to_partition++] =
  105510. abs_residual_partition_sums[from_partition ] +
  105511. abs_residual_partition_sums[from_partition+1];
  105512. from_partition += 2;
  105513. }
  105514. }
  105515. }
  105516. }
  105517. void precompute_partition_info_escapes_(
  105518. const FLAC__int32 residual[],
  105519. unsigned raw_bits_per_partition[],
  105520. unsigned residual_samples,
  105521. unsigned predictor_order,
  105522. unsigned min_partition_order,
  105523. unsigned max_partition_order
  105524. )
  105525. {
  105526. int partition_order;
  105527. unsigned from_partition, to_partition = 0;
  105528. const unsigned blocksize = residual_samples + predictor_order;
  105529. /* first do max_partition_order */
  105530. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105531. FLAC__int32 r;
  105532. FLAC__uint32 rmax;
  105533. unsigned partition, partition_sample, partition_samples, residual_sample;
  105534. const unsigned partitions = 1u << partition_order;
  105535. const unsigned default_partition_samples = blocksize >> partition_order;
  105536. FLAC__ASSERT(default_partition_samples > predictor_order);
  105537. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105538. partition_samples = default_partition_samples;
  105539. if(partition == 0)
  105540. partition_samples -= predictor_order;
  105541. rmax = 0;
  105542. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105543. r = residual[residual_sample++];
  105544. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105545. if(r < 0)
  105546. rmax |= ~r;
  105547. else
  105548. rmax |= r;
  105549. }
  105550. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105551. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105552. }
  105553. to_partition = partitions;
  105554. break; /*@@@ yuck, should remove the 'for' loop instead */
  105555. }
  105556. /* now merge partitions for lower orders */
  105557. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105558. unsigned m;
  105559. unsigned i;
  105560. const unsigned partitions = 1u << partition_order;
  105561. for(i = 0; i < partitions; i++) {
  105562. m = raw_bits_per_partition[from_partition];
  105563. from_partition++;
  105564. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105565. from_partition++;
  105566. to_partition++;
  105567. }
  105568. }
  105569. }
  105570. #ifdef EXACT_RICE_BITS_CALCULATION
  105571. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105572. const unsigned rice_parameter,
  105573. const unsigned partition_samples,
  105574. const FLAC__int32 *residual
  105575. )
  105576. {
  105577. unsigned i, partition_bits =
  105578. 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 */
  105579. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105580. ;
  105581. for(i = 0; i < partition_samples; i++)
  105582. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105583. return partition_bits;
  105584. }
  105585. #else
  105586. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105587. const unsigned rice_parameter,
  105588. const unsigned partition_samples,
  105589. const FLAC__uint64 abs_residual_partition_sum
  105590. )
  105591. {
  105592. return
  105593. 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 */
  105594. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105595. (
  105596. rice_parameter?
  105597. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105598. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105599. )
  105600. - (partition_samples >> 1)
  105601. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105602. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105603. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105604. * So the subtraction term tries to guess how many extra bits were contributed.
  105605. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105606. */
  105607. ;
  105608. }
  105609. #endif
  105610. FLAC__bool set_partitioned_rice_(
  105611. #ifdef EXACT_RICE_BITS_CALCULATION
  105612. const FLAC__int32 residual[],
  105613. #endif
  105614. const FLAC__uint64 abs_residual_partition_sums[],
  105615. const unsigned raw_bits_per_partition[],
  105616. const unsigned residual_samples,
  105617. const unsigned predictor_order,
  105618. const unsigned suggested_rice_parameter,
  105619. const unsigned rice_parameter_limit,
  105620. const unsigned rice_parameter_search_dist,
  105621. const unsigned partition_order,
  105622. const FLAC__bool search_for_escapes,
  105623. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105624. unsigned *bits
  105625. )
  105626. {
  105627. unsigned rice_parameter, partition_bits;
  105628. unsigned best_partition_bits, best_rice_parameter = 0;
  105629. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105630. unsigned *parameters, *raw_bits;
  105631. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105632. unsigned min_rice_parameter, max_rice_parameter;
  105633. #else
  105634. (void)rice_parameter_search_dist;
  105635. #endif
  105636. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105637. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105638. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105639. parameters = partitioned_rice_contents->parameters;
  105640. raw_bits = partitioned_rice_contents->raw_bits;
  105641. if(partition_order == 0) {
  105642. best_partition_bits = (unsigned)(-1);
  105643. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105644. if(rice_parameter_search_dist) {
  105645. if(suggested_rice_parameter < rice_parameter_search_dist)
  105646. min_rice_parameter = 0;
  105647. else
  105648. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105649. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105650. if(max_rice_parameter >= rice_parameter_limit) {
  105651. #ifdef DEBUG_VERBOSE
  105652. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105653. #endif
  105654. max_rice_parameter = rice_parameter_limit - 1;
  105655. }
  105656. }
  105657. else
  105658. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105659. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105660. #else
  105661. rice_parameter = suggested_rice_parameter;
  105662. #endif
  105663. #ifdef EXACT_RICE_BITS_CALCULATION
  105664. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105665. #else
  105666. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105667. #endif
  105668. if(partition_bits < best_partition_bits) {
  105669. best_rice_parameter = rice_parameter;
  105670. best_partition_bits = partition_bits;
  105671. }
  105672. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105673. }
  105674. #endif
  105675. if(search_for_escapes) {
  105676. 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;
  105677. if(partition_bits <= best_partition_bits) {
  105678. raw_bits[0] = raw_bits_per_partition[0];
  105679. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105680. best_partition_bits = partition_bits;
  105681. }
  105682. else
  105683. raw_bits[0] = 0;
  105684. }
  105685. parameters[0] = best_rice_parameter;
  105686. bits_ += best_partition_bits;
  105687. }
  105688. else {
  105689. unsigned partition, residual_sample;
  105690. unsigned partition_samples;
  105691. FLAC__uint64 mean, k;
  105692. const unsigned partitions = 1u << partition_order;
  105693. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105694. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105695. if(partition == 0) {
  105696. if(partition_samples <= predictor_order)
  105697. return false;
  105698. else
  105699. partition_samples -= predictor_order;
  105700. }
  105701. mean = abs_residual_partition_sums[partition];
  105702. /* we are basically calculating the size in bits of the
  105703. * average residual magnitude in the partition:
  105704. * rice_parameter = floor(log2(mean/partition_samples))
  105705. * 'mean' is not a good name for the variable, it is
  105706. * actually the sum of magnitudes of all residual values
  105707. * in the partition, so the actual mean is
  105708. * mean/partition_samples
  105709. */
  105710. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105711. ;
  105712. if(rice_parameter >= rice_parameter_limit) {
  105713. #ifdef DEBUG_VERBOSE
  105714. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105715. #endif
  105716. rice_parameter = rice_parameter_limit - 1;
  105717. }
  105718. best_partition_bits = (unsigned)(-1);
  105719. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105720. if(rice_parameter_search_dist) {
  105721. if(rice_parameter < rice_parameter_search_dist)
  105722. min_rice_parameter = 0;
  105723. else
  105724. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105725. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105726. if(max_rice_parameter >= rice_parameter_limit) {
  105727. #ifdef DEBUG_VERBOSE
  105728. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105729. #endif
  105730. max_rice_parameter = rice_parameter_limit - 1;
  105731. }
  105732. }
  105733. else
  105734. min_rice_parameter = max_rice_parameter = rice_parameter;
  105735. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105736. #endif
  105737. #ifdef EXACT_RICE_BITS_CALCULATION
  105738. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105739. #else
  105740. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105741. #endif
  105742. if(partition_bits < best_partition_bits) {
  105743. best_rice_parameter = rice_parameter;
  105744. best_partition_bits = partition_bits;
  105745. }
  105746. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105747. }
  105748. #endif
  105749. if(search_for_escapes) {
  105750. 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;
  105751. if(partition_bits <= best_partition_bits) {
  105752. raw_bits[partition] = raw_bits_per_partition[partition];
  105753. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105754. best_partition_bits = partition_bits;
  105755. }
  105756. else
  105757. raw_bits[partition] = 0;
  105758. }
  105759. parameters[partition] = best_rice_parameter;
  105760. bits_ += best_partition_bits;
  105761. residual_sample += partition_samples;
  105762. }
  105763. }
  105764. *bits = bits_;
  105765. return true;
  105766. }
  105767. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105768. {
  105769. unsigned i, shift;
  105770. FLAC__int32 x = 0;
  105771. for(i = 0; i < samples && !(x&1); i++)
  105772. x |= signal[i];
  105773. if(x == 0) {
  105774. shift = 0;
  105775. }
  105776. else {
  105777. for(shift = 0; !(x&1); shift++)
  105778. x >>= 1;
  105779. }
  105780. if(shift > 0) {
  105781. for(i = 0; i < samples; i++)
  105782. signal[i] >>= shift;
  105783. }
  105784. return shift;
  105785. }
  105786. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105787. {
  105788. unsigned channel;
  105789. for(channel = 0; channel < channels; channel++)
  105790. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105791. fifo->tail += wide_samples;
  105792. FLAC__ASSERT(fifo->tail <= fifo->size);
  105793. }
  105794. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105795. {
  105796. unsigned channel;
  105797. unsigned sample, wide_sample;
  105798. unsigned tail = fifo->tail;
  105799. sample = input_offset * channels;
  105800. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105801. for(channel = 0; channel < channels; channel++)
  105802. fifo->data[channel][tail] = input[sample++];
  105803. tail++;
  105804. }
  105805. fifo->tail = tail;
  105806. FLAC__ASSERT(fifo->tail <= fifo->size);
  105807. }
  105808. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105809. {
  105810. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105811. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105812. (void)decoder;
  105813. if(encoder->private_->verify.needs_magic_hack) {
  105814. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105815. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105816. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105817. encoder->private_->verify.needs_magic_hack = false;
  105818. }
  105819. else {
  105820. if(encoded_bytes == 0) {
  105821. /*
  105822. * If we get here, a FIFO underflow has occurred,
  105823. * which means there is a bug somewhere.
  105824. */
  105825. FLAC__ASSERT(0);
  105826. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105827. }
  105828. else if(encoded_bytes < *bytes)
  105829. *bytes = encoded_bytes;
  105830. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105831. encoder->private_->verify.output.data += *bytes;
  105832. encoder->private_->verify.output.bytes -= *bytes;
  105833. }
  105834. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105835. }
  105836. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105837. {
  105838. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105839. unsigned channel;
  105840. const unsigned channels = frame->header.channels;
  105841. const unsigned blocksize = frame->header.blocksize;
  105842. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105843. (void)decoder;
  105844. for(channel = 0; channel < channels; channel++) {
  105845. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105846. unsigned i, sample = 0;
  105847. FLAC__int32 expect = 0, got = 0;
  105848. for(i = 0; i < blocksize; i++) {
  105849. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105850. sample = i;
  105851. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105852. got = (FLAC__int32)buffer[channel][i];
  105853. break;
  105854. }
  105855. }
  105856. FLAC__ASSERT(i < blocksize);
  105857. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105858. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105859. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105860. encoder->private_->verify.error_stats.channel = channel;
  105861. encoder->private_->verify.error_stats.sample = sample;
  105862. encoder->private_->verify.error_stats.expected = expect;
  105863. encoder->private_->verify.error_stats.got = got;
  105864. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105865. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105866. }
  105867. }
  105868. /* dequeue the frame from the fifo */
  105869. encoder->private_->verify.input_fifo.tail -= blocksize;
  105870. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105871. for(channel = 0; channel < channels; channel++)
  105872. 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]));
  105873. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105874. }
  105875. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105876. {
  105877. (void)decoder, (void)metadata, (void)client_data;
  105878. }
  105879. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105880. {
  105881. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105882. (void)decoder, (void)status;
  105883. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105884. }
  105885. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105886. {
  105887. (void)client_data;
  105888. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105889. if (*bytes == 0) {
  105890. if (feof(encoder->private_->file))
  105891. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105892. else if (ferror(encoder->private_->file))
  105893. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105894. }
  105895. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105896. }
  105897. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105898. {
  105899. (void)client_data;
  105900. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105901. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105902. else
  105903. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105904. }
  105905. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105906. {
  105907. off_t offset;
  105908. (void)client_data;
  105909. offset = ftello(encoder->private_->file);
  105910. if(offset < 0) {
  105911. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105912. }
  105913. else {
  105914. *absolute_byte_offset = (FLAC__uint64)offset;
  105915. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105916. }
  105917. }
  105918. #ifdef FLAC__VALGRIND_TESTING
  105919. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105920. {
  105921. size_t ret = fwrite(ptr, size, nmemb, stream);
  105922. if(!ferror(stream))
  105923. fflush(stream);
  105924. return ret;
  105925. }
  105926. #else
  105927. #define local__fwrite fwrite
  105928. #endif
  105929. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105930. {
  105931. (void)client_data, (void)current_frame;
  105932. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105933. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105934. #if FLAC__HAS_OGG
  105935. /* We would like to be able to use 'samples > 0' in the
  105936. * clause here but currently because of the nature of our
  105937. * Ogg writing implementation, 'samples' is always 0 (see
  105938. * ogg_encoder_aspect.c). The downside is extra progress
  105939. * callbacks.
  105940. */
  105941. encoder->private_->is_ogg? true :
  105942. #endif
  105943. samples > 0
  105944. );
  105945. if(call_it) {
  105946. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105947. * because at this point in the callback chain, the stats
  105948. * have not been updated. Only after we return and control
  105949. * gets back to write_frame_() are the stats updated
  105950. */
  105951. 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);
  105952. }
  105953. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105954. }
  105955. else
  105956. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105957. }
  105958. /*
  105959. * This will forcibly set stdout to binary mode (for OSes that require it)
  105960. */
  105961. FILE *get_binary_stdout_(void)
  105962. {
  105963. /* if something breaks here it is probably due to the presence or
  105964. * absence of an underscore before the identifiers 'setmode',
  105965. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105966. */
  105967. #if defined _MSC_VER || defined __MINGW32__
  105968. _setmode(_fileno(stdout), _O_BINARY);
  105969. #elif defined __CYGWIN__
  105970. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105971. setmode(_fileno(stdout), _O_BINARY);
  105972. #elif defined __EMX__
  105973. setmode(fileno(stdout), O_BINARY);
  105974. #endif
  105975. return stdout;
  105976. }
  105977. #endif
  105978. /*** End of inlined file: stream_encoder.c ***/
  105979. /*** Start of inlined file: stream_encoder_framing.c ***/
  105980. /*** Start of inlined file: juce_FlacHeader.h ***/
  105981. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105982. // tasks..
  105983. #define VERSION "1.2.1"
  105984. #define FLAC__NO_DLL 1
  105985. #if JUCE_MSVC
  105986. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105987. #endif
  105988. #if JUCE_MAC
  105989. #define FLAC__SYS_DARWIN 1
  105990. #endif
  105991. /*** End of inlined file: juce_FlacHeader.h ***/
  105992. #if JUCE_USE_FLAC
  105993. #if HAVE_CONFIG_H
  105994. # include <config.h>
  105995. #endif
  105996. #include <stdio.h>
  105997. #include <string.h> /* for strlen() */
  105998. #ifdef max
  105999. #undef max
  106000. #endif
  106001. #define max(x,y) ((x)>(y)?(x):(y))
  106002. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106003. 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);
  106004. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106005. {
  106006. unsigned i, j;
  106007. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106008. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106009. return false;
  106010. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106011. return false;
  106012. /*
  106013. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106014. */
  106015. i = metadata->length;
  106016. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106017. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106018. i -= metadata->data.vorbis_comment.vendor_string.length;
  106019. i += vendor_string_length;
  106020. }
  106021. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106022. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106023. return false;
  106024. switch(metadata->type) {
  106025. case FLAC__METADATA_TYPE_STREAMINFO:
  106026. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106027. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106028. return false;
  106029. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106030. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106031. return false;
  106032. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106033. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106034. return false;
  106035. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106036. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106037. return false;
  106038. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106039. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106040. return false;
  106041. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106042. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106043. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106044. return false;
  106045. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106046. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106047. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106048. return false;
  106049. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106050. return false;
  106051. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106052. return false;
  106053. break;
  106054. case FLAC__METADATA_TYPE_PADDING:
  106055. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106056. return false;
  106057. break;
  106058. case FLAC__METADATA_TYPE_APPLICATION:
  106059. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106060. return false;
  106061. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106062. return false;
  106063. break;
  106064. case FLAC__METADATA_TYPE_SEEKTABLE:
  106065. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106066. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106067. return false;
  106068. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106069. return false;
  106070. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106071. return false;
  106072. }
  106073. break;
  106074. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106075. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106076. return false;
  106077. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106078. return false;
  106079. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106080. return false;
  106081. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106082. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106083. return false;
  106084. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106085. return false;
  106086. }
  106087. break;
  106088. case FLAC__METADATA_TYPE_CUESHEET:
  106089. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106090. 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))
  106091. return false;
  106092. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106093. return false;
  106094. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106095. return false;
  106096. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106097. return false;
  106098. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106099. return false;
  106100. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106101. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106102. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106103. return false;
  106104. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106105. return false;
  106106. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106107. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106108. return false;
  106109. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106110. return false;
  106111. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106112. return false;
  106113. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106114. return false;
  106115. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106116. return false;
  106117. for(j = 0; j < track->num_indices; j++) {
  106118. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106119. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106120. return false;
  106121. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106122. return false;
  106123. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106124. return false;
  106125. }
  106126. }
  106127. break;
  106128. case FLAC__METADATA_TYPE_PICTURE:
  106129. {
  106130. size_t len;
  106131. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106132. return false;
  106133. len = strlen(metadata->data.picture.mime_type);
  106134. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106135. return false;
  106136. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106137. return false;
  106138. len = strlen((const char *)metadata->data.picture.description);
  106139. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106140. return false;
  106141. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106142. return false;
  106143. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106144. return false;
  106145. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106146. return false;
  106147. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106148. return false;
  106149. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106150. return false;
  106151. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106152. return false;
  106153. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106154. return false;
  106155. }
  106156. break;
  106157. default:
  106158. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106159. return false;
  106160. break;
  106161. }
  106162. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106163. return true;
  106164. }
  106165. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106166. {
  106167. unsigned u, blocksize_hint, sample_rate_hint;
  106168. FLAC__byte crc;
  106169. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106170. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106171. return false;
  106172. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106173. return false;
  106174. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106175. return false;
  106176. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106177. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106178. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106179. blocksize_hint = 0;
  106180. switch(header->blocksize) {
  106181. case 192: u = 1; break;
  106182. case 576: u = 2; break;
  106183. case 1152: u = 3; break;
  106184. case 2304: u = 4; break;
  106185. case 4608: u = 5; break;
  106186. case 256: u = 8; break;
  106187. case 512: u = 9; break;
  106188. case 1024: u = 10; break;
  106189. case 2048: u = 11; break;
  106190. case 4096: u = 12; break;
  106191. case 8192: u = 13; break;
  106192. case 16384: u = 14; break;
  106193. case 32768: u = 15; break;
  106194. default:
  106195. if(header->blocksize <= 0x100)
  106196. blocksize_hint = u = 6;
  106197. else
  106198. blocksize_hint = u = 7;
  106199. break;
  106200. }
  106201. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106202. return false;
  106203. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106204. sample_rate_hint = 0;
  106205. switch(header->sample_rate) {
  106206. case 88200: u = 1; break;
  106207. case 176400: u = 2; break;
  106208. case 192000: u = 3; break;
  106209. case 8000: u = 4; break;
  106210. case 16000: u = 5; break;
  106211. case 22050: u = 6; break;
  106212. case 24000: u = 7; break;
  106213. case 32000: u = 8; break;
  106214. case 44100: u = 9; break;
  106215. case 48000: u = 10; break;
  106216. case 96000: u = 11; break;
  106217. default:
  106218. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106219. sample_rate_hint = u = 12;
  106220. else if(header->sample_rate % 10 == 0)
  106221. sample_rate_hint = u = 14;
  106222. else if(header->sample_rate <= 0xffff)
  106223. sample_rate_hint = u = 13;
  106224. else
  106225. u = 0;
  106226. break;
  106227. }
  106228. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106229. return false;
  106230. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106231. switch(header->channel_assignment) {
  106232. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106233. u = header->channels - 1;
  106234. break;
  106235. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106236. FLAC__ASSERT(header->channels == 2);
  106237. u = 8;
  106238. break;
  106239. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106240. FLAC__ASSERT(header->channels == 2);
  106241. u = 9;
  106242. break;
  106243. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106244. FLAC__ASSERT(header->channels == 2);
  106245. u = 10;
  106246. break;
  106247. default:
  106248. FLAC__ASSERT(0);
  106249. }
  106250. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106251. return false;
  106252. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106253. switch(header->bits_per_sample) {
  106254. case 8 : u = 1; break;
  106255. case 12: u = 2; break;
  106256. case 16: u = 4; break;
  106257. case 20: u = 5; break;
  106258. case 24: u = 6; break;
  106259. default: u = 0; break;
  106260. }
  106261. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106262. return false;
  106263. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106264. return false;
  106265. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106266. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106267. return false;
  106268. }
  106269. else {
  106270. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106271. return false;
  106272. }
  106273. if(blocksize_hint)
  106274. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106275. return false;
  106276. switch(sample_rate_hint) {
  106277. case 12:
  106278. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106279. return false;
  106280. break;
  106281. case 13:
  106282. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106283. return false;
  106284. break;
  106285. case 14:
  106286. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106287. return false;
  106288. break;
  106289. }
  106290. /* write the CRC */
  106291. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106292. return false;
  106293. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106294. return false;
  106295. return true;
  106296. }
  106297. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106298. {
  106299. FLAC__bool ok;
  106300. ok =
  106301. 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) &&
  106302. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106303. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106304. ;
  106305. return ok;
  106306. }
  106307. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106308. {
  106309. unsigned i;
  106310. 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))
  106311. return false;
  106312. if(wasted_bits)
  106313. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106314. return false;
  106315. for(i = 0; i < subframe->order; i++)
  106316. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106317. return false;
  106318. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106319. return false;
  106320. switch(subframe->entropy_coding_method.type) {
  106321. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106322. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106323. if(!add_residual_partitioned_rice_(
  106324. bw,
  106325. subframe->residual,
  106326. residual_samples,
  106327. subframe->order,
  106328. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106329. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106330. subframe->entropy_coding_method.data.partitioned_rice.order,
  106331. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106332. ))
  106333. return false;
  106334. break;
  106335. default:
  106336. FLAC__ASSERT(0);
  106337. }
  106338. return true;
  106339. }
  106340. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106341. {
  106342. unsigned i;
  106343. 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))
  106344. return false;
  106345. if(wasted_bits)
  106346. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106347. return false;
  106348. for(i = 0; i < subframe->order; i++)
  106349. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106350. return false;
  106351. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106352. return false;
  106353. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106354. return false;
  106355. for(i = 0; i < subframe->order; i++)
  106356. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106357. return false;
  106358. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106359. return false;
  106360. switch(subframe->entropy_coding_method.type) {
  106361. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106362. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106363. if(!add_residual_partitioned_rice_(
  106364. bw,
  106365. subframe->residual,
  106366. residual_samples,
  106367. subframe->order,
  106368. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106369. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106370. subframe->entropy_coding_method.data.partitioned_rice.order,
  106371. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106372. ))
  106373. return false;
  106374. break;
  106375. default:
  106376. FLAC__ASSERT(0);
  106377. }
  106378. return true;
  106379. }
  106380. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106381. {
  106382. unsigned i;
  106383. const FLAC__int32 *signal = subframe->data;
  106384. 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))
  106385. return false;
  106386. if(wasted_bits)
  106387. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106388. return false;
  106389. for(i = 0; i < samples; i++)
  106390. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106391. return false;
  106392. return true;
  106393. }
  106394. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106395. {
  106396. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106397. return false;
  106398. switch(method->type) {
  106399. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106400. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106401. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106402. return false;
  106403. break;
  106404. default:
  106405. FLAC__ASSERT(0);
  106406. }
  106407. return true;
  106408. }
  106409. 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)
  106410. {
  106411. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106412. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106413. if(partition_order == 0) {
  106414. unsigned i;
  106415. if(raw_bits[0] == 0) {
  106416. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106417. return false;
  106418. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106419. return false;
  106420. }
  106421. else {
  106422. FLAC__ASSERT(rice_parameters[0] == 0);
  106423. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106424. return false;
  106425. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106426. return false;
  106427. for(i = 0; i < residual_samples; i++) {
  106428. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106429. return false;
  106430. }
  106431. }
  106432. return true;
  106433. }
  106434. else {
  106435. unsigned i, j, k = 0, k_last = 0;
  106436. unsigned partition_samples;
  106437. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106438. for(i = 0; i < (1u<<partition_order); i++) {
  106439. partition_samples = default_partition_samples;
  106440. if(i == 0)
  106441. partition_samples -= predictor_order;
  106442. k += partition_samples;
  106443. if(raw_bits[i] == 0) {
  106444. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106445. return false;
  106446. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106447. return false;
  106448. }
  106449. else {
  106450. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106451. return false;
  106452. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106453. return false;
  106454. for(j = k_last; j < k; j++) {
  106455. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106456. return false;
  106457. }
  106458. }
  106459. k_last = k;
  106460. }
  106461. return true;
  106462. }
  106463. }
  106464. #endif
  106465. /*** End of inlined file: stream_encoder_framing.c ***/
  106466. /*** Start of inlined file: window_flac.c ***/
  106467. /*** Start of inlined file: juce_FlacHeader.h ***/
  106468. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106469. // tasks..
  106470. #define VERSION "1.2.1"
  106471. #define FLAC__NO_DLL 1
  106472. #if JUCE_MSVC
  106473. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106474. #endif
  106475. #if JUCE_MAC
  106476. #define FLAC__SYS_DARWIN 1
  106477. #endif
  106478. /*** End of inlined file: juce_FlacHeader.h ***/
  106479. #if JUCE_USE_FLAC
  106480. #if HAVE_CONFIG_H
  106481. # include <config.h>
  106482. #endif
  106483. #include <math.h>
  106484. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106485. #ifndef M_PI
  106486. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106487. #define M_PI 3.14159265358979323846
  106488. #endif
  106489. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106490. {
  106491. const FLAC__int32 N = L - 1;
  106492. FLAC__int32 n;
  106493. if (L & 1) {
  106494. for (n = 0; n <= N/2; n++)
  106495. window[n] = 2.0f * n / (float)N;
  106496. for (; n <= N; n++)
  106497. window[n] = 2.0f - 2.0f * n / (float)N;
  106498. }
  106499. else {
  106500. for (n = 0; n <= L/2-1; n++)
  106501. window[n] = 2.0f * n / (float)N;
  106502. for (; n <= N; n++)
  106503. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106504. }
  106505. }
  106506. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106507. {
  106508. const FLAC__int32 N = L - 1;
  106509. FLAC__int32 n;
  106510. for (n = 0; n < L; n++)
  106511. 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)));
  106512. }
  106513. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106514. {
  106515. const FLAC__int32 N = L - 1;
  106516. FLAC__int32 n;
  106517. for (n = 0; n < L; n++)
  106518. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106519. }
  106520. /* 4-term -92dB side-lobe */
  106521. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106522. {
  106523. const FLAC__int32 N = L - 1;
  106524. FLAC__int32 n;
  106525. for (n = 0; n <= N; n++)
  106526. 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));
  106527. }
  106528. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106529. {
  106530. const FLAC__int32 N = L - 1;
  106531. const double N2 = (double)N / 2.;
  106532. FLAC__int32 n;
  106533. for (n = 0; n <= N; n++) {
  106534. double k = ((double)n - N2) / N2;
  106535. k = 1.0f - k * k;
  106536. window[n] = (FLAC__real)(k * k);
  106537. }
  106538. }
  106539. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106540. {
  106541. const FLAC__int32 N = L - 1;
  106542. FLAC__int32 n;
  106543. for (n = 0; n < L; n++)
  106544. 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));
  106545. }
  106546. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106547. {
  106548. const FLAC__int32 N = L - 1;
  106549. const double N2 = (double)N / 2.;
  106550. FLAC__int32 n;
  106551. for (n = 0; n <= N; n++) {
  106552. const double k = ((double)n - N2) / (stddev * N2);
  106553. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106554. }
  106555. }
  106556. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106557. {
  106558. const FLAC__int32 N = L - 1;
  106559. FLAC__int32 n;
  106560. for (n = 0; n < L; n++)
  106561. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106562. }
  106563. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106564. {
  106565. const FLAC__int32 N = L - 1;
  106566. FLAC__int32 n;
  106567. for (n = 0; n < L; n++)
  106568. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106569. }
  106570. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106571. {
  106572. const FLAC__int32 N = L - 1;
  106573. FLAC__int32 n;
  106574. for (n = 0; n < L; n++)
  106575. 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));
  106576. }
  106577. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106578. {
  106579. const FLAC__int32 N = L - 1;
  106580. FLAC__int32 n;
  106581. for (n = 0; n < L; n++)
  106582. 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));
  106583. }
  106584. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106585. {
  106586. FLAC__int32 n;
  106587. for (n = 0; n < L; n++)
  106588. window[n] = 1.0f;
  106589. }
  106590. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106591. {
  106592. FLAC__int32 n;
  106593. if (L & 1) {
  106594. for (n = 1; n <= L+1/2; n++)
  106595. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106596. for (; n <= L; n++)
  106597. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106598. }
  106599. else {
  106600. for (n = 1; n <= L/2; n++)
  106601. window[n-1] = 2.0f * n / (float)L;
  106602. for (; n <= L; n++)
  106603. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106604. }
  106605. }
  106606. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106607. {
  106608. if (p <= 0.0)
  106609. FLAC__window_rectangle(window, L);
  106610. else if (p >= 1.0)
  106611. FLAC__window_hann(window, L);
  106612. else {
  106613. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106614. FLAC__int32 n;
  106615. /* start with rectangle... */
  106616. FLAC__window_rectangle(window, L);
  106617. /* ...replace ends with hann */
  106618. if (Np > 0) {
  106619. for (n = 0; n <= Np; n++) {
  106620. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106621. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106622. }
  106623. }
  106624. }
  106625. }
  106626. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106627. {
  106628. const FLAC__int32 N = L - 1;
  106629. const double N2 = (double)N / 2.;
  106630. FLAC__int32 n;
  106631. for (n = 0; n <= N; n++) {
  106632. const double k = ((double)n - N2) / N2;
  106633. window[n] = (FLAC__real)(1.0f - k * k);
  106634. }
  106635. }
  106636. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106637. #endif
  106638. /*** End of inlined file: window_flac.c ***/
  106639. #else
  106640. #include <FLAC/all.h>
  106641. #endif
  106642. }
  106643. #undef max
  106644. #undef min
  106645. BEGIN_JUCE_NAMESPACE
  106646. static const char* const flacFormatName = "FLAC file";
  106647. static const char* const flacExtensions[] = { ".flac", 0 };
  106648. class FlacReader : public AudioFormatReader
  106649. {
  106650. public:
  106651. FlacReader (InputStream* const in)
  106652. : AudioFormatReader (in, TRANS (flacFormatName)),
  106653. reservoir (2, 0),
  106654. reservoirStart (0),
  106655. samplesInReservoir (0),
  106656. scanningForLength (false)
  106657. {
  106658. using namespace FlacNamespace;
  106659. lengthInSamples = 0;
  106660. decoder = FLAC__stream_decoder_new();
  106661. ok = FLAC__stream_decoder_init_stream (decoder,
  106662. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106663. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106664. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106665. if (ok)
  106666. {
  106667. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106668. if (lengthInSamples == 0 && sampleRate > 0)
  106669. {
  106670. // the length hasn't been stored in the metadata, so we'll need to
  106671. // work it out the length the hard way, by scanning the whole file..
  106672. scanningForLength = true;
  106673. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106674. scanningForLength = false;
  106675. const int64 tempLength = lengthInSamples;
  106676. FLAC__stream_decoder_reset (decoder);
  106677. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106678. lengthInSamples = tempLength;
  106679. }
  106680. }
  106681. }
  106682. ~FlacReader()
  106683. {
  106684. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106685. }
  106686. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106687. {
  106688. sampleRate = info.sample_rate;
  106689. bitsPerSample = info.bits_per_sample;
  106690. lengthInSamples = (unsigned int) info.total_samples;
  106691. numChannels = info.channels;
  106692. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106693. }
  106694. // returns the number of samples read
  106695. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106696. int64 startSampleInFile, int numSamples)
  106697. {
  106698. using namespace FlacNamespace;
  106699. if (! ok)
  106700. return false;
  106701. while (numSamples > 0)
  106702. {
  106703. if (startSampleInFile >= reservoirStart
  106704. && startSampleInFile < reservoirStart + samplesInReservoir)
  106705. {
  106706. const int num = (int) jmin ((int64) numSamples,
  106707. reservoirStart + samplesInReservoir - startSampleInFile);
  106708. jassert (num > 0);
  106709. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106710. if (destSamples[i] != 0)
  106711. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106712. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106713. sizeof (int) * num);
  106714. startOffsetInDestBuffer += num;
  106715. startSampleInFile += num;
  106716. numSamples -= num;
  106717. }
  106718. else
  106719. {
  106720. if (startSampleInFile >= (int) lengthInSamples)
  106721. {
  106722. samplesInReservoir = 0;
  106723. }
  106724. else if (startSampleInFile < reservoirStart
  106725. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106726. {
  106727. // had some problems with flac crashing if the read pos is aligned more
  106728. // accurately than this. Probably fixed in newer versions of the library, though.
  106729. reservoirStart = (int) (startSampleInFile & ~511);
  106730. samplesInReservoir = 0;
  106731. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106732. }
  106733. else
  106734. {
  106735. reservoirStart += samplesInReservoir;
  106736. samplesInReservoir = 0;
  106737. FLAC__stream_decoder_process_single (decoder);
  106738. }
  106739. if (samplesInReservoir == 0)
  106740. break;
  106741. }
  106742. }
  106743. if (numSamples > 0)
  106744. {
  106745. for (int i = numDestChannels; --i >= 0;)
  106746. if (destSamples[i] != 0)
  106747. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106748. sizeof (int) * numSamples);
  106749. }
  106750. return true;
  106751. }
  106752. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106753. {
  106754. if (scanningForLength)
  106755. {
  106756. lengthInSamples += numSamples;
  106757. }
  106758. else
  106759. {
  106760. if (numSamples > reservoir.getNumSamples())
  106761. reservoir.setSize (numChannels, numSamples, false, false, true);
  106762. const int bitsToShift = 32 - bitsPerSample;
  106763. for (int i = 0; i < (int) numChannels; ++i)
  106764. {
  106765. const FlacNamespace::FLAC__int32* src = buffer[i];
  106766. int n = i;
  106767. while (src == 0 && n > 0)
  106768. src = buffer [--n];
  106769. if (src != 0)
  106770. {
  106771. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106772. for (int j = 0; j < numSamples; ++j)
  106773. dest[j] = src[j] << bitsToShift;
  106774. }
  106775. }
  106776. samplesInReservoir = numSamples;
  106777. }
  106778. }
  106779. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106780. {
  106781. using namespace FlacNamespace;
  106782. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106783. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106784. }
  106785. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106786. {
  106787. using namespace FlacNamespace;
  106788. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106789. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106790. }
  106791. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106792. {
  106793. using namespace FlacNamespace;
  106794. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106795. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106796. }
  106797. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106798. {
  106799. using namespace FlacNamespace;
  106800. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106801. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106802. }
  106803. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106804. {
  106805. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106806. }
  106807. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106808. const FlacNamespace::FLAC__Frame* frame,
  106809. const FlacNamespace::FLAC__int32* const buffer[],
  106810. void* client_data)
  106811. {
  106812. using namespace FlacNamespace;
  106813. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106814. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106815. }
  106816. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106817. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106818. void* client_data)
  106819. {
  106820. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106821. }
  106822. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106823. {
  106824. }
  106825. private:
  106826. FlacNamespace::FLAC__StreamDecoder* decoder;
  106827. AudioSampleBuffer reservoir;
  106828. int reservoirStart, samplesInReservoir;
  106829. bool ok, scanningForLength;
  106830. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  106831. };
  106832. class FlacWriter : public AudioFormatWriter
  106833. {
  106834. public:
  106835. FlacWriter (OutputStream* const out, double sampleRate_,
  106836. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  106837. : AudioFormatWriter (out, TRANS (flacFormatName),
  106838. sampleRate_, numChannels_, bitsPerSample_)
  106839. {
  106840. using namespace FlacNamespace;
  106841. encoder = FLAC__stream_encoder_new();
  106842. if (qualityOptionIndex > 0)
  106843. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  106844. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106845. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106846. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106847. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106848. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106849. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106850. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106851. ok = FLAC__stream_encoder_init_stream (encoder,
  106852. encodeWriteCallback, encodeSeekCallback,
  106853. encodeTellCallback, encodeMetadataCallback,
  106854. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106855. }
  106856. ~FlacWriter()
  106857. {
  106858. if (ok)
  106859. {
  106860. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106861. output->flush();
  106862. }
  106863. else
  106864. {
  106865. output = 0; // to stop the base class deleting this, as it needs to be returned
  106866. // to the caller of createWriter()
  106867. }
  106868. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106869. }
  106870. bool write (const int** samplesToWrite, int numSamples)
  106871. {
  106872. using namespace FlacNamespace;
  106873. if (! ok)
  106874. return false;
  106875. int* buf[3];
  106876. HeapBlock<int> temp;
  106877. const int bitsToShift = 32 - bitsPerSample;
  106878. if (bitsToShift > 0)
  106879. {
  106880. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106881. temp.malloc (numSamples * numChannelsToWrite);
  106882. buf[0] = temp.getData();
  106883. buf[1] = temp.getData() + numSamples;
  106884. buf[2] = 0;
  106885. for (int i = numChannelsToWrite; --i >= 0;)
  106886. if (samplesToWrite[i] != 0)
  106887. for (int j = 0; j < numSamples; ++j)
  106888. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106889. samplesToWrite = const_cast<const int**> (buf);
  106890. }
  106891. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  106892. }
  106893. bool writeData (const void* const data, const int size) const
  106894. {
  106895. return output->write (data, size);
  106896. }
  106897. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106898. {
  106899. using namespace FlacNamespace;
  106900. b += bytes;
  106901. for (int i = 0; i < bytes; ++i)
  106902. {
  106903. *(--b) = (FLAC__byte) (val & 0xff);
  106904. val >>= 8;
  106905. }
  106906. }
  106907. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106908. {
  106909. using namespace FlacNamespace;
  106910. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106911. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106912. const unsigned int channelsMinus1 = info.channels - 1;
  106913. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106914. packUint32 (info.min_blocksize, buffer, 2);
  106915. packUint32 (info.max_blocksize, buffer + 2, 2);
  106916. packUint32 (info.min_framesize, buffer + 4, 3);
  106917. packUint32 (info.max_framesize, buffer + 7, 3);
  106918. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106919. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106920. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106921. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106922. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106923. memcpy (buffer + 18, info.md5sum, 16);
  106924. const bool seekOk = output->setPosition (4);
  106925. (void) seekOk;
  106926. // if this fails, you've given it an output stream that can't seek! It needs
  106927. // to be able to seek back to write the header
  106928. jassert (seekOk);
  106929. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106930. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106931. }
  106932. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106933. const FlacNamespace::FLAC__byte buffer[],
  106934. size_t bytes,
  106935. unsigned int /*samples*/,
  106936. unsigned int /*current_frame*/,
  106937. void* client_data)
  106938. {
  106939. using namespace FlacNamespace;
  106940. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106941. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106942. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106943. }
  106944. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106945. {
  106946. using namespace FlacNamespace;
  106947. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106948. }
  106949. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106950. {
  106951. using namespace FlacNamespace;
  106952. if (client_data == 0)
  106953. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106954. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106955. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106956. }
  106957. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106958. {
  106959. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106960. }
  106961. bool ok;
  106962. private:
  106963. FlacNamespace::FLAC__StreamEncoder* encoder;
  106964. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  106965. };
  106966. FlacAudioFormat::FlacAudioFormat()
  106967. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106968. {
  106969. }
  106970. FlacAudioFormat::~FlacAudioFormat()
  106971. {
  106972. }
  106973. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106974. {
  106975. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106976. return Array <int> (rates);
  106977. }
  106978. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106979. {
  106980. const int depths[] = { 16, 24, 0 };
  106981. return Array <int> (depths);
  106982. }
  106983. bool FlacAudioFormat::canDoStereo() { return true; }
  106984. bool FlacAudioFormat::canDoMono() { return true; }
  106985. bool FlacAudioFormat::isCompressed() { return true; }
  106986. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106987. const bool deleteStreamIfOpeningFails)
  106988. {
  106989. ScopedPointer<FlacReader> r (new FlacReader (in));
  106990. if (r->sampleRate != 0)
  106991. return r.release();
  106992. if (! deleteStreamIfOpeningFails)
  106993. r->input = 0;
  106994. return 0;
  106995. }
  106996. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106997. double sampleRate,
  106998. unsigned int numberOfChannels,
  106999. int bitsPerSample,
  107000. const StringPairArray& /*metadataValues*/,
  107001. int qualityOptionIndex)
  107002. {
  107003. if (getPossibleBitDepths().contains (bitsPerSample))
  107004. {
  107005. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107006. if (w->ok)
  107007. return w.release();
  107008. }
  107009. return 0;
  107010. }
  107011. END_JUCE_NAMESPACE
  107012. #endif
  107013. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107014. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107015. #if JUCE_USE_OGGVORBIS
  107016. #if JUCE_MAC
  107017. #define __MACOSX__ 1
  107018. #endif
  107019. namespace OggVorbisNamespace
  107020. {
  107021. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107022. /*** Start of inlined file: vorbisenc.h ***/
  107023. #ifndef _OV_ENC_H_
  107024. #define _OV_ENC_H_
  107025. #ifdef __cplusplus
  107026. extern "C"
  107027. {
  107028. #endif /* __cplusplus */
  107029. /*** Start of inlined file: codec.h ***/
  107030. #ifndef _vorbis_codec_h_
  107031. #define _vorbis_codec_h_
  107032. #ifdef __cplusplus
  107033. extern "C"
  107034. {
  107035. #endif /* __cplusplus */
  107036. /*** Start of inlined file: ogg.h ***/
  107037. #ifndef _OGG_H
  107038. #define _OGG_H
  107039. #ifdef __cplusplus
  107040. extern "C" {
  107041. #endif
  107042. /*** Start of inlined file: os_types.h ***/
  107043. #ifndef _OS_TYPES_H
  107044. #define _OS_TYPES_H
  107045. /* make it easy on the folks that want to compile the libs with a
  107046. different malloc than stdlib */
  107047. #define _ogg_malloc malloc
  107048. #define _ogg_calloc calloc
  107049. #define _ogg_realloc realloc
  107050. #define _ogg_free free
  107051. #if defined(_WIN32)
  107052. # if defined(__CYGWIN__)
  107053. # include <_G_config.h>
  107054. typedef _G_int64_t ogg_int64_t;
  107055. typedef _G_int32_t ogg_int32_t;
  107056. typedef _G_uint32_t ogg_uint32_t;
  107057. typedef _G_int16_t ogg_int16_t;
  107058. typedef _G_uint16_t ogg_uint16_t;
  107059. # elif defined(__MINGW32__)
  107060. typedef short ogg_int16_t;
  107061. typedef unsigned short ogg_uint16_t;
  107062. typedef int ogg_int32_t;
  107063. typedef unsigned int ogg_uint32_t;
  107064. typedef long long ogg_int64_t;
  107065. typedef unsigned long long ogg_uint64_t;
  107066. # elif defined(__MWERKS__)
  107067. typedef long long ogg_int64_t;
  107068. typedef int ogg_int32_t;
  107069. typedef unsigned int ogg_uint32_t;
  107070. typedef short ogg_int16_t;
  107071. typedef unsigned short ogg_uint16_t;
  107072. # else
  107073. /* MSVC/Borland */
  107074. typedef __int64 ogg_int64_t;
  107075. typedef __int32 ogg_int32_t;
  107076. typedef unsigned __int32 ogg_uint32_t;
  107077. typedef __int16 ogg_int16_t;
  107078. typedef unsigned __int16 ogg_uint16_t;
  107079. # endif
  107080. #elif defined(__MACOS__)
  107081. # include <sys/types.h>
  107082. typedef SInt16 ogg_int16_t;
  107083. typedef UInt16 ogg_uint16_t;
  107084. typedef SInt32 ogg_int32_t;
  107085. typedef UInt32 ogg_uint32_t;
  107086. typedef SInt64 ogg_int64_t;
  107087. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107088. # include <sys/types.h>
  107089. typedef int16_t ogg_int16_t;
  107090. typedef u_int16_t ogg_uint16_t;
  107091. typedef int32_t ogg_int32_t;
  107092. typedef u_int32_t ogg_uint32_t;
  107093. typedef int64_t ogg_int64_t;
  107094. #elif defined(__BEOS__)
  107095. /* Be */
  107096. # include <inttypes.h>
  107097. typedef int16_t ogg_int16_t;
  107098. typedef u_int16_t ogg_uint16_t;
  107099. typedef int32_t ogg_int32_t;
  107100. typedef u_int32_t ogg_uint32_t;
  107101. typedef int64_t ogg_int64_t;
  107102. #elif defined (__EMX__)
  107103. /* OS/2 GCC */
  107104. typedef short ogg_int16_t;
  107105. typedef unsigned short ogg_uint16_t;
  107106. typedef int ogg_int32_t;
  107107. typedef unsigned int ogg_uint32_t;
  107108. typedef long long ogg_int64_t;
  107109. #elif defined (DJGPP)
  107110. /* DJGPP */
  107111. typedef short ogg_int16_t;
  107112. typedef int ogg_int32_t;
  107113. typedef unsigned int ogg_uint32_t;
  107114. typedef long long ogg_int64_t;
  107115. #elif defined(R5900)
  107116. /* PS2 EE */
  107117. typedef long ogg_int64_t;
  107118. typedef int ogg_int32_t;
  107119. typedef unsigned ogg_uint32_t;
  107120. typedef short ogg_int16_t;
  107121. #elif defined(__SYMBIAN32__)
  107122. /* Symbian GCC */
  107123. typedef signed short ogg_int16_t;
  107124. typedef unsigned short ogg_uint16_t;
  107125. typedef signed int ogg_int32_t;
  107126. typedef unsigned int ogg_uint32_t;
  107127. typedef long long int ogg_int64_t;
  107128. #else
  107129. # include <sys/types.h>
  107130. /*** Start of inlined file: config_types.h ***/
  107131. #ifndef __CONFIG_TYPES_H__
  107132. #define __CONFIG_TYPES_H__
  107133. typedef int16_t ogg_int16_t;
  107134. typedef unsigned short ogg_uint16_t;
  107135. typedef int32_t ogg_int32_t;
  107136. typedef unsigned int ogg_uint32_t;
  107137. typedef int64_t ogg_int64_t;
  107138. #endif
  107139. /*** End of inlined file: config_types.h ***/
  107140. #endif
  107141. #endif /* _OS_TYPES_H */
  107142. /*** End of inlined file: os_types.h ***/
  107143. typedef struct {
  107144. long endbyte;
  107145. int endbit;
  107146. unsigned char *buffer;
  107147. unsigned char *ptr;
  107148. long storage;
  107149. } oggpack_buffer;
  107150. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107151. typedef struct {
  107152. unsigned char *header;
  107153. long header_len;
  107154. unsigned char *body;
  107155. long body_len;
  107156. } ogg_page;
  107157. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107158. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107159. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107160. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107161. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107162. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107163. }
  107164. /* ogg_stream_state contains the current encode/decode state of a logical
  107165. Ogg bitstream **********************************************************/
  107166. typedef struct {
  107167. unsigned char *body_data; /* bytes from packet bodies */
  107168. long body_storage; /* storage elements allocated */
  107169. long body_fill; /* elements stored; fill mark */
  107170. long body_returned; /* elements of fill returned */
  107171. int *lacing_vals; /* The values that will go to the segment table */
  107172. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107173. this way, but it is simple coupled to the
  107174. lacing fifo */
  107175. long lacing_storage;
  107176. long lacing_fill;
  107177. long lacing_packet;
  107178. long lacing_returned;
  107179. unsigned char header[282]; /* working space for header encode */
  107180. int header_fill;
  107181. int e_o_s; /* set when we have buffered the last packet in the
  107182. logical bitstream */
  107183. int b_o_s; /* set after we've written the initial page
  107184. of a logical bitstream */
  107185. long serialno;
  107186. long pageno;
  107187. ogg_int64_t packetno; /* sequence number for decode; the framing
  107188. knows where there's a hole in the data,
  107189. but we need coupling so that the codec
  107190. (which is in a seperate abstraction
  107191. layer) also knows about the gap */
  107192. ogg_int64_t granulepos;
  107193. } ogg_stream_state;
  107194. /* ogg_packet is used to encapsulate the data and metadata belonging
  107195. to a single raw Ogg/Vorbis packet *************************************/
  107196. typedef struct {
  107197. unsigned char *packet;
  107198. long bytes;
  107199. long b_o_s;
  107200. long e_o_s;
  107201. ogg_int64_t granulepos;
  107202. ogg_int64_t packetno; /* sequence number for decode; the framing
  107203. knows where there's a hole in the data,
  107204. but we need coupling so that the codec
  107205. (which is in a seperate abstraction
  107206. layer) also knows about the gap */
  107207. } ogg_packet;
  107208. typedef struct {
  107209. unsigned char *data;
  107210. int storage;
  107211. int fill;
  107212. int returned;
  107213. int unsynced;
  107214. int headerbytes;
  107215. int bodybytes;
  107216. } ogg_sync_state;
  107217. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107218. extern void oggpack_writeinit(oggpack_buffer *b);
  107219. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107220. extern void oggpack_writealign(oggpack_buffer *b);
  107221. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107222. extern void oggpack_reset(oggpack_buffer *b);
  107223. extern void oggpack_writeclear(oggpack_buffer *b);
  107224. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107225. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107226. extern long oggpack_look(oggpack_buffer *b,int bits);
  107227. extern long oggpack_look1(oggpack_buffer *b);
  107228. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107229. extern void oggpack_adv1(oggpack_buffer *b);
  107230. extern long oggpack_read(oggpack_buffer *b,int bits);
  107231. extern long oggpack_read1(oggpack_buffer *b);
  107232. extern long oggpack_bytes(oggpack_buffer *b);
  107233. extern long oggpack_bits(oggpack_buffer *b);
  107234. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107235. extern void oggpackB_writeinit(oggpack_buffer *b);
  107236. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107237. extern void oggpackB_writealign(oggpack_buffer *b);
  107238. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107239. extern void oggpackB_reset(oggpack_buffer *b);
  107240. extern void oggpackB_writeclear(oggpack_buffer *b);
  107241. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107242. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107243. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107244. extern long oggpackB_look1(oggpack_buffer *b);
  107245. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107246. extern void oggpackB_adv1(oggpack_buffer *b);
  107247. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107248. extern long oggpackB_read1(oggpack_buffer *b);
  107249. extern long oggpackB_bytes(oggpack_buffer *b);
  107250. extern long oggpackB_bits(oggpack_buffer *b);
  107251. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107252. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107253. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107254. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107255. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107256. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107257. extern int ogg_sync_init(ogg_sync_state *oy);
  107258. extern int ogg_sync_clear(ogg_sync_state *oy);
  107259. extern int ogg_sync_reset(ogg_sync_state *oy);
  107260. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107261. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107262. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107263. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107264. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107265. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107266. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107267. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107268. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107269. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107270. extern int ogg_stream_clear(ogg_stream_state *os);
  107271. extern int ogg_stream_reset(ogg_stream_state *os);
  107272. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107273. extern int ogg_stream_destroy(ogg_stream_state *os);
  107274. extern int ogg_stream_eos(ogg_stream_state *os);
  107275. extern void ogg_page_checksum_set(ogg_page *og);
  107276. extern int ogg_page_version(ogg_page *og);
  107277. extern int ogg_page_continued(ogg_page *og);
  107278. extern int ogg_page_bos(ogg_page *og);
  107279. extern int ogg_page_eos(ogg_page *og);
  107280. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107281. extern int ogg_page_serialno(ogg_page *og);
  107282. extern long ogg_page_pageno(ogg_page *og);
  107283. extern int ogg_page_packets(ogg_page *og);
  107284. extern void ogg_packet_clear(ogg_packet *op);
  107285. #ifdef __cplusplus
  107286. }
  107287. #endif
  107288. #endif /* _OGG_H */
  107289. /*** End of inlined file: ogg.h ***/
  107290. typedef struct vorbis_info{
  107291. int version;
  107292. int channels;
  107293. long rate;
  107294. /* The below bitrate declarations are *hints*.
  107295. Combinations of the three values carry the following implications:
  107296. all three set to the same value:
  107297. implies a fixed rate bitstream
  107298. only nominal set:
  107299. implies a VBR stream that averages the nominal bitrate. No hard
  107300. upper/lower limit
  107301. upper and or lower set:
  107302. implies a VBR bitstream that obeys the bitrate limits. nominal
  107303. may also be set to give a nominal rate.
  107304. none set:
  107305. the coder does not care to speculate.
  107306. */
  107307. long bitrate_upper;
  107308. long bitrate_nominal;
  107309. long bitrate_lower;
  107310. long bitrate_window;
  107311. void *codec_setup;
  107312. } vorbis_info;
  107313. /* vorbis_dsp_state buffers the current vorbis audio
  107314. analysis/synthesis state. The DSP state belongs to a specific
  107315. logical bitstream ****************************************************/
  107316. typedef struct vorbis_dsp_state{
  107317. int analysisp;
  107318. vorbis_info *vi;
  107319. float **pcm;
  107320. float **pcmret;
  107321. int pcm_storage;
  107322. int pcm_current;
  107323. int pcm_returned;
  107324. int preextrapolate;
  107325. int eofflag;
  107326. long lW;
  107327. long W;
  107328. long nW;
  107329. long centerW;
  107330. ogg_int64_t granulepos;
  107331. ogg_int64_t sequence;
  107332. ogg_int64_t glue_bits;
  107333. ogg_int64_t time_bits;
  107334. ogg_int64_t floor_bits;
  107335. ogg_int64_t res_bits;
  107336. void *backend_state;
  107337. } vorbis_dsp_state;
  107338. typedef struct vorbis_block{
  107339. /* necessary stream state for linking to the framing abstraction */
  107340. float **pcm; /* this is a pointer into local storage */
  107341. oggpack_buffer opb;
  107342. long lW;
  107343. long W;
  107344. long nW;
  107345. int pcmend;
  107346. int mode;
  107347. int eofflag;
  107348. ogg_int64_t granulepos;
  107349. ogg_int64_t sequence;
  107350. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107351. /* local storage to avoid remallocing; it's up to the mapping to
  107352. structure it */
  107353. void *localstore;
  107354. long localtop;
  107355. long localalloc;
  107356. long totaluse;
  107357. struct alloc_chain *reap;
  107358. /* bitmetrics for the frame */
  107359. long glue_bits;
  107360. long time_bits;
  107361. long floor_bits;
  107362. long res_bits;
  107363. void *internal;
  107364. } vorbis_block;
  107365. /* vorbis_block is a single block of data to be processed as part of
  107366. the analysis/synthesis stream; it belongs to a specific logical
  107367. bitstream, but is independant from other vorbis_blocks belonging to
  107368. that logical bitstream. *************************************************/
  107369. struct alloc_chain{
  107370. void *ptr;
  107371. struct alloc_chain *next;
  107372. };
  107373. /* vorbis_info contains all the setup information specific to the
  107374. specific compression/decompression mode in progress (eg,
  107375. psychoacoustic settings, channel setup, options, codebook
  107376. etc). vorbis_info and substructures are in backends.h.
  107377. *********************************************************************/
  107378. /* the comments are not part of vorbis_info so that vorbis_info can be
  107379. static storage */
  107380. typedef struct vorbis_comment{
  107381. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107382. whatever vendor is set to in encode */
  107383. char **user_comments;
  107384. int *comment_lengths;
  107385. int comments;
  107386. char *vendor;
  107387. } vorbis_comment;
  107388. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107389. and produce a packet (see docs/analysis.txt). The packet is then
  107390. coded into a framed OggSquish bitstream by the second layer (see
  107391. docs/framing.txt). Decode is the reverse process; we sync/frame
  107392. the bitstream and extract individual packets, then decode the
  107393. packet back into PCM audio.
  107394. The extra framing/packetizing is used in streaming formats, such as
  107395. files. Over the net (such as with UDP), the framing and
  107396. packetization aren't necessary as they're provided by the transport
  107397. and the streaming layer is not used */
  107398. /* Vorbis PRIMITIVES: general ***************************************/
  107399. extern void vorbis_info_init(vorbis_info *vi);
  107400. extern void vorbis_info_clear(vorbis_info *vi);
  107401. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107402. extern void vorbis_comment_init(vorbis_comment *vc);
  107403. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107404. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107405. const char *tag, char *contents);
  107406. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107407. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107408. extern void vorbis_comment_clear(vorbis_comment *vc);
  107409. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107410. extern int vorbis_block_clear(vorbis_block *vb);
  107411. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107412. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107413. ogg_int64_t granulepos);
  107414. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107415. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107416. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107417. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107418. vorbis_comment *vc,
  107419. ogg_packet *op,
  107420. ogg_packet *op_comm,
  107421. ogg_packet *op_code);
  107422. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107423. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107424. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107425. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107426. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107427. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107428. ogg_packet *op);
  107429. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107430. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107431. ogg_packet *op);
  107432. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107433. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107434. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107435. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107436. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107437. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107438. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107439. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107440. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107441. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107442. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107443. /* Vorbis ERRORS and return codes ***********************************/
  107444. #define OV_FALSE -1
  107445. #define OV_EOF -2
  107446. #define OV_HOLE -3
  107447. #define OV_EREAD -128
  107448. #define OV_EFAULT -129
  107449. #define OV_EIMPL -130
  107450. #define OV_EINVAL -131
  107451. #define OV_ENOTVORBIS -132
  107452. #define OV_EBADHEADER -133
  107453. #define OV_EVERSION -134
  107454. #define OV_ENOTAUDIO -135
  107455. #define OV_EBADPACKET -136
  107456. #define OV_EBADLINK -137
  107457. #define OV_ENOSEEK -138
  107458. #ifdef __cplusplus
  107459. }
  107460. #endif /* __cplusplus */
  107461. #endif
  107462. /*** End of inlined file: codec.h ***/
  107463. extern int vorbis_encode_init(vorbis_info *vi,
  107464. long channels,
  107465. long rate,
  107466. long max_bitrate,
  107467. long nominal_bitrate,
  107468. long min_bitrate);
  107469. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107470. long channels,
  107471. long rate,
  107472. long max_bitrate,
  107473. long nominal_bitrate,
  107474. long min_bitrate);
  107475. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107476. long channels,
  107477. long rate,
  107478. float quality /* quality level from 0. (lo) to 1. (hi) */
  107479. );
  107480. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107481. long channels,
  107482. long rate,
  107483. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107484. );
  107485. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107486. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107487. /* deprecated rate management supported only for compatability */
  107488. #define OV_ECTL_RATEMANAGE_GET 0x10
  107489. #define OV_ECTL_RATEMANAGE_SET 0x11
  107490. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107491. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107492. struct ovectl_ratemanage_arg {
  107493. int management_active;
  107494. long bitrate_hard_min;
  107495. long bitrate_hard_max;
  107496. double bitrate_hard_window;
  107497. long bitrate_av_lo;
  107498. long bitrate_av_hi;
  107499. double bitrate_av_window;
  107500. double bitrate_av_window_center;
  107501. };
  107502. /* new rate setup */
  107503. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107504. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107505. struct ovectl_ratemanage2_arg {
  107506. int management_active;
  107507. long bitrate_limit_min_kbps;
  107508. long bitrate_limit_max_kbps;
  107509. long bitrate_limit_reservoir_bits;
  107510. double bitrate_limit_reservoir_bias;
  107511. long bitrate_average_kbps;
  107512. double bitrate_average_damping;
  107513. };
  107514. #define OV_ECTL_LOWPASS_GET 0x20
  107515. #define OV_ECTL_LOWPASS_SET 0x21
  107516. #define OV_ECTL_IBLOCK_GET 0x30
  107517. #define OV_ECTL_IBLOCK_SET 0x31
  107518. #ifdef __cplusplus
  107519. }
  107520. #endif /* __cplusplus */
  107521. #endif
  107522. /*** End of inlined file: vorbisenc.h ***/
  107523. /*** Start of inlined file: vorbisfile.h ***/
  107524. #ifndef _OV_FILE_H_
  107525. #define _OV_FILE_H_
  107526. #ifdef __cplusplus
  107527. extern "C"
  107528. {
  107529. #endif /* __cplusplus */
  107530. #include <stdio.h>
  107531. /* The function prototypes for the callbacks are basically the same as for
  107532. * the stdio functions fread, fseek, fclose, ftell.
  107533. * The one difference is that the FILE * arguments have been replaced with
  107534. * a void * - this is to be used as a pointer to whatever internal data these
  107535. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107536. *
  107537. * If you use other functions, check the docs for these functions and return
  107538. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107539. * unseekable
  107540. */
  107541. typedef struct {
  107542. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107543. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107544. int (*close_func) (void *datasource);
  107545. long (*tell_func) (void *datasource);
  107546. } ov_callbacks;
  107547. #define NOTOPEN 0
  107548. #define PARTOPEN 1
  107549. #define OPENED 2
  107550. #define STREAMSET 3
  107551. #define INITSET 4
  107552. typedef struct OggVorbis_File {
  107553. void *datasource; /* Pointer to a FILE *, etc. */
  107554. int seekable;
  107555. ogg_int64_t offset;
  107556. ogg_int64_t end;
  107557. ogg_sync_state oy;
  107558. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107559. stream appears */
  107560. int links;
  107561. ogg_int64_t *offsets;
  107562. ogg_int64_t *dataoffsets;
  107563. long *serialnos;
  107564. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107565. compatability; x2 size, stores both
  107566. beginning and end values */
  107567. vorbis_info *vi;
  107568. vorbis_comment *vc;
  107569. /* Decoding working state local storage */
  107570. ogg_int64_t pcm_offset;
  107571. int ready_state;
  107572. long current_serialno;
  107573. int current_link;
  107574. double bittrack;
  107575. double samptrack;
  107576. ogg_stream_state os; /* take physical pages, weld into a logical
  107577. stream of packets */
  107578. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107579. vorbis_block vb; /* local working space for packet->PCM decode */
  107580. ov_callbacks callbacks;
  107581. } OggVorbis_File;
  107582. extern int ov_clear(OggVorbis_File *vf);
  107583. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107584. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107585. char *initial, long ibytes, ov_callbacks callbacks);
  107586. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107587. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107588. char *initial, long ibytes, ov_callbacks callbacks);
  107589. extern int ov_test_open(OggVorbis_File *vf);
  107590. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107591. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107592. extern long ov_streams(OggVorbis_File *vf);
  107593. extern long ov_seekable(OggVorbis_File *vf);
  107594. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107595. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107596. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107597. extern double ov_time_total(OggVorbis_File *vf,int i);
  107598. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107599. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107600. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107601. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107602. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107603. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107604. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107605. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107606. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107607. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107608. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107609. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107610. extern double ov_time_tell(OggVorbis_File *vf);
  107611. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107612. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107613. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107614. int *bitstream);
  107615. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107616. int bigendianp,int word,int sgned,int *bitstream);
  107617. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107618. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107619. extern int ov_halfrate_p(OggVorbis_File *vf);
  107620. #ifdef __cplusplus
  107621. }
  107622. #endif /* __cplusplus */
  107623. #endif
  107624. /*** End of inlined file: vorbisfile.h ***/
  107625. /*** Start of inlined file: bitwise.c ***/
  107626. /* We're 'LSb' endian; if we write a word but read individual bits,
  107627. then we'll read the lsb first */
  107628. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107629. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107630. // tasks..
  107631. #if JUCE_MSVC
  107632. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107633. #endif
  107634. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107635. #if JUCE_USE_OGGVORBIS
  107636. #include <string.h>
  107637. #include <stdlib.h>
  107638. #define BUFFER_INCREMENT 256
  107639. static const unsigned long mask[]=
  107640. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107641. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107642. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107643. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107644. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107645. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107646. 0x3fffffff,0x7fffffff,0xffffffff };
  107647. static const unsigned int mask8B[]=
  107648. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107649. void oggpack_writeinit(oggpack_buffer *b){
  107650. memset(b,0,sizeof(*b));
  107651. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107652. b->buffer[0]='\0';
  107653. b->storage=BUFFER_INCREMENT;
  107654. }
  107655. void oggpackB_writeinit(oggpack_buffer *b){
  107656. oggpack_writeinit(b);
  107657. }
  107658. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107659. long bytes=bits>>3;
  107660. bits-=bytes*8;
  107661. b->ptr=b->buffer+bytes;
  107662. b->endbit=bits;
  107663. b->endbyte=bytes;
  107664. *b->ptr&=mask[bits];
  107665. }
  107666. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107667. long bytes=bits>>3;
  107668. bits-=bytes*8;
  107669. b->ptr=b->buffer+bytes;
  107670. b->endbit=bits;
  107671. b->endbyte=bytes;
  107672. *b->ptr&=mask8B[bits];
  107673. }
  107674. /* Takes only up to 32 bits. */
  107675. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107676. if(b->endbyte+4>=b->storage){
  107677. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107678. b->storage+=BUFFER_INCREMENT;
  107679. b->ptr=b->buffer+b->endbyte;
  107680. }
  107681. value&=mask[bits];
  107682. bits+=b->endbit;
  107683. b->ptr[0]|=value<<b->endbit;
  107684. if(bits>=8){
  107685. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107686. if(bits>=16){
  107687. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107688. if(bits>=24){
  107689. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107690. if(bits>=32){
  107691. if(b->endbit)
  107692. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107693. else
  107694. b->ptr[4]=0;
  107695. }
  107696. }
  107697. }
  107698. }
  107699. b->endbyte+=bits/8;
  107700. b->ptr+=bits/8;
  107701. b->endbit=bits&7;
  107702. }
  107703. /* Takes only up to 32 bits. */
  107704. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107705. if(b->endbyte+4>=b->storage){
  107706. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107707. b->storage+=BUFFER_INCREMENT;
  107708. b->ptr=b->buffer+b->endbyte;
  107709. }
  107710. value=(value&mask[bits])<<(32-bits);
  107711. bits+=b->endbit;
  107712. b->ptr[0]|=value>>(24+b->endbit);
  107713. if(bits>=8){
  107714. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107715. if(bits>=16){
  107716. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107717. if(bits>=24){
  107718. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107719. if(bits>=32){
  107720. if(b->endbit)
  107721. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107722. else
  107723. b->ptr[4]=0;
  107724. }
  107725. }
  107726. }
  107727. }
  107728. b->endbyte+=bits/8;
  107729. b->ptr+=bits/8;
  107730. b->endbit=bits&7;
  107731. }
  107732. void oggpack_writealign(oggpack_buffer *b){
  107733. int bits=8-b->endbit;
  107734. if(bits<8)
  107735. oggpack_write(b,0,bits);
  107736. }
  107737. void oggpackB_writealign(oggpack_buffer *b){
  107738. int bits=8-b->endbit;
  107739. if(bits<8)
  107740. oggpackB_write(b,0,bits);
  107741. }
  107742. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107743. void *source,
  107744. long bits,
  107745. void (*w)(oggpack_buffer *,
  107746. unsigned long,
  107747. int),
  107748. int msb){
  107749. unsigned char *ptr=(unsigned char *)source;
  107750. long bytes=bits/8;
  107751. bits-=bytes*8;
  107752. if(b->endbit){
  107753. int i;
  107754. /* unaligned copy. Do it the hard way. */
  107755. for(i=0;i<bytes;i++)
  107756. w(b,(unsigned long)(ptr[i]),8);
  107757. }else{
  107758. /* aligned block copy */
  107759. if(b->endbyte+bytes+1>=b->storage){
  107760. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107761. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107762. b->ptr=b->buffer+b->endbyte;
  107763. }
  107764. memmove(b->ptr,source,bytes);
  107765. b->ptr+=bytes;
  107766. b->endbyte+=bytes;
  107767. *b->ptr=0;
  107768. }
  107769. if(bits){
  107770. if(msb)
  107771. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107772. else
  107773. w(b,(unsigned long)(ptr[bytes]),bits);
  107774. }
  107775. }
  107776. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107777. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107778. }
  107779. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107780. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107781. }
  107782. void oggpack_reset(oggpack_buffer *b){
  107783. b->ptr=b->buffer;
  107784. b->buffer[0]=0;
  107785. b->endbit=b->endbyte=0;
  107786. }
  107787. void oggpackB_reset(oggpack_buffer *b){
  107788. oggpack_reset(b);
  107789. }
  107790. void oggpack_writeclear(oggpack_buffer *b){
  107791. _ogg_free(b->buffer);
  107792. memset(b,0,sizeof(*b));
  107793. }
  107794. void oggpackB_writeclear(oggpack_buffer *b){
  107795. oggpack_writeclear(b);
  107796. }
  107797. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107798. memset(b,0,sizeof(*b));
  107799. b->buffer=b->ptr=buf;
  107800. b->storage=bytes;
  107801. }
  107802. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107803. oggpack_readinit(b,buf,bytes);
  107804. }
  107805. /* Read in bits without advancing the bitptr; bits <= 32 */
  107806. long oggpack_look(oggpack_buffer *b,int bits){
  107807. unsigned long ret;
  107808. unsigned long m=mask[bits];
  107809. bits+=b->endbit;
  107810. if(b->endbyte+4>=b->storage){
  107811. /* not the main path */
  107812. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107813. }
  107814. ret=b->ptr[0]>>b->endbit;
  107815. if(bits>8){
  107816. ret|=b->ptr[1]<<(8-b->endbit);
  107817. if(bits>16){
  107818. ret|=b->ptr[2]<<(16-b->endbit);
  107819. if(bits>24){
  107820. ret|=b->ptr[3]<<(24-b->endbit);
  107821. if(bits>32 && b->endbit)
  107822. ret|=b->ptr[4]<<(32-b->endbit);
  107823. }
  107824. }
  107825. }
  107826. return(m&ret);
  107827. }
  107828. /* Read in bits without advancing the bitptr; bits <= 32 */
  107829. long oggpackB_look(oggpack_buffer *b,int bits){
  107830. unsigned long ret;
  107831. int m=32-bits;
  107832. bits+=b->endbit;
  107833. if(b->endbyte+4>=b->storage){
  107834. /* not the main path */
  107835. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107836. }
  107837. ret=b->ptr[0]<<(24+b->endbit);
  107838. if(bits>8){
  107839. ret|=b->ptr[1]<<(16+b->endbit);
  107840. if(bits>16){
  107841. ret|=b->ptr[2]<<(8+b->endbit);
  107842. if(bits>24){
  107843. ret|=b->ptr[3]<<(b->endbit);
  107844. if(bits>32 && b->endbit)
  107845. ret|=b->ptr[4]>>(8-b->endbit);
  107846. }
  107847. }
  107848. }
  107849. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107850. }
  107851. long oggpack_look1(oggpack_buffer *b){
  107852. if(b->endbyte>=b->storage)return(-1);
  107853. return((b->ptr[0]>>b->endbit)&1);
  107854. }
  107855. long oggpackB_look1(oggpack_buffer *b){
  107856. if(b->endbyte>=b->storage)return(-1);
  107857. return((b->ptr[0]>>(7-b->endbit))&1);
  107858. }
  107859. void oggpack_adv(oggpack_buffer *b,int bits){
  107860. bits+=b->endbit;
  107861. b->ptr+=bits/8;
  107862. b->endbyte+=bits/8;
  107863. b->endbit=bits&7;
  107864. }
  107865. void oggpackB_adv(oggpack_buffer *b,int bits){
  107866. oggpack_adv(b,bits);
  107867. }
  107868. void oggpack_adv1(oggpack_buffer *b){
  107869. if(++(b->endbit)>7){
  107870. b->endbit=0;
  107871. b->ptr++;
  107872. b->endbyte++;
  107873. }
  107874. }
  107875. void oggpackB_adv1(oggpack_buffer *b){
  107876. oggpack_adv1(b);
  107877. }
  107878. /* bits <= 32 */
  107879. long oggpack_read(oggpack_buffer *b,int bits){
  107880. long ret;
  107881. unsigned long m=mask[bits];
  107882. bits+=b->endbit;
  107883. if(b->endbyte+4>=b->storage){
  107884. /* not the main path */
  107885. ret=-1L;
  107886. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107887. }
  107888. ret=b->ptr[0]>>b->endbit;
  107889. if(bits>8){
  107890. ret|=b->ptr[1]<<(8-b->endbit);
  107891. if(bits>16){
  107892. ret|=b->ptr[2]<<(16-b->endbit);
  107893. if(bits>24){
  107894. ret|=b->ptr[3]<<(24-b->endbit);
  107895. if(bits>32 && b->endbit){
  107896. ret|=b->ptr[4]<<(32-b->endbit);
  107897. }
  107898. }
  107899. }
  107900. }
  107901. ret&=m;
  107902. overflow:
  107903. b->ptr+=bits/8;
  107904. b->endbyte+=bits/8;
  107905. b->endbit=bits&7;
  107906. return(ret);
  107907. }
  107908. /* bits <= 32 */
  107909. long oggpackB_read(oggpack_buffer *b,int bits){
  107910. long ret;
  107911. long m=32-bits;
  107912. bits+=b->endbit;
  107913. if(b->endbyte+4>=b->storage){
  107914. /* not the main path */
  107915. ret=-1L;
  107916. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107917. }
  107918. ret=b->ptr[0]<<(24+b->endbit);
  107919. if(bits>8){
  107920. ret|=b->ptr[1]<<(16+b->endbit);
  107921. if(bits>16){
  107922. ret|=b->ptr[2]<<(8+b->endbit);
  107923. if(bits>24){
  107924. ret|=b->ptr[3]<<(b->endbit);
  107925. if(bits>32 && b->endbit)
  107926. ret|=b->ptr[4]>>(8-b->endbit);
  107927. }
  107928. }
  107929. }
  107930. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107931. overflow:
  107932. b->ptr+=bits/8;
  107933. b->endbyte+=bits/8;
  107934. b->endbit=bits&7;
  107935. return(ret);
  107936. }
  107937. long oggpack_read1(oggpack_buffer *b){
  107938. long ret;
  107939. if(b->endbyte>=b->storage){
  107940. /* not the main path */
  107941. ret=-1L;
  107942. goto overflow;
  107943. }
  107944. ret=(b->ptr[0]>>b->endbit)&1;
  107945. overflow:
  107946. b->endbit++;
  107947. if(b->endbit>7){
  107948. b->endbit=0;
  107949. b->ptr++;
  107950. b->endbyte++;
  107951. }
  107952. return(ret);
  107953. }
  107954. long oggpackB_read1(oggpack_buffer *b){
  107955. long ret;
  107956. if(b->endbyte>=b->storage){
  107957. /* not the main path */
  107958. ret=-1L;
  107959. goto overflow;
  107960. }
  107961. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107962. overflow:
  107963. b->endbit++;
  107964. if(b->endbit>7){
  107965. b->endbit=0;
  107966. b->ptr++;
  107967. b->endbyte++;
  107968. }
  107969. return(ret);
  107970. }
  107971. long oggpack_bytes(oggpack_buffer *b){
  107972. return(b->endbyte+(b->endbit+7)/8);
  107973. }
  107974. long oggpack_bits(oggpack_buffer *b){
  107975. return(b->endbyte*8+b->endbit);
  107976. }
  107977. long oggpackB_bytes(oggpack_buffer *b){
  107978. return oggpack_bytes(b);
  107979. }
  107980. long oggpackB_bits(oggpack_buffer *b){
  107981. return oggpack_bits(b);
  107982. }
  107983. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107984. return(b->buffer);
  107985. }
  107986. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107987. return oggpack_get_buffer(b);
  107988. }
  107989. /* Self test of the bitwise routines; everything else is based on
  107990. them, so they damned well better be solid. */
  107991. #ifdef _V_SELFTEST
  107992. #include <stdio.h>
  107993. static int ilog(unsigned int v){
  107994. int ret=0;
  107995. while(v){
  107996. ret++;
  107997. v>>=1;
  107998. }
  107999. return(ret);
  108000. }
  108001. oggpack_buffer o;
  108002. oggpack_buffer r;
  108003. void report(char *in){
  108004. fprintf(stderr,"%s",in);
  108005. exit(1);
  108006. }
  108007. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108008. long bytes,i;
  108009. unsigned char *buffer;
  108010. oggpack_reset(&o);
  108011. for(i=0;i<vals;i++)
  108012. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108013. buffer=oggpack_get_buffer(&o);
  108014. bytes=oggpack_bytes(&o);
  108015. if(bytes!=compsize)report("wrong number of bytes!\n");
  108016. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108017. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108018. report("wrote incorrect value!\n");
  108019. }
  108020. oggpack_readinit(&r,buffer,bytes);
  108021. for(i=0;i<vals;i++){
  108022. int tbit=bits?bits:ilog(b[i]);
  108023. if(oggpack_look(&r,tbit)==-1)
  108024. report("out of data!\n");
  108025. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108026. report("looked at incorrect value!\n");
  108027. if(tbit==1)
  108028. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108029. report("looked at single bit incorrect value!\n");
  108030. if(tbit==1){
  108031. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108032. report("read incorrect single bit value!\n");
  108033. }else{
  108034. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108035. report("read incorrect value!\n");
  108036. }
  108037. }
  108038. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108039. }
  108040. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108041. long bytes,i;
  108042. unsigned char *buffer;
  108043. oggpackB_reset(&o);
  108044. for(i=0;i<vals;i++)
  108045. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108046. buffer=oggpackB_get_buffer(&o);
  108047. bytes=oggpackB_bytes(&o);
  108048. if(bytes!=compsize)report("wrong number of bytes!\n");
  108049. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108050. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108051. report("wrote incorrect value!\n");
  108052. }
  108053. oggpackB_readinit(&r,buffer,bytes);
  108054. for(i=0;i<vals;i++){
  108055. int tbit=bits?bits:ilog(b[i]);
  108056. if(oggpackB_look(&r,tbit)==-1)
  108057. report("out of data!\n");
  108058. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108059. report("looked at incorrect value!\n");
  108060. if(tbit==1)
  108061. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108062. report("looked at single bit incorrect value!\n");
  108063. if(tbit==1){
  108064. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108065. report("read incorrect single bit value!\n");
  108066. }else{
  108067. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108068. report("read incorrect value!\n");
  108069. }
  108070. }
  108071. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108072. }
  108073. int main(void){
  108074. unsigned char *buffer;
  108075. long bytes,i;
  108076. static unsigned long testbuffer1[]=
  108077. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108078. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108079. int test1size=43;
  108080. static unsigned long testbuffer2[]=
  108081. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108082. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108083. 85525151,0,12321,1,349528352};
  108084. int test2size=21;
  108085. static unsigned long testbuffer3[]=
  108086. {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,
  108087. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108088. int test3size=56;
  108089. static unsigned long large[]=
  108090. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108091. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108092. 85525151,0,12321,1,2146528352};
  108093. int onesize=33;
  108094. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108095. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108096. 223,4};
  108097. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108098. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108099. 245,251,128};
  108100. int twosize=6;
  108101. static int two[6]={61,255,255,251,231,29};
  108102. static int twoB[6]={247,63,255,253,249,120};
  108103. int threesize=54;
  108104. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108105. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108106. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108107. 100,52,4,14,18,86,77,1};
  108108. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108109. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108110. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108111. 200,20,254,4,58,106,176,144,0};
  108112. int foursize=38;
  108113. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108114. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108115. 28,2,133,0,1};
  108116. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108117. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108118. 129,10,4,32};
  108119. int fivesize=45;
  108120. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108121. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108122. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108123. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108124. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108125. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108126. int sixsize=7;
  108127. static int six[7]={17,177,170,242,169,19,148};
  108128. static int sixB[7]={136,141,85,79,149,200,41};
  108129. /* Test read/write together */
  108130. /* Later we test against pregenerated bitstreams */
  108131. oggpack_writeinit(&o);
  108132. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108133. cliptest(testbuffer1,test1size,0,one,onesize);
  108134. fprintf(stderr,"ok.");
  108135. fprintf(stderr,"\nNull bit call (LSb): ");
  108136. cliptest(testbuffer3,test3size,0,two,twosize);
  108137. fprintf(stderr,"ok.");
  108138. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108139. cliptest(testbuffer2,test2size,0,three,threesize);
  108140. fprintf(stderr,"ok.");
  108141. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108142. oggpack_reset(&o);
  108143. for(i=0;i<test2size;i++)
  108144. oggpack_write(&o,large[i],32);
  108145. buffer=oggpack_get_buffer(&o);
  108146. bytes=oggpack_bytes(&o);
  108147. oggpack_readinit(&r,buffer,bytes);
  108148. for(i=0;i<test2size;i++){
  108149. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108150. if(oggpack_look(&r,32)!=large[i]){
  108151. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108152. oggpack_look(&r,32),large[i]);
  108153. report("read incorrect value!\n");
  108154. }
  108155. oggpack_adv(&r,32);
  108156. }
  108157. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108158. fprintf(stderr,"ok.");
  108159. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108160. cliptest(testbuffer1,test1size,7,four,foursize);
  108161. fprintf(stderr,"ok.");
  108162. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108163. cliptest(testbuffer2,test2size,17,five,fivesize);
  108164. fprintf(stderr,"ok.");
  108165. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108166. cliptest(testbuffer3,test3size,1,six,sixsize);
  108167. fprintf(stderr,"ok.");
  108168. fprintf(stderr,"\nTesting read past end (LSb): ");
  108169. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108170. for(i=0;i<64;i++){
  108171. if(oggpack_read(&r,1)!=0){
  108172. fprintf(stderr,"failed; got -1 prematurely.\n");
  108173. exit(1);
  108174. }
  108175. }
  108176. if(oggpack_look(&r,1)!=-1 ||
  108177. oggpack_read(&r,1)!=-1){
  108178. fprintf(stderr,"failed; read past end without -1.\n");
  108179. exit(1);
  108180. }
  108181. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108182. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108183. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108184. exit(1);
  108185. }
  108186. if(oggpack_look(&r,18)!=0 ||
  108187. oggpack_look(&r,18)!=0){
  108188. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108189. exit(1);
  108190. }
  108191. if(oggpack_look(&r,19)!=-1 ||
  108192. oggpack_look(&r,19)!=-1){
  108193. fprintf(stderr,"failed; read past end without -1.\n");
  108194. exit(1);
  108195. }
  108196. if(oggpack_look(&r,32)!=-1 ||
  108197. oggpack_look(&r,32)!=-1){
  108198. fprintf(stderr,"failed; read past end without -1.\n");
  108199. exit(1);
  108200. }
  108201. oggpack_writeclear(&o);
  108202. fprintf(stderr,"ok.\n");
  108203. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108204. /* Test read/write together */
  108205. /* Later we test against pregenerated bitstreams */
  108206. oggpackB_writeinit(&o);
  108207. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108208. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108209. fprintf(stderr,"ok.");
  108210. fprintf(stderr,"\nNull bit call (MSb): ");
  108211. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108212. fprintf(stderr,"ok.");
  108213. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108214. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108215. fprintf(stderr,"ok.");
  108216. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108217. oggpackB_reset(&o);
  108218. for(i=0;i<test2size;i++)
  108219. oggpackB_write(&o,large[i],32);
  108220. buffer=oggpackB_get_buffer(&o);
  108221. bytes=oggpackB_bytes(&o);
  108222. oggpackB_readinit(&r,buffer,bytes);
  108223. for(i=0;i<test2size;i++){
  108224. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108225. if(oggpackB_look(&r,32)!=large[i]){
  108226. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108227. oggpackB_look(&r,32),large[i]);
  108228. report("read incorrect value!\n");
  108229. }
  108230. oggpackB_adv(&r,32);
  108231. }
  108232. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108233. fprintf(stderr,"ok.");
  108234. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108235. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108236. fprintf(stderr,"ok.");
  108237. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108238. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108239. fprintf(stderr,"ok.");
  108240. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108241. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108242. fprintf(stderr,"ok.");
  108243. fprintf(stderr,"\nTesting read past end (MSb): ");
  108244. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108245. for(i=0;i<64;i++){
  108246. if(oggpackB_read(&r,1)!=0){
  108247. fprintf(stderr,"failed; got -1 prematurely.\n");
  108248. exit(1);
  108249. }
  108250. }
  108251. if(oggpackB_look(&r,1)!=-1 ||
  108252. oggpackB_read(&r,1)!=-1){
  108253. fprintf(stderr,"failed; read past end without -1.\n");
  108254. exit(1);
  108255. }
  108256. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108257. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108258. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108259. exit(1);
  108260. }
  108261. if(oggpackB_look(&r,18)!=0 ||
  108262. oggpackB_look(&r,18)!=0){
  108263. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108264. exit(1);
  108265. }
  108266. if(oggpackB_look(&r,19)!=-1 ||
  108267. oggpackB_look(&r,19)!=-1){
  108268. fprintf(stderr,"failed; read past end without -1.\n");
  108269. exit(1);
  108270. }
  108271. if(oggpackB_look(&r,32)!=-1 ||
  108272. oggpackB_look(&r,32)!=-1){
  108273. fprintf(stderr,"failed; read past end without -1.\n");
  108274. exit(1);
  108275. }
  108276. oggpackB_writeclear(&o);
  108277. fprintf(stderr,"ok.\n\n");
  108278. return(0);
  108279. }
  108280. #endif /* _V_SELFTEST */
  108281. #undef BUFFER_INCREMENT
  108282. #endif
  108283. /*** End of inlined file: bitwise.c ***/
  108284. /*** Start of inlined file: framing.c ***/
  108285. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108286. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108287. // tasks..
  108288. #if JUCE_MSVC
  108289. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108290. #endif
  108291. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108292. #if JUCE_USE_OGGVORBIS
  108293. #include <stdlib.h>
  108294. #include <string.h>
  108295. /* A complete description of Ogg framing exists in docs/framing.html */
  108296. int ogg_page_version(ogg_page *og){
  108297. return((int)(og->header[4]));
  108298. }
  108299. int ogg_page_continued(ogg_page *og){
  108300. return((int)(og->header[5]&0x01));
  108301. }
  108302. int ogg_page_bos(ogg_page *og){
  108303. return((int)(og->header[5]&0x02));
  108304. }
  108305. int ogg_page_eos(ogg_page *og){
  108306. return((int)(og->header[5]&0x04));
  108307. }
  108308. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108309. unsigned char *page=og->header;
  108310. ogg_int64_t granulepos=page[13]&(0xff);
  108311. granulepos= (granulepos<<8)|(page[12]&0xff);
  108312. granulepos= (granulepos<<8)|(page[11]&0xff);
  108313. granulepos= (granulepos<<8)|(page[10]&0xff);
  108314. granulepos= (granulepos<<8)|(page[9]&0xff);
  108315. granulepos= (granulepos<<8)|(page[8]&0xff);
  108316. granulepos= (granulepos<<8)|(page[7]&0xff);
  108317. granulepos= (granulepos<<8)|(page[6]&0xff);
  108318. return(granulepos);
  108319. }
  108320. int ogg_page_serialno(ogg_page *og){
  108321. return(og->header[14] |
  108322. (og->header[15]<<8) |
  108323. (og->header[16]<<16) |
  108324. (og->header[17]<<24));
  108325. }
  108326. long ogg_page_pageno(ogg_page *og){
  108327. return(og->header[18] |
  108328. (og->header[19]<<8) |
  108329. (og->header[20]<<16) |
  108330. (og->header[21]<<24));
  108331. }
  108332. /* returns the number of packets that are completed on this page (if
  108333. the leading packet is begun on a previous page, but ends on this
  108334. page, it's counted */
  108335. /* NOTE:
  108336. If a page consists of a packet begun on a previous page, and a new
  108337. packet begun (but not completed) on this page, the return will be:
  108338. ogg_page_packets(page) ==1,
  108339. ogg_page_continued(page) !=0
  108340. If a page happens to be a single packet that was begun on a
  108341. previous page, and spans to the next page (in the case of a three or
  108342. more page packet), the return will be:
  108343. ogg_page_packets(page) ==0,
  108344. ogg_page_continued(page) !=0
  108345. */
  108346. int ogg_page_packets(ogg_page *og){
  108347. int i,n=og->header[26],count=0;
  108348. for(i=0;i<n;i++)
  108349. if(og->header[27+i]<255)count++;
  108350. return(count);
  108351. }
  108352. #if 0
  108353. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108354. use the static init below) */
  108355. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108356. int i;
  108357. unsigned long r;
  108358. r = index << 24;
  108359. for (i=0; i<8; i++)
  108360. if (r & 0x80000000UL)
  108361. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108362. polynomial, although we use an
  108363. unreflected alg and an init/final
  108364. of 0, not 0xffffffff */
  108365. else
  108366. r<<=1;
  108367. return (r & 0xffffffffUL);
  108368. }
  108369. #endif
  108370. static const ogg_uint32_t crc_lookup[256]={
  108371. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108372. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108373. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108374. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108375. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108376. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108377. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108378. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108379. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108380. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108381. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108382. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108383. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108384. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108385. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108386. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108387. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108388. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108389. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108390. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108391. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108392. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108393. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108394. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108395. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108396. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108397. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108398. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108399. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108400. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108401. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108402. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108403. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108404. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108405. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108406. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108407. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108408. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108409. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108410. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108411. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108412. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108413. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108414. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108415. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108416. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108417. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108418. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108419. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108420. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108421. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108422. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108423. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108424. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108425. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108426. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108427. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108428. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108429. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108430. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108431. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108432. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108433. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108434. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108435. /* init the encode/decode logical stream state */
  108436. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108437. if(os){
  108438. memset(os,0,sizeof(*os));
  108439. os->body_storage=16*1024;
  108440. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108441. os->lacing_storage=1024;
  108442. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108443. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108444. os->serialno=serialno;
  108445. return(0);
  108446. }
  108447. return(-1);
  108448. }
  108449. /* _clear does not free os, only the non-flat storage within */
  108450. int ogg_stream_clear(ogg_stream_state *os){
  108451. if(os){
  108452. if(os->body_data)_ogg_free(os->body_data);
  108453. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108454. if(os->granule_vals)_ogg_free(os->granule_vals);
  108455. memset(os,0,sizeof(*os));
  108456. }
  108457. return(0);
  108458. }
  108459. int ogg_stream_destroy(ogg_stream_state *os){
  108460. if(os){
  108461. ogg_stream_clear(os);
  108462. _ogg_free(os);
  108463. }
  108464. return(0);
  108465. }
  108466. /* Helpers for ogg_stream_encode; this keeps the structure and
  108467. what's happening fairly clear */
  108468. static void _os_body_expand(ogg_stream_state *os,int needed){
  108469. if(os->body_storage<=os->body_fill+needed){
  108470. os->body_storage+=(needed+1024);
  108471. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108472. }
  108473. }
  108474. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108475. if(os->lacing_storage<=os->lacing_fill+needed){
  108476. os->lacing_storage+=(needed+32);
  108477. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108478. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108479. }
  108480. }
  108481. /* checksum the page */
  108482. /* Direct table CRC; note that this will be faster in the future if we
  108483. perform the checksum silmultaneously with other copies */
  108484. void ogg_page_checksum_set(ogg_page *og){
  108485. if(og){
  108486. ogg_uint32_t crc_reg=0;
  108487. int i;
  108488. /* safety; needed for API behavior, but not framing code */
  108489. og->header[22]=0;
  108490. og->header[23]=0;
  108491. og->header[24]=0;
  108492. og->header[25]=0;
  108493. for(i=0;i<og->header_len;i++)
  108494. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108495. for(i=0;i<og->body_len;i++)
  108496. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108497. og->header[22]=(unsigned char)(crc_reg&0xff);
  108498. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108499. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108500. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108501. }
  108502. }
  108503. /* submit data to the internal buffer of the framing engine */
  108504. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108505. int lacing_vals=op->bytes/255+1,i;
  108506. if(os->body_returned){
  108507. /* advance packet data according to the body_returned pointer. We
  108508. had to keep it around to return a pointer into the buffer last
  108509. call */
  108510. os->body_fill-=os->body_returned;
  108511. if(os->body_fill)
  108512. memmove(os->body_data,os->body_data+os->body_returned,
  108513. os->body_fill);
  108514. os->body_returned=0;
  108515. }
  108516. /* make sure we have the buffer storage */
  108517. _os_body_expand(os,op->bytes);
  108518. _os_lacing_expand(os,lacing_vals);
  108519. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108520. the liability of overly clean abstraction for the time being. It
  108521. will actually be fairly easy to eliminate the extra copy in the
  108522. future */
  108523. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108524. os->body_fill+=op->bytes;
  108525. /* Store lacing vals for this packet */
  108526. for(i=0;i<lacing_vals-1;i++){
  108527. os->lacing_vals[os->lacing_fill+i]=255;
  108528. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108529. }
  108530. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108531. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108532. /* flag the first segment as the beginning of the packet */
  108533. os->lacing_vals[os->lacing_fill]|= 0x100;
  108534. os->lacing_fill+=lacing_vals;
  108535. /* for the sake of completeness */
  108536. os->packetno++;
  108537. if(op->e_o_s)os->e_o_s=1;
  108538. return(0);
  108539. }
  108540. /* This will flush remaining packets into a page (returning nonzero),
  108541. even if there is not enough data to trigger a flush normally
  108542. (undersized page). If there are no packets or partial packets to
  108543. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108544. try to flush a normal sized page like ogg_stream_pageout; a call to
  108545. ogg_stream_flush does not guarantee that all packets have flushed.
  108546. Only a return value of 0 from ogg_stream_flush indicates all packet
  108547. data is flushed into pages.
  108548. since ogg_stream_flush will flush the last page in a stream even if
  108549. it's undersized, you almost certainly want to use ogg_stream_pageout
  108550. (and *not* ogg_stream_flush) unless you specifically need to flush
  108551. an page regardless of size in the middle of a stream. */
  108552. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108553. int i;
  108554. int vals=0;
  108555. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108556. int bytes=0;
  108557. long acc=0;
  108558. ogg_int64_t granule_pos=-1;
  108559. if(maxvals==0)return(0);
  108560. /* construct a page */
  108561. /* decide how many segments to include */
  108562. /* If this is the initial header case, the first page must only include
  108563. the initial header packet */
  108564. if(os->b_o_s==0){ /* 'initial header page' case */
  108565. granule_pos=0;
  108566. for(vals=0;vals<maxvals;vals++){
  108567. if((os->lacing_vals[vals]&0x0ff)<255){
  108568. vals++;
  108569. break;
  108570. }
  108571. }
  108572. }else{
  108573. for(vals=0;vals<maxvals;vals++){
  108574. if(acc>4096)break;
  108575. acc+=os->lacing_vals[vals]&0x0ff;
  108576. if((os->lacing_vals[vals]&0xff)<255)
  108577. granule_pos=os->granule_vals[vals];
  108578. }
  108579. }
  108580. /* construct the header in temp storage */
  108581. memcpy(os->header,"OggS",4);
  108582. /* stream structure version */
  108583. os->header[4]=0x00;
  108584. /* continued packet flag? */
  108585. os->header[5]=0x00;
  108586. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108587. /* first page flag? */
  108588. if(os->b_o_s==0)os->header[5]|=0x02;
  108589. /* last page flag? */
  108590. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108591. os->b_o_s=1;
  108592. /* 64 bits of PCM position */
  108593. for(i=6;i<14;i++){
  108594. os->header[i]=(unsigned char)(granule_pos&0xff);
  108595. granule_pos>>=8;
  108596. }
  108597. /* 32 bits of stream serial number */
  108598. {
  108599. long serialno=os->serialno;
  108600. for(i=14;i<18;i++){
  108601. os->header[i]=(unsigned char)(serialno&0xff);
  108602. serialno>>=8;
  108603. }
  108604. }
  108605. /* 32 bits of page counter (we have both counter and page header
  108606. because this val can roll over) */
  108607. if(os->pageno==-1)os->pageno=0; /* because someone called
  108608. stream_reset; this would be a
  108609. strange thing to do in an
  108610. encode stream, but it has
  108611. plausible uses */
  108612. {
  108613. long pageno=os->pageno++;
  108614. for(i=18;i<22;i++){
  108615. os->header[i]=(unsigned char)(pageno&0xff);
  108616. pageno>>=8;
  108617. }
  108618. }
  108619. /* zero for computation; filled in later */
  108620. os->header[22]=0;
  108621. os->header[23]=0;
  108622. os->header[24]=0;
  108623. os->header[25]=0;
  108624. /* segment table */
  108625. os->header[26]=(unsigned char)(vals&0xff);
  108626. for(i=0;i<vals;i++)
  108627. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108628. /* set pointers in the ogg_page struct */
  108629. og->header=os->header;
  108630. og->header_len=os->header_fill=vals+27;
  108631. og->body=os->body_data+os->body_returned;
  108632. og->body_len=bytes;
  108633. /* advance the lacing data and set the body_returned pointer */
  108634. os->lacing_fill-=vals;
  108635. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108636. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108637. os->body_returned+=bytes;
  108638. /* calculate the checksum */
  108639. ogg_page_checksum_set(og);
  108640. /* done */
  108641. return(1);
  108642. }
  108643. /* This constructs pages from buffered packet segments. The pointers
  108644. returned are to static buffers; do not free. The returned buffers are
  108645. good only until the next call (using the same ogg_stream_state) */
  108646. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108647. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108648. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108649. os->lacing_fill>=255 || /* 'segment table full' case */
  108650. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108651. return(ogg_stream_flush(os,og));
  108652. }
  108653. /* not enough data to construct a page and not end of stream */
  108654. return(0);
  108655. }
  108656. int ogg_stream_eos(ogg_stream_state *os){
  108657. return os->e_o_s;
  108658. }
  108659. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108660. /* This has two layers to place more of the multi-serialno and paging
  108661. control in the application's hands. First, we expose a data buffer
  108662. using ogg_sync_buffer(). The app either copies into the
  108663. buffer, or passes it directly to read(), etc. We then call
  108664. ogg_sync_wrote() to tell how many bytes we just added.
  108665. Pages are returned (pointers into the buffer in ogg_sync_state)
  108666. by ogg_sync_pageout(). The page is then submitted to
  108667. ogg_stream_pagein() along with the appropriate
  108668. ogg_stream_state* (ie, matching serialno). We then get raw
  108669. packets out calling ogg_stream_packetout() with a
  108670. ogg_stream_state. */
  108671. /* initialize the struct to a known state */
  108672. int ogg_sync_init(ogg_sync_state *oy){
  108673. if(oy){
  108674. memset(oy,0,sizeof(*oy));
  108675. }
  108676. return(0);
  108677. }
  108678. /* clear non-flat storage within */
  108679. int ogg_sync_clear(ogg_sync_state *oy){
  108680. if(oy){
  108681. if(oy->data)_ogg_free(oy->data);
  108682. ogg_sync_init(oy);
  108683. }
  108684. return(0);
  108685. }
  108686. int ogg_sync_destroy(ogg_sync_state *oy){
  108687. if(oy){
  108688. ogg_sync_clear(oy);
  108689. _ogg_free(oy);
  108690. }
  108691. return(0);
  108692. }
  108693. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108694. /* first, clear out any space that has been previously returned */
  108695. if(oy->returned){
  108696. oy->fill-=oy->returned;
  108697. if(oy->fill>0)
  108698. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108699. oy->returned=0;
  108700. }
  108701. if(size>oy->storage-oy->fill){
  108702. /* We need to extend the internal buffer */
  108703. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108704. if(oy->data)
  108705. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108706. else
  108707. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108708. oy->storage=newsize;
  108709. }
  108710. /* expose a segment at least as large as requested at the fill mark */
  108711. return((char *)oy->data+oy->fill);
  108712. }
  108713. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108714. if(oy->fill+bytes>oy->storage)return(-1);
  108715. oy->fill+=bytes;
  108716. return(0);
  108717. }
  108718. /* sync the stream. This is meant to be useful for finding page
  108719. boundaries.
  108720. return values for this:
  108721. -n) skipped n bytes
  108722. 0) page not ready; more data (no bytes skipped)
  108723. n) page synced at current location; page length n bytes
  108724. */
  108725. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108726. unsigned char *page=oy->data+oy->returned;
  108727. unsigned char *next;
  108728. long bytes=oy->fill-oy->returned;
  108729. if(oy->headerbytes==0){
  108730. int headerbytes,i;
  108731. if(bytes<27)return(0); /* not enough for a header */
  108732. /* verify capture pattern */
  108733. if(memcmp(page,"OggS",4))goto sync_fail;
  108734. headerbytes=page[26]+27;
  108735. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108736. /* count up body length in the segment table */
  108737. for(i=0;i<page[26];i++)
  108738. oy->bodybytes+=page[27+i];
  108739. oy->headerbytes=headerbytes;
  108740. }
  108741. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108742. /* The whole test page is buffered. Verify the checksum */
  108743. {
  108744. /* Grab the checksum bytes, set the header field to zero */
  108745. char chksum[4];
  108746. ogg_page log;
  108747. memcpy(chksum,page+22,4);
  108748. memset(page+22,0,4);
  108749. /* set up a temp page struct and recompute the checksum */
  108750. log.header=page;
  108751. log.header_len=oy->headerbytes;
  108752. log.body=page+oy->headerbytes;
  108753. log.body_len=oy->bodybytes;
  108754. ogg_page_checksum_set(&log);
  108755. /* Compare */
  108756. if(memcmp(chksum,page+22,4)){
  108757. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108758. at all) */
  108759. /* replace the computed checksum with the one actually read in */
  108760. memcpy(page+22,chksum,4);
  108761. /* Bad checksum. Lose sync */
  108762. goto sync_fail;
  108763. }
  108764. }
  108765. /* yes, have a whole page all ready to go */
  108766. {
  108767. unsigned char *page=oy->data+oy->returned;
  108768. long bytes;
  108769. if(og){
  108770. og->header=page;
  108771. og->header_len=oy->headerbytes;
  108772. og->body=page+oy->headerbytes;
  108773. og->body_len=oy->bodybytes;
  108774. }
  108775. oy->unsynced=0;
  108776. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108777. oy->headerbytes=0;
  108778. oy->bodybytes=0;
  108779. return(bytes);
  108780. }
  108781. sync_fail:
  108782. oy->headerbytes=0;
  108783. oy->bodybytes=0;
  108784. /* search for possible capture */
  108785. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108786. if(!next)
  108787. next=oy->data+oy->fill;
  108788. oy->returned=next-oy->data;
  108789. return(-(next-page));
  108790. }
  108791. /* sync the stream and get a page. Keep trying until we find a page.
  108792. Supress 'sync errors' after reporting the first.
  108793. return values:
  108794. -1) recapture (hole in data)
  108795. 0) need more data
  108796. 1) page returned
  108797. Returns pointers into buffered data; invalidated by next call to
  108798. _stream, _clear, _init, or _buffer */
  108799. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108800. /* all we need to do is verify a page at the head of the stream
  108801. buffer. If it doesn't verify, we look for the next potential
  108802. frame */
  108803. for(;;){
  108804. long ret=ogg_sync_pageseek(oy,og);
  108805. if(ret>0){
  108806. /* have a page */
  108807. return(1);
  108808. }
  108809. if(ret==0){
  108810. /* need more data */
  108811. return(0);
  108812. }
  108813. /* head did not start a synced page... skipped some bytes */
  108814. if(!oy->unsynced){
  108815. oy->unsynced=1;
  108816. return(-1);
  108817. }
  108818. /* loop. keep looking */
  108819. }
  108820. }
  108821. /* add the incoming page to the stream state; we decompose the page
  108822. into packet segments here as well. */
  108823. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108824. unsigned char *header=og->header;
  108825. unsigned char *body=og->body;
  108826. long bodysize=og->body_len;
  108827. int segptr=0;
  108828. int version=ogg_page_version(og);
  108829. int continued=ogg_page_continued(og);
  108830. int bos=ogg_page_bos(og);
  108831. int eos=ogg_page_eos(og);
  108832. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108833. int serialno=ogg_page_serialno(og);
  108834. long pageno=ogg_page_pageno(og);
  108835. int segments=header[26];
  108836. /* clean up 'returned data' */
  108837. {
  108838. long lr=os->lacing_returned;
  108839. long br=os->body_returned;
  108840. /* body data */
  108841. if(br){
  108842. os->body_fill-=br;
  108843. if(os->body_fill)
  108844. memmove(os->body_data,os->body_data+br,os->body_fill);
  108845. os->body_returned=0;
  108846. }
  108847. if(lr){
  108848. /* segment table */
  108849. if(os->lacing_fill-lr){
  108850. memmove(os->lacing_vals,os->lacing_vals+lr,
  108851. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108852. memmove(os->granule_vals,os->granule_vals+lr,
  108853. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108854. }
  108855. os->lacing_fill-=lr;
  108856. os->lacing_packet-=lr;
  108857. os->lacing_returned=0;
  108858. }
  108859. }
  108860. /* check the serial number */
  108861. if(serialno!=os->serialno)return(-1);
  108862. if(version>0)return(-1);
  108863. _os_lacing_expand(os,segments+1);
  108864. /* are we in sequence? */
  108865. if(pageno!=os->pageno){
  108866. int i;
  108867. /* unroll previous partial packet (if any) */
  108868. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108869. os->body_fill-=os->lacing_vals[i]&0xff;
  108870. os->lacing_fill=os->lacing_packet;
  108871. /* make a note of dropped data in segment table */
  108872. if(os->pageno!=-1){
  108873. os->lacing_vals[os->lacing_fill++]=0x400;
  108874. os->lacing_packet++;
  108875. }
  108876. }
  108877. /* are we a 'continued packet' page? If so, we may need to skip
  108878. some segments */
  108879. if(continued){
  108880. if(os->lacing_fill<1 ||
  108881. os->lacing_vals[os->lacing_fill-1]==0x400){
  108882. bos=0;
  108883. for(;segptr<segments;segptr++){
  108884. int val=header[27+segptr];
  108885. body+=val;
  108886. bodysize-=val;
  108887. if(val<255){
  108888. segptr++;
  108889. break;
  108890. }
  108891. }
  108892. }
  108893. }
  108894. if(bodysize){
  108895. _os_body_expand(os,bodysize);
  108896. memcpy(os->body_data+os->body_fill,body,bodysize);
  108897. os->body_fill+=bodysize;
  108898. }
  108899. {
  108900. int saved=-1;
  108901. while(segptr<segments){
  108902. int val=header[27+segptr];
  108903. os->lacing_vals[os->lacing_fill]=val;
  108904. os->granule_vals[os->lacing_fill]=-1;
  108905. if(bos){
  108906. os->lacing_vals[os->lacing_fill]|=0x100;
  108907. bos=0;
  108908. }
  108909. if(val<255)saved=os->lacing_fill;
  108910. os->lacing_fill++;
  108911. segptr++;
  108912. if(val<255)os->lacing_packet=os->lacing_fill;
  108913. }
  108914. /* set the granulepos on the last granuleval of the last full packet */
  108915. if(saved!=-1){
  108916. os->granule_vals[saved]=granulepos;
  108917. }
  108918. }
  108919. if(eos){
  108920. os->e_o_s=1;
  108921. if(os->lacing_fill>0)
  108922. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108923. }
  108924. os->pageno=pageno+1;
  108925. return(0);
  108926. }
  108927. /* clear things to an initial state. Good to call, eg, before seeking */
  108928. int ogg_sync_reset(ogg_sync_state *oy){
  108929. oy->fill=0;
  108930. oy->returned=0;
  108931. oy->unsynced=0;
  108932. oy->headerbytes=0;
  108933. oy->bodybytes=0;
  108934. return(0);
  108935. }
  108936. int ogg_stream_reset(ogg_stream_state *os){
  108937. os->body_fill=0;
  108938. os->body_returned=0;
  108939. os->lacing_fill=0;
  108940. os->lacing_packet=0;
  108941. os->lacing_returned=0;
  108942. os->header_fill=0;
  108943. os->e_o_s=0;
  108944. os->b_o_s=0;
  108945. os->pageno=-1;
  108946. os->packetno=0;
  108947. os->granulepos=0;
  108948. return(0);
  108949. }
  108950. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108951. ogg_stream_reset(os);
  108952. os->serialno=serialno;
  108953. return(0);
  108954. }
  108955. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108956. /* The last part of decode. We have the stream broken into packet
  108957. segments. Now we need to group them into packets (or return the
  108958. out of sync markers) */
  108959. int ptr=os->lacing_returned;
  108960. if(os->lacing_packet<=ptr)return(0);
  108961. if(os->lacing_vals[ptr]&0x400){
  108962. /* we need to tell the codec there's a gap; it might need to
  108963. handle previous packet dependencies. */
  108964. os->lacing_returned++;
  108965. os->packetno++;
  108966. return(-1);
  108967. }
  108968. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108969. to ask if there's a whole packet
  108970. waiting */
  108971. /* Gather the whole packet. We'll have no holes or a partial packet */
  108972. {
  108973. int size=os->lacing_vals[ptr]&0xff;
  108974. int bytes=size;
  108975. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108976. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108977. while(size==255){
  108978. int val=os->lacing_vals[++ptr];
  108979. size=val&0xff;
  108980. if(val&0x200)eos=0x200;
  108981. bytes+=size;
  108982. }
  108983. if(op){
  108984. op->e_o_s=eos;
  108985. op->b_o_s=bos;
  108986. op->packet=os->body_data+os->body_returned;
  108987. op->packetno=os->packetno;
  108988. op->granulepos=os->granule_vals[ptr];
  108989. op->bytes=bytes;
  108990. }
  108991. if(adv){
  108992. os->body_returned+=bytes;
  108993. os->lacing_returned=ptr+1;
  108994. os->packetno++;
  108995. }
  108996. }
  108997. return(1);
  108998. }
  108999. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109000. return _packetout(os,op,1);
  109001. }
  109002. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109003. return _packetout(os,op,0);
  109004. }
  109005. void ogg_packet_clear(ogg_packet *op) {
  109006. _ogg_free(op->packet);
  109007. memset(op, 0, sizeof(*op));
  109008. }
  109009. #ifdef _V_SELFTEST
  109010. #include <stdio.h>
  109011. ogg_stream_state os_en, os_de;
  109012. ogg_sync_state oy;
  109013. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109014. long j;
  109015. static int sequence=0;
  109016. static int lastno=0;
  109017. if(op->bytes!=len){
  109018. fprintf(stderr,"incorrect packet length!\n");
  109019. exit(1);
  109020. }
  109021. if(op->granulepos!=pos){
  109022. fprintf(stderr,"incorrect packet position!\n");
  109023. exit(1);
  109024. }
  109025. /* packet number just follows sequence/gap; adjust the input number
  109026. for that */
  109027. if(no==0){
  109028. sequence=0;
  109029. }else{
  109030. sequence++;
  109031. if(no>lastno+1)
  109032. sequence++;
  109033. }
  109034. lastno=no;
  109035. if(op->packetno!=sequence){
  109036. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109037. (long)(op->packetno),sequence);
  109038. exit(1);
  109039. }
  109040. /* Test data */
  109041. for(j=0;j<op->bytes;j++)
  109042. if(op->packet[j]!=((j+no)&0xff)){
  109043. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109044. j,op->packet[j],(j+no)&0xff);
  109045. exit(1);
  109046. }
  109047. }
  109048. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109049. long j;
  109050. /* Test data */
  109051. for(j=0;j<og->body_len;j++)
  109052. if(og->body[j]!=data[j]){
  109053. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109054. j,data[j],og->body[j]);
  109055. exit(1);
  109056. }
  109057. /* Test header */
  109058. for(j=0;j<og->header_len;j++){
  109059. if(og->header[j]!=header[j]){
  109060. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109061. for(j=0;j<header[26]+27;j++)
  109062. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109063. fprintf(stderr,"\n");
  109064. exit(1);
  109065. }
  109066. }
  109067. if(og->header_len!=header[26]+27){
  109068. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109069. og->header_len,header[26]+27);
  109070. exit(1);
  109071. }
  109072. }
  109073. void print_header(ogg_page *og){
  109074. int j;
  109075. fprintf(stderr,"\nHEADER:\n");
  109076. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109077. og->header[0],og->header[1],og->header[2],og->header[3],
  109078. (int)og->header[4],(int)og->header[5]);
  109079. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109080. (og->header[9]<<24)|(og->header[8]<<16)|
  109081. (og->header[7]<<8)|og->header[6],
  109082. (og->header[17]<<24)|(og->header[16]<<16)|
  109083. (og->header[15]<<8)|og->header[14],
  109084. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109085. (og->header[19]<<8)|og->header[18]);
  109086. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109087. (int)og->header[22],(int)og->header[23],
  109088. (int)og->header[24],(int)og->header[25],
  109089. (int)og->header[26]);
  109090. for(j=27;j<og->header_len;j++)
  109091. fprintf(stderr,"%d ",(int)og->header[j]);
  109092. fprintf(stderr,")\n\n");
  109093. }
  109094. void copy_page(ogg_page *og){
  109095. unsigned char *temp=_ogg_malloc(og->header_len);
  109096. memcpy(temp,og->header,og->header_len);
  109097. og->header=temp;
  109098. temp=_ogg_malloc(og->body_len);
  109099. memcpy(temp,og->body,og->body_len);
  109100. og->body=temp;
  109101. }
  109102. void free_page(ogg_page *og){
  109103. _ogg_free (og->header);
  109104. _ogg_free (og->body);
  109105. }
  109106. void error(void){
  109107. fprintf(stderr,"error!\n");
  109108. exit(1);
  109109. }
  109110. /* 17 only */
  109111. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109112. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109113. 0x01,0x02,0x03,0x04,0,0,0,0,
  109114. 0x15,0xed,0xec,0x91,
  109115. 1,
  109116. 17};
  109117. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109118. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109119. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109120. 0x01,0x02,0x03,0x04,0,0,0,0,
  109121. 0x59,0x10,0x6c,0x2c,
  109122. 1,
  109123. 17};
  109124. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109125. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109126. 0x01,0x02,0x03,0x04,1,0,0,0,
  109127. 0x89,0x33,0x85,0xce,
  109128. 13,
  109129. 254,255,0,255,1,255,245,255,255,0,
  109130. 255,255,90};
  109131. /* nil packets; beginning,middle,end */
  109132. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109133. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109134. 0x01,0x02,0x03,0x04,0,0,0,0,
  109135. 0xff,0x7b,0x23,0x17,
  109136. 1,
  109137. 0};
  109138. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109139. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109140. 0x01,0x02,0x03,0x04,1,0,0,0,
  109141. 0x5c,0x3f,0x66,0xcb,
  109142. 17,
  109143. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109144. 255,255,90,0};
  109145. /* large initial packet */
  109146. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109147. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109148. 0x01,0x02,0x03,0x04,0,0,0,0,
  109149. 0x01,0x27,0x31,0xaa,
  109150. 18,
  109151. 255,255,255,255,255,255,255,255,
  109152. 255,255,255,255,255,255,255,255,255,10};
  109153. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109154. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109155. 0x01,0x02,0x03,0x04,1,0,0,0,
  109156. 0x7f,0x4e,0x8a,0xd2,
  109157. 4,
  109158. 255,4,255,0};
  109159. /* continuing packet test */
  109160. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109161. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109162. 0x01,0x02,0x03,0x04,0,0,0,0,
  109163. 0xff,0x7b,0x23,0x17,
  109164. 1,
  109165. 0};
  109166. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109167. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109168. 0x01,0x02,0x03,0x04,1,0,0,0,
  109169. 0x54,0x05,0x51,0xc8,
  109170. 17,
  109171. 255,255,255,255,255,255,255,255,
  109172. 255,255,255,255,255,255,255,255,255};
  109173. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109174. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109175. 0x01,0x02,0x03,0x04,2,0,0,0,
  109176. 0xc8,0xc3,0xcb,0xed,
  109177. 5,
  109178. 10,255,4,255,0};
  109179. /* page with the 255 segment limit */
  109180. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109181. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109182. 0x01,0x02,0x03,0x04,0,0,0,0,
  109183. 0xff,0x7b,0x23,0x17,
  109184. 1,
  109185. 0};
  109186. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109187. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109188. 0x01,0x02,0x03,0x04,1,0,0,0,
  109189. 0xed,0x2a,0x2e,0xa7,
  109190. 255,
  109191. 10,10,10,10,10,10,10,10,
  109192. 10,10,10,10,10,10,10,10,
  109193. 10,10,10,10,10,10,10,10,
  109194. 10,10,10,10,10,10,10,10,
  109195. 10,10,10,10,10,10,10,10,
  109196. 10,10,10,10,10,10,10,10,
  109197. 10,10,10,10,10,10,10,10,
  109198. 10,10,10,10,10,10,10,10,
  109199. 10,10,10,10,10,10,10,10,
  109200. 10,10,10,10,10,10,10,10,
  109201. 10,10,10,10,10,10,10,10,
  109202. 10,10,10,10,10,10,10,10,
  109203. 10,10,10,10,10,10,10,10,
  109204. 10,10,10,10,10,10,10,10,
  109205. 10,10,10,10,10,10,10,10,
  109206. 10,10,10,10,10,10,10,10,
  109207. 10,10,10,10,10,10,10,10,
  109208. 10,10,10,10,10,10,10,10,
  109209. 10,10,10,10,10,10,10,10,
  109210. 10,10,10,10,10,10,10,10,
  109211. 10,10,10,10,10,10,10,10,
  109212. 10,10,10,10,10,10,10,10,
  109213. 10,10,10,10,10,10,10,10,
  109214. 10,10,10,10,10,10,10,10,
  109215. 10,10,10,10,10,10,10,10,
  109216. 10,10,10,10,10,10,10,10,
  109217. 10,10,10,10,10,10,10,10,
  109218. 10,10,10,10,10,10,10,10,
  109219. 10,10,10,10,10,10,10,10,
  109220. 10,10,10,10,10,10,10,10,
  109221. 10,10,10,10,10,10,10,10,
  109222. 10,10,10,10,10,10,10};
  109223. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109224. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109225. 0x01,0x02,0x03,0x04,2,0,0,0,
  109226. 0x6c,0x3b,0x82,0x3d,
  109227. 1,
  109228. 50};
  109229. /* packet that overspans over an entire page */
  109230. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109231. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109232. 0x01,0x02,0x03,0x04,0,0,0,0,
  109233. 0xff,0x7b,0x23,0x17,
  109234. 1,
  109235. 0};
  109236. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109237. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109238. 0x01,0x02,0x03,0x04,1,0,0,0,
  109239. 0x3c,0xd9,0x4d,0x3f,
  109240. 17,
  109241. 100,255,255,255,255,255,255,255,255,
  109242. 255,255,255,255,255,255,255,255};
  109243. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109244. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109245. 0x01,0x02,0x03,0x04,2,0,0,0,
  109246. 0x01,0xd2,0xe5,0xe5,
  109247. 17,
  109248. 255,255,255,255,255,255,255,255,
  109249. 255,255,255,255,255,255,255,255,255};
  109250. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109251. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109252. 0x01,0x02,0x03,0x04,3,0,0,0,
  109253. 0xef,0xdd,0x88,0xde,
  109254. 7,
  109255. 255,255,75,255,4,255,0};
  109256. /* packet that overspans over an entire page */
  109257. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109258. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109259. 0x01,0x02,0x03,0x04,0,0,0,0,
  109260. 0xff,0x7b,0x23,0x17,
  109261. 1,
  109262. 0};
  109263. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109264. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109265. 0x01,0x02,0x03,0x04,1,0,0,0,
  109266. 0x3c,0xd9,0x4d,0x3f,
  109267. 17,
  109268. 100,255,255,255,255,255,255,255,255,
  109269. 255,255,255,255,255,255,255,255};
  109270. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109271. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109272. 0x01,0x02,0x03,0x04,2,0,0,0,
  109273. 0xd4,0xe0,0x60,0xe5,
  109274. 1,0};
  109275. void test_pack(const int *pl, const int **headers, int byteskip,
  109276. int pageskip, int packetskip){
  109277. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109278. long inptr=0;
  109279. long outptr=0;
  109280. long deptr=0;
  109281. long depacket=0;
  109282. long granule_pos=7,pageno=0;
  109283. int i,j,packets,pageout=pageskip;
  109284. int eosflag=0;
  109285. int bosflag=0;
  109286. int byteskipcount=0;
  109287. ogg_stream_reset(&os_en);
  109288. ogg_stream_reset(&os_de);
  109289. ogg_sync_reset(&oy);
  109290. for(packets=0;packets<packetskip;packets++)
  109291. depacket+=pl[packets];
  109292. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109293. for(i=0;i<packets;i++){
  109294. /* construct a test packet */
  109295. ogg_packet op;
  109296. int len=pl[i];
  109297. op.packet=data+inptr;
  109298. op.bytes=len;
  109299. op.e_o_s=(pl[i+1]<0?1:0);
  109300. op.granulepos=granule_pos;
  109301. granule_pos+=1024;
  109302. for(j=0;j<len;j++)data[inptr++]=i+j;
  109303. /* submit the test packet */
  109304. ogg_stream_packetin(&os_en,&op);
  109305. /* retrieve any finished pages */
  109306. {
  109307. ogg_page og;
  109308. while(ogg_stream_pageout(&os_en,&og)){
  109309. /* We have a page. Check it carefully */
  109310. fprintf(stderr,"%ld, ",pageno);
  109311. if(headers[pageno]==NULL){
  109312. fprintf(stderr,"coded too many pages!\n");
  109313. exit(1);
  109314. }
  109315. check_page(data+outptr,headers[pageno],&og);
  109316. outptr+=og.body_len;
  109317. pageno++;
  109318. if(pageskip){
  109319. bosflag=1;
  109320. pageskip--;
  109321. deptr+=og.body_len;
  109322. }
  109323. /* have a complete page; submit it to sync/decode */
  109324. {
  109325. ogg_page og_de;
  109326. ogg_packet op_de,op_de2;
  109327. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109328. char *next=buf;
  109329. byteskipcount+=og.header_len;
  109330. if(byteskipcount>byteskip){
  109331. memcpy(next,og.header,byteskipcount-byteskip);
  109332. next+=byteskipcount-byteskip;
  109333. byteskipcount=byteskip;
  109334. }
  109335. byteskipcount+=og.body_len;
  109336. if(byteskipcount>byteskip){
  109337. memcpy(next,og.body,byteskipcount-byteskip);
  109338. next+=byteskipcount-byteskip;
  109339. byteskipcount=byteskip;
  109340. }
  109341. ogg_sync_wrote(&oy,next-buf);
  109342. while(1){
  109343. int ret=ogg_sync_pageout(&oy,&og_de);
  109344. if(ret==0)break;
  109345. if(ret<0)continue;
  109346. /* got a page. Happy happy. Verify that it's good. */
  109347. fprintf(stderr,"(%ld), ",pageout);
  109348. check_page(data+deptr,headers[pageout],&og_de);
  109349. deptr+=og_de.body_len;
  109350. pageout++;
  109351. /* submit it to deconstitution */
  109352. ogg_stream_pagein(&os_de,&og_de);
  109353. /* packets out? */
  109354. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109355. ogg_stream_packetpeek(&os_de,NULL);
  109356. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109357. /* verify peek and out match */
  109358. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109359. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109360. depacket);
  109361. exit(1);
  109362. }
  109363. /* verify the packet! */
  109364. /* check data */
  109365. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109366. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109367. depacket);
  109368. exit(1);
  109369. }
  109370. /* check bos flag */
  109371. if(bosflag==0 && op_de.b_o_s==0){
  109372. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109373. exit(1);
  109374. }
  109375. if(bosflag && op_de.b_o_s){
  109376. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109377. exit(1);
  109378. }
  109379. bosflag=1;
  109380. depacket+=op_de.bytes;
  109381. /* check eos flag */
  109382. if(eosflag){
  109383. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109384. exit(1);
  109385. }
  109386. if(op_de.e_o_s)eosflag=1;
  109387. /* check granulepos flag */
  109388. if(op_de.granulepos!=-1){
  109389. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109390. }
  109391. }
  109392. }
  109393. }
  109394. }
  109395. }
  109396. }
  109397. _ogg_free(data);
  109398. if(headers[pageno]!=NULL){
  109399. fprintf(stderr,"did not write last page!\n");
  109400. exit(1);
  109401. }
  109402. if(headers[pageout]!=NULL){
  109403. fprintf(stderr,"did not decode last page!\n");
  109404. exit(1);
  109405. }
  109406. if(inptr!=outptr){
  109407. fprintf(stderr,"encoded page data incomplete!\n");
  109408. exit(1);
  109409. }
  109410. if(inptr!=deptr){
  109411. fprintf(stderr,"decoded page data incomplete!\n");
  109412. exit(1);
  109413. }
  109414. if(inptr!=depacket){
  109415. fprintf(stderr,"decoded packet data incomplete!\n");
  109416. exit(1);
  109417. }
  109418. if(!eosflag){
  109419. fprintf(stderr,"Never got a packet with EOS set!\n");
  109420. exit(1);
  109421. }
  109422. fprintf(stderr,"ok.\n");
  109423. }
  109424. int main(void){
  109425. ogg_stream_init(&os_en,0x04030201);
  109426. ogg_stream_init(&os_de,0x04030201);
  109427. ogg_sync_init(&oy);
  109428. /* Exercise each code path in the framing code. Also verify that
  109429. the checksums are working. */
  109430. {
  109431. /* 17 only */
  109432. const int packets[]={17, -1};
  109433. const int *headret[]={head1_0,NULL};
  109434. fprintf(stderr,"testing single page encoding... ");
  109435. test_pack(packets,headret,0,0,0);
  109436. }
  109437. {
  109438. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109439. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109440. const int *headret[]={head1_1,head2_1,NULL};
  109441. fprintf(stderr,"testing basic page encoding... ");
  109442. test_pack(packets,headret,0,0,0);
  109443. }
  109444. {
  109445. /* nil packets; beginning,middle,end */
  109446. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109447. const int *headret[]={head1_2,head2_2,NULL};
  109448. fprintf(stderr,"testing basic nil packets... ");
  109449. test_pack(packets,headret,0,0,0);
  109450. }
  109451. {
  109452. /* large initial packet */
  109453. const int packets[]={4345,259,255,-1};
  109454. const int *headret[]={head1_3,head2_3,NULL};
  109455. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109456. test_pack(packets,headret,0,0,0);
  109457. }
  109458. {
  109459. /* continuing packet test */
  109460. const int packets[]={0,4345,259,255,-1};
  109461. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109462. fprintf(stderr,"testing single packet page span... ");
  109463. test_pack(packets,headret,0,0,0);
  109464. }
  109465. /* page with the 255 segment limit */
  109466. {
  109467. const int packets[]={0,10,10,10,10,10,10,10,10,
  109468. 10,10,10,10,10,10,10,10,
  109469. 10,10,10,10,10,10,10,10,
  109470. 10,10,10,10,10,10,10,10,
  109471. 10,10,10,10,10,10,10,10,
  109472. 10,10,10,10,10,10,10,10,
  109473. 10,10,10,10,10,10,10,10,
  109474. 10,10,10,10,10,10,10,10,
  109475. 10,10,10,10,10,10,10,10,
  109476. 10,10,10,10,10,10,10,10,
  109477. 10,10,10,10,10,10,10,10,
  109478. 10,10,10,10,10,10,10,10,
  109479. 10,10,10,10,10,10,10,10,
  109480. 10,10,10,10,10,10,10,10,
  109481. 10,10,10,10,10,10,10,10,
  109482. 10,10,10,10,10,10,10,10,
  109483. 10,10,10,10,10,10,10,10,
  109484. 10,10,10,10,10,10,10,10,
  109485. 10,10,10,10,10,10,10,10,
  109486. 10,10,10,10,10,10,10,10,
  109487. 10,10,10,10,10,10,10,10,
  109488. 10,10,10,10,10,10,10,10,
  109489. 10,10,10,10,10,10,10,10,
  109490. 10,10,10,10,10,10,10,10,
  109491. 10,10,10,10,10,10,10,10,
  109492. 10,10,10,10,10,10,10,10,
  109493. 10,10,10,10,10,10,10,10,
  109494. 10,10,10,10,10,10,10,10,
  109495. 10,10,10,10,10,10,10,10,
  109496. 10,10,10,10,10,10,10,10,
  109497. 10,10,10,10,10,10,10,10,
  109498. 10,10,10,10,10,10,10,50,-1};
  109499. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109500. fprintf(stderr,"testing max packet segments... ");
  109501. test_pack(packets,headret,0,0,0);
  109502. }
  109503. {
  109504. /* packet that overspans over an entire page */
  109505. const int packets[]={0,100,9000,259,255,-1};
  109506. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109507. fprintf(stderr,"testing very large packets... ");
  109508. test_pack(packets,headret,0,0,0);
  109509. }
  109510. {
  109511. /* test for the libogg 1.1.1 resync in large continuation bug
  109512. found by Josh Coalson) */
  109513. const int packets[]={0,100,9000,259,255,-1};
  109514. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109515. fprintf(stderr,"testing continuation resync in very large packets... ");
  109516. test_pack(packets,headret,100,2,3);
  109517. }
  109518. {
  109519. /* term only page. why not? */
  109520. const int packets[]={0,100,4080,-1};
  109521. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109522. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109523. test_pack(packets,headret,0,0,0);
  109524. }
  109525. {
  109526. /* build a bunch of pages for testing */
  109527. unsigned char *data=_ogg_malloc(1024*1024);
  109528. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109529. int inptr=0,i,j;
  109530. ogg_page og[5];
  109531. ogg_stream_reset(&os_en);
  109532. for(i=0;pl[i]!=-1;i++){
  109533. ogg_packet op;
  109534. int len=pl[i];
  109535. op.packet=data+inptr;
  109536. op.bytes=len;
  109537. op.e_o_s=(pl[i+1]<0?1:0);
  109538. op.granulepos=(i+1)*1000;
  109539. for(j=0;j<len;j++)data[inptr++]=i+j;
  109540. ogg_stream_packetin(&os_en,&op);
  109541. }
  109542. _ogg_free(data);
  109543. /* retrieve finished pages */
  109544. for(i=0;i<5;i++){
  109545. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109546. fprintf(stderr,"Too few pages output building sync tests!\n");
  109547. exit(1);
  109548. }
  109549. copy_page(&og[i]);
  109550. }
  109551. /* Test lost pages on pagein/packetout: no rollback */
  109552. {
  109553. ogg_page temp;
  109554. ogg_packet test;
  109555. fprintf(stderr,"Testing loss of pages... ");
  109556. ogg_sync_reset(&oy);
  109557. ogg_stream_reset(&os_de);
  109558. for(i=0;i<5;i++){
  109559. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109560. og[i].header_len);
  109561. ogg_sync_wrote(&oy,og[i].header_len);
  109562. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109563. ogg_sync_wrote(&oy,og[i].body_len);
  109564. }
  109565. ogg_sync_pageout(&oy,&temp);
  109566. ogg_stream_pagein(&os_de,&temp);
  109567. ogg_sync_pageout(&oy,&temp);
  109568. ogg_stream_pagein(&os_de,&temp);
  109569. ogg_sync_pageout(&oy,&temp);
  109570. /* skip */
  109571. ogg_sync_pageout(&oy,&temp);
  109572. ogg_stream_pagein(&os_de,&temp);
  109573. /* do we get the expected results/packets? */
  109574. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109575. checkpacket(&test,0,0,0);
  109576. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109577. checkpacket(&test,100,1,-1);
  109578. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109579. checkpacket(&test,4079,2,3000);
  109580. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109581. fprintf(stderr,"Error: loss of page did not return error\n");
  109582. exit(1);
  109583. }
  109584. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109585. checkpacket(&test,76,5,-1);
  109586. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109587. checkpacket(&test,34,6,-1);
  109588. fprintf(stderr,"ok.\n");
  109589. }
  109590. /* Test lost pages on pagein/packetout: rollback with continuation */
  109591. {
  109592. ogg_page temp;
  109593. ogg_packet test;
  109594. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109595. ogg_sync_reset(&oy);
  109596. ogg_stream_reset(&os_de);
  109597. for(i=0;i<5;i++){
  109598. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109599. og[i].header_len);
  109600. ogg_sync_wrote(&oy,og[i].header_len);
  109601. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109602. ogg_sync_wrote(&oy,og[i].body_len);
  109603. }
  109604. ogg_sync_pageout(&oy,&temp);
  109605. ogg_stream_pagein(&os_de,&temp);
  109606. ogg_sync_pageout(&oy,&temp);
  109607. ogg_stream_pagein(&os_de,&temp);
  109608. ogg_sync_pageout(&oy,&temp);
  109609. ogg_stream_pagein(&os_de,&temp);
  109610. ogg_sync_pageout(&oy,&temp);
  109611. /* skip */
  109612. ogg_sync_pageout(&oy,&temp);
  109613. ogg_stream_pagein(&os_de,&temp);
  109614. /* do we get the expected results/packets? */
  109615. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109616. checkpacket(&test,0,0,0);
  109617. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109618. checkpacket(&test,100,1,-1);
  109619. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109620. checkpacket(&test,4079,2,3000);
  109621. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109622. checkpacket(&test,2956,3,4000);
  109623. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109624. fprintf(stderr,"Error: loss of page did not return error\n");
  109625. exit(1);
  109626. }
  109627. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109628. checkpacket(&test,300,13,14000);
  109629. fprintf(stderr,"ok.\n");
  109630. }
  109631. /* the rest only test sync */
  109632. {
  109633. ogg_page og_de;
  109634. /* Test fractional page inputs: incomplete capture */
  109635. fprintf(stderr,"Testing sync on partial inputs... ");
  109636. ogg_sync_reset(&oy);
  109637. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109638. 3);
  109639. ogg_sync_wrote(&oy,3);
  109640. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109641. /* Test fractional page inputs: incomplete fixed header */
  109642. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109643. 20);
  109644. ogg_sync_wrote(&oy,20);
  109645. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109646. /* Test fractional page inputs: incomplete header */
  109647. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109648. 5);
  109649. ogg_sync_wrote(&oy,5);
  109650. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109651. /* Test fractional page inputs: incomplete body */
  109652. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109653. og[1].header_len-28);
  109654. ogg_sync_wrote(&oy,og[1].header_len-28);
  109655. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109656. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109657. ogg_sync_wrote(&oy,1000);
  109658. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109659. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109660. og[1].body_len-1000);
  109661. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109662. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109663. fprintf(stderr,"ok.\n");
  109664. }
  109665. /* Test fractional page inputs: page + incomplete capture */
  109666. {
  109667. ogg_page og_de;
  109668. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109669. ogg_sync_reset(&oy);
  109670. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109671. og[1].header_len);
  109672. ogg_sync_wrote(&oy,og[1].header_len);
  109673. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109674. og[1].body_len);
  109675. ogg_sync_wrote(&oy,og[1].body_len);
  109676. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109677. 20);
  109678. ogg_sync_wrote(&oy,20);
  109679. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109680. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109681. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109682. og[1].header_len-20);
  109683. ogg_sync_wrote(&oy,og[1].header_len-20);
  109684. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109685. og[1].body_len);
  109686. ogg_sync_wrote(&oy,og[1].body_len);
  109687. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109688. fprintf(stderr,"ok.\n");
  109689. }
  109690. /* Test recapture: garbage + page */
  109691. {
  109692. ogg_page og_de;
  109693. fprintf(stderr,"Testing search for capture... ");
  109694. ogg_sync_reset(&oy);
  109695. /* 'garbage' */
  109696. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109697. og[1].body_len);
  109698. ogg_sync_wrote(&oy,og[1].body_len);
  109699. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109700. og[1].header_len);
  109701. ogg_sync_wrote(&oy,og[1].header_len);
  109702. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109703. og[1].body_len);
  109704. ogg_sync_wrote(&oy,og[1].body_len);
  109705. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109706. 20);
  109707. ogg_sync_wrote(&oy,20);
  109708. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109709. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109710. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109711. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109712. og[2].header_len-20);
  109713. ogg_sync_wrote(&oy,og[2].header_len-20);
  109714. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109715. og[2].body_len);
  109716. ogg_sync_wrote(&oy,og[2].body_len);
  109717. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109718. fprintf(stderr,"ok.\n");
  109719. }
  109720. /* Test recapture: page + garbage + page */
  109721. {
  109722. ogg_page og_de;
  109723. fprintf(stderr,"Testing recapture... ");
  109724. ogg_sync_reset(&oy);
  109725. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109726. og[1].header_len);
  109727. ogg_sync_wrote(&oy,og[1].header_len);
  109728. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109729. og[1].body_len);
  109730. ogg_sync_wrote(&oy,og[1].body_len);
  109731. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109732. og[2].header_len);
  109733. ogg_sync_wrote(&oy,og[2].header_len);
  109734. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109735. og[2].header_len);
  109736. ogg_sync_wrote(&oy,og[2].header_len);
  109737. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109738. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109739. og[2].body_len-5);
  109740. ogg_sync_wrote(&oy,og[2].body_len-5);
  109741. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109742. og[3].header_len);
  109743. ogg_sync_wrote(&oy,og[3].header_len);
  109744. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109745. og[3].body_len);
  109746. ogg_sync_wrote(&oy,og[3].body_len);
  109747. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109748. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109749. fprintf(stderr,"ok.\n");
  109750. }
  109751. /* Free page data that was previously copied */
  109752. {
  109753. for(i=0;i<5;i++){
  109754. free_page(&og[i]);
  109755. }
  109756. }
  109757. }
  109758. return(0);
  109759. }
  109760. #endif
  109761. #endif
  109762. /*** End of inlined file: framing.c ***/
  109763. /*** Start of inlined file: analysis.c ***/
  109764. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109765. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109766. // tasks..
  109767. #if JUCE_MSVC
  109768. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109769. #endif
  109770. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109771. #if JUCE_USE_OGGVORBIS
  109772. #include <stdio.h>
  109773. #include <string.h>
  109774. #include <math.h>
  109775. /*** Start of inlined file: codec_internal.h ***/
  109776. #ifndef _V_CODECI_H_
  109777. #define _V_CODECI_H_
  109778. /*** Start of inlined file: envelope.h ***/
  109779. #ifndef _V_ENVELOPE_
  109780. #define _V_ENVELOPE_
  109781. /*** Start of inlined file: mdct.h ***/
  109782. #ifndef _OGG_mdct_H_
  109783. #define _OGG_mdct_H_
  109784. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109785. #ifdef MDCT_INTEGERIZED
  109786. #define DATA_TYPE int
  109787. #define REG_TYPE register int
  109788. #define TRIGBITS 14
  109789. #define cPI3_8 6270
  109790. #define cPI2_8 11585
  109791. #define cPI1_8 15137
  109792. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109793. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109794. #define HALVE(x) ((x)>>1)
  109795. #else
  109796. #define DATA_TYPE float
  109797. #define REG_TYPE float
  109798. #define cPI3_8 .38268343236508977175F
  109799. #define cPI2_8 .70710678118654752441F
  109800. #define cPI1_8 .92387953251128675613F
  109801. #define FLOAT_CONV(x) (x)
  109802. #define MULT_NORM(x) (x)
  109803. #define HALVE(x) ((x)*.5f)
  109804. #endif
  109805. typedef struct {
  109806. int n;
  109807. int log2n;
  109808. DATA_TYPE *trig;
  109809. int *bitrev;
  109810. DATA_TYPE scale;
  109811. } mdct_lookup;
  109812. extern void mdct_init(mdct_lookup *lookup,int n);
  109813. extern void mdct_clear(mdct_lookup *l);
  109814. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109815. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109816. #endif
  109817. /*** End of inlined file: mdct.h ***/
  109818. #define VE_PRE 16
  109819. #define VE_WIN 4
  109820. #define VE_POST 2
  109821. #define VE_AMP (VE_PRE+VE_POST-1)
  109822. #define VE_BANDS 7
  109823. #define VE_NEARDC 15
  109824. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109825. #define VE_MAXSTRETCH 12 /* one-third full block */
  109826. typedef struct {
  109827. float ampbuf[VE_AMP];
  109828. int ampptr;
  109829. float nearDC[VE_NEARDC];
  109830. float nearDC_acc;
  109831. float nearDC_partialacc;
  109832. int nearptr;
  109833. } envelope_filter_state;
  109834. typedef struct {
  109835. int begin;
  109836. int end;
  109837. float *window;
  109838. float total;
  109839. } envelope_band;
  109840. typedef struct {
  109841. int ch;
  109842. int winlength;
  109843. int searchstep;
  109844. float minenergy;
  109845. mdct_lookup mdct;
  109846. float *mdct_win;
  109847. envelope_band band[VE_BANDS];
  109848. envelope_filter_state *filter;
  109849. int stretch;
  109850. int *mark;
  109851. long storage;
  109852. long current;
  109853. long curmark;
  109854. long cursor;
  109855. } envelope_lookup;
  109856. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109857. extern void _ve_envelope_clear(envelope_lookup *e);
  109858. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109859. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109860. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109861. #endif
  109862. /*** End of inlined file: envelope.h ***/
  109863. /*** Start of inlined file: codebook.h ***/
  109864. #ifndef _V_CODEBOOK_H_
  109865. #define _V_CODEBOOK_H_
  109866. /* This structure encapsulates huffman and VQ style encoding books; it
  109867. doesn't do anything specific to either.
  109868. valuelist/quantlist are nonNULL (and q_* significant) only if
  109869. there's entry->value mapping to be done.
  109870. If encode-side mapping must be done (and thus the entry needs to be
  109871. hunted), the auxiliary encode pointer will point to a decision
  109872. tree. This is true of both VQ and huffman, but is mostly useful
  109873. with VQ.
  109874. */
  109875. typedef struct static_codebook{
  109876. long dim; /* codebook dimensions (elements per vector) */
  109877. long entries; /* codebook entries */
  109878. long *lengthlist; /* codeword lengths in bits */
  109879. /* mapping ***************************************************************/
  109880. int maptype; /* 0=none
  109881. 1=implicitly populated values from map column
  109882. 2=listed arbitrary values */
  109883. /* The below does a linear, single monotonic sequence mapping. */
  109884. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109885. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109886. int q_quant; /* bits: 0 < quant <= 16 */
  109887. int q_sequencep; /* bitflag */
  109888. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109889. map == 2: list of dim*entries quantized entry vals
  109890. */
  109891. /* encode helpers ********************************************************/
  109892. struct encode_aux_nearestmatch *nearest_tree;
  109893. struct encode_aux_threshmatch *thresh_tree;
  109894. struct encode_aux_pigeonhole *pigeon_tree;
  109895. int allocedp;
  109896. } static_codebook;
  109897. /* this structures an arbitrary trained book to quickly find the
  109898. nearest cell match */
  109899. typedef struct encode_aux_nearestmatch{
  109900. /* pre-calculated partitioning tree */
  109901. long *ptr0;
  109902. long *ptr1;
  109903. long *p; /* decision points (each is an entry) */
  109904. long *q; /* decision points (each is an entry) */
  109905. long aux; /* number of tree entries */
  109906. long alloc;
  109907. } encode_aux_nearestmatch;
  109908. /* assumes a maptype of 1; encode side only, so that's OK */
  109909. typedef struct encode_aux_threshmatch{
  109910. float *quantthresh;
  109911. long *quantmap;
  109912. int quantvals;
  109913. int threshvals;
  109914. } encode_aux_threshmatch;
  109915. typedef struct encode_aux_pigeonhole{
  109916. float min;
  109917. float del;
  109918. int mapentries;
  109919. int quantvals;
  109920. long *pigeonmap;
  109921. long fittotal;
  109922. long *fitlist;
  109923. long *fitmap;
  109924. long *fitlength;
  109925. } encode_aux_pigeonhole;
  109926. typedef struct codebook{
  109927. long dim; /* codebook dimensions (elements per vector) */
  109928. long entries; /* codebook entries */
  109929. long used_entries; /* populated codebook entries */
  109930. const static_codebook *c;
  109931. /* for encode, the below are entry-ordered, fully populated */
  109932. /* for decode, the below are ordered by bitreversed codeword and only
  109933. used entries are populated */
  109934. float *valuelist; /* list of dim*entries actual entry values */
  109935. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109936. int *dec_index; /* only used if sparseness collapsed */
  109937. char *dec_codelengths;
  109938. ogg_uint32_t *dec_firsttable;
  109939. int dec_firsttablen;
  109940. int dec_maxlength;
  109941. } codebook;
  109942. extern void vorbis_staticbook_clear(static_codebook *b);
  109943. extern void vorbis_staticbook_destroy(static_codebook *b);
  109944. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109945. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109946. extern void vorbis_book_clear(codebook *b);
  109947. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109948. extern float *_book_logdist(const static_codebook *b,float *vals);
  109949. extern float _float32_unpack(long val);
  109950. extern long _float32_pack(float val);
  109951. extern int _best(codebook *book, float *a, int step);
  109952. extern int _ilog(unsigned int v);
  109953. extern long _book_maptype1_quantvals(const static_codebook *b);
  109954. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109955. extern long vorbis_book_codeword(codebook *book,int entry);
  109956. extern long vorbis_book_codelen(codebook *book,int entry);
  109957. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109958. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109959. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109960. extern int vorbis_book_errorv(codebook *book, float *a);
  109961. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109962. oggpack_buffer *b);
  109963. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109964. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109965. oggpack_buffer *b,int n);
  109966. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109967. oggpack_buffer *b,int n);
  109968. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109969. oggpack_buffer *b,int n);
  109970. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109971. long off,int ch,
  109972. oggpack_buffer *b,int n);
  109973. #endif
  109974. /*** End of inlined file: codebook.h ***/
  109975. #define BLOCKTYPE_IMPULSE 0
  109976. #define BLOCKTYPE_PADDING 1
  109977. #define BLOCKTYPE_TRANSITION 0
  109978. #define BLOCKTYPE_LONG 1
  109979. #define PACKETBLOBS 15
  109980. typedef struct vorbis_block_internal{
  109981. float **pcmdelay; /* this is a pointer into local storage */
  109982. float ampmax;
  109983. int blocktype;
  109984. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109985. blob [PACKETBLOBS/2] points to
  109986. the oggpack_buffer in the
  109987. main vorbis_block */
  109988. } vorbis_block_internal;
  109989. typedef void vorbis_look_floor;
  109990. typedef void vorbis_look_residue;
  109991. typedef void vorbis_look_transform;
  109992. /* mode ************************************************************/
  109993. typedef struct {
  109994. int blockflag;
  109995. int windowtype;
  109996. int transformtype;
  109997. int mapping;
  109998. } vorbis_info_mode;
  109999. typedef void vorbis_info_floor;
  110000. typedef void vorbis_info_residue;
  110001. typedef void vorbis_info_mapping;
  110002. /*** Start of inlined file: psy.h ***/
  110003. #ifndef _V_PSY_H_
  110004. #define _V_PSY_H_
  110005. /*** Start of inlined file: smallft.h ***/
  110006. #ifndef _V_SMFT_H_
  110007. #define _V_SMFT_H_
  110008. typedef struct {
  110009. int n;
  110010. float *trigcache;
  110011. int *splitcache;
  110012. } drft_lookup;
  110013. extern void drft_forward(drft_lookup *l,float *data);
  110014. extern void drft_backward(drft_lookup *l,float *data);
  110015. extern void drft_init(drft_lookup *l,int n);
  110016. extern void drft_clear(drft_lookup *l);
  110017. #endif
  110018. /*** End of inlined file: smallft.h ***/
  110019. /*** Start of inlined file: backends.h ***/
  110020. /* this is exposed up here because we need it for static modes.
  110021. Lookups for each backend aren't exposed because there's no reason
  110022. to do so */
  110023. #ifndef _vorbis_backend_h_
  110024. #define _vorbis_backend_h_
  110025. /* this would all be simpler/shorter with templates, but.... */
  110026. /* Floor backend generic *****************************************/
  110027. typedef struct{
  110028. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110029. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110030. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110031. void (*free_info) (vorbis_info_floor *);
  110032. void (*free_look) (vorbis_look_floor *);
  110033. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110034. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110035. void *buffer,float *);
  110036. } vorbis_func_floor;
  110037. typedef struct{
  110038. int order;
  110039. long rate;
  110040. long barkmap;
  110041. int ampbits;
  110042. int ampdB;
  110043. int numbooks; /* <= 16 */
  110044. int books[16];
  110045. float lessthan; /* encode-only config setting hacks for libvorbis */
  110046. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110047. } vorbis_info_floor0;
  110048. #define VIF_POSIT 63
  110049. #define VIF_CLASS 16
  110050. #define VIF_PARTS 31
  110051. typedef struct{
  110052. int partitions; /* 0 to 31 */
  110053. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110054. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110055. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110056. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110057. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110058. int mult; /* 1 2 3 or 4 */
  110059. int postlist[VIF_POSIT+2]; /* first two implicit */
  110060. /* encode side analysis parameters */
  110061. float maxover;
  110062. float maxunder;
  110063. float maxerr;
  110064. float twofitweight;
  110065. float twofitatten;
  110066. int n;
  110067. } vorbis_info_floor1;
  110068. /* Residue backend generic *****************************************/
  110069. typedef struct{
  110070. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110071. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110072. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110073. vorbis_info_residue *);
  110074. void (*free_info) (vorbis_info_residue *);
  110075. void (*free_look) (vorbis_look_residue *);
  110076. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110077. float **,int *,int);
  110078. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110079. vorbis_look_residue *,
  110080. float **,float **,int *,int,long **);
  110081. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110082. float **,int *,int);
  110083. } vorbis_func_residue;
  110084. typedef struct vorbis_info_residue0{
  110085. /* block-partitioned VQ coded straight residue */
  110086. long begin;
  110087. long end;
  110088. /* first stage (lossless partitioning) */
  110089. int grouping; /* group n vectors per partition */
  110090. int partitions; /* possible codebooks for a partition */
  110091. int groupbook; /* huffbook for partitioning */
  110092. int secondstages[64]; /* expanded out to pointers in lookup */
  110093. int booklist[256]; /* list of second stage books */
  110094. float classmetric1[64];
  110095. float classmetric2[64];
  110096. } vorbis_info_residue0;
  110097. /* Mapping backend generic *****************************************/
  110098. typedef struct{
  110099. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110100. oggpack_buffer *);
  110101. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110102. void (*free_info) (vorbis_info_mapping *);
  110103. int (*forward) (struct vorbis_block *vb);
  110104. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110105. } vorbis_func_mapping;
  110106. typedef struct vorbis_info_mapping0{
  110107. int submaps; /* <= 16 */
  110108. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110109. int floorsubmap[16]; /* [mux] submap to floors */
  110110. int residuesubmap[16]; /* [mux] submap to residue */
  110111. int coupling_steps;
  110112. int coupling_mag[256];
  110113. int coupling_ang[256];
  110114. } vorbis_info_mapping0;
  110115. #endif
  110116. /*** End of inlined file: backends.h ***/
  110117. #ifndef EHMER_MAX
  110118. #define EHMER_MAX 56
  110119. #endif
  110120. /* psychoacoustic setup ********************************************/
  110121. #define P_BANDS 17 /* 62Hz to 16kHz */
  110122. #define P_LEVELS 8 /* 30dB to 100dB */
  110123. #define P_LEVEL_0 30. /* 30 dB */
  110124. #define P_NOISECURVES 3
  110125. #define NOISE_COMPAND_LEVELS 40
  110126. typedef struct vorbis_info_psy{
  110127. int blockflag;
  110128. float ath_adjatt;
  110129. float ath_maxatt;
  110130. float tone_masteratt[P_NOISECURVES];
  110131. float tone_centerboost;
  110132. float tone_decay;
  110133. float tone_abs_limit;
  110134. float toneatt[P_BANDS];
  110135. int noisemaskp;
  110136. float noisemaxsupp;
  110137. float noisewindowlo;
  110138. float noisewindowhi;
  110139. int noisewindowlomin;
  110140. int noisewindowhimin;
  110141. int noisewindowfixed;
  110142. float noiseoff[P_NOISECURVES][P_BANDS];
  110143. float noisecompand[NOISE_COMPAND_LEVELS];
  110144. float max_curve_dB;
  110145. int normal_channel_p;
  110146. int normal_point_p;
  110147. int normal_start;
  110148. int normal_partition;
  110149. double normal_thresh;
  110150. } vorbis_info_psy;
  110151. typedef struct{
  110152. int eighth_octave_lines;
  110153. /* for block long/short tuning; encode only */
  110154. float preecho_thresh[VE_BANDS];
  110155. float postecho_thresh[VE_BANDS];
  110156. float stretch_penalty;
  110157. float preecho_minenergy;
  110158. float ampmax_att_per_sec;
  110159. /* channel coupling config */
  110160. int coupling_pkHz[PACKETBLOBS];
  110161. int coupling_pointlimit[2][PACKETBLOBS];
  110162. int coupling_prepointamp[PACKETBLOBS];
  110163. int coupling_postpointamp[PACKETBLOBS];
  110164. int sliding_lowpass[2][PACKETBLOBS];
  110165. } vorbis_info_psy_global;
  110166. typedef struct {
  110167. float ampmax;
  110168. int channels;
  110169. vorbis_info_psy_global *gi;
  110170. int coupling_pointlimit[2][P_NOISECURVES];
  110171. } vorbis_look_psy_global;
  110172. typedef struct {
  110173. int n;
  110174. struct vorbis_info_psy *vi;
  110175. float ***tonecurves;
  110176. float **noiseoffset;
  110177. float *ath;
  110178. long *octave; /* in n.ocshift format */
  110179. long *bark;
  110180. long firstoc;
  110181. long shiftoc;
  110182. int eighth_octave_lines; /* power of two, please */
  110183. int total_octave_lines;
  110184. long rate; /* cache it */
  110185. float m_val; /* Masking compensation value */
  110186. } vorbis_look_psy;
  110187. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110188. vorbis_info_psy_global *gi,int n,long rate);
  110189. extern void _vp_psy_clear(vorbis_look_psy *p);
  110190. extern void *_vi_psy_dup(void *source);
  110191. extern void _vi_psy_free(vorbis_info_psy *i);
  110192. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110193. extern void _vp_remove_floor(vorbis_look_psy *p,
  110194. float *mdct,
  110195. int *icodedflr,
  110196. float *residue,
  110197. int sliding_lowpass);
  110198. extern void _vp_noisemask(vorbis_look_psy *p,
  110199. float *logmdct,
  110200. float *logmask);
  110201. extern void _vp_tonemask(vorbis_look_psy *p,
  110202. float *logfft,
  110203. float *logmask,
  110204. float global_specmax,
  110205. float local_specmax);
  110206. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110207. float *noise,
  110208. float *tone,
  110209. int offset_select,
  110210. float *logmask,
  110211. float *mdct,
  110212. float *logmdct);
  110213. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110214. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110215. vorbis_info_psy_global *g,
  110216. vorbis_look_psy *p,
  110217. vorbis_info_mapping0 *vi,
  110218. float **mdct);
  110219. extern void _vp_couple(int blobno,
  110220. vorbis_info_psy_global *g,
  110221. vorbis_look_psy *p,
  110222. vorbis_info_mapping0 *vi,
  110223. float **res,
  110224. float **mag_memo,
  110225. int **mag_sort,
  110226. int **ifloor,
  110227. int *nonzero,
  110228. int sliding_lowpass);
  110229. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110230. float *in,float *out,int *sortedindex);
  110231. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110232. float *magnitudes,int *sortedindex);
  110233. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110234. vorbis_look_psy *p,
  110235. vorbis_info_mapping0 *vi,
  110236. float **mags);
  110237. extern void hf_reduction(vorbis_info_psy_global *g,
  110238. vorbis_look_psy *p,
  110239. vorbis_info_mapping0 *vi,
  110240. float **mdct);
  110241. #endif
  110242. /*** End of inlined file: psy.h ***/
  110243. /*** Start of inlined file: bitrate.h ***/
  110244. #ifndef _V_BITRATE_H_
  110245. #define _V_BITRATE_H_
  110246. /*** Start of inlined file: os.h ***/
  110247. #ifndef _OS_H
  110248. #define _OS_H
  110249. /********************************************************************
  110250. * *
  110251. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110252. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110253. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110254. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110255. * *
  110256. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110257. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110258. * *
  110259. ********************************************************************
  110260. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110261. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110262. ********************************************************************/
  110263. #ifdef HAVE_CONFIG_H
  110264. #include "config.h"
  110265. #endif
  110266. #include <math.h>
  110267. /*** Start of inlined file: misc.h ***/
  110268. #ifndef _V_RANDOM_H_
  110269. #define _V_RANDOM_H_
  110270. extern int analysis_noisy;
  110271. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110272. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110273. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110274. ogg_int64_t off);
  110275. #ifdef DEBUG_MALLOC
  110276. #define _VDBG_GRAPHFILE "malloc.m"
  110277. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110278. extern void _VDBG_free(void *ptr,char *file,long line);
  110279. #ifndef MISC_C
  110280. #undef _ogg_malloc
  110281. #undef _ogg_calloc
  110282. #undef _ogg_realloc
  110283. #undef _ogg_free
  110284. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110285. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110286. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110287. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110288. #endif
  110289. #endif
  110290. #endif
  110291. /*** End of inlined file: misc.h ***/
  110292. #ifndef _V_IFDEFJAIL_H_
  110293. # define _V_IFDEFJAIL_H_
  110294. # ifdef __GNUC__
  110295. # define STIN static __inline__
  110296. # elif _WIN32
  110297. # define STIN static __inline
  110298. # else
  110299. # define STIN static
  110300. # endif
  110301. #ifdef DJGPP
  110302. # define rint(x) (floor((x)+0.5f))
  110303. #endif
  110304. #ifndef M_PI
  110305. # define M_PI (3.1415926536f)
  110306. #endif
  110307. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110308. # include <malloc.h>
  110309. # define rint(x) (floor((x)+0.5f))
  110310. # define NO_FLOAT_MATH_LIB
  110311. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110312. #endif
  110313. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110314. void *_alloca(size_t size);
  110315. # define alloca _alloca
  110316. #endif
  110317. #ifndef FAST_HYPOT
  110318. # define FAST_HYPOT hypot
  110319. #endif
  110320. #endif
  110321. #ifdef HAVE_ALLOCA_H
  110322. # include <alloca.h>
  110323. #endif
  110324. #ifdef USE_MEMORY_H
  110325. # include <memory.h>
  110326. #endif
  110327. #ifndef min
  110328. # define min(x,y) ((x)>(y)?(y):(x))
  110329. #endif
  110330. #ifndef max
  110331. # define max(x,y) ((x)<(y)?(y):(x))
  110332. #endif
  110333. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110334. # define VORBIS_FPU_CONTROL
  110335. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110336. Because of encapsulation constraints (GCC can't see inside the asm
  110337. block and so we end up doing stupid things like a store/load that
  110338. is collectively a noop), we do it this way */
  110339. /* we must set up the fpu before this works!! */
  110340. typedef ogg_int16_t vorbis_fpu_control;
  110341. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110342. ogg_int16_t ret;
  110343. ogg_int16_t temp;
  110344. __asm__ __volatile__("fnstcw %0\n\t"
  110345. "movw %0,%%dx\n\t"
  110346. "orw $62463,%%dx\n\t"
  110347. "movw %%dx,%1\n\t"
  110348. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110349. *fpu=ret;
  110350. }
  110351. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110352. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110353. }
  110354. /* assumes the FPU is in round mode! */
  110355. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110356. we get extra fst/fld to
  110357. truncate precision */
  110358. int i;
  110359. __asm__("fistl %0": "=m"(i) : "t"(f));
  110360. return(i);
  110361. }
  110362. #endif
  110363. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110364. # define VORBIS_FPU_CONTROL
  110365. typedef ogg_int16_t vorbis_fpu_control;
  110366. static __inline int vorbis_ftoi(double f){
  110367. int i;
  110368. __asm{
  110369. fld f
  110370. fistp i
  110371. }
  110372. return i;
  110373. }
  110374. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110375. }
  110376. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110377. }
  110378. #endif
  110379. #ifndef VORBIS_FPU_CONTROL
  110380. typedef int vorbis_fpu_control;
  110381. static int vorbis_ftoi(double f){
  110382. return (int)(f+.5);
  110383. }
  110384. /* We don't have special code for this compiler/arch, so do it the slow way */
  110385. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110386. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110387. #endif
  110388. #endif /* _OS_H */
  110389. /*** End of inlined file: os.h ***/
  110390. /* encode side bitrate tracking */
  110391. typedef struct bitrate_manager_state {
  110392. int managed;
  110393. long avg_reservoir;
  110394. long minmax_reservoir;
  110395. long avg_bitsper;
  110396. long min_bitsper;
  110397. long max_bitsper;
  110398. long short_per_long;
  110399. double avgfloat;
  110400. vorbis_block *vb;
  110401. int choice;
  110402. } bitrate_manager_state;
  110403. typedef struct bitrate_manager_info{
  110404. long avg_rate;
  110405. long min_rate;
  110406. long max_rate;
  110407. long reservoir_bits;
  110408. double reservoir_bias;
  110409. double slew_damp;
  110410. } bitrate_manager_info;
  110411. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110412. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110413. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110414. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110415. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110416. #endif
  110417. /*** End of inlined file: bitrate.h ***/
  110418. static int ilog(unsigned int v){
  110419. int ret=0;
  110420. while(v){
  110421. ret++;
  110422. v>>=1;
  110423. }
  110424. return(ret);
  110425. }
  110426. static int ilog2(unsigned int v){
  110427. int ret=0;
  110428. if(v)--v;
  110429. while(v){
  110430. ret++;
  110431. v>>=1;
  110432. }
  110433. return(ret);
  110434. }
  110435. typedef struct private_state {
  110436. /* local lookup storage */
  110437. envelope_lookup *ve; /* envelope lookup */
  110438. int window[2];
  110439. vorbis_look_transform **transform[2]; /* block, type */
  110440. drft_lookup fft_look[2];
  110441. int modebits;
  110442. vorbis_look_floor **flr;
  110443. vorbis_look_residue **residue;
  110444. vorbis_look_psy *psy;
  110445. vorbis_look_psy_global *psy_g_look;
  110446. /* local storage, only used on the encoding side. This way the
  110447. application does not need to worry about freeing some packets'
  110448. memory and not others'; packet storage is always tracked.
  110449. Cleared next call to a _dsp_ function */
  110450. unsigned char *header;
  110451. unsigned char *header1;
  110452. unsigned char *header2;
  110453. bitrate_manager_state bms;
  110454. ogg_int64_t sample_count;
  110455. } private_state;
  110456. /* codec_setup_info contains all the setup information specific to the
  110457. specific compression/decompression mode in progress (eg,
  110458. psychoacoustic settings, channel setup, options, codebook
  110459. etc).
  110460. *********************************************************************/
  110461. /*** Start of inlined file: highlevel.h ***/
  110462. typedef struct highlevel_byblocktype {
  110463. double tone_mask_setting;
  110464. double tone_peaklimit_setting;
  110465. double noise_bias_setting;
  110466. double noise_compand_setting;
  110467. } highlevel_byblocktype;
  110468. typedef struct highlevel_encode_setup {
  110469. void *setup;
  110470. int set_in_stone;
  110471. double base_setting;
  110472. double long_setting;
  110473. double short_setting;
  110474. double impulse_noisetune;
  110475. int managed;
  110476. long bitrate_min;
  110477. long bitrate_av;
  110478. double bitrate_av_damp;
  110479. long bitrate_max;
  110480. long bitrate_reservoir;
  110481. double bitrate_reservoir_bias;
  110482. int impulse_block_p;
  110483. int noise_normalize_p;
  110484. double stereo_point_setting;
  110485. double lowpass_kHz;
  110486. double ath_floating_dB;
  110487. double ath_absolute_dB;
  110488. double amplitude_track_dBpersec;
  110489. double trigger_setting;
  110490. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110491. } highlevel_encode_setup;
  110492. /*** End of inlined file: highlevel.h ***/
  110493. typedef struct codec_setup_info {
  110494. /* Vorbis supports only short and long blocks, but allows the
  110495. encoder to choose the sizes */
  110496. long blocksizes[2];
  110497. /* modes are the primary means of supporting on-the-fly different
  110498. blocksizes, different channel mappings (LR or M/A),
  110499. different residue backends, etc. Each mode consists of a
  110500. blocksize flag and a mapping (along with the mapping setup */
  110501. int modes;
  110502. int maps;
  110503. int floors;
  110504. int residues;
  110505. int books;
  110506. int psys; /* encode only */
  110507. vorbis_info_mode *mode_param[64];
  110508. int map_type[64];
  110509. vorbis_info_mapping *map_param[64];
  110510. int floor_type[64];
  110511. vorbis_info_floor *floor_param[64];
  110512. int residue_type[64];
  110513. vorbis_info_residue *residue_param[64];
  110514. static_codebook *book_param[256];
  110515. codebook *fullbooks;
  110516. vorbis_info_psy *psy_param[4]; /* encode only */
  110517. vorbis_info_psy_global psy_g_param;
  110518. bitrate_manager_info bi;
  110519. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110520. highly redundant structure, but
  110521. improves clarity of program flow. */
  110522. int halfrate_flag; /* painless downsample for decode */
  110523. } codec_setup_info;
  110524. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110525. extern void _vp_global_free(vorbis_look_psy_global *look);
  110526. #endif
  110527. /*** End of inlined file: codec_internal.h ***/
  110528. /*** Start of inlined file: registry.h ***/
  110529. #ifndef _V_REG_H_
  110530. #define _V_REG_H_
  110531. #define VI_TRANSFORMB 1
  110532. #define VI_WINDOWB 1
  110533. #define VI_TIMEB 1
  110534. #define VI_FLOORB 2
  110535. #define VI_RESB 3
  110536. #define VI_MAPB 1
  110537. extern vorbis_func_floor *_floor_P[];
  110538. extern vorbis_func_residue *_residue_P[];
  110539. extern vorbis_func_mapping *_mapping_P[];
  110540. #endif
  110541. /*** End of inlined file: registry.h ***/
  110542. /*** Start of inlined file: scales.h ***/
  110543. #ifndef _V_SCALES_H_
  110544. #define _V_SCALES_H_
  110545. #include <math.h>
  110546. /* 20log10(x) */
  110547. #define VORBIS_IEEE_FLOAT32 1
  110548. #ifdef VORBIS_IEEE_FLOAT32
  110549. static float unitnorm(float x){
  110550. union {
  110551. ogg_uint32_t i;
  110552. float f;
  110553. } ix;
  110554. ix.f = x;
  110555. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110556. return ix.f;
  110557. }
  110558. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110559. static float todB(const float *x){
  110560. union {
  110561. ogg_uint32_t i;
  110562. float f;
  110563. } ix;
  110564. ix.f = *x;
  110565. ix.i = ix.i&0x7fffffff;
  110566. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110567. }
  110568. #define todB_nn(x) todB(x)
  110569. #else
  110570. static float unitnorm(float x){
  110571. if(x<0)return(-1.f);
  110572. return(1.f);
  110573. }
  110574. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110575. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110576. #endif
  110577. #define fromdB(x) (exp((x)*.11512925f))
  110578. /* The bark scale equations are approximations, since the original
  110579. table was somewhat hand rolled. The below are chosen to have the
  110580. best possible fit to the rolled tables, thus their somewhat odd
  110581. appearance (these are more accurate and over a longer range than
  110582. the oft-quoted bark equations found in the texts I have). The
  110583. approximations are valid from 0 - 30kHz (nyquist) or so.
  110584. all f in Hz, z in Bark */
  110585. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110586. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110587. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110588. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110589. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110590. 0.0 */
  110591. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110592. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110593. #endif
  110594. /*** End of inlined file: scales.h ***/
  110595. int analysis_noisy=1;
  110596. /* decides between modes, dispatches to the appropriate mapping. */
  110597. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110598. int ret,i;
  110599. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110600. vb->glue_bits=0;
  110601. vb->time_bits=0;
  110602. vb->floor_bits=0;
  110603. vb->res_bits=0;
  110604. /* first things first. Make sure encode is ready */
  110605. for(i=0;i<PACKETBLOBS;i++)
  110606. oggpack_reset(vbi->packetblob[i]);
  110607. /* we only have one mapping type (0), and we let the mapping code
  110608. itself figure out what soft mode to use. This allows easier
  110609. bitrate management */
  110610. if((ret=_mapping_P[0]->forward(vb)))
  110611. return(ret);
  110612. if(op){
  110613. if(vorbis_bitrate_managed(vb))
  110614. /* The app is using a bitmanaged mode... but not using the
  110615. bitrate management interface. */
  110616. return(OV_EINVAL);
  110617. op->packet=oggpack_get_buffer(&vb->opb);
  110618. op->bytes=oggpack_bytes(&vb->opb);
  110619. op->b_o_s=0;
  110620. op->e_o_s=vb->eofflag;
  110621. op->granulepos=vb->granulepos;
  110622. op->packetno=vb->sequence; /* for sake of completeness */
  110623. }
  110624. return(0);
  110625. }
  110626. /* there was no great place to put this.... */
  110627. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110628. int j;
  110629. FILE *of;
  110630. char buffer[80];
  110631. /* if(i==5870){*/
  110632. sprintf(buffer,"%s_%d.m",base,i);
  110633. of=fopen(buffer,"w");
  110634. if(!of)perror("failed to open data dump file");
  110635. for(j=0;j<n;j++){
  110636. if(bark){
  110637. float b=toBARK((4000.f*j/n)+.25);
  110638. fprintf(of,"%f ",b);
  110639. }else
  110640. if(off!=0)
  110641. fprintf(of,"%f ",(double)(j+off)/8000.);
  110642. else
  110643. fprintf(of,"%f ",(double)j);
  110644. if(dB){
  110645. float val;
  110646. if(v[j]==0.)
  110647. val=-140.;
  110648. else
  110649. val=todB(v+j);
  110650. fprintf(of,"%f\n",val);
  110651. }else{
  110652. fprintf(of,"%f\n",v[j]);
  110653. }
  110654. }
  110655. fclose(of);
  110656. /* } */
  110657. }
  110658. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110659. ogg_int64_t off){
  110660. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110661. }
  110662. #endif
  110663. /*** End of inlined file: analysis.c ***/
  110664. /*** Start of inlined file: bitrate.c ***/
  110665. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110666. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110667. // tasks..
  110668. #if JUCE_MSVC
  110669. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110670. #endif
  110671. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110672. #if JUCE_USE_OGGVORBIS
  110673. #include <stdlib.h>
  110674. #include <string.h>
  110675. #include <math.h>
  110676. /* compute bitrate tracking setup */
  110677. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110678. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110679. bitrate_manager_info *bi=&ci->bi;
  110680. memset(bm,0,sizeof(*bm));
  110681. if(bi && (bi->reservoir_bits>0)){
  110682. long ratesamples=vi->rate;
  110683. int halfsamples=ci->blocksizes[0]>>1;
  110684. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110685. bm->managed=1;
  110686. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110687. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110688. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110689. bm->avgfloat=PACKETBLOBS/2;
  110690. /* not a necessary fix, but one that leads to a more balanced
  110691. typical initialization */
  110692. {
  110693. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110694. bm->minmax_reservoir=desired_fill;
  110695. bm->avg_reservoir=desired_fill;
  110696. }
  110697. }
  110698. }
  110699. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110700. memset(bm,0,sizeof(*bm));
  110701. return;
  110702. }
  110703. int vorbis_bitrate_managed(vorbis_block *vb){
  110704. vorbis_dsp_state *vd=vb->vd;
  110705. private_state *b=(private_state*)vd->backend_state;
  110706. bitrate_manager_state *bm=&b->bms;
  110707. if(bm && bm->managed)return(1);
  110708. return(0);
  110709. }
  110710. /* finish taking in the block we just processed */
  110711. int vorbis_bitrate_addblock(vorbis_block *vb){
  110712. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110713. vorbis_dsp_state *vd=vb->vd;
  110714. private_state *b=(private_state*)vd->backend_state;
  110715. bitrate_manager_state *bm=&b->bms;
  110716. vorbis_info *vi=vd->vi;
  110717. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110718. bitrate_manager_info *bi=&ci->bi;
  110719. int choice=rint(bm->avgfloat);
  110720. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110721. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110722. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110723. int samples=ci->blocksizes[vb->W]>>1;
  110724. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110725. if(!bm->managed){
  110726. /* not a bitrate managed stream, but for API simplicity, we'll
  110727. buffer the packet to keep the code path clean */
  110728. if(bm->vb)return(-1); /* one has been submitted without
  110729. being claimed */
  110730. bm->vb=vb;
  110731. return(0);
  110732. }
  110733. bm->vb=vb;
  110734. /* look ahead for avg floater */
  110735. if(bm->avg_bitsper>0){
  110736. double slew=0.;
  110737. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110738. double slewlimit= 15./bi->slew_damp;
  110739. /* choosing a new floater:
  110740. if we're over target, we slew down
  110741. if we're under target, we slew up
  110742. choose slew as follows: look through packetblobs of this frame
  110743. and set slew as the first in the appropriate direction that
  110744. gives us the slew we want. This may mean no slew if delta is
  110745. already favorable.
  110746. Then limit slew to slew max */
  110747. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110748. while(choice>0 && this_bits>avg_target_bits &&
  110749. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110750. choice--;
  110751. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110752. }
  110753. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110754. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110755. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110756. choice++;
  110757. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110758. }
  110759. }
  110760. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110761. if(slew<-slewlimit)slew=-slewlimit;
  110762. if(slew>slewlimit)slew=slewlimit;
  110763. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110764. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110765. }
  110766. /* enforce min(if used) on the current floater (if used) */
  110767. if(bm->min_bitsper>0){
  110768. /* do we need to force the bitrate up? */
  110769. if(this_bits<min_target_bits){
  110770. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110771. choice++;
  110772. if(choice>=PACKETBLOBS)break;
  110773. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110774. }
  110775. }
  110776. }
  110777. /* enforce max (if used) on the current floater (if used) */
  110778. if(bm->max_bitsper>0){
  110779. /* do we need to force the bitrate down? */
  110780. if(this_bits>max_target_bits){
  110781. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110782. choice--;
  110783. if(choice<0)break;
  110784. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110785. }
  110786. }
  110787. }
  110788. /* Choice of packetblobs now made based on floater, and min/max
  110789. requirements. Now boundary check extreme choices */
  110790. if(choice<0){
  110791. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110792. frame will need to be truncated */
  110793. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110794. bm->choice=choice=0;
  110795. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110796. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110797. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110798. }
  110799. }else{
  110800. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110801. if(choice>=PACKETBLOBS)
  110802. choice=PACKETBLOBS-1;
  110803. bm->choice=choice;
  110804. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110805. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110806. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110807. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110808. }
  110809. /* now we have the final packet and the final packet size. Update statistics */
  110810. /* min and max reservoir */
  110811. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110812. if(max_target_bits>0 && this_bits>max_target_bits){
  110813. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110814. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110815. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110816. }else{
  110817. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110818. if(bm->minmax_reservoir>desired_fill){
  110819. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110820. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110821. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110822. }else{
  110823. bm->minmax_reservoir=desired_fill;
  110824. }
  110825. }else{
  110826. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110827. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110828. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110829. }else{
  110830. bm->minmax_reservoir=desired_fill;
  110831. }
  110832. }
  110833. }
  110834. }
  110835. /* avg reservoir */
  110836. if(bm->avg_bitsper>0){
  110837. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110838. bm->avg_reservoir+=this_bits-avg_target_bits;
  110839. }
  110840. return(0);
  110841. }
  110842. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110843. private_state *b=(private_state*)vd->backend_state;
  110844. bitrate_manager_state *bm=&b->bms;
  110845. vorbis_block *vb=bm->vb;
  110846. int choice=PACKETBLOBS/2;
  110847. if(!vb)return 0;
  110848. if(op){
  110849. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110850. if(vorbis_bitrate_managed(vb))
  110851. choice=bm->choice;
  110852. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110853. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110854. op->b_o_s=0;
  110855. op->e_o_s=vb->eofflag;
  110856. op->granulepos=vb->granulepos;
  110857. op->packetno=vb->sequence; /* for sake of completeness */
  110858. }
  110859. bm->vb=0;
  110860. return(1);
  110861. }
  110862. #endif
  110863. /*** End of inlined file: bitrate.c ***/
  110864. /*** Start of inlined file: block.c ***/
  110865. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110866. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110867. // tasks..
  110868. #if JUCE_MSVC
  110869. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110870. #endif
  110871. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110872. #if JUCE_USE_OGGVORBIS
  110873. #include <stdio.h>
  110874. #include <stdlib.h>
  110875. #include <string.h>
  110876. /*** Start of inlined file: window.h ***/
  110877. #ifndef _V_WINDOW_
  110878. #define _V_WINDOW_
  110879. extern float *_vorbis_window_get(int n);
  110880. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110881. int lW,int W,int nW);
  110882. #endif
  110883. /*** End of inlined file: window.h ***/
  110884. /*** Start of inlined file: lpc.h ***/
  110885. #ifndef _V_LPC_H_
  110886. #define _V_LPC_H_
  110887. /* simple linear scale LPC code */
  110888. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110889. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110890. float *data,long n);
  110891. #endif
  110892. /*** End of inlined file: lpc.h ***/
  110893. /* pcm accumulator examples (not exhaustive):
  110894. <-------------- lW ---------------->
  110895. <--------------- W ---------------->
  110896. : .....|..... _______________ |
  110897. : .''' | '''_--- | |\ |
  110898. :.....''' |_____--- '''......| | \_______|
  110899. :.................|__________________|_______|__|______|
  110900. |<------ Sl ------>| > Sr < |endW
  110901. |beginSl |endSl | |endSr
  110902. |beginW |endlW |beginSr
  110903. |< lW >|
  110904. <--------------- W ---------------->
  110905. | | .. ______________ |
  110906. | | ' `/ | ---_ |
  110907. |___.'___/`. | ---_____|
  110908. |_______|__|_______|_________________|
  110909. | >|Sl|< |<------ Sr ----->|endW
  110910. | | |endSl |beginSr |endSr
  110911. |beginW | |endlW
  110912. mult[0] |beginSl mult[n]
  110913. <-------------- lW ----------------->
  110914. |<--W-->|
  110915. : .............. ___ | |
  110916. : .''' |`/ \ | |
  110917. :.....''' |/`....\|...|
  110918. :.........................|___|___|___|
  110919. |Sl |Sr |endW
  110920. | | |endSr
  110921. | |beginSr
  110922. | |endSl
  110923. |beginSl
  110924. |beginW
  110925. */
  110926. /* block abstraction setup *********************************************/
  110927. #ifndef WORD_ALIGN
  110928. #define WORD_ALIGN 8
  110929. #endif
  110930. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110931. int i;
  110932. memset(vb,0,sizeof(*vb));
  110933. vb->vd=v;
  110934. vb->localalloc=0;
  110935. vb->localstore=NULL;
  110936. if(v->analysisp){
  110937. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110938. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110939. vbi->ampmax=-9999;
  110940. for(i=0;i<PACKETBLOBS;i++){
  110941. if(i==PACKETBLOBS/2){
  110942. vbi->packetblob[i]=&vb->opb;
  110943. }else{
  110944. vbi->packetblob[i]=
  110945. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110946. }
  110947. oggpack_writeinit(vbi->packetblob[i]);
  110948. }
  110949. }
  110950. return(0);
  110951. }
  110952. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110953. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110954. if(bytes+vb->localtop>vb->localalloc){
  110955. /* can't just _ogg_realloc... there are outstanding pointers */
  110956. if(vb->localstore){
  110957. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110958. vb->totaluse+=vb->localtop;
  110959. link->next=vb->reap;
  110960. link->ptr=vb->localstore;
  110961. vb->reap=link;
  110962. }
  110963. /* highly conservative */
  110964. vb->localalloc=bytes;
  110965. vb->localstore=_ogg_malloc(vb->localalloc);
  110966. vb->localtop=0;
  110967. }
  110968. {
  110969. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110970. vb->localtop+=bytes;
  110971. return ret;
  110972. }
  110973. }
  110974. /* reap the chain, pull the ripcord */
  110975. void _vorbis_block_ripcord(vorbis_block *vb){
  110976. /* reap the chain */
  110977. struct alloc_chain *reap=vb->reap;
  110978. while(reap){
  110979. struct alloc_chain *next=reap->next;
  110980. _ogg_free(reap->ptr);
  110981. memset(reap,0,sizeof(*reap));
  110982. _ogg_free(reap);
  110983. reap=next;
  110984. }
  110985. /* consolidate storage */
  110986. if(vb->totaluse){
  110987. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110988. vb->localalloc+=vb->totaluse;
  110989. vb->totaluse=0;
  110990. }
  110991. /* pull the ripcord */
  110992. vb->localtop=0;
  110993. vb->reap=NULL;
  110994. }
  110995. int vorbis_block_clear(vorbis_block *vb){
  110996. int i;
  110997. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110998. _vorbis_block_ripcord(vb);
  110999. if(vb->localstore)_ogg_free(vb->localstore);
  111000. if(vbi){
  111001. for(i=0;i<PACKETBLOBS;i++){
  111002. oggpack_writeclear(vbi->packetblob[i]);
  111003. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111004. }
  111005. _ogg_free(vbi);
  111006. }
  111007. memset(vb,0,sizeof(*vb));
  111008. return(0);
  111009. }
  111010. /* Analysis side code, but directly related to blocking. Thus it's
  111011. here and not in analysis.c (which is for analysis transforms only).
  111012. The init is here because some of it is shared */
  111013. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111014. int i;
  111015. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111016. private_state *b=NULL;
  111017. int hs;
  111018. if(ci==NULL) return 1;
  111019. hs=ci->halfrate_flag;
  111020. memset(v,0,sizeof(*v));
  111021. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111022. v->vi=vi;
  111023. b->modebits=ilog2(ci->modes);
  111024. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111025. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111026. /* MDCT is tranform 0 */
  111027. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111028. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111029. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111030. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111031. /* Vorbis I uses only window type 0 */
  111032. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111033. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111034. if(encp){ /* encode/decode differ here */
  111035. /* analysis always needs an fft */
  111036. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111037. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111038. /* finish the codebooks */
  111039. if(!ci->fullbooks){
  111040. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111041. for(i=0;i<ci->books;i++)
  111042. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111043. }
  111044. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111045. for(i=0;i<ci->psys;i++){
  111046. _vp_psy_init(b->psy+i,
  111047. ci->psy_param[i],
  111048. &ci->psy_g_param,
  111049. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111050. vi->rate);
  111051. }
  111052. v->analysisp=1;
  111053. }else{
  111054. /* finish the codebooks */
  111055. if(!ci->fullbooks){
  111056. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111057. for(i=0;i<ci->books;i++){
  111058. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111059. /* decode codebooks are now standalone after init */
  111060. vorbis_staticbook_destroy(ci->book_param[i]);
  111061. ci->book_param[i]=NULL;
  111062. }
  111063. }
  111064. }
  111065. /* initialize the storage vectors. blocksize[1] is small for encode,
  111066. but the correct size for decode */
  111067. v->pcm_storage=ci->blocksizes[1];
  111068. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111069. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111070. {
  111071. int i;
  111072. for(i=0;i<vi->channels;i++)
  111073. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111074. }
  111075. /* all 1 (large block) or 0 (small block) */
  111076. /* explicitly set for the sake of clarity */
  111077. v->lW=0; /* previous window size */
  111078. v->W=0; /* current window size */
  111079. /* all vector indexes */
  111080. v->centerW=ci->blocksizes[1]/2;
  111081. v->pcm_current=v->centerW;
  111082. /* initialize all the backend lookups */
  111083. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111084. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111085. for(i=0;i<ci->floors;i++)
  111086. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111087. look(v,ci->floor_param[i]);
  111088. for(i=0;i<ci->residues;i++)
  111089. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111090. look(v,ci->residue_param[i]);
  111091. return 0;
  111092. }
  111093. /* arbitrary settings and spec-mandated numbers get filled in here */
  111094. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111095. private_state *b=NULL;
  111096. if(_vds_shared_init(v,vi,1))return 1;
  111097. b=(private_state*)v->backend_state;
  111098. b->psy_g_look=_vp_global_look(vi);
  111099. /* Initialize the envelope state storage */
  111100. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111101. _ve_envelope_init(b->ve,vi);
  111102. vorbis_bitrate_init(vi,&b->bms);
  111103. /* compressed audio packets start after the headers
  111104. with sequence number 3 */
  111105. v->sequence=3;
  111106. return(0);
  111107. }
  111108. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111109. int i;
  111110. if(v){
  111111. vorbis_info *vi=v->vi;
  111112. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111113. private_state *b=(private_state*)v->backend_state;
  111114. if(b){
  111115. if(b->ve){
  111116. _ve_envelope_clear(b->ve);
  111117. _ogg_free(b->ve);
  111118. }
  111119. if(b->transform[0]){
  111120. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111121. _ogg_free(b->transform[0][0]);
  111122. _ogg_free(b->transform[0]);
  111123. }
  111124. if(b->transform[1]){
  111125. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111126. _ogg_free(b->transform[1][0]);
  111127. _ogg_free(b->transform[1]);
  111128. }
  111129. if(b->flr){
  111130. for(i=0;i<ci->floors;i++)
  111131. _floor_P[ci->floor_type[i]]->
  111132. free_look(b->flr[i]);
  111133. _ogg_free(b->flr);
  111134. }
  111135. if(b->residue){
  111136. for(i=0;i<ci->residues;i++)
  111137. _residue_P[ci->residue_type[i]]->
  111138. free_look(b->residue[i]);
  111139. _ogg_free(b->residue);
  111140. }
  111141. if(b->psy){
  111142. for(i=0;i<ci->psys;i++)
  111143. _vp_psy_clear(b->psy+i);
  111144. _ogg_free(b->psy);
  111145. }
  111146. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111147. vorbis_bitrate_clear(&b->bms);
  111148. drft_clear(&b->fft_look[0]);
  111149. drft_clear(&b->fft_look[1]);
  111150. }
  111151. if(v->pcm){
  111152. for(i=0;i<vi->channels;i++)
  111153. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111154. _ogg_free(v->pcm);
  111155. if(v->pcmret)_ogg_free(v->pcmret);
  111156. }
  111157. if(b){
  111158. /* free header, header1, header2 */
  111159. if(b->header)_ogg_free(b->header);
  111160. if(b->header1)_ogg_free(b->header1);
  111161. if(b->header2)_ogg_free(b->header2);
  111162. _ogg_free(b);
  111163. }
  111164. memset(v,0,sizeof(*v));
  111165. }
  111166. }
  111167. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111168. int i;
  111169. vorbis_info *vi=v->vi;
  111170. private_state *b=(private_state*)v->backend_state;
  111171. /* free header, header1, header2 */
  111172. if(b->header)_ogg_free(b->header);b->header=NULL;
  111173. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111174. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111175. /* Do we have enough storage space for the requested buffer? If not,
  111176. expand the PCM (and envelope) storage */
  111177. if(v->pcm_current+vals>=v->pcm_storage){
  111178. v->pcm_storage=v->pcm_current+vals*2;
  111179. for(i=0;i<vi->channels;i++){
  111180. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111181. }
  111182. }
  111183. for(i=0;i<vi->channels;i++)
  111184. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111185. return(v->pcmret);
  111186. }
  111187. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111188. int i;
  111189. int order=32;
  111190. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111191. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111192. long j;
  111193. v->preextrapolate=1;
  111194. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111195. for(i=0;i<v->vi->channels;i++){
  111196. /* need to run the extrapolation in reverse! */
  111197. for(j=0;j<v->pcm_current;j++)
  111198. work[j]=v->pcm[i][v->pcm_current-j-1];
  111199. /* prime as above */
  111200. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111201. /* run the predictor filter */
  111202. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111203. order,
  111204. work+v->pcm_current-v->centerW,
  111205. v->centerW);
  111206. for(j=0;j<v->pcm_current;j++)
  111207. v->pcm[i][v->pcm_current-j-1]=work[j];
  111208. }
  111209. }
  111210. }
  111211. /* call with val<=0 to set eof */
  111212. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111213. vorbis_info *vi=v->vi;
  111214. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111215. if(vals<=0){
  111216. int order=32;
  111217. int i;
  111218. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111219. /* if it wasn't done earlier (very short sample) */
  111220. if(!v->preextrapolate)
  111221. _preextrapolate_helper(v);
  111222. /* We're encoding the end of the stream. Just make sure we have
  111223. [at least] a few full blocks of zeroes at the end. */
  111224. /* actually, we don't want zeroes; that could drop a large
  111225. amplitude off a cliff, creating spread spectrum noise that will
  111226. suck to encode. Extrapolate for the sake of cleanliness. */
  111227. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111228. v->eofflag=v->pcm_current;
  111229. v->pcm_current+=ci->blocksizes[1]*3;
  111230. for(i=0;i<vi->channels;i++){
  111231. if(v->eofflag>order*2){
  111232. /* extrapolate with LPC to fill in */
  111233. long n;
  111234. /* make a predictor filter */
  111235. n=v->eofflag;
  111236. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111237. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111238. /* run the predictor filter */
  111239. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111240. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111241. }else{
  111242. /* not enough data to extrapolate (unlikely to happen due to
  111243. guarding the overlap, but bulletproof in case that
  111244. assumtion goes away). zeroes will do. */
  111245. memset(v->pcm[i]+v->eofflag,0,
  111246. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111247. }
  111248. }
  111249. }else{
  111250. if(v->pcm_current+vals>v->pcm_storage)
  111251. return(OV_EINVAL);
  111252. v->pcm_current+=vals;
  111253. /* we may want to reverse extrapolate the beginning of a stream
  111254. too... in case we're beginning on a cliff! */
  111255. /* clumsy, but simple. It only runs once, so simple is good. */
  111256. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111257. _preextrapolate_helper(v);
  111258. }
  111259. return(0);
  111260. }
  111261. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111262. the next block on which to continue analysis */
  111263. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111264. int i;
  111265. vorbis_info *vi=v->vi;
  111266. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111267. private_state *b=(private_state*)v->backend_state;
  111268. vorbis_look_psy_global *g=b->psy_g_look;
  111269. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111270. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111271. /* check to see if we're started... */
  111272. if(!v->preextrapolate)return(0);
  111273. /* check to see if we're done... */
  111274. if(v->eofflag==-1)return(0);
  111275. /* By our invariant, we have lW, W and centerW set. Search for
  111276. the next boundary so we can determine nW (the next window size)
  111277. which lets us compute the shape of the current block's window */
  111278. /* we do an envelope search even on a single blocksize; we may still
  111279. be throwing more bits at impulses, and envelope search handles
  111280. marking impulses too. */
  111281. {
  111282. long bp=_ve_envelope_search(v);
  111283. if(bp==-1){
  111284. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111285. full long block */
  111286. v->nW=0;
  111287. }else{
  111288. if(ci->blocksizes[0]==ci->blocksizes[1])
  111289. v->nW=0;
  111290. else
  111291. v->nW=bp;
  111292. }
  111293. }
  111294. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111295. {
  111296. /* center of next block + next block maximum right side. */
  111297. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111298. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111299. although this check is
  111300. less strict that the
  111301. _ve_envelope_search,
  111302. the search is not run
  111303. if we only use one
  111304. block size */
  111305. }
  111306. /* fill in the block. Note that for a short window, lW and nW are *short*
  111307. regardless of actual settings in the stream */
  111308. _vorbis_block_ripcord(vb);
  111309. vb->lW=v->lW;
  111310. vb->W=v->W;
  111311. vb->nW=v->nW;
  111312. if(v->W){
  111313. if(!v->lW || !v->nW){
  111314. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111315. /*fprintf(stderr,"-");*/
  111316. }else{
  111317. vbi->blocktype=BLOCKTYPE_LONG;
  111318. /*fprintf(stderr,"_");*/
  111319. }
  111320. }else{
  111321. if(_ve_envelope_mark(v)){
  111322. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111323. /*fprintf(stderr,"|");*/
  111324. }else{
  111325. vbi->blocktype=BLOCKTYPE_PADDING;
  111326. /*fprintf(stderr,".");*/
  111327. }
  111328. }
  111329. vb->vd=v;
  111330. vb->sequence=v->sequence++;
  111331. vb->granulepos=v->granulepos;
  111332. vb->pcmend=ci->blocksizes[v->W];
  111333. /* copy the vectors; this uses the local storage in vb */
  111334. /* this tracks 'strongest peak' for later psychoacoustics */
  111335. /* moved to the global psy state; clean this mess up */
  111336. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111337. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111338. vbi->ampmax=g->ampmax;
  111339. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111340. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111341. for(i=0;i<vi->channels;i++){
  111342. vbi->pcmdelay[i]=
  111343. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111344. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111345. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111346. /* before we added the delay
  111347. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111348. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111349. */
  111350. }
  111351. /* handle eof detection: eof==0 means that we've not yet received EOF
  111352. eof>0 marks the last 'real' sample in pcm[]
  111353. eof<0 'no more to do'; doesn't get here */
  111354. if(v->eofflag){
  111355. if(v->centerW>=v->eofflag){
  111356. v->eofflag=-1;
  111357. vb->eofflag=1;
  111358. return(1);
  111359. }
  111360. }
  111361. /* advance storage vectors and clean up */
  111362. {
  111363. int new_centerNext=ci->blocksizes[1]/2;
  111364. int movementW=centerNext-new_centerNext;
  111365. if(movementW>0){
  111366. _ve_envelope_shift(b->ve,movementW);
  111367. v->pcm_current-=movementW;
  111368. for(i=0;i<vi->channels;i++)
  111369. memmove(v->pcm[i],v->pcm[i]+movementW,
  111370. v->pcm_current*sizeof(*v->pcm[i]));
  111371. v->lW=v->W;
  111372. v->W=v->nW;
  111373. v->centerW=new_centerNext;
  111374. if(v->eofflag){
  111375. v->eofflag-=movementW;
  111376. if(v->eofflag<=0)v->eofflag=-1;
  111377. /* do not add padding to end of stream! */
  111378. if(v->centerW>=v->eofflag){
  111379. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111380. }else{
  111381. v->granulepos+=movementW;
  111382. }
  111383. }else{
  111384. v->granulepos+=movementW;
  111385. }
  111386. }
  111387. }
  111388. /* done */
  111389. return(1);
  111390. }
  111391. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111392. vorbis_info *vi=v->vi;
  111393. codec_setup_info *ci;
  111394. int hs;
  111395. if(!v->backend_state)return -1;
  111396. if(!vi)return -1;
  111397. ci=(codec_setup_info*) vi->codec_setup;
  111398. if(!ci)return -1;
  111399. hs=ci->halfrate_flag;
  111400. v->centerW=ci->blocksizes[1]>>(hs+1);
  111401. v->pcm_current=v->centerW>>hs;
  111402. v->pcm_returned=-1;
  111403. v->granulepos=-1;
  111404. v->sequence=-1;
  111405. v->eofflag=0;
  111406. ((private_state *)(v->backend_state))->sample_count=-1;
  111407. return(0);
  111408. }
  111409. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111410. if(_vds_shared_init(v,vi,0)) return 1;
  111411. vorbis_synthesis_restart(v);
  111412. return 0;
  111413. }
  111414. /* Unlike in analysis, the window is only partially applied for each
  111415. block. The time domain envelope is not yet handled at the point of
  111416. calling (as it relies on the previous block). */
  111417. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111418. vorbis_info *vi=v->vi;
  111419. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111420. private_state *b=(private_state*)v->backend_state;
  111421. int hs=ci->halfrate_flag;
  111422. int i,j;
  111423. if(!vb)return(OV_EINVAL);
  111424. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111425. v->lW=v->W;
  111426. v->W=vb->W;
  111427. v->nW=-1;
  111428. if((v->sequence==-1)||
  111429. (v->sequence+1 != vb->sequence)){
  111430. v->granulepos=-1; /* out of sequence; lose count */
  111431. b->sample_count=-1;
  111432. }
  111433. v->sequence=vb->sequence;
  111434. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111435. was called on block */
  111436. int n=ci->blocksizes[v->W]>>(hs+1);
  111437. int n0=ci->blocksizes[0]>>(hs+1);
  111438. int n1=ci->blocksizes[1]>>(hs+1);
  111439. int thisCenter;
  111440. int prevCenter;
  111441. v->glue_bits+=vb->glue_bits;
  111442. v->time_bits+=vb->time_bits;
  111443. v->floor_bits+=vb->floor_bits;
  111444. v->res_bits+=vb->res_bits;
  111445. if(v->centerW){
  111446. thisCenter=n1;
  111447. prevCenter=0;
  111448. }else{
  111449. thisCenter=0;
  111450. prevCenter=n1;
  111451. }
  111452. /* v->pcm is now used like a two-stage double buffer. We don't want
  111453. to have to constantly shift *or* adjust memory usage. Don't
  111454. accept a new block until the old is shifted out */
  111455. for(j=0;j<vi->channels;j++){
  111456. /* the overlap/add section */
  111457. if(v->lW){
  111458. if(v->W){
  111459. /* large/large */
  111460. float *w=_vorbis_window_get(b->window[1]-hs);
  111461. float *pcm=v->pcm[j]+prevCenter;
  111462. float *p=vb->pcm[j];
  111463. for(i=0;i<n1;i++)
  111464. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111465. }else{
  111466. /* large/small */
  111467. float *w=_vorbis_window_get(b->window[0]-hs);
  111468. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111469. float *p=vb->pcm[j];
  111470. for(i=0;i<n0;i++)
  111471. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111472. }
  111473. }else{
  111474. if(v->W){
  111475. /* small/large */
  111476. float *w=_vorbis_window_get(b->window[0]-hs);
  111477. float *pcm=v->pcm[j]+prevCenter;
  111478. float *p=vb->pcm[j]+n1/2-n0/2;
  111479. for(i=0;i<n0;i++)
  111480. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111481. for(;i<n1/2+n0/2;i++)
  111482. pcm[i]=p[i];
  111483. }else{
  111484. /* small/small */
  111485. float *w=_vorbis_window_get(b->window[0]-hs);
  111486. float *pcm=v->pcm[j]+prevCenter;
  111487. float *p=vb->pcm[j];
  111488. for(i=0;i<n0;i++)
  111489. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111490. }
  111491. }
  111492. /* the copy section */
  111493. {
  111494. float *pcm=v->pcm[j]+thisCenter;
  111495. float *p=vb->pcm[j]+n;
  111496. for(i=0;i<n;i++)
  111497. pcm[i]=p[i];
  111498. }
  111499. }
  111500. if(v->centerW)
  111501. v->centerW=0;
  111502. else
  111503. v->centerW=n1;
  111504. /* deal with initial packet state; we do this using the explicit
  111505. pcm_returned==-1 flag otherwise we're sensitive to first block
  111506. being short or long */
  111507. if(v->pcm_returned==-1){
  111508. v->pcm_returned=thisCenter;
  111509. v->pcm_current=thisCenter;
  111510. }else{
  111511. v->pcm_returned=prevCenter;
  111512. v->pcm_current=prevCenter+
  111513. ((ci->blocksizes[v->lW]/4+
  111514. ci->blocksizes[v->W]/4)>>hs);
  111515. }
  111516. }
  111517. /* track the frame number... This is for convenience, but also
  111518. making sure our last packet doesn't end with added padding. If
  111519. the last packet is partial, the number of samples we'll have to
  111520. return will be past the vb->granulepos.
  111521. This is not foolproof! It will be confused if we begin
  111522. decoding at the last page after a seek or hole. In that case,
  111523. we don't have a starting point to judge where the last frame
  111524. is. For this reason, vorbisfile will always try to make sure
  111525. it reads the last two marked pages in proper sequence */
  111526. if(b->sample_count==-1){
  111527. b->sample_count=0;
  111528. }else{
  111529. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111530. }
  111531. if(v->granulepos==-1){
  111532. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111533. v->granulepos=vb->granulepos;
  111534. /* is this a short page? */
  111535. if(b->sample_count>v->granulepos){
  111536. /* corner case; if this is both the first and last audio page,
  111537. then spec says the end is cut, not beginning */
  111538. if(vb->eofflag){
  111539. /* trim the end */
  111540. /* no preceeding granulepos; assume we started at zero (we'd
  111541. have to in a short single-page stream) */
  111542. /* granulepos could be -1 due to a seek, but that would result
  111543. in a long count, not short count */
  111544. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111545. }else{
  111546. /* trim the beginning */
  111547. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111548. if(v->pcm_returned>v->pcm_current)
  111549. v->pcm_returned=v->pcm_current;
  111550. }
  111551. }
  111552. }
  111553. }else{
  111554. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111555. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111556. if(v->granulepos>vb->granulepos){
  111557. long extra=v->granulepos-vb->granulepos;
  111558. if(extra)
  111559. if(vb->eofflag){
  111560. /* partial last frame. Strip the extra samples off */
  111561. v->pcm_current-=extra>>hs;
  111562. } /* else {Shouldn't happen *unless* the bitstream is out of
  111563. spec. Either way, believe the bitstream } */
  111564. } /* else {Shouldn't happen *unless* the bitstream is out of
  111565. spec. Either way, believe the bitstream } */
  111566. v->granulepos=vb->granulepos;
  111567. }
  111568. }
  111569. /* Update, cleanup */
  111570. if(vb->eofflag)v->eofflag=1;
  111571. return(0);
  111572. }
  111573. /* pcm==NULL indicates we just want the pending samples, no more */
  111574. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111575. vorbis_info *vi=v->vi;
  111576. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111577. if(pcm){
  111578. int i;
  111579. for(i=0;i<vi->channels;i++)
  111580. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111581. *pcm=v->pcmret;
  111582. }
  111583. return(v->pcm_current-v->pcm_returned);
  111584. }
  111585. return(0);
  111586. }
  111587. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111588. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111589. v->pcm_returned+=n;
  111590. return(0);
  111591. }
  111592. /* intended for use with a specific vorbisfile feature; we want access
  111593. to the [usually synthetic/postextrapolated] buffer and lapping at
  111594. the end of a decode cycle, specifically, a half-short-block worth.
  111595. This funtion works like pcmout above, except it will also expose
  111596. this implicit buffer data not normally decoded. */
  111597. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111598. vorbis_info *vi=v->vi;
  111599. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111600. int hs=ci->halfrate_flag;
  111601. int n=ci->blocksizes[v->W]>>(hs+1);
  111602. int n0=ci->blocksizes[0]>>(hs+1);
  111603. int n1=ci->blocksizes[1]>>(hs+1);
  111604. int i,j;
  111605. if(v->pcm_returned<0)return 0;
  111606. /* our returned data ends at pcm_returned; because the synthesis pcm
  111607. buffer is a two-fragment ring, that means our data block may be
  111608. fragmented by buffering, wrapping or a short block not filling
  111609. out a buffer. To simplify things, we unfragment if it's at all
  111610. possibly needed. Otherwise, we'd need to call lapout more than
  111611. once as well as hold additional dsp state. Opt for
  111612. simplicity. */
  111613. /* centerW was advanced by blockin; it would be the center of the
  111614. *next* block */
  111615. if(v->centerW==n1){
  111616. /* the data buffer wraps; swap the halves */
  111617. /* slow, sure, small */
  111618. for(j=0;j<vi->channels;j++){
  111619. float *p=v->pcm[j];
  111620. for(i=0;i<n1;i++){
  111621. float temp=p[i];
  111622. p[i]=p[i+n1];
  111623. p[i+n1]=temp;
  111624. }
  111625. }
  111626. v->pcm_current-=n1;
  111627. v->pcm_returned-=n1;
  111628. v->centerW=0;
  111629. }
  111630. /* solidify buffer into contiguous space */
  111631. if((v->lW^v->W)==1){
  111632. /* long/short or short/long */
  111633. for(j=0;j<vi->channels;j++){
  111634. float *s=v->pcm[j];
  111635. float *d=v->pcm[j]+(n1-n0)/2;
  111636. for(i=(n1+n0)/2-1;i>=0;--i)
  111637. d[i]=s[i];
  111638. }
  111639. v->pcm_returned+=(n1-n0)/2;
  111640. v->pcm_current+=(n1-n0)/2;
  111641. }else{
  111642. if(v->lW==0){
  111643. /* short/short */
  111644. for(j=0;j<vi->channels;j++){
  111645. float *s=v->pcm[j];
  111646. float *d=v->pcm[j]+n1-n0;
  111647. for(i=n0-1;i>=0;--i)
  111648. d[i]=s[i];
  111649. }
  111650. v->pcm_returned+=n1-n0;
  111651. v->pcm_current+=n1-n0;
  111652. }
  111653. }
  111654. if(pcm){
  111655. int i;
  111656. for(i=0;i<vi->channels;i++)
  111657. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111658. *pcm=v->pcmret;
  111659. }
  111660. return(n1+n-v->pcm_returned);
  111661. }
  111662. float *vorbis_window(vorbis_dsp_state *v,int W){
  111663. vorbis_info *vi=v->vi;
  111664. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111665. int hs=ci->halfrate_flag;
  111666. private_state *b=(private_state*)v->backend_state;
  111667. if(b->window[W]-1<0)return NULL;
  111668. return _vorbis_window_get(b->window[W]-hs);
  111669. }
  111670. #endif
  111671. /*** End of inlined file: block.c ***/
  111672. /*** Start of inlined file: codebook.c ***/
  111673. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111674. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111675. // tasks..
  111676. #if JUCE_MSVC
  111677. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111678. #endif
  111679. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111680. #if JUCE_USE_OGGVORBIS
  111681. #include <stdlib.h>
  111682. #include <string.h>
  111683. #include <math.h>
  111684. /* packs the given codebook into the bitstream **************************/
  111685. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111686. long i,j;
  111687. int ordered=0;
  111688. /* first the basic parameters */
  111689. oggpack_write(opb,0x564342,24);
  111690. oggpack_write(opb,c->dim,16);
  111691. oggpack_write(opb,c->entries,24);
  111692. /* pack the codewords. There are two packings; length ordered and
  111693. length random. Decide between the two now. */
  111694. for(i=1;i<c->entries;i++)
  111695. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111696. if(i==c->entries)ordered=1;
  111697. if(ordered){
  111698. /* length ordered. We only need to say how many codewords of
  111699. each length. The actual codewords are generated
  111700. deterministically */
  111701. long count=0;
  111702. oggpack_write(opb,1,1); /* ordered */
  111703. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111704. for(i=1;i<c->entries;i++){
  111705. long thisx=c->lengthlist[i];
  111706. long last=c->lengthlist[i-1];
  111707. if(thisx>last){
  111708. for(j=last;j<thisx;j++){
  111709. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111710. count=i;
  111711. }
  111712. }
  111713. }
  111714. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111715. }else{
  111716. /* length random. Again, we don't code the codeword itself, just
  111717. the length. This time, though, we have to encode each length */
  111718. oggpack_write(opb,0,1); /* unordered */
  111719. /* algortihmic mapping has use for 'unused entries', which we tag
  111720. here. The algorithmic mapping happens as usual, but the unused
  111721. entry has no codeword. */
  111722. for(i=0;i<c->entries;i++)
  111723. if(c->lengthlist[i]==0)break;
  111724. if(i==c->entries){
  111725. oggpack_write(opb,0,1); /* no unused entries */
  111726. for(i=0;i<c->entries;i++)
  111727. oggpack_write(opb,c->lengthlist[i]-1,5);
  111728. }else{
  111729. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111730. for(i=0;i<c->entries;i++){
  111731. if(c->lengthlist[i]==0){
  111732. oggpack_write(opb,0,1);
  111733. }else{
  111734. oggpack_write(opb,1,1);
  111735. oggpack_write(opb,c->lengthlist[i]-1,5);
  111736. }
  111737. }
  111738. }
  111739. }
  111740. /* is the entry number the desired return value, or do we have a
  111741. mapping? If we have a mapping, what type? */
  111742. oggpack_write(opb,c->maptype,4);
  111743. switch(c->maptype){
  111744. case 0:
  111745. /* no mapping */
  111746. break;
  111747. case 1:case 2:
  111748. /* implicitly populated value mapping */
  111749. /* explicitly populated value mapping */
  111750. if(!c->quantlist){
  111751. /* no quantlist? error */
  111752. return(-1);
  111753. }
  111754. /* values that define the dequantization */
  111755. oggpack_write(opb,c->q_min,32);
  111756. oggpack_write(opb,c->q_delta,32);
  111757. oggpack_write(opb,c->q_quant-1,4);
  111758. oggpack_write(opb,c->q_sequencep,1);
  111759. {
  111760. int quantvals;
  111761. switch(c->maptype){
  111762. case 1:
  111763. /* a single column of (c->entries/c->dim) quantized values for
  111764. building a full value list algorithmically (square lattice) */
  111765. quantvals=_book_maptype1_quantvals(c);
  111766. break;
  111767. case 2:
  111768. /* every value (c->entries*c->dim total) specified explicitly */
  111769. quantvals=c->entries*c->dim;
  111770. break;
  111771. default: /* NOT_REACHABLE */
  111772. quantvals=-1;
  111773. }
  111774. /* quantized values */
  111775. for(i=0;i<quantvals;i++)
  111776. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111777. }
  111778. break;
  111779. default:
  111780. /* error case; we don't have any other map types now */
  111781. return(-1);
  111782. }
  111783. return(0);
  111784. }
  111785. /* unpacks a codebook from the packet buffer into the codebook struct,
  111786. readies the codebook auxiliary structures for decode *************/
  111787. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111788. long i,j;
  111789. memset(s,0,sizeof(*s));
  111790. s->allocedp=1;
  111791. /* make sure alignment is correct */
  111792. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111793. /* first the basic parameters */
  111794. s->dim=oggpack_read(opb,16);
  111795. s->entries=oggpack_read(opb,24);
  111796. if(s->entries==-1)goto _eofout;
  111797. /* codeword ordering.... length ordered or unordered? */
  111798. switch((int)oggpack_read(opb,1)){
  111799. case 0:
  111800. /* unordered */
  111801. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111802. /* allocated but unused entries? */
  111803. if(oggpack_read(opb,1)){
  111804. /* yes, unused entries */
  111805. for(i=0;i<s->entries;i++){
  111806. if(oggpack_read(opb,1)){
  111807. long num=oggpack_read(opb,5);
  111808. if(num==-1)goto _eofout;
  111809. s->lengthlist[i]=num+1;
  111810. }else
  111811. s->lengthlist[i]=0;
  111812. }
  111813. }else{
  111814. /* all entries used; no tagging */
  111815. for(i=0;i<s->entries;i++){
  111816. long num=oggpack_read(opb,5);
  111817. if(num==-1)goto _eofout;
  111818. s->lengthlist[i]=num+1;
  111819. }
  111820. }
  111821. break;
  111822. case 1:
  111823. /* ordered */
  111824. {
  111825. long length=oggpack_read(opb,5)+1;
  111826. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111827. for(i=0;i<s->entries;){
  111828. long num=oggpack_read(opb,_ilog(s->entries-i));
  111829. if(num==-1)goto _eofout;
  111830. for(j=0;j<num && i<s->entries;j++,i++)
  111831. s->lengthlist[i]=length;
  111832. length++;
  111833. }
  111834. }
  111835. break;
  111836. default:
  111837. /* EOF */
  111838. return(-1);
  111839. }
  111840. /* Do we have a mapping to unpack? */
  111841. switch((s->maptype=oggpack_read(opb,4))){
  111842. case 0:
  111843. /* no mapping */
  111844. break;
  111845. case 1: case 2:
  111846. /* implicitly populated value mapping */
  111847. /* explicitly populated value mapping */
  111848. s->q_min=oggpack_read(opb,32);
  111849. s->q_delta=oggpack_read(opb,32);
  111850. s->q_quant=oggpack_read(opb,4)+1;
  111851. s->q_sequencep=oggpack_read(opb,1);
  111852. {
  111853. int quantvals=0;
  111854. switch(s->maptype){
  111855. case 1:
  111856. quantvals=_book_maptype1_quantvals(s);
  111857. break;
  111858. case 2:
  111859. quantvals=s->entries*s->dim;
  111860. break;
  111861. }
  111862. /* quantized values */
  111863. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111864. for(i=0;i<quantvals;i++)
  111865. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111866. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111867. }
  111868. break;
  111869. default:
  111870. goto _errout;
  111871. }
  111872. /* all set */
  111873. return(0);
  111874. _errout:
  111875. _eofout:
  111876. vorbis_staticbook_clear(s);
  111877. return(-1);
  111878. }
  111879. /* returns the number of bits ************************************************/
  111880. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111881. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111882. return(book->c->lengthlist[a]);
  111883. }
  111884. /* One the encode side, our vector writers are each designed for a
  111885. specific purpose, and the encoder is not flexible without modification:
  111886. The LSP vector coder uses a single stage nearest-match with no
  111887. interleave, so no step and no error return. This is specced by floor0
  111888. and doesn't change.
  111889. Residue0 encoding interleaves, uses multiple stages, and each stage
  111890. peels of a specific amount of resolution from a lattice (thus we want
  111891. to match by threshold, not nearest match). Residue doesn't *have* to
  111892. be encoded that way, but to change it, one will need to add more
  111893. infrastructure on the encode side (decode side is specced and simpler) */
  111894. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111895. /* returns entry number and *modifies a* to the quantization value *****/
  111896. int vorbis_book_errorv(codebook *book,float *a){
  111897. int dim=book->dim,k;
  111898. int best=_best(book,a,1);
  111899. for(k=0;k<dim;k++)
  111900. a[k]=(book->valuelist+best*dim)[k];
  111901. return(best);
  111902. }
  111903. /* returns the number of bits and *modifies a* to the quantization value *****/
  111904. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111905. int k,dim=book->dim;
  111906. for(k=0;k<dim;k++)
  111907. a[k]=(book->valuelist+best*dim)[k];
  111908. return(vorbis_book_encode(book,best,b));
  111909. }
  111910. /* the 'eliminate the decode tree' optimization actually requires the
  111911. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111912. (and one of the first places where carefully thought out design
  111913. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111914. to an MSb bitpacker), but not actually the huge hit it appears to
  111915. be. The first-stage decode table catches most words so that
  111916. bitreverse is not in the main execution path. */
  111917. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111918. int read=book->dec_maxlength;
  111919. long lo,hi;
  111920. long lok = oggpack_look(b,book->dec_firsttablen);
  111921. if (lok >= 0) {
  111922. long entry = book->dec_firsttable[lok];
  111923. if(entry&0x80000000UL){
  111924. lo=(entry>>15)&0x7fff;
  111925. hi=book->used_entries-(entry&0x7fff);
  111926. }else{
  111927. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111928. return(entry-1);
  111929. }
  111930. }else{
  111931. lo=0;
  111932. hi=book->used_entries;
  111933. }
  111934. lok = oggpack_look(b, read);
  111935. while(lok<0 && read>1)
  111936. lok = oggpack_look(b, --read);
  111937. if(lok<0)return -1;
  111938. /* bisect search for the codeword in the ordered list */
  111939. {
  111940. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111941. while(hi-lo>1){
  111942. long p=(hi-lo)>>1;
  111943. long test=book->codelist[lo+p]>testword;
  111944. lo+=p&(test-1);
  111945. hi-=p&(-test);
  111946. }
  111947. if(book->dec_codelengths[lo]<=read){
  111948. oggpack_adv(b, book->dec_codelengths[lo]);
  111949. return(lo);
  111950. }
  111951. }
  111952. oggpack_adv(b, read);
  111953. return(-1);
  111954. }
  111955. /* Decode side is specced and easier, because we don't need to find
  111956. matches using different criteria; we simply read and map. There are
  111957. two things we need to do 'depending':
  111958. We may need to support interleave. We don't really, but it's
  111959. convenient to do it here rather than rebuild the vector later.
  111960. Cascades may be additive or multiplicitive; this is not inherent in
  111961. the codebook, but set in the code using the codebook. Like
  111962. interleaving, it's easiest to do it here.
  111963. addmul==0 -> declarative (set the value)
  111964. addmul==1 -> additive
  111965. addmul==2 -> multiplicitive */
  111966. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111967. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111968. long packed_entry=decode_packed_entry_number(book,b);
  111969. if(packed_entry>=0)
  111970. return(book->dec_index[packed_entry]);
  111971. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111972. return(packed_entry);
  111973. }
  111974. /* returns 0 on OK or -1 on eof *************************************/
  111975. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111976. int step=n/book->dim;
  111977. long *entry = (long*)alloca(sizeof(*entry)*step);
  111978. float **t = (float**)alloca(sizeof(*t)*step);
  111979. int i,j,o;
  111980. for (i = 0; i < step; i++) {
  111981. entry[i]=decode_packed_entry_number(book,b);
  111982. if(entry[i]==-1)return(-1);
  111983. t[i] = book->valuelist+entry[i]*book->dim;
  111984. }
  111985. for(i=0,o=0;i<book->dim;i++,o+=step)
  111986. for (j=0;j<step;j++)
  111987. a[o+j]+=t[j][i];
  111988. return(0);
  111989. }
  111990. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111991. int i,j,entry;
  111992. float *t;
  111993. if(book->dim>8){
  111994. for(i=0;i<n;){
  111995. entry = decode_packed_entry_number(book,b);
  111996. if(entry==-1)return(-1);
  111997. t = book->valuelist+entry*book->dim;
  111998. for (j=0;j<book->dim;)
  111999. a[i++]+=t[j++];
  112000. }
  112001. }else{
  112002. for(i=0;i<n;){
  112003. entry = decode_packed_entry_number(book,b);
  112004. if(entry==-1)return(-1);
  112005. t = book->valuelist+entry*book->dim;
  112006. j=0;
  112007. switch((int)book->dim){
  112008. case 8:
  112009. a[i++]+=t[j++];
  112010. case 7:
  112011. a[i++]+=t[j++];
  112012. case 6:
  112013. a[i++]+=t[j++];
  112014. case 5:
  112015. a[i++]+=t[j++];
  112016. case 4:
  112017. a[i++]+=t[j++];
  112018. case 3:
  112019. a[i++]+=t[j++];
  112020. case 2:
  112021. a[i++]+=t[j++];
  112022. case 1:
  112023. a[i++]+=t[j++];
  112024. case 0:
  112025. break;
  112026. }
  112027. }
  112028. }
  112029. return(0);
  112030. }
  112031. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112032. int i,j,entry;
  112033. float *t;
  112034. for(i=0;i<n;){
  112035. entry = decode_packed_entry_number(book,b);
  112036. if(entry==-1)return(-1);
  112037. t = book->valuelist+entry*book->dim;
  112038. for (j=0;j<book->dim;)
  112039. a[i++]=t[j++];
  112040. }
  112041. return(0);
  112042. }
  112043. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112044. oggpack_buffer *b,int n){
  112045. long i,j,entry;
  112046. int chptr=0;
  112047. for(i=offset/ch;i<(offset+n)/ch;){
  112048. entry = decode_packed_entry_number(book,b);
  112049. if(entry==-1)return(-1);
  112050. {
  112051. const float *t = book->valuelist+entry*book->dim;
  112052. for (j=0;j<book->dim;j++){
  112053. a[chptr++][i]+=t[j];
  112054. if(chptr==ch){
  112055. chptr=0;
  112056. i++;
  112057. }
  112058. }
  112059. }
  112060. }
  112061. return(0);
  112062. }
  112063. #ifdef _V_SELFTEST
  112064. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112065. number of vectors through (keeping track of the quantized values),
  112066. and decode using the unpacked book. quantized version of in should
  112067. exactly equal out */
  112068. #include <stdio.h>
  112069. #include "vorbis/book/lsp20_0.vqh"
  112070. #include "vorbis/book/res0a_13.vqh"
  112071. #define TESTSIZE 40
  112072. float test1[TESTSIZE]={
  112073. 0.105939f,
  112074. 0.215373f,
  112075. 0.429117f,
  112076. 0.587974f,
  112077. 0.181173f,
  112078. 0.296583f,
  112079. 0.515707f,
  112080. 0.715261f,
  112081. 0.162327f,
  112082. 0.263834f,
  112083. 0.342876f,
  112084. 0.406025f,
  112085. 0.103571f,
  112086. 0.223561f,
  112087. 0.368513f,
  112088. 0.540313f,
  112089. 0.136672f,
  112090. 0.395882f,
  112091. 0.587183f,
  112092. 0.652476f,
  112093. 0.114338f,
  112094. 0.417300f,
  112095. 0.525486f,
  112096. 0.698679f,
  112097. 0.147492f,
  112098. 0.324481f,
  112099. 0.643089f,
  112100. 0.757582f,
  112101. 0.139556f,
  112102. 0.215795f,
  112103. 0.324559f,
  112104. 0.399387f,
  112105. 0.120236f,
  112106. 0.267420f,
  112107. 0.446940f,
  112108. 0.608760f,
  112109. 0.115587f,
  112110. 0.287234f,
  112111. 0.571081f,
  112112. 0.708603f,
  112113. };
  112114. float test3[TESTSIZE]={
  112115. 0,1,-2,3,4,-5,6,7,8,9,
  112116. 8,-2,7,-1,4,6,8,3,1,-9,
  112117. 10,11,12,13,14,15,26,17,18,19,
  112118. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112119. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112120. &_vq_book_res0a_13,NULL};
  112121. float *testvec[]={test1,test3};
  112122. int main(){
  112123. oggpack_buffer write;
  112124. oggpack_buffer read;
  112125. long ptr=0,i;
  112126. oggpack_writeinit(&write);
  112127. fprintf(stderr,"Testing codebook abstraction...:\n");
  112128. while(testlist[ptr]){
  112129. codebook c;
  112130. static_codebook s;
  112131. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112132. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112133. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112134. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112135. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112136. /* pack the codebook, write the testvector */
  112137. oggpack_reset(&write);
  112138. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112139. we can write */
  112140. vorbis_staticbook_pack(testlist[ptr],&write);
  112141. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112142. for(i=0;i<TESTSIZE;i+=c.dim){
  112143. int best=_best(&c,qv+i,1);
  112144. vorbis_book_encodev(&c,best,qv+i,&write);
  112145. }
  112146. vorbis_book_clear(&c);
  112147. fprintf(stderr,"OK.\n");
  112148. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112149. /* transfer the write data to a read buffer and unpack/read */
  112150. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112151. if(vorbis_staticbook_unpack(&read,&s)){
  112152. fprintf(stderr,"Error unpacking codebook.\n");
  112153. exit(1);
  112154. }
  112155. if(vorbis_book_init_decode(&c,&s)){
  112156. fprintf(stderr,"Error initializing codebook.\n");
  112157. exit(1);
  112158. }
  112159. for(i=0;i<TESTSIZE;i+=c.dim)
  112160. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112161. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112162. exit(1);
  112163. }
  112164. for(i=0;i<TESTSIZE;i++)
  112165. if(fabs(qv[i]-iv[i])>.000001){
  112166. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112167. iv[i],qv[i],i);
  112168. exit(1);
  112169. }
  112170. fprintf(stderr,"OK\n");
  112171. ptr++;
  112172. }
  112173. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112174. exit(0);
  112175. }
  112176. #endif
  112177. #endif
  112178. /*** End of inlined file: codebook.c ***/
  112179. /*** Start of inlined file: envelope.c ***/
  112180. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112181. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112182. // tasks..
  112183. #if JUCE_MSVC
  112184. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112185. #endif
  112186. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112187. #if JUCE_USE_OGGVORBIS
  112188. #include <stdlib.h>
  112189. #include <string.h>
  112190. #include <stdio.h>
  112191. #include <math.h>
  112192. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112193. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112194. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112195. int ch=vi->channels;
  112196. int i,j;
  112197. int n=e->winlength=128;
  112198. e->searchstep=64; /* not random */
  112199. e->minenergy=gi->preecho_minenergy;
  112200. e->ch=ch;
  112201. e->storage=128;
  112202. e->cursor=ci->blocksizes[1]/2;
  112203. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112204. mdct_init(&e->mdct,n);
  112205. for(i=0;i<n;i++){
  112206. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112207. e->mdct_win[i]*=e->mdct_win[i];
  112208. }
  112209. /* magic follows */
  112210. e->band[0].begin=2; e->band[0].end=4;
  112211. e->band[1].begin=4; e->band[1].end=5;
  112212. e->band[2].begin=6; e->band[2].end=6;
  112213. e->band[3].begin=9; e->band[3].end=8;
  112214. e->band[4].begin=13; e->band[4].end=8;
  112215. e->band[5].begin=17; e->band[5].end=8;
  112216. e->band[6].begin=22; e->band[6].end=8;
  112217. for(j=0;j<VE_BANDS;j++){
  112218. n=e->band[j].end;
  112219. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112220. for(i=0;i<n;i++){
  112221. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112222. e->band[j].total+=e->band[j].window[i];
  112223. }
  112224. e->band[j].total=1./e->band[j].total;
  112225. }
  112226. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112227. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112228. }
  112229. void _ve_envelope_clear(envelope_lookup *e){
  112230. int i;
  112231. mdct_clear(&e->mdct);
  112232. for(i=0;i<VE_BANDS;i++)
  112233. _ogg_free(e->band[i].window);
  112234. _ogg_free(e->mdct_win);
  112235. _ogg_free(e->filter);
  112236. _ogg_free(e->mark);
  112237. memset(e,0,sizeof(*e));
  112238. }
  112239. /* fairly straight threshhold-by-band based until we find something
  112240. that works better and isn't patented. */
  112241. static int _ve_amp(envelope_lookup *ve,
  112242. vorbis_info_psy_global *gi,
  112243. float *data,
  112244. envelope_band *bands,
  112245. envelope_filter_state *filters,
  112246. long pos){
  112247. long n=ve->winlength;
  112248. int ret=0;
  112249. long i,j;
  112250. float decay;
  112251. /* we want to have a 'minimum bar' for energy, else we're just
  112252. basing blocks on quantization noise that outweighs the signal
  112253. itself (for low power signals) */
  112254. float minV=ve->minenergy;
  112255. float *vec=(float*) alloca(n*sizeof(*vec));
  112256. /* stretch is used to gradually lengthen the number of windows
  112257. considered prevoius-to-potential-trigger */
  112258. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112259. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112260. if(penalty<0.f)penalty=0.f;
  112261. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112262. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112263. totalshift+pos*ve->searchstep);*/
  112264. /* window and transform */
  112265. for(i=0;i<n;i++)
  112266. vec[i]=data[i]*ve->mdct_win[i];
  112267. mdct_forward(&ve->mdct,vec,vec);
  112268. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112269. /* near-DC spreading function; this has nothing to do with
  112270. psychoacoustics, just sidelobe leakage and window size */
  112271. {
  112272. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112273. int ptr=filters->nearptr;
  112274. /* the accumulation is regularly refreshed from scratch to avoid
  112275. floating point creep */
  112276. if(ptr==0){
  112277. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112278. filters->nearDC_partialacc=temp;
  112279. }else{
  112280. decay=filters->nearDC_acc+=temp;
  112281. filters->nearDC_partialacc+=temp;
  112282. }
  112283. filters->nearDC_acc-=filters->nearDC[ptr];
  112284. filters->nearDC[ptr]=temp;
  112285. decay*=(1./(VE_NEARDC+1));
  112286. filters->nearptr++;
  112287. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112288. decay=todB(&decay)*.5-15.f;
  112289. }
  112290. /* perform spreading and limiting, also smooth the spectrum. yes,
  112291. the MDCT results in all real coefficients, but it still *behaves*
  112292. like real/imaginary pairs */
  112293. for(i=0;i<n/2;i+=2){
  112294. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112295. val=todB(&val)*.5f;
  112296. if(val<decay)val=decay;
  112297. if(val<minV)val=minV;
  112298. vec[i>>1]=val;
  112299. decay-=8.;
  112300. }
  112301. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112302. /* perform preecho/postecho triggering by band */
  112303. for(j=0;j<VE_BANDS;j++){
  112304. float acc=0.;
  112305. float valmax,valmin;
  112306. /* accumulate amplitude */
  112307. for(i=0;i<bands[j].end;i++)
  112308. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112309. acc*=bands[j].total;
  112310. /* convert amplitude to delta */
  112311. {
  112312. int p,thisx=filters[j].ampptr;
  112313. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112314. p=thisx;
  112315. p--;
  112316. if(p<0)p+=VE_AMP;
  112317. postmax=max(acc,filters[j].ampbuf[p]);
  112318. postmin=min(acc,filters[j].ampbuf[p]);
  112319. for(i=0;i<stretch;i++){
  112320. p--;
  112321. if(p<0)p+=VE_AMP;
  112322. premax=max(premax,filters[j].ampbuf[p]);
  112323. premin=min(premin,filters[j].ampbuf[p]);
  112324. }
  112325. valmin=postmin-premin;
  112326. valmax=postmax-premax;
  112327. /*filters[j].markers[pos]=valmax;*/
  112328. filters[j].ampbuf[thisx]=acc;
  112329. filters[j].ampptr++;
  112330. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112331. }
  112332. /* look at min/max, decide trigger */
  112333. if(valmax>gi->preecho_thresh[j]+penalty){
  112334. ret|=1;
  112335. ret|=4;
  112336. }
  112337. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112338. }
  112339. return(ret);
  112340. }
  112341. #if 0
  112342. static int seq=0;
  112343. static ogg_int64_t totalshift=-1024;
  112344. #endif
  112345. long _ve_envelope_search(vorbis_dsp_state *v){
  112346. vorbis_info *vi=v->vi;
  112347. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112348. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112349. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112350. long i,j;
  112351. int first=ve->current/ve->searchstep;
  112352. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112353. if(first<0)first=0;
  112354. /* make sure we have enough storage to match the PCM */
  112355. if(last+VE_WIN+VE_POST>ve->storage){
  112356. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112357. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112358. }
  112359. for(j=first;j<last;j++){
  112360. int ret=0;
  112361. ve->stretch++;
  112362. if(ve->stretch>VE_MAXSTRETCH*2)
  112363. ve->stretch=VE_MAXSTRETCH*2;
  112364. for(i=0;i<ve->ch;i++){
  112365. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112366. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112367. }
  112368. ve->mark[j+VE_POST]=0;
  112369. if(ret&1){
  112370. ve->mark[j]=1;
  112371. ve->mark[j+1]=1;
  112372. }
  112373. if(ret&2){
  112374. ve->mark[j]=1;
  112375. if(j>0)ve->mark[j-1]=1;
  112376. }
  112377. if(ret&4)ve->stretch=-1;
  112378. }
  112379. ve->current=last*ve->searchstep;
  112380. {
  112381. long centerW=v->centerW;
  112382. long testW=
  112383. centerW+
  112384. ci->blocksizes[v->W]/4+
  112385. ci->blocksizes[1]/2+
  112386. ci->blocksizes[0]/4;
  112387. j=ve->cursor;
  112388. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112389. working back one window */
  112390. if(j>=testW)return(1);
  112391. ve->cursor=j;
  112392. if(ve->mark[j/ve->searchstep]){
  112393. if(j>centerW){
  112394. #if 0
  112395. if(j>ve->curmark){
  112396. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112397. int l,m;
  112398. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112399. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112400. seq,
  112401. (totalshift+ve->cursor)/44100.,
  112402. (totalshift+j)/44100.);
  112403. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112404. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112405. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112406. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112407. for(m=0;m<VE_BANDS;m++){
  112408. char buf[80];
  112409. sprintf(buf,"delL%d",m);
  112410. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112411. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112412. }
  112413. for(m=0;m<VE_BANDS;m++){
  112414. char buf[80];
  112415. sprintf(buf,"delR%d",m);
  112416. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112417. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112418. }
  112419. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112420. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112421. seq++;
  112422. }
  112423. #endif
  112424. ve->curmark=j;
  112425. if(j>=testW)return(1);
  112426. return(0);
  112427. }
  112428. }
  112429. j+=ve->searchstep;
  112430. }
  112431. }
  112432. return(-1);
  112433. }
  112434. int _ve_envelope_mark(vorbis_dsp_state *v){
  112435. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112436. vorbis_info *vi=v->vi;
  112437. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112438. long centerW=v->centerW;
  112439. long beginW=centerW-ci->blocksizes[v->W]/4;
  112440. long endW=centerW+ci->blocksizes[v->W]/4;
  112441. if(v->W){
  112442. beginW-=ci->blocksizes[v->lW]/4;
  112443. endW+=ci->blocksizes[v->nW]/4;
  112444. }else{
  112445. beginW-=ci->blocksizes[0]/4;
  112446. endW+=ci->blocksizes[0]/4;
  112447. }
  112448. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112449. {
  112450. long first=beginW/ve->searchstep;
  112451. long last=endW/ve->searchstep;
  112452. long i;
  112453. for(i=first;i<last;i++)
  112454. if(ve->mark[i])return(1);
  112455. }
  112456. return(0);
  112457. }
  112458. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112459. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112460. ahead of ve->current */
  112461. int smallshift=shift/e->searchstep;
  112462. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112463. #if 0
  112464. for(i=0;i<VE_BANDS*e->ch;i++)
  112465. memmove(e->filter[i].markers,
  112466. e->filter[i].markers+smallshift,
  112467. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112468. totalshift+=shift;
  112469. #endif
  112470. e->current-=shift;
  112471. if(e->curmark>=0)
  112472. e->curmark-=shift;
  112473. e->cursor-=shift;
  112474. }
  112475. #endif
  112476. /*** End of inlined file: envelope.c ***/
  112477. /*** Start of inlined file: floor0.c ***/
  112478. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112479. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112480. // tasks..
  112481. #if JUCE_MSVC
  112482. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112483. #endif
  112484. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112485. #if JUCE_USE_OGGVORBIS
  112486. #include <stdlib.h>
  112487. #include <string.h>
  112488. #include <math.h>
  112489. /*** Start of inlined file: lsp.h ***/
  112490. #ifndef _V_LSP_H_
  112491. #define _V_LSP_H_
  112492. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112493. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112494. float *lsp,int m,
  112495. float amp,float ampoffset);
  112496. #endif
  112497. /*** End of inlined file: lsp.h ***/
  112498. #include <stdio.h>
  112499. typedef struct {
  112500. int ln;
  112501. int m;
  112502. int **linearmap;
  112503. int n[2];
  112504. vorbis_info_floor0 *vi;
  112505. long bits;
  112506. long frames;
  112507. } vorbis_look_floor0;
  112508. /***********************************************/
  112509. static void floor0_free_info(vorbis_info_floor *i){
  112510. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112511. if(info){
  112512. memset(info,0,sizeof(*info));
  112513. _ogg_free(info);
  112514. }
  112515. }
  112516. static void floor0_free_look(vorbis_look_floor *i){
  112517. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112518. if(look){
  112519. if(look->linearmap){
  112520. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112521. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112522. _ogg_free(look->linearmap);
  112523. }
  112524. memset(look,0,sizeof(*look));
  112525. _ogg_free(look);
  112526. }
  112527. }
  112528. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112529. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112530. int j;
  112531. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112532. info->order=oggpack_read(opb,8);
  112533. info->rate=oggpack_read(opb,16);
  112534. info->barkmap=oggpack_read(opb,16);
  112535. info->ampbits=oggpack_read(opb,6);
  112536. info->ampdB=oggpack_read(opb,8);
  112537. info->numbooks=oggpack_read(opb,4)+1;
  112538. if(info->order<1)goto err_out;
  112539. if(info->rate<1)goto err_out;
  112540. if(info->barkmap<1)goto err_out;
  112541. if(info->numbooks<1)goto err_out;
  112542. for(j=0;j<info->numbooks;j++){
  112543. info->books[j]=oggpack_read(opb,8);
  112544. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112545. }
  112546. return(info);
  112547. err_out:
  112548. floor0_free_info(info);
  112549. return(NULL);
  112550. }
  112551. /* initialize Bark scale and normalization lookups. We could do this
  112552. with static tables, but Vorbis allows a number of possible
  112553. combinations, so it's best to do it computationally.
  112554. The below is authoritative in terms of defining scale mapping.
  112555. Note that the scale depends on the sampling rate as well as the
  112556. linear block and mapping sizes */
  112557. static void floor0_map_lazy_init(vorbis_block *vb,
  112558. vorbis_info_floor *infoX,
  112559. vorbis_look_floor0 *look){
  112560. if(!look->linearmap[vb->W]){
  112561. vorbis_dsp_state *vd=vb->vd;
  112562. vorbis_info *vi=vd->vi;
  112563. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112564. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112565. int W=vb->W;
  112566. int n=ci->blocksizes[W]/2,j;
  112567. /* we choose a scaling constant so that:
  112568. floor(bark(rate/2-1)*C)=mapped-1
  112569. floor(bark(rate/2)*C)=mapped */
  112570. float scale=look->ln/toBARK(info->rate/2.f);
  112571. /* the mapping from a linear scale to a smaller bark scale is
  112572. straightforward. We do *not* make sure that the linear mapping
  112573. does not skip bark-scale bins; the decoder simply skips them and
  112574. the encoder may do what it wishes in filling them. They're
  112575. necessary in some mapping combinations to keep the scale spacing
  112576. accurate */
  112577. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112578. for(j=0;j<n;j++){
  112579. int val=floor( toBARK((info->rate/2.f)/n*j)
  112580. *scale); /* bark numbers represent band edges */
  112581. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112582. look->linearmap[W][j]=val;
  112583. }
  112584. look->linearmap[W][j]=-1;
  112585. look->n[W]=n;
  112586. }
  112587. }
  112588. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112589. vorbis_info_floor *i){
  112590. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112591. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112592. look->m=info->order;
  112593. look->ln=info->barkmap;
  112594. look->vi=info;
  112595. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112596. return look;
  112597. }
  112598. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112599. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112600. vorbis_info_floor0 *info=look->vi;
  112601. int j,k;
  112602. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112603. if(ampraw>0){ /* also handles the -1 out of data case */
  112604. long maxval=(1<<info->ampbits)-1;
  112605. float amp=(float)ampraw/maxval*info->ampdB;
  112606. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112607. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112608. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112609. codebook *b=ci->fullbooks+info->books[booknum];
  112610. float last=0.f;
  112611. /* the additional b->dim is a guard against any possible stack
  112612. smash; b->dim is provably more than we can overflow the
  112613. vector */
  112614. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112615. for(j=0;j<look->m;j+=b->dim)
  112616. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112617. for(j=0;j<look->m;){
  112618. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112619. last=lsp[j-1];
  112620. }
  112621. lsp[look->m]=amp;
  112622. return(lsp);
  112623. }
  112624. }
  112625. eop:
  112626. return(NULL);
  112627. }
  112628. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112629. void *memo,float *out){
  112630. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112631. vorbis_info_floor0 *info=look->vi;
  112632. floor0_map_lazy_init(vb,info,look);
  112633. if(memo){
  112634. float *lsp=(float *)memo;
  112635. float amp=lsp[look->m];
  112636. /* take the coefficients back to a spectral envelope curve */
  112637. vorbis_lsp_to_curve(out,
  112638. look->linearmap[vb->W],
  112639. look->n[vb->W],
  112640. look->ln,
  112641. lsp,look->m,amp,(float)info->ampdB);
  112642. return(1);
  112643. }
  112644. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112645. return(0);
  112646. }
  112647. /* export hooks */
  112648. vorbis_func_floor floor0_exportbundle={
  112649. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112650. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112651. };
  112652. #endif
  112653. /*** End of inlined file: floor0.c ***/
  112654. /*** Start of inlined file: floor1.c ***/
  112655. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112656. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112657. // tasks..
  112658. #if JUCE_MSVC
  112659. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112660. #endif
  112661. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112662. #if JUCE_USE_OGGVORBIS
  112663. #include <stdlib.h>
  112664. #include <string.h>
  112665. #include <math.h>
  112666. #include <stdio.h>
  112667. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112668. typedef struct {
  112669. int sorted_index[VIF_POSIT+2];
  112670. int forward_index[VIF_POSIT+2];
  112671. int reverse_index[VIF_POSIT+2];
  112672. int hineighbor[VIF_POSIT];
  112673. int loneighbor[VIF_POSIT];
  112674. int posts;
  112675. int n;
  112676. int quant_q;
  112677. vorbis_info_floor1 *vi;
  112678. long phrasebits;
  112679. long postbits;
  112680. long frames;
  112681. } vorbis_look_floor1;
  112682. typedef struct lsfit_acc{
  112683. long x0;
  112684. long x1;
  112685. long xa;
  112686. long ya;
  112687. long x2a;
  112688. long y2a;
  112689. long xya;
  112690. long an;
  112691. } lsfit_acc;
  112692. /***********************************************/
  112693. static void floor1_free_info(vorbis_info_floor *i){
  112694. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112695. if(info){
  112696. memset(info,0,sizeof(*info));
  112697. _ogg_free(info);
  112698. }
  112699. }
  112700. static void floor1_free_look(vorbis_look_floor *i){
  112701. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112702. if(look){
  112703. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112704. (float)look->phrasebits/look->frames,
  112705. (float)look->postbits/look->frames,
  112706. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112707. memset(look,0,sizeof(*look));
  112708. _ogg_free(look);
  112709. }
  112710. }
  112711. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112712. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112713. int j,k;
  112714. int count=0;
  112715. int rangebits;
  112716. int maxposit=info->postlist[1];
  112717. int maxclass=-1;
  112718. /* save out partitions */
  112719. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112720. for(j=0;j<info->partitions;j++){
  112721. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112722. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112723. }
  112724. /* save out partition classes */
  112725. for(j=0;j<maxclass+1;j++){
  112726. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112727. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112728. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112729. for(k=0;k<(1<<info->class_subs[j]);k++)
  112730. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112731. }
  112732. /* save out the post list */
  112733. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112734. oggpack_write(opb,ilog2(maxposit),4);
  112735. rangebits=ilog2(maxposit);
  112736. for(j=0,k=0;j<info->partitions;j++){
  112737. count+=info->class_dim[info->partitionclass[j]];
  112738. for(;k<count;k++)
  112739. oggpack_write(opb,info->postlist[k+2],rangebits);
  112740. }
  112741. }
  112742. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112743. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112744. int j,k,count=0,maxclass=-1,rangebits;
  112745. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112746. /* read partitions */
  112747. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112748. for(j=0;j<info->partitions;j++){
  112749. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112750. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112751. }
  112752. /* read partition classes */
  112753. for(j=0;j<maxclass+1;j++){
  112754. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112755. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112756. if(info->class_subs[j]<0)
  112757. goto err_out;
  112758. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112759. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112760. goto err_out;
  112761. for(k=0;k<(1<<info->class_subs[j]);k++){
  112762. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112763. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112764. goto err_out;
  112765. }
  112766. }
  112767. /* read the post list */
  112768. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112769. rangebits=oggpack_read(opb,4);
  112770. for(j=0,k=0;j<info->partitions;j++){
  112771. count+=info->class_dim[info->partitionclass[j]];
  112772. for(;k<count;k++){
  112773. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112774. if(t<0 || t>=(1<<rangebits))
  112775. goto err_out;
  112776. }
  112777. }
  112778. info->postlist[0]=0;
  112779. info->postlist[1]=1<<rangebits;
  112780. return(info);
  112781. err_out:
  112782. floor1_free_info(info);
  112783. return(NULL);
  112784. }
  112785. static int JUCE_CDECL icomp(const void *a,const void *b){
  112786. return(**(int **)a-**(int **)b);
  112787. }
  112788. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112789. vorbis_info_floor *in){
  112790. int *sortpointer[VIF_POSIT+2];
  112791. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112792. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112793. int i,j,n=0;
  112794. look->vi=info;
  112795. look->n=info->postlist[1];
  112796. /* we drop each position value in-between already decoded values,
  112797. and use linear interpolation to predict each new value past the
  112798. edges. The positions are read in the order of the position
  112799. list... we precompute the bounding positions in the lookup. Of
  112800. course, the neighbors can change (if a position is declined), but
  112801. this is an initial mapping */
  112802. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112803. n+=2;
  112804. look->posts=n;
  112805. /* also store a sorted position index */
  112806. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112807. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112808. /* points from sort order back to range number */
  112809. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112810. /* points from range order to sorted position */
  112811. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112812. /* we actually need the post values too */
  112813. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112814. /* quantize values to multiplier spec */
  112815. switch(info->mult){
  112816. case 1: /* 1024 -> 256 */
  112817. look->quant_q=256;
  112818. break;
  112819. case 2: /* 1024 -> 128 */
  112820. look->quant_q=128;
  112821. break;
  112822. case 3: /* 1024 -> 86 */
  112823. look->quant_q=86;
  112824. break;
  112825. case 4: /* 1024 -> 64 */
  112826. look->quant_q=64;
  112827. break;
  112828. }
  112829. /* discover our neighbors for decode where we don't use fit flags
  112830. (that would push the neighbors outward) */
  112831. for(i=0;i<n-2;i++){
  112832. int lo=0;
  112833. int hi=1;
  112834. int lx=0;
  112835. int hx=look->n;
  112836. int currentx=info->postlist[i+2];
  112837. for(j=0;j<i+2;j++){
  112838. int x=info->postlist[j];
  112839. if(x>lx && x<currentx){
  112840. lo=j;
  112841. lx=x;
  112842. }
  112843. if(x<hx && x>currentx){
  112844. hi=j;
  112845. hx=x;
  112846. }
  112847. }
  112848. look->loneighbor[i]=lo;
  112849. look->hineighbor[i]=hi;
  112850. }
  112851. return(look);
  112852. }
  112853. static int render_point(int x0,int x1,int y0,int y1,int x){
  112854. y0&=0x7fff; /* mask off flag */
  112855. y1&=0x7fff;
  112856. {
  112857. int dy=y1-y0;
  112858. int adx=x1-x0;
  112859. int ady=abs(dy);
  112860. int err=ady*(x-x0);
  112861. int off=err/adx;
  112862. if(dy<0)return(y0-off);
  112863. return(y0+off);
  112864. }
  112865. }
  112866. static int vorbis_dBquant(const float *x){
  112867. int i= *x*7.3142857f+1023.5f;
  112868. if(i>1023)return(1023);
  112869. if(i<0)return(0);
  112870. return i;
  112871. }
  112872. static float FLOOR1_fromdB_LOOKUP[256]={
  112873. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112874. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112875. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112876. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112877. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112878. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112879. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112880. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112881. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112882. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112883. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112884. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112885. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112886. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112887. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112888. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112889. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112890. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112891. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112892. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112893. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112894. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112895. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112896. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112897. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112898. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112899. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112900. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112901. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112902. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112903. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112904. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112905. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112906. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112907. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112908. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112909. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112910. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112911. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112912. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112913. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112914. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112915. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112916. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112917. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112918. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112919. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112920. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112921. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112922. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112923. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112924. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112925. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112926. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112927. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112928. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112929. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112930. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112931. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112932. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112933. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112934. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112935. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112936. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112937. };
  112938. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112939. int dy=y1-y0;
  112940. int adx=x1-x0;
  112941. int ady=abs(dy);
  112942. int base=dy/adx;
  112943. int sy=(dy<0?base-1:base+1);
  112944. int x=x0;
  112945. int y=y0;
  112946. int err=0;
  112947. ady-=abs(base*adx);
  112948. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112949. while(++x<x1){
  112950. err=err+ady;
  112951. if(err>=adx){
  112952. err-=adx;
  112953. y+=sy;
  112954. }else{
  112955. y+=base;
  112956. }
  112957. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112958. }
  112959. }
  112960. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112961. int dy=y1-y0;
  112962. int adx=x1-x0;
  112963. int ady=abs(dy);
  112964. int base=dy/adx;
  112965. int sy=(dy<0?base-1:base+1);
  112966. int x=x0;
  112967. int y=y0;
  112968. int err=0;
  112969. ady-=abs(base*adx);
  112970. d[x]=y;
  112971. while(++x<x1){
  112972. err=err+ady;
  112973. if(err>=adx){
  112974. err-=adx;
  112975. y+=sy;
  112976. }else{
  112977. y+=base;
  112978. }
  112979. d[x]=y;
  112980. }
  112981. }
  112982. /* the floor has already been filtered to only include relevant sections */
  112983. static int accumulate_fit(const float *flr,const float *mdct,
  112984. int x0, int x1,lsfit_acc *a,
  112985. int n,vorbis_info_floor1 *info){
  112986. long i;
  112987. 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;
  112988. memset(a,0,sizeof(*a));
  112989. a->x0=x0;
  112990. a->x1=x1;
  112991. if(x1>=n)x1=n-1;
  112992. for(i=x0;i<=x1;i++){
  112993. int quantized=vorbis_dBquant(flr+i);
  112994. if(quantized){
  112995. if(mdct[i]+info->twofitatten>=flr[i]){
  112996. xa += i;
  112997. ya += quantized;
  112998. x2a += i*i;
  112999. y2a += quantized*quantized;
  113000. xya += i*quantized;
  113001. na++;
  113002. }else{
  113003. xb += i;
  113004. yb += quantized;
  113005. x2b += i*i;
  113006. y2b += quantized*quantized;
  113007. xyb += i*quantized;
  113008. nb++;
  113009. }
  113010. }
  113011. }
  113012. xb+=xa;
  113013. yb+=ya;
  113014. x2b+=x2a;
  113015. y2b+=y2a;
  113016. xyb+=xya;
  113017. nb+=na;
  113018. /* weight toward the actually used frequencies if we meet the threshhold */
  113019. {
  113020. int weight=nb*info->twofitweight/(na+1);
  113021. a->xa=xa*weight+xb;
  113022. a->ya=ya*weight+yb;
  113023. a->x2a=x2a*weight+x2b;
  113024. a->y2a=y2a*weight+y2b;
  113025. a->xya=xya*weight+xyb;
  113026. a->an=na*weight+nb;
  113027. }
  113028. return(na);
  113029. }
  113030. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113031. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113032. long x0=a[0].x0;
  113033. long x1=a[fits-1].x1;
  113034. for(i=0;i<fits;i++){
  113035. x+=a[i].xa;
  113036. y+=a[i].ya;
  113037. x2+=a[i].x2a;
  113038. y2+=a[i].y2a;
  113039. xy+=a[i].xya;
  113040. an+=a[i].an;
  113041. }
  113042. if(*y0>=0){
  113043. x+= x0;
  113044. y+= *y0;
  113045. x2+= x0 * x0;
  113046. y2+= *y0 * *y0;
  113047. xy+= *y0 * x0;
  113048. an++;
  113049. }
  113050. if(*y1>=0){
  113051. x+= x1;
  113052. y+= *y1;
  113053. x2+= x1 * x1;
  113054. y2+= *y1 * *y1;
  113055. xy+= *y1 * x1;
  113056. an++;
  113057. }
  113058. if(an){
  113059. /* need 64 bit multiplies, which C doesn't give portably as int */
  113060. double fx=x;
  113061. double fy=y;
  113062. double fx2=x2;
  113063. double fxy=xy;
  113064. double denom=1./(an*fx2-fx*fx);
  113065. double a=(fy*fx2-fxy*fx)*denom;
  113066. double b=(an*fxy-fx*fy)*denom;
  113067. *y0=rint(a+b*x0);
  113068. *y1=rint(a+b*x1);
  113069. /* limit to our range! */
  113070. if(*y0>1023)*y0=1023;
  113071. if(*y1>1023)*y1=1023;
  113072. if(*y0<0)*y0=0;
  113073. if(*y1<0)*y1=0;
  113074. }else{
  113075. *y0=0;
  113076. *y1=0;
  113077. }
  113078. }
  113079. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113080. long y=0;
  113081. int i;
  113082. for(i=0;i<fits && y==0;i++)
  113083. y+=a[i].ya;
  113084. *y0=*y1=y;
  113085. }*/
  113086. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113087. const float *mdct,
  113088. vorbis_info_floor1 *info){
  113089. int dy=y1-y0;
  113090. int adx=x1-x0;
  113091. int ady=abs(dy);
  113092. int base=dy/adx;
  113093. int sy=(dy<0?base-1:base+1);
  113094. int x=x0;
  113095. int y=y0;
  113096. int err=0;
  113097. int val=vorbis_dBquant(mask+x);
  113098. int mse=0;
  113099. int n=0;
  113100. ady-=abs(base*adx);
  113101. mse=(y-val);
  113102. mse*=mse;
  113103. n++;
  113104. if(mdct[x]+info->twofitatten>=mask[x]){
  113105. if(y+info->maxover<val)return(1);
  113106. if(y-info->maxunder>val)return(1);
  113107. }
  113108. while(++x<x1){
  113109. err=err+ady;
  113110. if(err>=adx){
  113111. err-=adx;
  113112. y+=sy;
  113113. }else{
  113114. y+=base;
  113115. }
  113116. val=vorbis_dBquant(mask+x);
  113117. mse+=((y-val)*(y-val));
  113118. n++;
  113119. if(mdct[x]+info->twofitatten>=mask[x]){
  113120. if(val){
  113121. if(y+info->maxover<val)return(1);
  113122. if(y-info->maxunder>val)return(1);
  113123. }
  113124. }
  113125. }
  113126. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113127. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113128. if(mse/n>info->maxerr)return(1);
  113129. return(0);
  113130. }
  113131. static int post_Y(int *A,int *B,int pos){
  113132. if(A[pos]<0)
  113133. return B[pos];
  113134. if(B[pos]<0)
  113135. return A[pos];
  113136. return (A[pos]+B[pos])>>1;
  113137. }
  113138. int *floor1_fit(vorbis_block *vb,void *look_,
  113139. const float *logmdct, /* in */
  113140. const float *logmask){
  113141. long i,j;
  113142. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113143. vorbis_info_floor1 *info=look->vi;
  113144. long n=look->n;
  113145. long posts=look->posts;
  113146. long nonzero=0;
  113147. lsfit_acc fits[VIF_POSIT+1];
  113148. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113149. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113150. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113151. int hineighbor[VIF_POSIT+2];
  113152. int *output=NULL;
  113153. int memo[VIF_POSIT+2];
  113154. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113155. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113156. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113157. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113158. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113159. /* quantize the relevant floor points and collect them into line fit
  113160. structures (one per minimal division) at the same time */
  113161. if(posts==0){
  113162. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113163. }else{
  113164. for(i=0;i<posts-1;i++)
  113165. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113166. look->sorted_index[i+1],fits+i,
  113167. n,info);
  113168. }
  113169. if(nonzero){
  113170. /* start by fitting the implicit base case.... */
  113171. int y0=-200;
  113172. int y1=-200;
  113173. fit_line(fits,posts-1,&y0,&y1);
  113174. fit_valueA[0]=y0;
  113175. fit_valueB[0]=y0;
  113176. fit_valueB[1]=y1;
  113177. fit_valueA[1]=y1;
  113178. /* Non degenerate case */
  113179. /* start progressive splitting. This is a greedy, non-optimal
  113180. algorithm, but simple and close enough to the best
  113181. answer. */
  113182. for(i=2;i<posts;i++){
  113183. int sortpos=look->reverse_index[i];
  113184. int ln=loneighbor[sortpos];
  113185. int hn=hineighbor[sortpos];
  113186. /* eliminate repeat searches of a particular range with a memo */
  113187. if(memo[ln]!=hn){
  113188. /* haven't performed this error search yet */
  113189. int lsortpos=look->reverse_index[ln];
  113190. int hsortpos=look->reverse_index[hn];
  113191. memo[ln]=hn;
  113192. {
  113193. /* A note: we want to bound/minimize *local*, not global, error */
  113194. int lx=info->postlist[ln];
  113195. int hx=info->postlist[hn];
  113196. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113197. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113198. if(ly==-1 || hy==-1){
  113199. exit(1);
  113200. }
  113201. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113202. /* outside error bounds/begin search area. Split it. */
  113203. int ly0=-200;
  113204. int ly1=-200;
  113205. int hy0=-200;
  113206. int hy1=-200;
  113207. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113208. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113209. /* store new edge values */
  113210. fit_valueB[ln]=ly0;
  113211. if(ln==0)fit_valueA[ln]=ly0;
  113212. fit_valueA[i]=ly1;
  113213. fit_valueB[i]=hy0;
  113214. fit_valueA[hn]=hy1;
  113215. if(hn==1)fit_valueB[hn]=hy1;
  113216. if(ly1>=0 || hy0>=0){
  113217. /* store new neighbor values */
  113218. for(j=sortpos-1;j>=0;j--)
  113219. if(hineighbor[j]==hn)
  113220. hineighbor[j]=i;
  113221. else
  113222. break;
  113223. for(j=sortpos+1;j<posts;j++)
  113224. if(loneighbor[j]==ln)
  113225. loneighbor[j]=i;
  113226. else
  113227. break;
  113228. }
  113229. }else{
  113230. fit_valueA[i]=-200;
  113231. fit_valueB[i]=-200;
  113232. }
  113233. }
  113234. }
  113235. }
  113236. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113237. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113238. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113239. /* fill in posts marked as not using a fit; we will zero
  113240. back out to 'unused' when encoding them so long as curve
  113241. interpolation doesn't force them into use */
  113242. for(i=2;i<posts;i++){
  113243. int ln=look->loneighbor[i-2];
  113244. int hn=look->hineighbor[i-2];
  113245. int x0=info->postlist[ln];
  113246. int x1=info->postlist[hn];
  113247. int y0=output[ln];
  113248. int y1=output[hn];
  113249. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113250. int vx=post_Y(fit_valueA,fit_valueB,i);
  113251. if(vx>=0 && predicted!=vx){
  113252. output[i]=vx;
  113253. }else{
  113254. output[i]= predicted|0x8000;
  113255. }
  113256. }
  113257. }
  113258. return(output);
  113259. }
  113260. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113261. int *A,int *B,
  113262. int del){
  113263. long i;
  113264. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113265. long posts=look->posts;
  113266. int *output=NULL;
  113267. if(A && B){
  113268. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113269. for(i=0;i<posts;i++){
  113270. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113271. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113272. }
  113273. }
  113274. return(output);
  113275. }
  113276. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113277. void*look_,
  113278. int *post,int *ilogmask){
  113279. long i,j;
  113280. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113281. vorbis_info_floor1 *info=look->vi;
  113282. long posts=look->posts;
  113283. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113284. int out[VIF_POSIT+2];
  113285. static_codebook **sbooks=ci->book_param;
  113286. codebook *books=ci->fullbooks;
  113287. static long seq=0;
  113288. /* quantize values to multiplier spec */
  113289. if(post){
  113290. for(i=0;i<posts;i++){
  113291. int val=post[i]&0x7fff;
  113292. switch(info->mult){
  113293. case 1: /* 1024 -> 256 */
  113294. val>>=2;
  113295. break;
  113296. case 2: /* 1024 -> 128 */
  113297. val>>=3;
  113298. break;
  113299. case 3: /* 1024 -> 86 */
  113300. val/=12;
  113301. break;
  113302. case 4: /* 1024 -> 64 */
  113303. val>>=4;
  113304. break;
  113305. }
  113306. post[i]=val | (post[i]&0x8000);
  113307. }
  113308. out[0]=post[0];
  113309. out[1]=post[1];
  113310. /* find prediction values for each post and subtract them */
  113311. for(i=2;i<posts;i++){
  113312. int ln=look->loneighbor[i-2];
  113313. int hn=look->hineighbor[i-2];
  113314. int x0=info->postlist[ln];
  113315. int x1=info->postlist[hn];
  113316. int y0=post[ln];
  113317. int y1=post[hn];
  113318. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113319. if((post[i]&0x8000) || (predicted==post[i])){
  113320. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113321. in interpolation */
  113322. out[i]=0;
  113323. }else{
  113324. int headroom=(look->quant_q-predicted<predicted?
  113325. look->quant_q-predicted:predicted);
  113326. int val=post[i]-predicted;
  113327. /* at this point the 'deviation' value is in the range +/- max
  113328. range, but the real, unique range can always be mapped to
  113329. only [0-maxrange). So we want to wrap the deviation into
  113330. this limited range, but do it in the way that least screws
  113331. an essentially gaussian probability distribution. */
  113332. if(val<0)
  113333. if(val<-headroom)
  113334. val=headroom-val-1;
  113335. else
  113336. val=-1-(val<<1);
  113337. else
  113338. if(val>=headroom)
  113339. val= val+headroom;
  113340. else
  113341. val<<=1;
  113342. out[i]=val;
  113343. post[ln]&=0x7fff;
  113344. post[hn]&=0x7fff;
  113345. }
  113346. }
  113347. /* we have everything we need. pack it out */
  113348. /* mark nontrivial floor */
  113349. oggpack_write(opb,1,1);
  113350. /* beginning/end post */
  113351. look->frames++;
  113352. look->postbits+=ilog(look->quant_q-1)*2;
  113353. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113354. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113355. /* partition by partition */
  113356. for(i=0,j=2;i<info->partitions;i++){
  113357. int classx=info->partitionclass[i];
  113358. int cdim=info->class_dim[classx];
  113359. int csubbits=info->class_subs[classx];
  113360. int csub=1<<csubbits;
  113361. int bookas[8]={0,0,0,0,0,0,0,0};
  113362. int cval=0;
  113363. int cshift=0;
  113364. int k,l;
  113365. /* generate the partition's first stage cascade value */
  113366. if(csubbits){
  113367. int maxval[8];
  113368. for(k=0;k<csub;k++){
  113369. int booknum=info->class_subbook[classx][k];
  113370. if(booknum<0){
  113371. maxval[k]=1;
  113372. }else{
  113373. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113374. }
  113375. }
  113376. for(k=0;k<cdim;k++){
  113377. for(l=0;l<csub;l++){
  113378. int val=out[j+k];
  113379. if(val<maxval[l]){
  113380. bookas[k]=l;
  113381. break;
  113382. }
  113383. }
  113384. cval|= bookas[k]<<cshift;
  113385. cshift+=csubbits;
  113386. }
  113387. /* write it */
  113388. look->phrasebits+=
  113389. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113390. #ifdef TRAIN_FLOOR1
  113391. {
  113392. FILE *of;
  113393. char buffer[80];
  113394. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113395. vb->pcmend/2,posts-2,class);
  113396. of=fopen(buffer,"a");
  113397. fprintf(of,"%d\n",cval);
  113398. fclose(of);
  113399. }
  113400. #endif
  113401. }
  113402. /* write post values */
  113403. for(k=0;k<cdim;k++){
  113404. int book=info->class_subbook[classx][bookas[k]];
  113405. if(book>=0){
  113406. /* hack to allow training with 'bad' books */
  113407. if(out[j+k]<(books+book)->entries)
  113408. look->postbits+=vorbis_book_encode(books+book,
  113409. out[j+k],opb);
  113410. /*else
  113411. fprintf(stderr,"+!");*/
  113412. #ifdef TRAIN_FLOOR1
  113413. {
  113414. FILE *of;
  113415. char buffer[80];
  113416. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113417. vb->pcmend/2,posts-2,class,bookas[k]);
  113418. of=fopen(buffer,"a");
  113419. fprintf(of,"%d\n",out[j+k]);
  113420. fclose(of);
  113421. }
  113422. #endif
  113423. }
  113424. }
  113425. j+=cdim;
  113426. }
  113427. {
  113428. /* generate quantized floor equivalent to what we'd unpack in decode */
  113429. /* render the lines */
  113430. int hx=0;
  113431. int lx=0;
  113432. int ly=post[0]*info->mult;
  113433. for(j=1;j<look->posts;j++){
  113434. int current=look->forward_index[j];
  113435. int hy=post[current]&0x7fff;
  113436. if(hy==post[current]){
  113437. hy*=info->mult;
  113438. hx=info->postlist[current];
  113439. render_line0(lx,hx,ly,hy,ilogmask);
  113440. lx=hx;
  113441. ly=hy;
  113442. }
  113443. }
  113444. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113445. seq++;
  113446. return(1);
  113447. }
  113448. }else{
  113449. oggpack_write(opb,0,1);
  113450. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113451. seq++;
  113452. return(0);
  113453. }
  113454. }
  113455. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113456. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113457. vorbis_info_floor1 *info=look->vi;
  113458. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113459. int i,j,k;
  113460. codebook *books=ci->fullbooks;
  113461. /* unpack wrapped/predicted values from stream */
  113462. if(oggpack_read(&vb->opb,1)==1){
  113463. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113464. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113465. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113466. /* partition by partition */
  113467. for(i=0,j=2;i<info->partitions;i++){
  113468. int classx=info->partitionclass[i];
  113469. int cdim=info->class_dim[classx];
  113470. int csubbits=info->class_subs[classx];
  113471. int csub=1<<csubbits;
  113472. int cval=0;
  113473. /* decode the partition's first stage cascade value */
  113474. if(csubbits){
  113475. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113476. if(cval==-1)goto eop;
  113477. }
  113478. for(k=0;k<cdim;k++){
  113479. int book=info->class_subbook[classx][cval&(csub-1)];
  113480. cval>>=csubbits;
  113481. if(book>=0){
  113482. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113483. goto eop;
  113484. }else{
  113485. fit_value[j+k]=0;
  113486. }
  113487. }
  113488. j+=cdim;
  113489. }
  113490. /* unwrap positive values and reconsitute via linear interpolation */
  113491. for(i=2;i<look->posts;i++){
  113492. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113493. info->postlist[look->hineighbor[i-2]],
  113494. fit_value[look->loneighbor[i-2]],
  113495. fit_value[look->hineighbor[i-2]],
  113496. info->postlist[i]);
  113497. int hiroom=look->quant_q-predicted;
  113498. int loroom=predicted;
  113499. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113500. int val=fit_value[i];
  113501. if(val){
  113502. if(val>=room){
  113503. if(hiroom>loroom){
  113504. val = val-loroom;
  113505. }else{
  113506. val = -1-(val-hiroom);
  113507. }
  113508. }else{
  113509. if(val&1){
  113510. val= -((val+1)>>1);
  113511. }else{
  113512. val>>=1;
  113513. }
  113514. }
  113515. fit_value[i]=val+predicted;
  113516. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113517. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113518. }else{
  113519. fit_value[i]=predicted|0x8000;
  113520. }
  113521. }
  113522. return(fit_value);
  113523. }
  113524. eop:
  113525. return(NULL);
  113526. }
  113527. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113528. float *out){
  113529. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113530. vorbis_info_floor1 *info=look->vi;
  113531. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113532. int n=ci->blocksizes[vb->W]/2;
  113533. int j;
  113534. if(memo){
  113535. /* render the lines */
  113536. int *fit_value=(int *)memo;
  113537. int hx=0;
  113538. int lx=0;
  113539. int ly=fit_value[0]*info->mult;
  113540. for(j=1;j<look->posts;j++){
  113541. int current=look->forward_index[j];
  113542. int hy=fit_value[current]&0x7fff;
  113543. if(hy==fit_value[current]){
  113544. hy*=info->mult;
  113545. hx=info->postlist[current];
  113546. render_line(lx,hx,ly,hy,out);
  113547. lx=hx;
  113548. ly=hy;
  113549. }
  113550. }
  113551. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113552. return(1);
  113553. }
  113554. memset(out,0,sizeof(*out)*n);
  113555. return(0);
  113556. }
  113557. /* export hooks */
  113558. vorbis_func_floor floor1_exportbundle={
  113559. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113560. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113561. };
  113562. #endif
  113563. /*** End of inlined file: floor1.c ***/
  113564. /*** Start of inlined file: info.c ***/
  113565. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113566. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113567. // tasks..
  113568. #if JUCE_MSVC
  113569. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113570. #endif
  113571. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113572. #if JUCE_USE_OGGVORBIS
  113573. /* general handling of the header and the vorbis_info structure (and
  113574. substructures) */
  113575. #include <stdlib.h>
  113576. #include <string.h>
  113577. #include <ctype.h>
  113578. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113579. while(bytes--){
  113580. oggpack_write(o,*s++,8);
  113581. }
  113582. }
  113583. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113584. while(bytes--){
  113585. *buf++=oggpack_read(o,8);
  113586. }
  113587. }
  113588. void vorbis_comment_init(vorbis_comment *vc){
  113589. memset(vc,0,sizeof(*vc));
  113590. }
  113591. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113592. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113593. (vc->comments+2)*sizeof(*vc->user_comments));
  113594. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113595. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113596. vc->comment_lengths[vc->comments]=strlen(comment);
  113597. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113598. strcpy(vc->user_comments[vc->comments], comment);
  113599. vc->comments++;
  113600. vc->user_comments[vc->comments]=NULL;
  113601. }
  113602. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113603. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113604. strcpy(comment, tag);
  113605. strcat(comment, "=");
  113606. strcat(comment, contents);
  113607. vorbis_comment_add(vc, comment);
  113608. }
  113609. /* This is more or less the same as strncasecmp - but that doesn't exist
  113610. * everywhere, and this is a fairly trivial function, so we include it */
  113611. static int tagcompare(const char *s1, const char *s2, int n){
  113612. int c=0;
  113613. while(c < n){
  113614. if(toupper(s1[c]) != toupper(s2[c]))
  113615. return !0;
  113616. c++;
  113617. }
  113618. return 0;
  113619. }
  113620. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113621. long i;
  113622. int found = 0;
  113623. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113624. char *fulltag = (char*)alloca(taglen+ 1);
  113625. strcpy(fulltag, tag);
  113626. strcat(fulltag, "=");
  113627. for(i=0;i<vc->comments;i++){
  113628. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113629. if(count == found)
  113630. /* We return a pointer to the data, not a copy */
  113631. return vc->user_comments[i] + taglen;
  113632. else
  113633. found++;
  113634. }
  113635. }
  113636. return NULL; /* didn't find anything */
  113637. }
  113638. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113639. int i,count=0;
  113640. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113641. char *fulltag = (char*)alloca(taglen+1);
  113642. strcpy(fulltag,tag);
  113643. strcat(fulltag, "=");
  113644. for(i=0;i<vc->comments;i++){
  113645. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113646. count++;
  113647. }
  113648. return count;
  113649. }
  113650. void vorbis_comment_clear(vorbis_comment *vc){
  113651. if(vc){
  113652. long i;
  113653. for(i=0;i<vc->comments;i++)
  113654. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113655. if(vc->user_comments)_ogg_free(vc->user_comments);
  113656. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113657. if(vc->vendor)_ogg_free(vc->vendor);
  113658. }
  113659. memset(vc,0,sizeof(*vc));
  113660. }
  113661. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113662. They may be equal, but short will never ge greater than long */
  113663. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113664. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113665. return ci ? ci->blocksizes[zo] : -1;
  113666. }
  113667. /* used by synthesis, which has a full, alloced vi */
  113668. void vorbis_info_init(vorbis_info *vi){
  113669. memset(vi,0,sizeof(*vi));
  113670. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113671. }
  113672. void vorbis_info_clear(vorbis_info *vi){
  113673. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113674. int i;
  113675. if(ci){
  113676. for(i=0;i<ci->modes;i++)
  113677. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113678. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113679. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113680. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113681. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113682. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113683. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113684. for(i=0;i<ci->books;i++){
  113685. if(ci->book_param[i]){
  113686. /* knows if the book was not alloced */
  113687. vorbis_staticbook_destroy(ci->book_param[i]);
  113688. }
  113689. if(ci->fullbooks)
  113690. vorbis_book_clear(ci->fullbooks+i);
  113691. }
  113692. if(ci->fullbooks)
  113693. _ogg_free(ci->fullbooks);
  113694. for(i=0;i<ci->psys;i++)
  113695. _vi_psy_free(ci->psy_param[i]);
  113696. _ogg_free(ci);
  113697. }
  113698. memset(vi,0,sizeof(*vi));
  113699. }
  113700. /* Header packing/unpacking ********************************************/
  113701. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113702. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113703. if(!ci)return(OV_EFAULT);
  113704. vi->version=oggpack_read(opb,32);
  113705. if(vi->version!=0)return(OV_EVERSION);
  113706. vi->channels=oggpack_read(opb,8);
  113707. vi->rate=oggpack_read(opb,32);
  113708. vi->bitrate_upper=oggpack_read(opb,32);
  113709. vi->bitrate_nominal=oggpack_read(opb,32);
  113710. vi->bitrate_lower=oggpack_read(opb,32);
  113711. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113712. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113713. if(vi->rate<1)goto err_out;
  113714. if(vi->channels<1)goto err_out;
  113715. if(ci->blocksizes[0]<8)goto err_out;
  113716. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113717. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113718. return(0);
  113719. err_out:
  113720. vorbis_info_clear(vi);
  113721. return(OV_EBADHEADER);
  113722. }
  113723. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113724. int i;
  113725. int vendorlen=oggpack_read(opb,32);
  113726. if(vendorlen<0)goto err_out;
  113727. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113728. _v_readstring(opb,vc->vendor,vendorlen);
  113729. vc->comments=oggpack_read(opb,32);
  113730. if(vc->comments<0)goto err_out;
  113731. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113732. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113733. for(i=0;i<vc->comments;i++){
  113734. int len=oggpack_read(opb,32);
  113735. if(len<0)goto err_out;
  113736. vc->comment_lengths[i]=len;
  113737. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113738. _v_readstring(opb,vc->user_comments[i],len);
  113739. }
  113740. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113741. return(0);
  113742. err_out:
  113743. vorbis_comment_clear(vc);
  113744. return(OV_EBADHEADER);
  113745. }
  113746. /* all of the real encoding details are here. The modes, books,
  113747. everything */
  113748. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113749. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113750. int i;
  113751. if(!ci)return(OV_EFAULT);
  113752. /* codebooks */
  113753. ci->books=oggpack_read(opb,8)+1;
  113754. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113755. for(i=0;i<ci->books;i++){
  113756. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113757. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113758. }
  113759. /* time backend settings; hooks are unused */
  113760. {
  113761. int times=oggpack_read(opb,6)+1;
  113762. for(i=0;i<times;i++){
  113763. int test=oggpack_read(opb,16);
  113764. if(test<0 || test>=VI_TIMEB)goto err_out;
  113765. }
  113766. }
  113767. /* floor backend settings */
  113768. ci->floors=oggpack_read(opb,6)+1;
  113769. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113770. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113771. for(i=0;i<ci->floors;i++){
  113772. ci->floor_type[i]=oggpack_read(opb,16);
  113773. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113774. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113775. if(!ci->floor_param[i])goto err_out;
  113776. }
  113777. /* residue backend settings */
  113778. ci->residues=oggpack_read(opb,6)+1;
  113779. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113780. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113781. for(i=0;i<ci->residues;i++){
  113782. ci->residue_type[i]=oggpack_read(opb,16);
  113783. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113784. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113785. if(!ci->residue_param[i])goto err_out;
  113786. }
  113787. /* map backend settings */
  113788. ci->maps=oggpack_read(opb,6)+1;
  113789. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113790. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113791. for(i=0;i<ci->maps;i++){
  113792. ci->map_type[i]=oggpack_read(opb,16);
  113793. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113794. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113795. if(!ci->map_param[i])goto err_out;
  113796. }
  113797. /* mode settings */
  113798. ci->modes=oggpack_read(opb,6)+1;
  113799. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113800. for(i=0;i<ci->modes;i++){
  113801. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113802. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113803. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113804. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113805. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113806. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113807. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113808. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113809. }
  113810. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113811. return(0);
  113812. err_out:
  113813. vorbis_info_clear(vi);
  113814. return(OV_EBADHEADER);
  113815. }
  113816. /* The Vorbis header is in three packets; the initial small packet in
  113817. the first page that identifies basic parameters, a second packet
  113818. with bitstream comments and a third packet that holds the
  113819. codebook. */
  113820. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113821. oggpack_buffer opb;
  113822. if(op){
  113823. oggpack_readinit(&opb,op->packet,op->bytes);
  113824. /* Which of the three types of header is this? */
  113825. /* Also verify header-ness, vorbis */
  113826. {
  113827. char buffer[6];
  113828. int packtype=oggpack_read(&opb,8);
  113829. memset(buffer,0,6);
  113830. _v_readstring(&opb,buffer,6);
  113831. if(memcmp(buffer,"vorbis",6)){
  113832. /* not a vorbis header */
  113833. return(OV_ENOTVORBIS);
  113834. }
  113835. switch(packtype){
  113836. case 0x01: /* least significant *bit* is read first */
  113837. if(!op->b_o_s){
  113838. /* Not the initial packet */
  113839. return(OV_EBADHEADER);
  113840. }
  113841. if(vi->rate!=0){
  113842. /* previously initialized info header */
  113843. return(OV_EBADHEADER);
  113844. }
  113845. return(_vorbis_unpack_info(vi,&opb));
  113846. case 0x03: /* least significant *bit* is read first */
  113847. if(vi->rate==0){
  113848. /* um... we didn't get the initial header */
  113849. return(OV_EBADHEADER);
  113850. }
  113851. return(_vorbis_unpack_comment(vc,&opb));
  113852. case 0x05: /* least significant *bit* is read first */
  113853. if(vi->rate==0 || vc->vendor==NULL){
  113854. /* um... we didn;t get the initial header or comments yet */
  113855. return(OV_EBADHEADER);
  113856. }
  113857. return(_vorbis_unpack_books(vi,&opb));
  113858. default:
  113859. /* Not a valid vorbis header type */
  113860. return(OV_EBADHEADER);
  113861. break;
  113862. }
  113863. }
  113864. }
  113865. return(OV_EBADHEADER);
  113866. }
  113867. /* pack side **********************************************************/
  113868. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113869. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113870. if(!ci)return(OV_EFAULT);
  113871. /* preamble */
  113872. oggpack_write(opb,0x01,8);
  113873. _v_writestring(opb,"vorbis", 6);
  113874. /* basic information about the stream */
  113875. oggpack_write(opb,0x00,32);
  113876. oggpack_write(opb,vi->channels,8);
  113877. oggpack_write(opb,vi->rate,32);
  113878. oggpack_write(opb,vi->bitrate_upper,32);
  113879. oggpack_write(opb,vi->bitrate_nominal,32);
  113880. oggpack_write(opb,vi->bitrate_lower,32);
  113881. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113882. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113883. oggpack_write(opb,1,1);
  113884. return(0);
  113885. }
  113886. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113887. char temp[]="Xiph.Org libVorbis I 20050304";
  113888. int bytes = strlen(temp);
  113889. /* preamble */
  113890. oggpack_write(opb,0x03,8);
  113891. _v_writestring(opb,"vorbis", 6);
  113892. /* vendor */
  113893. oggpack_write(opb,bytes,32);
  113894. _v_writestring(opb,temp, bytes);
  113895. /* comments */
  113896. oggpack_write(opb,vc->comments,32);
  113897. if(vc->comments){
  113898. int i;
  113899. for(i=0;i<vc->comments;i++){
  113900. if(vc->user_comments[i]){
  113901. oggpack_write(opb,vc->comment_lengths[i],32);
  113902. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113903. }else{
  113904. oggpack_write(opb,0,32);
  113905. }
  113906. }
  113907. }
  113908. oggpack_write(opb,1,1);
  113909. return(0);
  113910. }
  113911. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113912. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113913. int i;
  113914. if(!ci)return(OV_EFAULT);
  113915. oggpack_write(opb,0x05,8);
  113916. _v_writestring(opb,"vorbis", 6);
  113917. /* books */
  113918. oggpack_write(opb,ci->books-1,8);
  113919. for(i=0;i<ci->books;i++)
  113920. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113921. /* times; hook placeholders */
  113922. oggpack_write(opb,0,6);
  113923. oggpack_write(opb,0,16);
  113924. /* floors */
  113925. oggpack_write(opb,ci->floors-1,6);
  113926. for(i=0;i<ci->floors;i++){
  113927. oggpack_write(opb,ci->floor_type[i],16);
  113928. if(_floor_P[ci->floor_type[i]]->pack)
  113929. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113930. else
  113931. goto err_out;
  113932. }
  113933. /* residues */
  113934. oggpack_write(opb,ci->residues-1,6);
  113935. for(i=0;i<ci->residues;i++){
  113936. oggpack_write(opb,ci->residue_type[i],16);
  113937. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113938. }
  113939. /* maps */
  113940. oggpack_write(opb,ci->maps-1,6);
  113941. for(i=0;i<ci->maps;i++){
  113942. oggpack_write(opb,ci->map_type[i],16);
  113943. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113944. }
  113945. /* modes */
  113946. oggpack_write(opb,ci->modes-1,6);
  113947. for(i=0;i<ci->modes;i++){
  113948. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113949. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113950. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113951. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113952. }
  113953. oggpack_write(opb,1,1);
  113954. return(0);
  113955. err_out:
  113956. return(-1);
  113957. }
  113958. int vorbis_commentheader_out(vorbis_comment *vc,
  113959. ogg_packet *op){
  113960. oggpack_buffer opb;
  113961. oggpack_writeinit(&opb);
  113962. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113963. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113964. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113965. op->bytes=oggpack_bytes(&opb);
  113966. op->b_o_s=0;
  113967. op->e_o_s=0;
  113968. op->granulepos=0;
  113969. op->packetno=1;
  113970. return 0;
  113971. }
  113972. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113973. vorbis_comment *vc,
  113974. ogg_packet *op,
  113975. ogg_packet *op_comm,
  113976. ogg_packet *op_code){
  113977. int ret=OV_EIMPL;
  113978. vorbis_info *vi=v->vi;
  113979. oggpack_buffer opb;
  113980. private_state *b=(private_state*)v->backend_state;
  113981. if(!b){
  113982. ret=OV_EFAULT;
  113983. goto err_out;
  113984. }
  113985. /* first header packet **********************************************/
  113986. oggpack_writeinit(&opb);
  113987. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113988. /* build the packet */
  113989. if(b->header)_ogg_free(b->header);
  113990. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113991. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113992. op->packet=b->header;
  113993. op->bytes=oggpack_bytes(&opb);
  113994. op->b_o_s=1;
  113995. op->e_o_s=0;
  113996. op->granulepos=0;
  113997. op->packetno=0;
  113998. /* second header packet (comments) **********************************/
  113999. oggpack_reset(&opb);
  114000. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114001. if(b->header1)_ogg_free(b->header1);
  114002. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114003. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114004. op_comm->packet=b->header1;
  114005. op_comm->bytes=oggpack_bytes(&opb);
  114006. op_comm->b_o_s=0;
  114007. op_comm->e_o_s=0;
  114008. op_comm->granulepos=0;
  114009. op_comm->packetno=1;
  114010. /* third header packet (modes/codebooks) ****************************/
  114011. oggpack_reset(&opb);
  114012. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114013. if(b->header2)_ogg_free(b->header2);
  114014. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114015. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114016. op_code->packet=b->header2;
  114017. op_code->bytes=oggpack_bytes(&opb);
  114018. op_code->b_o_s=0;
  114019. op_code->e_o_s=0;
  114020. op_code->granulepos=0;
  114021. op_code->packetno=2;
  114022. oggpack_writeclear(&opb);
  114023. return(0);
  114024. err_out:
  114025. oggpack_writeclear(&opb);
  114026. memset(op,0,sizeof(*op));
  114027. memset(op_comm,0,sizeof(*op_comm));
  114028. memset(op_code,0,sizeof(*op_code));
  114029. if(b->header)_ogg_free(b->header);
  114030. if(b->header1)_ogg_free(b->header1);
  114031. if(b->header2)_ogg_free(b->header2);
  114032. b->header=NULL;
  114033. b->header1=NULL;
  114034. b->header2=NULL;
  114035. return(ret);
  114036. }
  114037. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114038. if(granulepos>=0)
  114039. return((double)granulepos/v->vi->rate);
  114040. return(-1);
  114041. }
  114042. #endif
  114043. /*** End of inlined file: info.c ***/
  114044. /*** Start of inlined file: lpc.c ***/
  114045. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114046. are derived from code written by Jutta Degener and Carsten Bormann;
  114047. thus we include their copyright below. The entirety of this file
  114048. is freely redistributable on the condition that both of these
  114049. copyright notices are preserved without modification. */
  114050. /* Preserved Copyright: *********************************************/
  114051. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114052. Technische Universita"t Berlin
  114053. Any use of this software is permitted provided that this notice is not
  114054. removed and that neither the authors nor the Technische Universita"t
  114055. Berlin are deemed to have made any representations as to the
  114056. suitability of this software for any purpose nor are held responsible
  114057. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114058. THIS SOFTWARE.
  114059. As a matter of courtesy, the authors request to be informed about uses
  114060. this software has found, about bugs in this software, and about any
  114061. improvements that may be of general interest.
  114062. Berlin, 28.11.1994
  114063. Jutta Degener
  114064. Carsten Bormann
  114065. *********************************************************************/
  114066. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114067. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114068. // tasks..
  114069. #if JUCE_MSVC
  114070. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114071. #endif
  114072. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114073. #if JUCE_USE_OGGVORBIS
  114074. #include <stdlib.h>
  114075. #include <string.h>
  114076. #include <math.h>
  114077. /* Autocorrelation LPC coeff generation algorithm invented by
  114078. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114079. /* Input : n elements of time doamin data
  114080. Output: m lpc coefficients, excitation energy */
  114081. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114082. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114083. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114084. double error;
  114085. int i,j;
  114086. /* autocorrelation, p+1 lag coefficients */
  114087. j=m+1;
  114088. while(j--){
  114089. double d=0; /* double needed for accumulator depth */
  114090. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114091. aut[j]=d;
  114092. }
  114093. /* Generate lpc coefficients from autocorr values */
  114094. error=aut[0];
  114095. for(i=0;i<m;i++){
  114096. double r= -aut[i+1];
  114097. if(error==0){
  114098. memset(lpci,0,m*sizeof(*lpci));
  114099. return 0;
  114100. }
  114101. /* Sum up this iteration's reflection coefficient; note that in
  114102. Vorbis we don't save it. If anyone wants to recycle this code
  114103. and needs reflection coefficients, save the results of 'r' from
  114104. each iteration. */
  114105. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114106. r/=error;
  114107. /* Update LPC coefficients and total error */
  114108. lpc[i]=r;
  114109. for(j=0;j<i/2;j++){
  114110. double tmp=lpc[j];
  114111. lpc[j]+=r*lpc[i-1-j];
  114112. lpc[i-1-j]+=r*tmp;
  114113. }
  114114. if(i%2)lpc[j]+=lpc[j]*r;
  114115. error*=1.f-r*r;
  114116. }
  114117. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114118. /* we need the error value to know how big an impulse to hit the
  114119. filter with later */
  114120. return error;
  114121. }
  114122. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114123. float *data,long n){
  114124. /* in: coeff[0...m-1] LPC coefficients
  114125. prime[0...m-1] initial values (allocated size of n+m-1)
  114126. out: data[0...n-1] data samples */
  114127. long i,j,o,p;
  114128. float y;
  114129. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114130. if(!prime)
  114131. for(i=0;i<m;i++)
  114132. work[i]=0.f;
  114133. else
  114134. for(i=0;i<m;i++)
  114135. work[i]=prime[i];
  114136. for(i=0;i<n;i++){
  114137. y=0;
  114138. o=i;
  114139. p=m;
  114140. for(j=0;j<m;j++)
  114141. y-=work[o++]*coeff[--p];
  114142. data[i]=work[o]=y;
  114143. }
  114144. }
  114145. #endif
  114146. /*** End of inlined file: lpc.c ***/
  114147. /*** Start of inlined file: lsp.c ***/
  114148. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114149. an iterative root polisher (CACM algorithm 283). It *is* possible
  114150. to confuse this algorithm into not converging; that should only
  114151. happen with absurdly closely spaced roots (very sharp peaks in the
  114152. LPC f response) which in turn should be impossible in our use of
  114153. the code. If this *does* happen anyway, it's a bug in the floor
  114154. finder; find the cause of the confusion (probably a single bin
  114155. spike or accidental near-float-limit resolution problems) and
  114156. correct it. */
  114157. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114158. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114159. // tasks..
  114160. #if JUCE_MSVC
  114161. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114162. #endif
  114163. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114164. #if JUCE_USE_OGGVORBIS
  114165. #include <math.h>
  114166. #include <string.h>
  114167. #include <stdlib.h>
  114168. /*** Start of inlined file: lookup.h ***/
  114169. #ifndef _V_LOOKUP_H_
  114170. #ifdef FLOAT_LOOKUP
  114171. extern float vorbis_coslook(float a);
  114172. extern float vorbis_invsqlook(float a);
  114173. extern float vorbis_invsq2explook(int a);
  114174. extern float vorbis_fromdBlook(float a);
  114175. #endif
  114176. #ifdef INT_LOOKUP
  114177. extern long vorbis_invsqlook_i(long a,long e);
  114178. extern long vorbis_coslook_i(long a);
  114179. extern float vorbis_fromdBlook_i(long a);
  114180. #endif
  114181. #endif
  114182. /*** End of inlined file: lookup.h ***/
  114183. /* three possible LSP to f curve functions; the exact computation
  114184. (float), a lookup based float implementation, and an integer
  114185. implementation. The float lookup is likely the optimal choice on
  114186. any machine with an FPU. The integer implementation is *not* fixed
  114187. point (due to the need for a large dynamic range and thus a
  114188. seperately tracked exponent) and thus much more complex than the
  114189. relatively simple float implementations. It's mostly for future
  114190. work on a fully fixed point implementation for processors like the
  114191. ARM family. */
  114192. /* undefine both for the 'old' but more precise implementation */
  114193. #define FLOAT_LOOKUP
  114194. #undef INT_LOOKUP
  114195. #ifdef FLOAT_LOOKUP
  114196. /*** Start of inlined file: lookup.c ***/
  114197. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114198. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114199. // tasks..
  114200. #if JUCE_MSVC
  114201. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114202. #endif
  114203. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114204. #if JUCE_USE_OGGVORBIS
  114205. #include <math.h>
  114206. /*** Start of inlined file: lookup.h ***/
  114207. #ifndef _V_LOOKUP_H_
  114208. #ifdef FLOAT_LOOKUP
  114209. extern float vorbis_coslook(float a);
  114210. extern float vorbis_invsqlook(float a);
  114211. extern float vorbis_invsq2explook(int a);
  114212. extern float vorbis_fromdBlook(float a);
  114213. #endif
  114214. #ifdef INT_LOOKUP
  114215. extern long vorbis_invsqlook_i(long a,long e);
  114216. extern long vorbis_coslook_i(long a);
  114217. extern float vorbis_fromdBlook_i(long a);
  114218. #endif
  114219. #endif
  114220. /*** End of inlined file: lookup.h ***/
  114221. /*** Start of inlined file: lookup_data.h ***/
  114222. #ifndef _V_LOOKUP_DATA_H_
  114223. #ifdef FLOAT_LOOKUP
  114224. #define COS_LOOKUP_SZ 128
  114225. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114226. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114227. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114228. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114229. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114230. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114231. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114232. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114233. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114234. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114235. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114236. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114237. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114238. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114239. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114240. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114241. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114242. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114243. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114244. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114245. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114246. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114247. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114248. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114249. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114250. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114251. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114252. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114253. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114254. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114255. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114256. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114257. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114258. -1.0000000000000f,
  114259. };
  114260. #define INVSQ_LOOKUP_SZ 32
  114261. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114262. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114263. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114264. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114265. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114266. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114267. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114268. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114269. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114270. 1.000000000000f,
  114271. };
  114272. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114273. #define INVSQ2EXP_LOOKUP_MAX 32
  114274. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114275. INVSQ2EXP_LOOKUP_MIN+1]={
  114276. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114277. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114278. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114279. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114280. 256.f, 181.019336f, 128.f, 90.50966799f,
  114281. 64.f, 45.254834f, 32.f, 22.627417f,
  114282. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114283. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114284. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114285. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114286. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114287. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114288. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114289. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114290. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114291. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114292. 1.525878906e-05f,
  114293. };
  114294. #endif
  114295. #define FROMdB_LOOKUP_SZ 35
  114296. #define FROMdB2_LOOKUP_SZ 32
  114297. #define FROMdB_SHIFT 5
  114298. #define FROMdB2_SHIFT 3
  114299. #define FROMdB2_MASK 31
  114300. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114301. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114302. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114303. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114304. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114305. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114306. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114307. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114308. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114309. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114310. };
  114311. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114312. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114313. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114314. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114315. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114316. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114317. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114318. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114319. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114320. };
  114321. #ifdef INT_LOOKUP
  114322. #define INVSQ_LOOKUP_I_SHIFT 10
  114323. #define INVSQ_LOOKUP_I_MASK 1023
  114324. static long INVSQ_LOOKUP_I[64+1]={
  114325. 92682l, 91966l, 91267l, 90583l,
  114326. 89915l, 89261l, 88621l, 87995l,
  114327. 87381l, 86781l, 86192l, 85616l,
  114328. 85051l, 84497l, 83953l, 83420l,
  114329. 82897l, 82384l, 81880l, 81385l,
  114330. 80899l, 80422l, 79953l, 79492l,
  114331. 79039l, 78594l, 78156l, 77726l,
  114332. 77302l, 76885l, 76475l, 76072l,
  114333. 75674l, 75283l, 74898l, 74519l,
  114334. 74146l, 73778l, 73415l, 73058l,
  114335. 72706l, 72359l, 72016l, 71679l,
  114336. 71347l, 71019l, 70695l, 70376l,
  114337. 70061l, 69750l, 69444l, 69141l,
  114338. 68842l, 68548l, 68256l, 67969l,
  114339. 67685l, 67405l, 67128l, 66855l,
  114340. 66585l, 66318l, 66054l, 65794l,
  114341. 65536l,
  114342. };
  114343. #define COS_LOOKUP_I_SHIFT 9
  114344. #define COS_LOOKUP_I_MASK 511
  114345. #define COS_LOOKUP_I_SZ 128
  114346. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114347. 16384l, 16379l, 16364l, 16340l,
  114348. 16305l, 16261l, 16207l, 16143l,
  114349. 16069l, 15986l, 15893l, 15791l,
  114350. 15679l, 15557l, 15426l, 15286l,
  114351. 15137l, 14978l, 14811l, 14635l,
  114352. 14449l, 14256l, 14053l, 13842l,
  114353. 13623l, 13395l, 13160l, 12916l,
  114354. 12665l, 12406l, 12140l, 11866l,
  114355. 11585l, 11297l, 11003l, 10702l,
  114356. 10394l, 10080l, 9760l, 9434l,
  114357. 9102l, 8765l, 8423l, 8076l,
  114358. 7723l, 7366l, 7005l, 6639l,
  114359. 6270l, 5897l, 5520l, 5139l,
  114360. 4756l, 4370l, 3981l, 3590l,
  114361. 3196l, 2801l, 2404l, 2006l,
  114362. 1606l, 1205l, 804l, 402l,
  114363. 0l, -401l, -803l, -1204l,
  114364. -1605l, -2005l, -2403l, -2800l,
  114365. -3195l, -3589l, -3980l, -4369l,
  114366. -4755l, -5138l, -5519l, -5896l,
  114367. -6269l, -6638l, -7004l, -7365l,
  114368. -7722l, -8075l, -8422l, -8764l,
  114369. -9101l, -9433l, -9759l, -10079l,
  114370. -10393l, -10701l, -11002l, -11296l,
  114371. -11584l, -11865l, -12139l, -12405l,
  114372. -12664l, -12915l, -13159l, -13394l,
  114373. -13622l, -13841l, -14052l, -14255l,
  114374. -14448l, -14634l, -14810l, -14977l,
  114375. -15136l, -15285l, -15425l, -15556l,
  114376. -15678l, -15790l, -15892l, -15985l,
  114377. -16068l, -16142l, -16206l, -16260l,
  114378. -16304l, -16339l, -16363l, -16378l,
  114379. -16383l,
  114380. };
  114381. #endif
  114382. #endif
  114383. /*** End of inlined file: lookup_data.h ***/
  114384. #ifdef FLOAT_LOOKUP
  114385. /* interpolated lookup based cos function, domain 0 to PI only */
  114386. float vorbis_coslook(float a){
  114387. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114388. int i=vorbis_ftoi(d-.5);
  114389. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114390. }
  114391. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114392. float vorbis_invsqlook(float a){
  114393. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114394. int i=vorbis_ftoi(d-.5f);
  114395. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114396. }
  114397. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114398. float vorbis_invsq2explook(int a){
  114399. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114400. }
  114401. #include <stdio.h>
  114402. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114403. float vorbis_fromdBlook(float a){
  114404. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114405. return (i<0)?1.f:
  114406. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114407. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114408. }
  114409. #endif
  114410. #ifdef INT_LOOKUP
  114411. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114412. 16.16 format
  114413. returns in m.8 format */
  114414. long vorbis_invsqlook_i(long a,long e){
  114415. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114416. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114417. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114418. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114419. d)>>16); /* result 1.16 */
  114420. e+=32;
  114421. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114422. e=(e>>1)-8;
  114423. return(val>>e);
  114424. }
  114425. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114426. /* a is in n.12 format */
  114427. float vorbis_fromdBlook_i(long a){
  114428. int i=(-a)>>(12-FROMdB2_SHIFT);
  114429. return (i<0)?1.f:
  114430. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114431. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114432. }
  114433. /* interpolated lookup based cos function, domain 0 to PI only */
  114434. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114435. long vorbis_coslook_i(long a){
  114436. int i=a>>COS_LOOKUP_I_SHIFT;
  114437. int d=a&COS_LOOKUP_I_MASK;
  114438. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114439. COS_LOOKUP_I_SHIFT);
  114440. }
  114441. #endif
  114442. #endif
  114443. /*** End of inlined file: lookup.c ***/
  114444. /* catch this in the build system; we #include for
  114445. compilers (like gcc) that can't inline across
  114446. modules */
  114447. /* side effect: changes *lsp to cosines of lsp */
  114448. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114449. float amp,float ampoffset){
  114450. int i;
  114451. float wdel=M_PI/ln;
  114452. vorbis_fpu_control fpu;
  114453. (void) fpu; // to avoid an unused variable warning
  114454. vorbis_fpu_setround(&fpu);
  114455. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114456. i=0;
  114457. while(i<n){
  114458. int k=map[i];
  114459. int qexp;
  114460. float p=.7071067812f;
  114461. float q=.7071067812f;
  114462. float w=vorbis_coslook(wdel*k);
  114463. float *ftmp=lsp;
  114464. int c=m>>1;
  114465. do{
  114466. q*=ftmp[0]-w;
  114467. p*=ftmp[1]-w;
  114468. ftmp+=2;
  114469. }while(--c);
  114470. if(m&1){
  114471. /* odd order filter; slightly assymetric */
  114472. /* the last coefficient */
  114473. q*=ftmp[0]-w;
  114474. q*=q;
  114475. p*=p*(1.f-w*w);
  114476. }else{
  114477. /* even order filter; still symmetric */
  114478. q*=q*(1.f+w);
  114479. p*=p*(1.f-w);
  114480. }
  114481. q=frexp(p+q,&qexp);
  114482. q=vorbis_fromdBlook(amp*
  114483. vorbis_invsqlook(q)*
  114484. vorbis_invsq2explook(qexp+m)-
  114485. ampoffset);
  114486. do{
  114487. curve[i++]*=q;
  114488. }while(map[i]==k);
  114489. }
  114490. vorbis_fpu_restore(fpu);
  114491. }
  114492. #else
  114493. #ifdef INT_LOOKUP
  114494. /*** Start of inlined file: lookup.c ***/
  114495. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114496. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114497. // tasks..
  114498. #if JUCE_MSVC
  114499. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114500. #endif
  114501. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114502. #if JUCE_USE_OGGVORBIS
  114503. #include <math.h>
  114504. /*** Start of inlined file: lookup.h ***/
  114505. #ifndef _V_LOOKUP_H_
  114506. #ifdef FLOAT_LOOKUP
  114507. extern float vorbis_coslook(float a);
  114508. extern float vorbis_invsqlook(float a);
  114509. extern float vorbis_invsq2explook(int a);
  114510. extern float vorbis_fromdBlook(float a);
  114511. #endif
  114512. #ifdef INT_LOOKUP
  114513. extern long vorbis_invsqlook_i(long a,long e);
  114514. extern long vorbis_coslook_i(long a);
  114515. extern float vorbis_fromdBlook_i(long a);
  114516. #endif
  114517. #endif
  114518. /*** End of inlined file: lookup.h ***/
  114519. /*** Start of inlined file: lookup_data.h ***/
  114520. #ifndef _V_LOOKUP_DATA_H_
  114521. #ifdef FLOAT_LOOKUP
  114522. #define COS_LOOKUP_SZ 128
  114523. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114524. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114525. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114526. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114527. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114528. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114529. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114530. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114531. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114532. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114533. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114534. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114535. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114536. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114537. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114538. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114539. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114540. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114541. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114542. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114543. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114544. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114545. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114546. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114547. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114548. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114549. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114550. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114551. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114552. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114553. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114554. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114555. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114556. -1.0000000000000f,
  114557. };
  114558. #define INVSQ_LOOKUP_SZ 32
  114559. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114560. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114561. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114562. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114563. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114564. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114565. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114566. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114567. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114568. 1.000000000000f,
  114569. };
  114570. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114571. #define INVSQ2EXP_LOOKUP_MAX 32
  114572. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114573. INVSQ2EXP_LOOKUP_MIN+1]={
  114574. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114575. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114576. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114577. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114578. 256.f, 181.019336f, 128.f, 90.50966799f,
  114579. 64.f, 45.254834f, 32.f, 22.627417f,
  114580. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114581. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114582. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114583. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114584. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114585. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114586. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114587. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114588. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114589. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114590. 1.525878906e-05f,
  114591. };
  114592. #endif
  114593. #define FROMdB_LOOKUP_SZ 35
  114594. #define FROMdB2_LOOKUP_SZ 32
  114595. #define FROMdB_SHIFT 5
  114596. #define FROMdB2_SHIFT 3
  114597. #define FROMdB2_MASK 31
  114598. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114599. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114600. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114601. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114602. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114603. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114604. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114605. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114606. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114607. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114608. };
  114609. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114610. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114611. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114612. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114613. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114614. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114615. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114616. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114617. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114618. };
  114619. #ifdef INT_LOOKUP
  114620. #define INVSQ_LOOKUP_I_SHIFT 10
  114621. #define INVSQ_LOOKUP_I_MASK 1023
  114622. static long INVSQ_LOOKUP_I[64+1]={
  114623. 92682l, 91966l, 91267l, 90583l,
  114624. 89915l, 89261l, 88621l, 87995l,
  114625. 87381l, 86781l, 86192l, 85616l,
  114626. 85051l, 84497l, 83953l, 83420l,
  114627. 82897l, 82384l, 81880l, 81385l,
  114628. 80899l, 80422l, 79953l, 79492l,
  114629. 79039l, 78594l, 78156l, 77726l,
  114630. 77302l, 76885l, 76475l, 76072l,
  114631. 75674l, 75283l, 74898l, 74519l,
  114632. 74146l, 73778l, 73415l, 73058l,
  114633. 72706l, 72359l, 72016l, 71679l,
  114634. 71347l, 71019l, 70695l, 70376l,
  114635. 70061l, 69750l, 69444l, 69141l,
  114636. 68842l, 68548l, 68256l, 67969l,
  114637. 67685l, 67405l, 67128l, 66855l,
  114638. 66585l, 66318l, 66054l, 65794l,
  114639. 65536l,
  114640. };
  114641. #define COS_LOOKUP_I_SHIFT 9
  114642. #define COS_LOOKUP_I_MASK 511
  114643. #define COS_LOOKUP_I_SZ 128
  114644. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114645. 16384l, 16379l, 16364l, 16340l,
  114646. 16305l, 16261l, 16207l, 16143l,
  114647. 16069l, 15986l, 15893l, 15791l,
  114648. 15679l, 15557l, 15426l, 15286l,
  114649. 15137l, 14978l, 14811l, 14635l,
  114650. 14449l, 14256l, 14053l, 13842l,
  114651. 13623l, 13395l, 13160l, 12916l,
  114652. 12665l, 12406l, 12140l, 11866l,
  114653. 11585l, 11297l, 11003l, 10702l,
  114654. 10394l, 10080l, 9760l, 9434l,
  114655. 9102l, 8765l, 8423l, 8076l,
  114656. 7723l, 7366l, 7005l, 6639l,
  114657. 6270l, 5897l, 5520l, 5139l,
  114658. 4756l, 4370l, 3981l, 3590l,
  114659. 3196l, 2801l, 2404l, 2006l,
  114660. 1606l, 1205l, 804l, 402l,
  114661. 0l, -401l, -803l, -1204l,
  114662. -1605l, -2005l, -2403l, -2800l,
  114663. -3195l, -3589l, -3980l, -4369l,
  114664. -4755l, -5138l, -5519l, -5896l,
  114665. -6269l, -6638l, -7004l, -7365l,
  114666. -7722l, -8075l, -8422l, -8764l,
  114667. -9101l, -9433l, -9759l, -10079l,
  114668. -10393l, -10701l, -11002l, -11296l,
  114669. -11584l, -11865l, -12139l, -12405l,
  114670. -12664l, -12915l, -13159l, -13394l,
  114671. -13622l, -13841l, -14052l, -14255l,
  114672. -14448l, -14634l, -14810l, -14977l,
  114673. -15136l, -15285l, -15425l, -15556l,
  114674. -15678l, -15790l, -15892l, -15985l,
  114675. -16068l, -16142l, -16206l, -16260l,
  114676. -16304l, -16339l, -16363l, -16378l,
  114677. -16383l,
  114678. };
  114679. #endif
  114680. #endif
  114681. /*** End of inlined file: lookup_data.h ***/
  114682. #ifdef FLOAT_LOOKUP
  114683. /* interpolated lookup based cos function, domain 0 to PI only */
  114684. float vorbis_coslook(float a){
  114685. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114686. int i=vorbis_ftoi(d-.5);
  114687. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114688. }
  114689. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114690. float vorbis_invsqlook(float a){
  114691. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114692. int i=vorbis_ftoi(d-.5f);
  114693. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114694. }
  114695. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114696. float vorbis_invsq2explook(int a){
  114697. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114698. }
  114699. #include <stdio.h>
  114700. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114701. float vorbis_fromdBlook(float a){
  114702. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114703. return (i<0)?1.f:
  114704. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114705. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114706. }
  114707. #endif
  114708. #ifdef INT_LOOKUP
  114709. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114710. 16.16 format
  114711. returns in m.8 format */
  114712. long vorbis_invsqlook_i(long a,long e){
  114713. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114714. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114715. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114716. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114717. d)>>16); /* result 1.16 */
  114718. e+=32;
  114719. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114720. e=(e>>1)-8;
  114721. return(val>>e);
  114722. }
  114723. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114724. /* a is in n.12 format */
  114725. float vorbis_fromdBlook_i(long a){
  114726. int i=(-a)>>(12-FROMdB2_SHIFT);
  114727. return (i<0)?1.f:
  114728. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114729. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114730. }
  114731. /* interpolated lookup based cos function, domain 0 to PI only */
  114732. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114733. long vorbis_coslook_i(long a){
  114734. int i=a>>COS_LOOKUP_I_SHIFT;
  114735. int d=a&COS_LOOKUP_I_MASK;
  114736. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114737. COS_LOOKUP_I_SHIFT);
  114738. }
  114739. #endif
  114740. #endif
  114741. /*** End of inlined file: lookup.c ***/
  114742. /* catch this in the build system; we #include for
  114743. compilers (like gcc) that can't inline across
  114744. modules */
  114745. static int MLOOP_1[64]={
  114746. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114747. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114748. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114749. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114750. };
  114751. static int MLOOP_2[64]={
  114752. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114753. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114754. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114755. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114756. };
  114757. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114758. /* side effect: changes *lsp to cosines of lsp */
  114759. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114760. float amp,float ampoffset){
  114761. /* 0 <= m < 256 */
  114762. /* set up for using all int later */
  114763. int i;
  114764. int ampoffseti=rint(ampoffset*4096.f);
  114765. int ampi=rint(amp*16.f);
  114766. long *ilsp=alloca(m*sizeof(*ilsp));
  114767. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114768. i=0;
  114769. while(i<n){
  114770. int j,k=map[i];
  114771. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114772. unsigned long qi=46341;
  114773. int qexp=0,shift;
  114774. long wi=vorbis_coslook_i(k*65536/ln);
  114775. qi*=labs(ilsp[0]-wi);
  114776. pi*=labs(ilsp[1]-wi);
  114777. for(j=3;j<m;j+=2){
  114778. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114779. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114780. shift=MLOOP_3[(pi|qi)>>16];
  114781. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114782. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114783. qexp+=shift;
  114784. }
  114785. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114786. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114787. shift=MLOOP_3[(pi|qi)>>16];
  114788. /* pi,qi normalized collectively, both tracked using qexp */
  114789. if(m&1){
  114790. /* odd order filter; slightly assymetric */
  114791. /* the last coefficient */
  114792. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114793. pi=(pi>>shift)<<14;
  114794. qexp+=shift;
  114795. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114796. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114797. shift=MLOOP_3[(pi|qi)>>16];
  114798. pi>>=shift;
  114799. qi>>=shift;
  114800. qexp+=shift-14*((m+1)>>1);
  114801. pi=((pi*pi)>>16);
  114802. qi=((qi*qi)>>16);
  114803. qexp=qexp*2+m;
  114804. pi*=(1<<14)-((wi*wi)>>14);
  114805. qi+=pi>>14;
  114806. }else{
  114807. /* even order filter; still symmetric */
  114808. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114809. worth tracking step by step */
  114810. pi>>=shift;
  114811. qi>>=shift;
  114812. qexp+=shift-7*m;
  114813. pi=((pi*pi)>>16);
  114814. qi=((qi*qi)>>16);
  114815. qexp=qexp*2+m;
  114816. pi*=(1<<14)-wi;
  114817. qi*=(1<<14)+wi;
  114818. qi=(qi+pi)>>14;
  114819. }
  114820. /* we've let the normalization drift because it wasn't important;
  114821. however, for the lookup, things must be normalized again. We
  114822. need at most one right shift or a number of left shifts */
  114823. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114824. qi>>=1; qexp++;
  114825. }else
  114826. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114827. qi<<=1; qexp--;
  114828. }
  114829. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114830. vorbis_invsqlook_i(qi,qexp)-
  114831. /* m.8, m+n<=8 */
  114832. ampoffseti); /* 8.12[0] */
  114833. curve[i]*=amp;
  114834. while(map[++i]==k)curve[i]*=amp;
  114835. }
  114836. }
  114837. #else
  114838. /* old, nonoptimized but simple version for any poor sap who needs to
  114839. figure out what the hell this code does, or wants the other
  114840. fraction of a dB precision */
  114841. /* side effect: changes *lsp to cosines of lsp */
  114842. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114843. float amp,float ampoffset){
  114844. int i;
  114845. float wdel=M_PI/ln;
  114846. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114847. i=0;
  114848. while(i<n){
  114849. int j,k=map[i];
  114850. float p=.5f;
  114851. float q=.5f;
  114852. float w=2.f*cos(wdel*k);
  114853. for(j=1;j<m;j+=2){
  114854. q *= w-lsp[j-1];
  114855. p *= w-lsp[j];
  114856. }
  114857. if(j==m){
  114858. /* odd order filter; slightly assymetric */
  114859. /* the last coefficient */
  114860. q*=w-lsp[j-1];
  114861. p*=p*(4.f-w*w);
  114862. q*=q;
  114863. }else{
  114864. /* even order filter; still symmetric */
  114865. p*=p*(2.f-w);
  114866. q*=q*(2.f+w);
  114867. }
  114868. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114869. curve[i]*=q;
  114870. while(map[++i]==k)curve[i]*=q;
  114871. }
  114872. }
  114873. #endif
  114874. #endif
  114875. static void cheby(float *g, int ord) {
  114876. int i, j;
  114877. g[0] *= .5f;
  114878. for(i=2; i<= ord; i++) {
  114879. for(j=ord; j >= i; j--) {
  114880. g[j-2] -= g[j];
  114881. g[j] += g[j];
  114882. }
  114883. }
  114884. }
  114885. static int JUCE_CDECL comp(const void *a,const void *b){
  114886. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114887. }
  114888. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114889. but there are root sets for which it gets into limit cycles
  114890. (exacerbated by zero suppression) and fails. We can't afford to
  114891. fail, even if the failure is 1 in 100,000,000, so we now use
  114892. Laguerre and later polish with Newton-Raphson (which can then
  114893. afford to fail) */
  114894. #define EPSILON 10e-7
  114895. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114896. int i,m;
  114897. double lastdelta=0.f;
  114898. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114899. for(i=0;i<=ord;i++)defl[i]=a[i];
  114900. for(m=ord;m>0;m--){
  114901. double newx=0.f,delta;
  114902. /* iterate a root */
  114903. while(1){
  114904. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114905. /* eval the polynomial and its first two derivatives */
  114906. for(i=m;i>0;i--){
  114907. ppp = newx*ppp + pp;
  114908. pp = newx*pp + p;
  114909. p = newx*p + defl[i-1];
  114910. }
  114911. /* Laguerre's method */
  114912. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114913. if(denom<0)
  114914. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114915. if(pp>0){
  114916. denom = pp + sqrt(denom);
  114917. if(denom<EPSILON)denom=EPSILON;
  114918. }else{
  114919. denom = pp - sqrt(denom);
  114920. if(denom>-(EPSILON))denom=-(EPSILON);
  114921. }
  114922. delta = m*p/denom;
  114923. newx -= delta;
  114924. if(delta<0.f)delta*=-1;
  114925. if(fabs(delta/newx)<10e-12)break;
  114926. lastdelta=delta;
  114927. }
  114928. r[m-1]=newx;
  114929. /* forward deflation */
  114930. for(i=m;i>0;i--)
  114931. defl[i-1]+=newx*defl[i];
  114932. defl++;
  114933. }
  114934. return(0);
  114935. }
  114936. /* for spit-and-polish only */
  114937. static int Newton_Raphson(float *a,int ord,float *r){
  114938. int i, k, count=0;
  114939. double error=1.f;
  114940. double *root=(double*)alloca(ord*sizeof(*root));
  114941. for(i=0; i<ord;i++) root[i] = r[i];
  114942. while(error>1e-20){
  114943. error=0;
  114944. for(i=0; i<ord; i++) { /* Update each point. */
  114945. double pp=0.,delta;
  114946. double rooti=root[i];
  114947. double p=a[ord];
  114948. for(k=ord-1; k>= 0; k--) {
  114949. pp= pp* rooti + p;
  114950. p = p * rooti + a[k];
  114951. }
  114952. delta = p/pp;
  114953. root[i] -= delta;
  114954. error+= delta*delta;
  114955. }
  114956. if(count>40)return(-1);
  114957. count++;
  114958. }
  114959. /* Replaced the original bubble sort with a real sort. With your
  114960. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114961. for(i=0; i<ord;i++) r[i] = root[i];
  114962. return(0);
  114963. }
  114964. /* Convert lpc coefficients to lsp coefficients */
  114965. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114966. int order2=(m+1)>>1;
  114967. int g1_order,g2_order;
  114968. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114969. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114970. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114971. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114972. int i;
  114973. /* even and odd are slightly different base cases */
  114974. g1_order=(m+1)>>1;
  114975. g2_order=(m) >>1;
  114976. /* Compute the lengths of the x polynomials. */
  114977. /* Compute the first half of K & R F1 & F2 polynomials. */
  114978. /* Compute half of the symmetric and antisymmetric polynomials. */
  114979. /* Remove the roots at +1 and -1. */
  114980. g1[g1_order] = 1.f;
  114981. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114982. g2[g2_order] = 1.f;
  114983. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114984. if(g1_order>g2_order){
  114985. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114986. }else{
  114987. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114988. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114989. }
  114990. /* Convert into polynomials in cos(alpha) */
  114991. cheby(g1,g1_order);
  114992. cheby(g2,g2_order);
  114993. /* Find the roots of the 2 even polynomials.*/
  114994. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114995. Laguerre_With_Deflation(g2,g2_order,g2r))
  114996. return(-1);
  114997. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114998. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114999. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115000. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115001. for(i=0;i<g1_order;i++)
  115002. lsp[i*2] = acos(g1r[i]);
  115003. for(i=0;i<g2_order;i++)
  115004. lsp[i*2+1] = acos(g2r[i]);
  115005. return(0);
  115006. }
  115007. #endif
  115008. /*** End of inlined file: lsp.c ***/
  115009. /*** Start of inlined file: mapping0.c ***/
  115010. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115011. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115012. // tasks..
  115013. #if JUCE_MSVC
  115014. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115015. #endif
  115016. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115017. #if JUCE_USE_OGGVORBIS
  115018. #include <stdlib.h>
  115019. #include <stdio.h>
  115020. #include <string.h>
  115021. #include <math.h>
  115022. /* simplistic, wasteful way of doing this (unique lookup for each
  115023. mode/submapping); there should be a central repository for
  115024. identical lookups. That will require minor work, so I'm putting it
  115025. off as low priority.
  115026. Why a lookup for each backend in a given mode? Because the
  115027. blocksize is set by the mode, and low backend lookups may require
  115028. parameters from other areas of the mode/mapping */
  115029. static void mapping0_free_info(vorbis_info_mapping *i){
  115030. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115031. if(info){
  115032. memset(info,0,sizeof(*info));
  115033. _ogg_free(info);
  115034. }
  115035. }
  115036. static int ilog3(unsigned int v){
  115037. int ret=0;
  115038. if(v)--v;
  115039. while(v){
  115040. ret++;
  115041. v>>=1;
  115042. }
  115043. return(ret);
  115044. }
  115045. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115046. oggpack_buffer *opb){
  115047. int i;
  115048. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115049. /* another 'we meant to do it this way' hack... up to beta 4, we
  115050. packed 4 binary zeros here to signify one submapping in use. We
  115051. now redefine that to mean four bitflags that indicate use of
  115052. deeper features; bit0:submappings, bit1:coupling,
  115053. bit2,3:reserved. This is backward compatable with all actual uses
  115054. of the beta code. */
  115055. if(info->submaps>1){
  115056. oggpack_write(opb,1,1);
  115057. oggpack_write(opb,info->submaps-1,4);
  115058. }else
  115059. oggpack_write(opb,0,1);
  115060. if(info->coupling_steps>0){
  115061. oggpack_write(opb,1,1);
  115062. oggpack_write(opb,info->coupling_steps-1,8);
  115063. for(i=0;i<info->coupling_steps;i++){
  115064. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115065. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115066. }
  115067. }else
  115068. oggpack_write(opb,0,1);
  115069. oggpack_write(opb,0,2); /* 2,3:reserved */
  115070. /* we don't write the channel submappings if we only have one... */
  115071. if(info->submaps>1){
  115072. for(i=0;i<vi->channels;i++)
  115073. oggpack_write(opb,info->chmuxlist[i],4);
  115074. }
  115075. for(i=0;i<info->submaps;i++){
  115076. oggpack_write(opb,0,8); /* time submap unused */
  115077. oggpack_write(opb,info->floorsubmap[i],8);
  115078. oggpack_write(opb,info->residuesubmap[i],8);
  115079. }
  115080. }
  115081. /* also responsible for range checking */
  115082. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115083. int i;
  115084. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115085. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115086. memset(info,0,sizeof(*info));
  115087. if(oggpack_read(opb,1))
  115088. info->submaps=oggpack_read(opb,4)+1;
  115089. else
  115090. info->submaps=1;
  115091. if(oggpack_read(opb,1)){
  115092. info->coupling_steps=oggpack_read(opb,8)+1;
  115093. for(i=0;i<info->coupling_steps;i++){
  115094. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115095. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115096. if(testM<0 ||
  115097. testA<0 ||
  115098. testM==testA ||
  115099. testM>=vi->channels ||
  115100. testA>=vi->channels) goto err_out;
  115101. }
  115102. }
  115103. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115104. if(info->submaps>1){
  115105. for(i=0;i<vi->channels;i++){
  115106. info->chmuxlist[i]=oggpack_read(opb,4);
  115107. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115108. }
  115109. }
  115110. for(i=0;i<info->submaps;i++){
  115111. oggpack_read(opb,8); /* time submap unused */
  115112. info->floorsubmap[i]=oggpack_read(opb,8);
  115113. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115114. info->residuesubmap[i]=oggpack_read(opb,8);
  115115. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115116. }
  115117. return info;
  115118. err_out:
  115119. mapping0_free_info(info);
  115120. return(NULL);
  115121. }
  115122. #if 0
  115123. static long seq=0;
  115124. static ogg_int64_t total=0;
  115125. static float FLOOR1_fromdB_LOOKUP[256]={
  115126. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115127. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115128. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115129. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115130. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115131. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115132. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115133. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115134. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115135. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115136. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115137. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115138. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115139. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115140. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115141. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115142. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115143. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115144. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115145. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115146. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115147. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115148. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115149. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115150. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115151. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115152. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115153. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115154. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115155. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115156. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115157. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115158. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115159. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115160. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115161. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115162. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115163. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115164. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115165. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115166. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115167. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115168. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115169. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115170. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115171. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115172. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115173. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115174. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115175. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115176. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115177. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115178. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115179. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115180. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115181. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115182. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115183. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115184. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115185. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115186. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115187. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115188. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115189. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115190. };
  115191. #endif
  115192. extern int *floor1_fit(vorbis_block *vb,void *look,
  115193. const float *logmdct, /* in */
  115194. const float *logmask);
  115195. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115196. int *A,int *B,
  115197. int del);
  115198. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115199. void*look,
  115200. int *post,int *ilogmask);
  115201. static int mapping0_forward(vorbis_block *vb){
  115202. vorbis_dsp_state *vd=vb->vd;
  115203. vorbis_info *vi=vd->vi;
  115204. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115205. private_state *b=(private_state*)vb->vd->backend_state;
  115206. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115207. int n=vb->pcmend;
  115208. int i,j,k;
  115209. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115210. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115211. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115212. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115213. float global_ampmax=vbi->ampmax;
  115214. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115215. int blocktype=vbi->blocktype;
  115216. int modenumber=vb->W;
  115217. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115218. vorbis_look_psy *psy_look=
  115219. b->psy+blocktype+(vb->W?2:0);
  115220. vb->mode=modenumber;
  115221. for(i=0;i<vi->channels;i++){
  115222. float scale=4.f/n;
  115223. float scale_dB;
  115224. float *pcm =vb->pcm[i];
  115225. float *logfft =pcm;
  115226. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115227. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115228. todB estimation used on IEEE 754
  115229. compliant machines had a bug that
  115230. returned dB values about a third
  115231. of a decibel too high. The bug
  115232. was harmless because tunings
  115233. implicitly took that into
  115234. account. However, fixing the bug
  115235. in the estimator requires
  115236. changing all the tunings as well.
  115237. For now, it's easier to sync
  115238. things back up here, and
  115239. recalibrate the tunings in the
  115240. next major model upgrade. */
  115241. #if 0
  115242. if(vi->channels==2)
  115243. if(i==0)
  115244. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115245. else
  115246. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115247. #endif
  115248. /* window the PCM data */
  115249. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115250. #if 0
  115251. if(vi->channels==2)
  115252. if(i==0)
  115253. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115254. else
  115255. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115256. #endif
  115257. /* transform the PCM data */
  115258. /* only MDCT right now.... */
  115259. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115260. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115261. drft_forward(&b->fft_look[vb->W],pcm);
  115262. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115263. original todB estimation used on
  115264. IEEE 754 compliant machines had a
  115265. bug that returned dB values about
  115266. a third of a decibel too high.
  115267. The bug was harmless because
  115268. tunings implicitly took that into
  115269. account. However, fixing the bug
  115270. in the estimator requires
  115271. changing all the tunings as well.
  115272. For now, it's easier to sync
  115273. things back up here, and
  115274. recalibrate the tunings in the
  115275. next major model upgrade. */
  115276. local_ampmax[i]=logfft[0];
  115277. for(j=1;j<n-1;j+=2){
  115278. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115279. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115280. .345 is a hack; the original todB
  115281. estimation used on IEEE 754
  115282. compliant machines had a bug that
  115283. returned dB values about a third
  115284. of a decibel too high. The bug
  115285. was harmless because tunings
  115286. implicitly took that into
  115287. account. However, fixing the bug
  115288. in the estimator requires
  115289. changing all the tunings as well.
  115290. For now, it's easier to sync
  115291. things back up here, and
  115292. recalibrate the tunings in the
  115293. next major model upgrade. */
  115294. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115295. }
  115296. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115297. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115298. #if 0
  115299. if(vi->channels==2){
  115300. if(i==0){
  115301. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115302. }else{
  115303. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115304. }
  115305. }
  115306. #endif
  115307. }
  115308. {
  115309. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115310. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115311. for(i=0;i<vi->channels;i++){
  115312. /* the encoder setup assumes that all the modes used by any
  115313. specific bitrate tweaking use the same floor */
  115314. int submap=info->chmuxlist[i];
  115315. /* the following makes things clearer to *me* anyway */
  115316. float *mdct =gmdct[i];
  115317. float *logfft =vb->pcm[i];
  115318. float *logmdct =logfft+n/2;
  115319. float *logmask =logfft;
  115320. vb->mode=modenumber;
  115321. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115322. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115323. for(j=0;j<n/2;j++)
  115324. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115325. todB estimation used on IEEE 754
  115326. compliant machines had a bug that
  115327. returned dB values about a third
  115328. of a decibel too high. The bug
  115329. was harmless because tunings
  115330. implicitly took that into
  115331. account. However, fixing the bug
  115332. in the estimator requires
  115333. changing all the tunings as well.
  115334. For now, it's easier to sync
  115335. things back up here, and
  115336. recalibrate the tunings in the
  115337. next major model upgrade. */
  115338. #if 0
  115339. if(vi->channels==2){
  115340. if(i==0)
  115341. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115342. else
  115343. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115344. }else{
  115345. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115346. }
  115347. #endif
  115348. /* first step; noise masking. Not only does 'noise masking'
  115349. give us curves from which we can decide how much resolution
  115350. to give noise parts of the spectrum, it also implicitly hands
  115351. us a tonality estimate (the larger the value in the
  115352. 'noise_depth' vector, the more tonal that area is) */
  115353. _vp_noisemask(psy_look,
  115354. logmdct,
  115355. noise); /* noise does not have by-frequency offset
  115356. bias applied yet */
  115357. #if 0
  115358. if(vi->channels==2){
  115359. if(i==0)
  115360. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115361. else
  115362. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115363. }
  115364. #endif
  115365. /* second step: 'all the other crap'; all the stuff that isn't
  115366. computed/fit for bitrate management goes in the second psy
  115367. vector. This includes tone masking, peak limiting and ATH */
  115368. _vp_tonemask(psy_look,
  115369. logfft,
  115370. tone,
  115371. global_ampmax,
  115372. local_ampmax[i]);
  115373. #if 0
  115374. if(vi->channels==2){
  115375. if(i==0)
  115376. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115377. else
  115378. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115379. }
  115380. #endif
  115381. /* third step; we offset the noise vectors, overlay tone
  115382. masking. We then do a floor1-specific line fit. If we're
  115383. performing bitrate management, the line fit is performed
  115384. multiple times for up/down tweakage on demand. */
  115385. #if 0
  115386. {
  115387. float aotuv[psy_look->n];
  115388. #endif
  115389. _vp_offset_and_mix(psy_look,
  115390. noise,
  115391. tone,
  115392. 1,
  115393. logmask,
  115394. mdct,
  115395. logmdct);
  115396. #if 0
  115397. if(vi->channels==2){
  115398. if(i==0)
  115399. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115400. else
  115401. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115402. }
  115403. }
  115404. #endif
  115405. #if 0
  115406. if(vi->channels==2){
  115407. if(i==0)
  115408. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115409. else
  115410. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115411. }
  115412. #endif
  115413. /* this algorithm is hardwired to floor 1 for now; abort out if
  115414. we're *not* floor1. This won't happen unless someone has
  115415. broken the encode setup lib. Guard it anyway. */
  115416. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115417. floor_posts[i][PACKETBLOBS/2]=
  115418. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115419. logmdct,
  115420. logmask);
  115421. /* are we managing bitrate? If so, perform two more fits for
  115422. later rate tweaking (fits represent hi/lo) */
  115423. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115424. /* higher rate by way of lower noise curve */
  115425. _vp_offset_and_mix(psy_look,
  115426. noise,
  115427. tone,
  115428. 2,
  115429. logmask,
  115430. mdct,
  115431. logmdct);
  115432. #if 0
  115433. if(vi->channels==2){
  115434. if(i==0)
  115435. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115436. else
  115437. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115438. }
  115439. #endif
  115440. floor_posts[i][PACKETBLOBS-1]=
  115441. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115442. logmdct,
  115443. logmask);
  115444. /* lower rate by way of higher noise curve */
  115445. _vp_offset_and_mix(psy_look,
  115446. noise,
  115447. tone,
  115448. 0,
  115449. logmask,
  115450. mdct,
  115451. logmdct);
  115452. #if 0
  115453. if(vi->channels==2)
  115454. if(i==0)
  115455. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115456. else
  115457. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115458. #endif
  115459. floor_posts[i][0]=
  115460. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115461. logmdct,
  115462. logmask);
  115463. /* we also interpolate a range of intermediate curves for
  115464. intermediate rates */
  115465. for(k=1;k<PACKETBLOBS/2;k++)
  115466. floor_posts[i][k]=
  115467. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115468. floor_posts[i][0],
  115469. floor_posts[i][PACKETBLOBS/2],
  115470. k*65536/(PACKETBLOBS/2));
  115471. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115472. floor_posts[i][k]=
  115473. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115474. floor_posts[i][PACKETBLOBS/2],
  115475. floor_posts[i][PACKETBLOBS-1],
  115476. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115477. }
  115478. }
  115479. }
  115480. vbi->ampmax=global_ampmax;
  115481. /*
  115482. the next phases are performed once for vbr-only and PACKETBLOB
  115483. times for bitrate managed modes.
  115484. 1) encode actual mode being used
  115485. 2) encode the floor for each channel, compute coded mask curve/res
  115486. 3) normalize and couple.
  115487. 4) encode residue
  115488. 5) save packet bytes to the packetblob vector
  115489. */
  115490. /* iterate over the many masking curve fits we've created */
  115491. {
  115492. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115493. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115494. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115495. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115496. float **mag_memo;
  115497. int **mag_sort;
  115498. if(info->coupling_steps){
  115499. mag_memo=_vp_quantize_couple_memo(vb,
  115500. &ci->psy_g_param,
  115501. psy_look,
  115502. info,
  115503. gmdct);
  115504. mag_sort=_vp_quantize_couple_sort(vb,
  115505. psy_look,
  115506. info,
  115507. mag_memo);
  115508. hf_reduction(&ci->psy_g_param,
  115509. psy_look,
  115510. info,
  115511. mag_memo);
  115512. }
  115513. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115514. if(psy_look->vi->normal_channel_p){
  115515. for(i=0;i<vi->channels;i++){
  115516. float *mdct =gmdct[i];
  115517. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115518. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115519. }
  115520. }
  115521. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115522. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115523. k++){
  115524. oggpack_buffer *opb=vbi->packetblob[k];
  115525. /* start out our new packet blob with packet type and mode */
  115526. /* Encode the packet type */
  115527. oggpack_write(opb,0,1);
  115528. /* Encode the modenumber */
  115529. /* Encode frame mode, pre,post windowsize, then dispatch */
  115530. oggpack_write(opb,modenumber,b->modebits);
  115531. if(vb->W){
  115532. oggpack_write(opb,vb->lW,1);
  115533. oggpack_write(opb,vb->nW,1);
  115534. }
  115535. /* encode floor, compute masking curve, sep out residue */
  115536. for(i=0;i<vi->channels;i++){
  115537. int submap=info->chmuxlist[i];
  115538. float *mdct =gmdct[i];
  115539. float *res =vb->pcm[i];
  115540. int *ilogmask=ilogmaskch[i]=
  115541. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115542. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115543. floor_posts[i][k],
  115544. ilogmask);
  115545. #if 0
  115546. {
  115547. char buf[80];
  115548. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115549. float work[n/2];
  115550. for(j=0;j<n/2;j++)
  115551. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115552. _analysis_output(buf,seq,work,n/2,1,1,0);
  115553. }
  115554. #endif
  115555. _vp_remove_floor(psy_look,
  115556. mdct,
  115557. ilogmask,
  115558. res,
  115559. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115560. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115561. #if 0
  115562. {
  115563. char buf[80];
  115564. float work[n/2];
  115565. for(j=0;j<n/2;j++)
  115566. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115567. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115568. _analysis_output(buf,seq,work,n/2,1,1,0);
  115569. }
  115570. #endif
  115571. }
  115572. /* our iteration is now based on masking curve, not prequant and
  115573. coupling. Only one prequant/coupling step */
  115574. /* quantize/couple */
  115575. /* incomplete implementation that assumes the tree is all depth
  115576. one, or no tree at all */
  115577. if(info->coupling_steps){
  115578. _vp_couple(k,
  115579. &ci->psy_g_param,
  115580. psy_look,
  115581. info,
  115582. vb->pcm,
  115583. mag_memo,
  115584. mag_sort,
  115585. ilogmaskch,
  115586. nonzero,
  115587. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115588. }
  115589. /* classify and encode by submap */
  115590. for(i=0;i<info->submaps;i++){
  115591. int ch_in_bundle=0;
  115592. long **classifications;
  115593. int resnum=info->residuesubmap[i];
  115594. for(j=0;j<vi->channels;j++){
  115595. if(info->chmuxlist[j]==i){
  115596. zerobundle[ch_in_bundle]=0;
  115597. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115598. res_bundle[ch_in_bundle]=vb->pcm[j];
  115599. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115600. }
  115601. }
  115602. classifications=_residue_P[ci->residue_type[resnum]]->
  115603. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115604. _residue_P[ci->residue_type[resnum]]->
  115605. forward(opb,vb,b->residue[resnum],
  115606. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115607. }
  115608. /* ok, done encoding. Next protopacket. */
  115609. }
  115610. }
  115611. #if 0
  115612. seq++;
  115613. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115614. #endif
  115615. return(0);
  115616. }
  115617. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115618. vorbis_dsp_state *vd=vb->vd;
  115619. vorbis_info *vi=vd->vi;
  115620. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115621. private_state *b=(private_state*)vd->backend_state;
  115622. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115623. int i,j;
  115624. long n=vb->pcmend=ci->blocksizes[vb->W];
  115625. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115626. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115627. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115628. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115629. /* recover the spectral envelope; store it in the PCM vector for now */
  115630. for(i=0;i<vi->channels;i++){
  115631. int submap=info->chmuxlist[i];
  115632. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115633. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115634. if(floormemo[i])
  115635. nonzero[i]=1;
  115636. else
  115637. nonzero[i]=0;
  115638. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115639. }
  115640. /* channel coupling can 'dirty' the nonzero listing */
  115641. for(i=0;i<info->coupling_steps;i++){
  115642. if(nonzero[info->coupling_mag[i]] ||
  115643. nonzero[info->coupling_ang[i]]){
  115644. nonzero[info->coupling_mag[i]]=1;
  115645. nonzero[info->coupling_ang[i]]=1;
  115646. }
  115647. }
  115648. /* recover the residue into our working vectors */
  115649. for(i=0;i<info->submaps;i++){
  115650. int ch_in_bundle=0;
  115651. for(j=0;j<vi->channels;j++){
  115652. if(info->chmuxlist[j]==i){
  115653. if(nonzero[j])
  115654. zerobundle[ch_in_bundle]=1;
  115655. else
  115656. zerobundle[ch_in_bundle]=0;
  115657. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115658. }
  115659. }
  115660. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115661. inverse(vb,b->residue[info->residuesubmap[i]],
  115662. pcmbundle,zerobundle,ch_in_bundle);
  115663. }
  115664. /* channel coupling */
  115665. for(i=info->coupling_steps-1;i>=0;i--){
  115666. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115667. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115668. for(j=0;j<n/2;j++){
  115669. float mag=pcmM[j];
  115670. float ang=pcmA[j];
  115671. if(mag>0)
  115672. if(ang>0){
  115673. pcmM[j]=mag;
  115674. pcmA[j]=mag-ang;
  115675. }else{
  115676. pcmA[j]=mag;
  115677. pcmM[j]=mag+ang;
  115678. }
  115679. else
  115680. if(ang>0){
  115681. pcmM[j]=mag;
  115682. pcmA[j]=mag+ang;
  115683. }else{
  115684. pcmA[j]=mag;
  115685. pcmM[j]=mag-ang;
  115686. }
  115687. }
  115688. }
  115689. /* compute and apply spectral envelope */
  115690. for(i=0;i<vi->channels;i++){
  115691. float *pcm=vb->pcm[i];
  115692. int submap=info->chmuxlist[i];
  115693. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115694. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115695. floormemo[i],pcm);
  115696. }
  115697. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115698. /* only MDCT right now.... */
  115699. for(i=0;i<vi->channels;i++){
  115700. float *pcm=vb->pcm[i];
  115701. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115702. }
  115703. /* all done! */
  115704. return(0);
  115705. }
  115706. /* export hooks */
  115707. vorbis_func_mapping mapping0_exportbundle={
  115708. &mapping0_pack,
  115709. &mapping0_unpack,
  115710. &mapping0_free_info,
  115711. &mapping0_forward,
  115712. &mapping0_inverse
  115713. };
  115714. #endif
  115715. /*** End of inlined file: mapping0.c ***/
  115716. /*** Start of inlined file: mdct.c ***/
  115717. /* this can also be run as an integer transform by uncommenting a
  115718. define in mdct.h; the integerization is a first pass and although
  115719. it's likely stable for Vorbis, the dynamic range is constrained and
  115720. roundoff isn't done (so it's noisy). Consider it functional, but
  115721. only a starting point. There's no point on a machine with an FPU */
  115722. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115723. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115724. // tasks..
  115725. #if JUCE_MSVC
  115726. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115727. #endif
  115728. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115729. #if JUCE_USE_OGGVORBIS
  115730. #include <stdio.h>
  115731. #include <stdlib.h>
  115732. #include <string.h>
  115733. #include <math.h>
  115734. /* build lookups for trig functions; also pre-figure scaling and
  115735. some window function algebra. */
  115736. void mdct_init(mdct_lookup *lookup,int n){
  115737. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115738. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115739. int i;
  115740. int n2=n>>1;
  115741. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115742. lookup->n=n;
  115743. lookup->trig=T;
  115744. lookup->bitrev=bitrev;
  115745. /* trig lookups... */
  115746. for(i=0;i<n/4;i++){
  115747. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115748. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115749. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115750. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115751. }
  115752. for(i=0;i<n/8;i++){
  115753. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115754. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115755. }
  115756. /* bitreverse lookup... */
  115757. {
  115758. int mask=(1<<(log2n-1))-1,i,j;
  115759. int msb=1<<(log2n-2);
  115760. for(i=0;i<n/8;i++){
  115761. int acc=0;
  115762. for(j=0;msb>>j;j++)
  115763. if((msb>>j)&i)acc|=1<<j;
  115764. bitrev[i*2]=((~acc)&mask)-1;
  115765. bitrev[i*2+1]=acc;
  115766. }
  115767. }
  115768. lookup->scale=FLOAT_CONV(4.f/n);
  115769. }
  115770. /* 8 point butterfly (in place, 4 register) */
  115771. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115772. REG_TYPE r0 = x[6] + x[2];
  115773. REG_TYPE r1 = x[6] - x[2];
  115774. REG_TYPE r2 = x[4] + x[0];
  115775. REG_TYPE r3 = x[4] - x[0];
  115776. x[6] = r0 + r2;
  115777. x[4] = r0 - r2;
  115778. r0 = x[5] - x[1];
  115779. r2 = x[7] - x[3];
  115780. x[0] = r1 + r0;
  115781. x[2] = r1 - r0;
  115782. r0 = x[5] + x[1];
  115783. r1 = x[7] + x[3];
  115784. x[3] = r2 + r3;
  115785. x[1] = r2 - r3;
  115786. x[7] = r1 + r0;
  115787. x[5] = r1 - r0;
  115788. }
  115789. /* 16 point butterfly (in place, 4 register) */
  115790. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115791. REG_TYPE r0 = x[1] - x[9];
  115792. REG_TYPE r1 = x[0] - x[8];
  115793. x[8] += x[0];
  115794. x[9] += x[1];
  115795. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115796. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115797. r0 = x[3] - x[11];
  115798. r1 = x[10] - x[2];
  115799. x[10] += x[2];
  115800. x[11] += x[3];
  115801. x[2] = r0;
  115802. x[3] = r1;
  115803. r0 = x[12] - x[4];
  115804. r1 = x[13] - x[5];
  115805. x[12] += x[4];
  115806. x[13] += x[5];
  115807. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115808. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115809. r0 = x[14] - x[6];
  115810. r1 = x[15] - x[7];
  115811. x[14] += x[6];
  115812. x[15] += x[7];
  115813. x[6] = r0;
  115814. x[7] = r1;
  115815. mdct_butterfly_8(x);
  115816. mdct_butterfly_8(x+8);
  115817. }
  115818. /* 32 point butterfly (in place, 4 register) */
  115819. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115820. REG_TYPE r0 = x[30] - x[14];
  115821. REG_TYPE r1 = x[31] - x[15];
  115822. x[30] += x[14];
  115823. x[31] += x[15];
  115824. x[14] = r0;
  115825. x[15] = r1;
  115826. r0 = x[28] - x[12];
  115827. r1 = x[29] - x[13];
  115828. x[28] += x[12];
  115829. x[29] += x[13];
  115830. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115831. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115832. r0 = x[26] - x[10];
  115833. r1 = x[27] - x[11];
  115834. x[26] += x[10];
  115835. x[27] += x[11];
  115836. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115837. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115838. r0 = x[24] - x[8];
  115839. r1 = x[25] - x[9];
  115840. x[24] += x[8];
  115841. x[25] += x[9];
  115842. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115843. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115844. r0 = x[22] - x[6];
  115845. r1 = x[7] - x[23];
  115846. x[22] += x[6];
  115847. x[23] += x[7];
  115848. x[6] = r1;
  115849. x[7] = r0;
  115850. r0 = x[4] - x[20];
  115851. r1 = x[5] - x[21];
  115852. x[20] += x[4];
  115853. x[21] += x[5];
  115854. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115855. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115856. r0 = x[2] - x[18];
  115857. r1 = x[3] - x[19];
  115858. x[18] += x[2];
  115859. x[19] += x[3];
  115860. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115861. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115862. r0 = x[0] - x[16];
  115863. r1 = x[1] - x[17];
  115864. x[16] += x[0];
  115865. x[17] += x[1];
  115866. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115867. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115868. mdct_butterfly_16(x);
  115869. mdct_butterfly_16(x+16);
  115870. }
  115871. /* N point first stage butterfly (in place, 2 register) */
  115872. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115873. DATA_TYPE *x,
  115874. int points){
  115875. DATA_TYPE *x1 = x + points - 8;
  115876. DATA_TYPE *x2 = x + (points>>1) - 8;
  115877. REG_TYPE r0;
  115878. REG_TYPE r1;
  115879. do{
  115880. r0 = x1[6] - x2[6];
  115881. r1 = x1[7] - x2[7];
  115882. x1[6] += x2[6];
  115883. x1[7] += x2[7];
  115884. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115885. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115886. r0 = x1[4] - x2[4];
  115887. r1 = x1[5] - x2[5];
  115888. x1[4] += x2[4];
  115889. x1[5] += x2[5];
  115890. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115891. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115892. r0 = x1[2] - x2[2];
  115893. r1 = x1[3] - x2[3];
  115894. x1[2] += x2[2];
  115895. x1[3] += x2[3];
  115896. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115897. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115898. r0 = x1[0] - x2[0];
  115899. r1 = x1[1] - x2[1];
  115900. x1[0] += x2[0];
  115901. x1[1] += x2[1];
  115902. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115903. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115904. x1-=8;
  115905. x2-=8;
  115906. T+=16;
  115907. }while(x2>=x);
  115908. }
  115909. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115910. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115911. DATA_TYPE *x,
  115912. int points,
  115913. int trigint){
  115914. DATA_TYPE *x1 = x + points - 8;
  115915. DATA_TYPE *x2 = x + (points>>1) - 8;
  115916. REG_TYPE r0;
  115917. REG_TYPE r1;
  115918. do{
  115919. r0 = x1[6] - x2[6];
  115920. r1 = x1[7] - x2[7];
  115921. x1[6] += x2[6];
  115922. x1[7] += x2[7];
  115923. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115924. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115925. T+=trigint;
  115926. r0 = x1[4] - x2[4];
  115927. r1 = x1[5] - x2[5];
  115928. x1[4] += x2[4];
  115929. x1[5] += x2[5];
  115930. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115931. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115932. T+=trigint;
  115933. r0 = x1[2] - x2[2];
  115934. r1 = x1[3] - x2[3];
  115935. x1[2] += x2[2];
  115936. x1[3] += x2[3];
  115937. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115938. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115939. T+=trigint;
  115940. r0 = x1[0] - x2[0];
  115941. r1 = x1[1] - x2[1];
  115942. x1[0] += x2[0];
  115943. x1[1] += x2[1];
  115944. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115945. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115946. T+=trigint;
  115947. x1-=8;
  115948. x2-=8;
  115949. }while(x2>=x);
  115950. }
  115951. STIN void mdct_butterflies(mdct_lookup *init,
  115952. DATA_TYPE *x,
  115953. int points){
  115954. DATA_TYPE *T=init->trig;
  115955. int stages=init->log2n-5;
  115956. int i,j;
  115957. if(--stages>0){
  115958. mdct_butterfly_first(T,x,points);
  115959. }
  115960. for(i=1;--stages>0;i++){
  115961. for(j=0;j<(1<<i);j++)
  115962. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115963. }
  115964. for(j=0;j<points;j+=32)
  115965. mdct_butterfly_32(x+j);
  115966. }
  115967. void mdct_clear(mdct_lookup *l){
  115968. if(l){
  115969. if(l->trig)_ogg_free(l->trig);
  115970. if(l->bitrev)_ogg_free(l->bitrev);
  115971. memset(l,0,sizeof(*l));
  115972. }
  115973. }
  115974. STIN void mdct_bitreverse(mdct_lookup *init,
  115975. DATA_TYPE *x){
  115976. int n = init->n;
  115977. int *bit = init->bitrev;
  115978. DATA_TYPE *w0 = x;
  115979. DATA_TYPE *w1 = x = w0+(n>>1);
  115980. DATA_TYPE *T = init->trig+n;
  115981. do{
  115982. DATA_TYPE *x0 = x+bit[0];
  115983. DATA_TYPE *x1 = x+bit[1];
  115984. REG_TYPE r0 = x0[1] - x1[1];
  115985. REG_TYPE r1 = x0[0] + x1[0];
  115986. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115987. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115988. w1 -= 4;
  115989. r0 = HALVE(x0[1] + x1[1]);
  115990. r1 = HALVE(x0[0] - x1[0]);
  115991. w0[0] = r0 + r2;
  115992. w1[2] = r0 - r2;
  115993. w0[1] = r1 + r3;
  115994. w1[3] = r3 - r1;
  115995. x0 = x+bit[2];
  115996. x1 = x+bit[3];
  115997. r0 = x0[1] - x1[1];
  115998. r1 = x0[0] + x1[0];
  115999. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116000. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116001. r0 = HALVE(x0[1] + x1[1]);
  116002. r1 = HALVE(x0[0] - x1[0]);
  116003. w0[2] = r0 + r2;
  116004. w1[0] = r0 - r2;
  116005. w0[3] = r1 + r3;
  116006. w1[1] = r3 - r1;
  116007. T += 4;
  116008. bit += 4;
  116009. w0 += 4;
  116010. }while(w0<w1);
  116011. }
  116012. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116013. int n=init->n;
  116014. int n2=n>>1;
  116015. int n4=n>>2;
  116016. /* rotate */
  116017. DATA_TYPE *iX = in+n2-7;
  116018. DATA_TYPE *oX = out+n2+n4;
  116019. DATA_TYPE *T = init->trig+n4;
  116020. do{
  116021. oX -= 4;
  116022. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116023. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116024. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116025. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116026. iX -= 8;
  116027. T += 4;
  116028. }while(iX>=in);
  116029. iX = in+n2-8;
  116030. oX = out+n2+n4;
  116031. T = init->trig+n4;
  116032. do{
  116033. T -= 4;
  116034. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116035. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116036. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116037. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116038. iX -= 8;
  116039. oX += 4;
  116040. }while(iX>=in);
  116041. mdct_butterflies(init,out+n2,n2);
  116042. mdct_bitreverse(init,out);
  116043. /* roatate + window */
  116044. {
  116045. DATA_TYPE *oX1=out+n2+n4;
  116046. DATA_TYPE *oX2=out+n2+n4;
  116047. DATA_TYPE *iX =out;
  116048. T =init->trig+n2;
  116049. do{
  116050. oX1-=4;
  116051. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116052. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116053. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116054. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116055. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116056. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116057. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116058. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116059. oX2+=4;
  116060. iX += 8;
  116061. T += 8;
  116062. }while(iX<oX1);
  116063. iX=out+n2+n4;
  116064. oX1=out+n4;
  116065. oX2=oX1;
  116066. do{
  116067. oX1-=4;
  116068. iX-=4;
  116069. oX2[0] = -(oX1[3] = iX[3]);
  116070. oX2[1] = -(oX1[2] = iX[2]);
  116071. oX2[2] = -(oX1[1] = iX[1]);
  116072. oX2[3] = -(oX1[0] = iX[0]);
  116073. oX2+=4;
  116074. }while(oX2<iX);
  116075. iX=out+n2+n4;
  116076. oX1=out+n2+n4;
  116077. oX2=out+n2;
  116078. do{
  116079. oX1-=4;
  116080. oX1[0]= iX[3];
  116081. oX1[1]= iX[2];
  116082. oX1[2]= iX[1];
  116083. oX1[3]= iX[0];
  116084. iX+=4;
  116085. }while(oX1>oX2);
  116086. }
  116087. }
  116088. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116089. int n=init->n;
  116090. int n2=n>>1;
  116091. int n4=n>>2;
  116092. int n8=n>>3;
  116093. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116094. DATA_TYPE *w2=w+n2;
  116095. /* rotate */
  116096. /* window + rotate + step 1 */
  116097. REG_TYPE r0;
  116098. REG_TYPE r1;
  116099. DATA_TYPE *x0=in+n2+n4;
  116100. DATA_TYPE *x1=x0+1;
  116101. DATA_TYPE *T=init->trig+n2;
  116102. int i=0;
  116103. for(i=0;i<n8;i+=2){
  116104. x0 -=4;
  116105. T-=2;
  116106. r0= x0[2] + x1[0];
  116107. r1= x0[0] + x1[2];
  116108. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116109. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116110. x1 +=4;
  116111. }
  116112. x1=in+1;
  116113. for(;i<n2-n8;i+=2){
  116114. T-=2;
  116115. x0 -=4;
  116116. r0= x0[2] - x1[0];
  116117. r1= x0[0] - x1[2];
  116118. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116119. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116120. x1 +=4;
  116121. }
  116122. x0=in+n;
  116123. for(;i<n2;i+=2){
  116124. T-=2;
  116125. x0 -=4;
  116126. r0= -x0[2] - x1[0];
  116127. r1= -x0[0] - x1[2];
  116128. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116129. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116130. x1 +=4;
  116131. }
  116132. mdct_butterflies(init,w+n2,n2);
  116133. mdct_bitreverse(init,w);
  116134. /* roatate + window */
  116135. T=init->trig+n2;
  116136. x0=out+n2;
  116137. for(i=0;i<n4;i++){
  116138. x0--;
  116139. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116140. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116141. w+=2;
  116142. T+=2;
  116143. }
  116144. }
  116145. #endif
  116146. /*** End of inlined file: mdct.c ***/
  116147. /*** Start of inlined file: psy.c ***/
  116148. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116149. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116150. // tasks..
  116151. #if JUCE_MSVC
  116152. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116153. #endif
  116154. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116155. #if JUCE_USE_OGGVORBIS
  116156. #include <stdlib.h>
  116157. #include <math.h>
  116158. #include <string.h>
  116159. /*** Start of inlined file: masking.h ***/
  116160. #ifndef _V_MASKING_H_
  116161. #define _V_MASKING_H_
  116162. /* more detailed ATH; the bass if flat to save stressing the floor
  116163. overly for only a bin or two of savings. */
  116164. #define MAX_ATH 88
  116165. static float ATH[]={
  116166. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116167. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116168. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116169. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116170. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116171. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116172. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116173. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116174. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116175. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116176. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116177. };
  116178. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116179. replaced by an empirically collected data set. The previously
  116180. published values were, far too often, simply on crack. */
  116181. #define EHMER_OFFSET 16
  116182. #define EHMER_MAX 56
  116183. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116184. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116185. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116186. for collection of these curves) */
  116187. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116188. /* 62.5 Hz */
  116189. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116190. -60, -60, -60, -60, -62, -62, -65, -73,
  116191. -69, -68, -68, -67, -70, -70, -72, -74,
  116192. -75, -79, -79, -80, -83, -88, -93, -100,
  116193. -110, -999, -999, -999, -999, -999, -999, -999,
  116194. -999, -999, -999, -999, -999, -999, -999, -999,
  116195. -999, -999, -999, -999, -999, -999, -999, -999},
  116196. { -48, -48, -48, -48, -48, -48, -48, -48,
  116197. -48, -48, -48, -48, -48, -53, -61, -66,
  116198. -66, -68, -67, -70, -76, -76, -72, -73,
  116199. -75, -76, -78, -79, -83, -88, -93, -100,
  116200. -110, -999, -999, -999, -999, -999, -999, -999,
  116201. -999, -999, -999, -999, -999, -999, -999, -999,
  116202. -999, -999, -999, -999, -999, -999, -999, -999},
  116203. { -37, -37, -37, -37, -37, -37, -37, -37,
  116204. -38, -40, -42, -46, -48, -53, -55, -62,
  116205. -65, -58, -56, -56, -61, -60, -65, -67,
  116206. -69, -71, -77, -77, -78, -80, -82, -84,
  116207. -88, -93, -98, -106, -112, -999, -999, -999,
  116208. -999, -999, -999, -999, -999, -999, -999, -999,
  116209. -999, -999, -999, -999, -999, -999, -999, -999},
  116210. { -25, -25, -25, -25, -25, -25, -25, -25,
  116211. -25, -26, -27, -29, -32, -38, -48, -52,
  116212. -52, -50, -48, -48, -51, -52, -54, -60,
  116213. -67, -67, -66, -68, -69, -73, -73, -76,
  116214. -80, -81, -81, -85, -85, -86, -88, -93,
  116215. -100, -110, -999, -999, -999, -999, -999, -999,
  116216. -999, -999, -999, -999, -999, -999, -999, -999},
  116217. { -16, -16, -16, -16, -16, -16, -16, -16,
  116218. -17, -19, -20, -22, -26, -28, -31, -40,
  116219. -47, -39, -39, -40, -42, -43, -47, -51,
  116220. -57, -52, -55, -55, -60, -58, -62, -63,
  116221. -70, -67, -69, -72, -73, -77, -80, -82,
  116222. -83, -87, -90, -94, -98, -104, -115, -999,
  116223. -999, -999, -999, -999, -999, -999, -999, -999},
  116224. { -8, -8, -8, -8, -8, -8, -8, -8,
  116225. -8, -8, -10, -11, -15, -19, -25, -30,
  116226. -34, -31, -30, -31, -29, -32, -35, -42,
  116227. -48, -42, -44, -46, -50, -50, -51, -52,
  116228. -59, -54, -55, -55, -58, -62, -63, -66,
  116229. -72, -73, -76, -75, -78, -80, -80, -81,
  116230. -84, -88, -90, -94, -98, -101, -106, -110}},
  116231. /* 88Hz */
  116232. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116233. -66, -66, -66, -66, -66, -67, -67, -67,
  116234. -76, -72, -71, -74, -76, -76, -75, -78,
  116235. -79, -79, -81, -83, -86, -89, -93, -97,
  116236. -100, -105, -110, -999, -999, -999, -999, -999,
  116237. -999, -999, -999, -999, -999, -999, -999, -999,
  116238. -999, -999, -999, -999, -999, -999, -999, -999},
  116239. { -47, -47, -47, -47, -47, -47, -47, -47,
  116240. -47, -47, -47, -48, -51, -55, -59, -66,
  116241. -66, -66, -67, -66, -68, -69, -70, -74,
  116242. -79, -77, -77, -78, -80, -81, -82, -84,
  116243. -86, -88, -91, -95, -100, -108, -116, -999,
  116244. -999, -999, -999, -999, -999, -999, -999, -999,
  116245. -999, -999, -999, -999, -999, -999, -999, -999},
  116246. { -36, -36, -36, -36, -36, -36, -36, -36,
  116247. -36, -37, -37, -41, -44, -48, -51, -58,
  116248. -62, -60, -57, -59, -59, -60, -63, -65,
  116249. -72, -71, -70, -72, -74, -77, -76, -78,
  116250. -81, -81, -80, -83, -86, -91, -96, -100,
  116251. -105, -110, -999, -999, -999, -999, -999, -999,
  116252. -999, -999, -999, -999, -999, -999, -999, -999},
  116253. { -28, -28, -28, -28, -28, -28, -28, -28,
  116254. -28, -30, -32, -32, -33, -35, -41, -49,
  116255. -50, -49, -47, -48, -48, -52, -51, -57,
  116256. -65, -61, -59, -61, -64, -69, -70, -74,
  116257. -77, -77, -78, -81, -84, -85, -87, -90,
  116258. -92, -96, -100, -107, -112, -999, -999, -999,
  116259. -999, -999, -999, -999, -999, -999, -999, -999},
  116260. { -19, -19, -19, -19, -19, -19, -19, -19,
  116261. -20, -21, -23, -27, -30, -35, -36, -41,
  116262. -46, -44, -42, -40, -41, -41, -43, -48,
  116263. -55, -53, -52, -53, -56, -59, -58, -60,
  116264. -67, -66, -69, -71, -72, -75, -79, -81,
  116265. -84, -87, -90, -93, -97, -101, -107, -114,
  116266. -999, -999, -999, -999, -999, -999, -999, -999},
  116267. { -9, -9, -9, -9, -9, -9, -9, -9,
  116268. -11, -12, -12, -15, -16, -20, -23, -30,
  116269. -37, -34, -33, -34, -31, -32, -32, -38,
  116270. -47, -44, -41, -40, -47, -49, -46, -46,
  116271. -58, -50, -50, -54, -58, -62, -64, -67,
  116272. -67, -70, -72, -76, -79, -83, -87, -91,
  116273. -96, -100, -104, -110, -999, -999, -999, -999}},
  116274. /* 125 Hz */
  116275. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116276. -62, -62, -63, -64, -66, -67, -66, -68,
  116277. -75, -72, -76, -75, -76, -78, -79, -82,
  116278. -84, -85, -90, -94, -101, -110, -999, -999,
  116279. -999, -999, -999, -999, -999, -999, -999, -999,
  116280. -999, -999, -999, -999, -999, -999, -999, -999,
  116281. -999, -999, -999, -999, -999, -999, -999, -999},
  116282. { -59, -59, -59, -59, -59, -59, -59, -59,
  116283. -59, -59, -59, -60, -60, -61, -63, -66,
  116284. -71, -68, -70, -70, -71, -72, -72, -75,
  116285. -81, -78, -79, -82, -83, -86, -90, -97,
  116286. -103, -113, -999, -999, -999, -999, -999, -999,
  116287. -999, -999, -999, -999, -999, -999, -999, -999,
  116288. -999, -999, -999, -999, -999, -999, -999, -999},
  116289. { -53, -53, -53, -53, -53, -53, -53, -53,
  116290. -53, -54, -55, -57, -56, -57, -55, -61,
  116291. -65, -60, -60, -62, -63, -63, -66, -68,
  116292. -74, -73, -75, -75, -78, -80, -80, -82,
  116293. -85, -90, -96, -101, -108, -999, -999, -999,
  116294. -999, -999, -999, -999, -999, -999, -999, -999,
  116295. -999, -999, -999, -999, -999, -999, -999, -999},
  116296. { -46, -46, -46, -46, -46, -46, -46, -46,
  116297. -46, -46, -47, -47, -47, -47, -48, -51,
  116298. -57, -51, -49, -50, -51, -53, -54, -59,
  116299. -66, -60, -62, -67, -67, -70, -72, -75,
  116300. -76, -78, -81, -85, -88, -94, -97, -104,
  116301. -112, -999, -999, -999, -999, -999, -999, -999,
  116302. -999, -999, -999, -999, -999, -999, -999, -999},
  116303. { -36, -36, -36, -36, -36, -36, -36, -36,
  116304. -39, -41, -42, -42, -39, -38, -41, -43,
  116305. -52, -44, -40, -39, -37, -37, -40, -47,
  116306. -54, -50, -48, -50, -55, -61, -59, -62,
  116307. -66, -66, -66, -69, -69, -73, -74, -74,
  116308. -75, -77, -79, -82, -87, -91, -95, -100,
  116309. -108, -115, -999, -999, -999, -999, -999, -999},
  116310. { -28, -26, -24, -22, -20, -20, -23, -29,
  116311. -30, -31, -28, -27, -28, -28, -28, -35,
  116312. -40, -33, -32, -29, -30, -30, -30, -37,
  116313. -45, -41, -37, -38, -45, -47, -47, -48,
  116314. -53, -49, -48, -50, -49, -49, -51, -52,
  116315. -58, -56, -57, -56, -60, -61, -62, -70,
  116316. -72, -74, -78, -83, -88, -93, -100, -106}},
  116317. /* 177 Hz */
  116318. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116319. -999, -110, -105, -100, -95, -91, -87, -83,
  116320. -80, -78, -76, -78, -78, -81, -83, -85,
  116321. -86, -85, -86, -87, -90, -97, -107, -999,
  116322. -999, -999, -999, -999, -999, -999, -999, -999,
  116323. -999, -999, -999, -999, -999, -999, -999, -999,
  116324. -999, -999, -999, -999, -999, -999, -999, -999},
  116325. {-999, -999, -999, -110, -105, -100, -95, -90,
  116326. -85, -81, -77, -73, -70, -67, -67, -68,
  116327. -75, -73, -70, -69, -70, -72, -75, -79,
  116328. -84, -83, -84, -86, -88, -89, -89, -93,
  116329. -98, -105, -112, -999, -999, -999, -999, -999,
  116330. -999, -999, -999, -999, -999, -999, -999, -999,
  116331. -999, -999, -999, -999, -999, -999, -999, -999},
  116332. {-105, -100, -95, -90, -85, -80, -76, -71,
  116333. -68, -68, -65, -63, -63, -62, -62, -64,
  116334. -65, -64, -61, -62, -63, -64, -66, -68,
  116335. -73, -73, -74, -75, -76, -81, -83, -85,
  116336. -88, -89, -92, -95, -100, -108, -999, -999,
  116337. -999, -999, -999, -999, -999, -999, -999, -999,
  116338. -999, -999, -999, -999, -999, -999, -999, -999},
  116339. { -80, -75, -71, -68, -65, -63, -62, -61,
  116340. -61, -61, -61, -59, -56, -57, -53, -50,
  116341. -58, -52, -50, -50, -52, -53, -54, -58,
  116342. -67, -63, -67, -68, -72, -75, -78, -80,
  116343. -81, -81, -82, -85, -89, -90, -93, -97,
  116344. -101, -107, -114, -999, -999, -999, -999, -999,
  116345. -999, -999, -999, -999, -999, -999, -999, -999},
  116346. { -65, -61, -59, -57, -56, -55, -55, -56,
  116347. -56, -57, -55, -53, -52, -47, -44, -44,
  116348. -50, -44, -41, -39, -39, -42, -40, -46,
  116349. -51, -49, -50, -53, -54, -63, -60, -61,
  116350. -62, -66, -66, -66, -70, -73, -74, -75,
  116351. -76, -75, -79, -85, -89, -91, -96, -102,
  116352. -110, -999, -999, -999, -999, -999, -999, -999},
  116353. { -52, -50, -49, -49, -48, -48, -48, -49,
  116354. -50, -50, -49, -46, -43, -39, -35, -33,
  116355. -38, -36, -32, -29, -32, -32, -32, -35,
  116356. -44, -39, -38, -38, -46, -50, -45, -46,
  116357. -53, -50, -50, -50, -54, -54, -53, -53,
  116358. -56, -57, -59, -66, -70, -72, -74, -79,
  116359. -83, -85, -90, -97, -114, -999, -999, -999}},
  116360. /* 250 Hz */
  116361. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116362. -100, -95, -90, -86, -80, -75, -75, -79,
  116363. -80, -79, -80, -81, -82, -88, -95, -103,
  116364. -110, -999, -999, -999, -999, -999, -999, -999,
  116365. -999, -999, -999, -999, -999, -999, -999, -999,
  116366. -999, -999, -999, -999, -999, -999, -999, -999,
  116367. -999, -999, -999, -999, -999, -999, -999, -999},
  116368. {-999, -999, -999, -999, -108, -103, -98, -93,
  116369. -88, -83, -79, -78, -75, -71, -67, -68,
  116370. -73, -73, -72, -73, -75, -77, -80, -82,
  116371. -88, -93, -100, -107, -114, -999, -999, -999,
  116372. -999, -999, -999, -999, -999, -999, -999, -999,
  116373. -999, -999, -999, -999, -999, -999, -999, -999,
  116374. -999, -999, -999, -999, -999, -999, -999, -999},
  116375. {-999, -999, -999, -110, -105, -101, -96, -90,
  116376. -86, -81, -77, -73, -69, -66, -61, -62,
  116377. -66, -64, -62, -65, -66, -70, -72, -76,
  116378. -81, -80, -84, -90, -95, -102, -110, -999,
  116379. -999, -999, -999, -999, -999, -999, -999, -999,
  116380. -999, -999, -999, -999, -999, -999, -999, -999,
  116381. -999, -999, -999, -999, -999, -999, -999, -999},
  116382. {-999, -999, -999, -107, -103, -97, -92, -88,
  116383. -83, -79, -74, -70, -66, -59, -53, -58,
  116384. -62, -55, -54, -54, -54, -58, -61, -62,
  116385. -72, -70, -72, -75, -78, -80, -81, -80,
  116386. -83, -83, -88, -93, -100, -107, -115, -999,
  116387. -999, -999, -999, -999, -999, -999, -999, -999,
  116388. -999, -999, -999, -999, -999, -999, -999, -999},
  116389. {-999, -999, -999, -105, -100, -95, -90, -85,
  116390. -80, -75, -70, -66, -62, -56, -48, -44,
  116391. -48, -46, -46, -43, -46, -48, -48, -51,
  116392. -58, -58, -59, -60, -62, -62, -61, -61,
  116393. -65, -64, -65, -68, -70, -74, -75, -78,
  116394. -81, -86, -95, -110, -999, -999, -999, -999,
  116395. -999, -999, -999, -999, -999, -999, -999, -999},
  116396. {-999, -999, -105, -100, -95, -90, -85, -80,
  116397. -75, -70, -65, -61, -55, -49, -39, -33,
  116398. -40, -35, -32, -38, -40, -33, -35, -37,
  116399. -46, -41, -45, -44, -46, -42, -45, -46,
  116400. -52, -50, -50, -50, -54, -54, -55, -57,
  116401. -62, -64, -66, -68, -70, -76, -81, -90,
  116402. -100, -110, -999, -999, -999, -999, -999, -999}},
  116403. /* 354 hz */
  116404. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116405. -105, -98, -90, -85, -82, -83, -80, -78,
  116406. -84, -79, -80, -83, -87, -89, -91, -93,
  116407. -99, -106, -117, -999, -999, -999, -999, -999,
  116408. -999, -999, -999, -999, -999, -999, -999, -999,
  116409. -999, -999, -999, -999, -999, -999, -999, -999,
  116410. -999, -999, -999, -999, -999, -999, -999, -999},
  116411. {-999, -999, -999, -999, -999, -999, -999, -999,
  116412. -105, -98, -90, -85, -80, -75, -70, -68,
  116413. -74, -72, -74, -77, -80, -82, -85, -87,
  116414. -92, -89, -91, -95, -100, -106, -112, -999,
  116415. -999, -999, -999, -999, -999, -999, -999, -999,
  116416. -999, -999, -999, -999, -999, -999, -999, -999,
  116417. -999, -999, -999, -999, -999, -999, -999, -999},
  116418. {-999, -999, -999, -999, -999, -999, -999, -999,
  116419. -105, -98, -90, -83, -75, -71, -63, -64,
  116420. -67, -62, -64, -67, -70, -73, -77, -81,
  116421. -84, -83, -85, -89, -90, -93, -98, -104,
  116422. -109, -114, -999, -999, -999, -999, -999, -999,
  116423. -999, -999, -999, -999, -999, -999, -999, -999,
  116424. -999, -999, -999, -999, -999, -999, -999, -999},
  116425. {-999, -999, -999, -999, -999, -999, -999, -999,
  116426. -103, -96, -88, -81, -75, -68, -58, -54,
  116427. -56, -54, -56, -56, -58, -60, -63, -66,
  116428. -74, -69, -72, -72, -75, -74, -77, -81,
  116429. -81, -82, -84, -87, -93, -96, -99, -104,
  116430. -110, -999, -999, -999, -999, -999, -999, -999,
  116431. -999, -999, -999, -999, -999, -999, -999, -999},
  116432. {-999, -999, -999, -999, -999, -108, -102, -96,
  116433. -91, -85, -80, -74, -68, -60, -51, -46,
  116434. -48, -46, -43, -45, -47, -47, -49, -48,
  116435. -56, -53, -55, -58, -57, -63, -58, -60,
  116436. -66, -64, -67, -70, -70, -74, -77, -84,
  116437. -86, -89, -91, -93, -94, -101, -109, -118,
  116438. -999, -999, -999, -999, -999, -999, -999, -999},
  116439. {-999, -999, -999, -108, -103, -98, -93, -88,
  116440. -83, -78, -73, -68, -60, -53, -44, -35,
  116441. -38, -38, -34, -34, -36, -40, -41, -44,
  116442. -51, -45, -46, -47, -46, -54, -50, -49,
  116443. -50, -50, -50, -51, -54, -57, -58, -60,
  116444. -66, -66, -66, -64, -65, -68, -77, -82,
  116445. -87, -95, -110, -999, -999, -999, -999, -999}},
  116446. /* 500 Hz */
  116447. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116448. -107, -102, -97, -92, -87, -83, -78, -75,
  116449. -82, -79, -83, -85, -89, -92, -95, -98,
  116450. -101, -105, -109, -113, -999, -999, -999, -999,
  116451. -999, -999, -999, -999, -999, -999, -999, -999,
  116452. -999, -999, -999, -999, -999, -999, -999, -999,
  116453. -999, -999, -999, -999, -999, -999, -999, -999},
  116454. {-999, -999, -999, -999, -999, -999, -999, -106,
  116455. -100, -95, -90, -86, -81, -78, -74, -69,
  116456. -74, -74, -76, -79, -83, -84, -86, -89,
  116457. -92, -97, -93, -100, -103, -107, -110, -999,
  116458. -999, -999, -999, -999, -999, -999, -999, -999,
  116459. -999, -999, -999, -999, -999, -999, -999, -999,
  116460. -999, -999, -999, -999, -999, -999, -999, -999},
  116461. {-999, -999, -999, -999, -999, -999, -106, -100,
  116462. -95, -90, -87, -83, -80, -75, -69, -60,
  116463. -66, -66, -68, -70, -74, -78, -79, -81,
  116464. -81, -83, -84, -87, -93, -96, -99, -103,
  116465. -107, -110, -999, -999, -999, -999, -999, -999,
  116466. -999, -999, -999, -999, -999, -999, -999, -999,
  116467. -999, -999, -999, -999, -999, -999, -999, -999},
  116468. {-999, -999, -999, -999, -999, -108, -103, -98,
  116469. -93, -89, -85, -82, -78, -71, -62, -55,
  116470. -58, -58, -54, -54, -55, -59, -61, -62,
  116471. -70, -66, -66, -67, -70, -72, -75, -78,
  116472. -84, -84, -84, -88, -91, -90, -95, -98,
  116473. -102, -103, -106, -110, -999, -999, -999, -999,
  116474. -999, -999, -999, -999, -999, -999, -999, -999},
  116475. {-999, -999, -999, -999, -108, -103, -98, -94,
  116476. -90, -87, -82, -79, -73, -67, -58, -47,
  116477. -50, -45, -41, -45, -48, -44, -44, -49,
  116478. -54, -51, -48, -47, -49, -50, -51, -57,
  116479. -58, -60, -63, -69, -70, -69, -71, -74,
  116480. -78, -82, -90, -95, -101, -105, -110, -999,
  116481. -999, -999, -999, -999, -999, -999, -999, -999},
  116482. {-999, -999, -999, -105, -101, -97, -93, -90,
  116483. -85, -80, -77, -72, -65, -56, -48, -37,
  116484. -40, -36, -34, -40, -50, -47, -38, -41,
  116485. -47, -38, -35, -39, -38, -43, -40, -45,
  116486. -50, -45, -44, -47, -50, -55, -48, -48,
  116487. -52, -66, -70, -76, -82, -90, -97, -105,
  116488. -110, -999, -999, -999, -999, -999, -999, -999}},
  116489. /* 707 Hz */
  116490. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116491. -999, -108, -103, -98, -93, -86, -79, -76,
  116492. -83, -81, -85, -87, -89, -93, -98, -102,
  116493. -107, -112, -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, -999, -999, -999, -999, -999},
  116497. {-999, -999, -999, -999, -999, -999, -999, -999,
  116498. -999, -108, -103, -98, -93, -86, -79, -71,
  116499. -77, -74, -77, -79, -81, -84, -85, -90,
  116500. -92, -93, -92, -98, -101, -108, -112, -999,
  116501. -999, -999, -999, -999, -999, -999, -999, -999,
  116502. -999, -999, -999, -999, -999, -999, -999, -999,
  116503. -999, -999, -999, -999, -999, -999, -999, -999},
  116504. {-999, -999, -999, -999, -999, -999, -999, -999,
  116505. -108, -103, -98, -93, -87, -78, -68, -65,
  116506. -66, -62, -65, -67, -70, -73, -75, -78,
  116507. -82, -82, -83, -84, -91, -93, -98, -102,
  116508. -106, -110, -999, -999, -999, -999, -999, -999,
  116509. -999, -999, -999, -999, -999, -999, -999, -999,
  116510. -999, -999, -999, -999, -999, -999, -999, -999},
  116511. {-999, -999, -999, -999, -999, -999, -999, -999,
  116512. -105, -100, -95, -90, -82, -74, -62, -57,
  116513. -58, -56, -51, -52, -52, -54, -54, -58,
  116514. -66, -59, -60, -63, -66, -69, -73, -79,
  116515. -83, -84, -80, -81, -81, -82, -88, -92,
  116516. -98, -105, -113, -999, -999, -999, -999, -999,
  116517. -999, -999, -999, -999, -999, -999, -999, -999},
  116518. {-999, -999, -999, -999, -999, -999, -999, -107,
  116519. -102, -97, -92, -84, -79, -69, -57, -47,
  116520. -52, -47, -44, -45, -50, -52, -42, -42,
  116521. -53, -43, -43, -48, -51, -56, -55, -52,
  116522. -57, -59, -61, -62, -67, -71, -78, -83,
  116523. -86, -94, -98, -103, -110, -999, -999, -999,
  116524. -999, -999, -999, -999, -999, -999, -999, -999},
  116525. {-999, -999, -999, -999, -999, -999, -105, -100,
  116526. -95, -90, -84, -78, -70, -61, -51, -41,
  116527. -40, -38, -40, -46, -52, -51, -41, -40,
  116528. -46, -40, -38, -38, -41, -46, -41, -46,
  116529. -47, -43, -43, -45, -41, -45, -56, -67,
  116530. -68, -83, -87, -90, -95, -102, -107, -113,
  116531. -999, -999, -999, -999, -999, -999, -999, -999}},
  116532. /* 1000 Hz */
  116533. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116534. -999, -109, -105, -101, -96, -91, -84, -77,
  116535. -82, -82, -85, -89, -94, -100, -106, -110,
  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, -999, -999, -999, -999},
  116540. {-999, -999, -999, -999, -999, -999, -999, -999,
  116541. -999, -106, -103, -98, -92, -85, -80, -71,
  116542. -75, -72, -76, -80, -84, -86, -89, -93,
  116543. -100, -107, -113, -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, -999, -999, -999, -999, -999},
  116547. {-999, -999, -999, -999, -999, -999, -999, -107,
  116548. -104, -101, -97, -92, -88, -84, -80, -64,
  116549. -66, -63, -64, -66, -69, -73, -77, -83,
  116550. -83, -86, -91, -98, -104, -111, -999, -999,
  116551. -999, -999, -999, -999, -999, -999, -999, -999,
  116552. -999, -999, -999, -999, -999, -999, -999, -999,
  116553. -999, -999, -999, -999, -999, -999, -999, -999},
  116554. {-999, -999, -999, -999, -999, -999, -999, -107,
  116555. -104, -101, -97, -92, -90, -84, -74, -57,
  116556. -58, -52, -55, -54, -50, -52, -50, -52,
  116557. -63, -62, -69, -76, -77, -78, -78, -79,
  116558. -82, -88, -94, -100, -106, -111, -999, -999,
  116559. -999, -999, -999, -999, -999, -999, -999, -999,
  116560. -999, -999, -999, -999, -999, -999, -999, -999},
  116561. {-999, -999, -999, -999, -999, -999, -106, -102,
  116562. -98, -95, -90, -85, -83, -78, -70, -50,
  116563. -50, -41, -44, -49, -47, -50, -50, -44,
  116564. -55, -46, -47, -48, -48, -54, -49, -49,
  116565. -58, -62, -71, -81, -87, -92, -97, -102,
  116566. -108, -114, -999, -999, -999, -999, -999, -999,
  116567. -999, -999, -999, -999, -999, -999, -999, -999},
  116568. {-999, -999, -999, -999, -999, -999, -106, -102,
  116569. -98, -95, -90, -85, -83, -78, -70, -45,
  116570. -43, -41, -47, -50, -51, -50, -49, -45,
  116571. -47, -41, -44, -41, -39, -43, -38, -37,
  116572. -40, -41, -44, -50, -58, -65, -73, -79,
  116573. -85, -92, -97, -101, -105, -109, -113, -999,
  116574. -999, -999, -999, -999, -999, -999, -999, -999}},
  116575. /* 1414 Hz */
  116576. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116577. -999, -999, -999, -107, -100, -95, -87, -81,
  116578. -85, -83, -88, -93, -100, -107, -114, -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, -999, -999, -999, -999, -999, -999},
  116583. {-999, -999, -999, -999, -999, -999, -999, -999,
  116584. -999, -999, -107, -101, -95, -88, -83, -76,
  116585. -73, -72, -79, -84, -90, -95, -100, -105,
  116586. -110, -115, -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, -999, -999, -999, -999, -999, -999, -999},
  116590. {-999, -999, -999, -999, -999, -999, -999, -999,
  116591. -999, -999, -104, -98, -92, -87, -81, -70,
  116592. -65, -62, -67, -71, -74, -80, -85, -91,
  116593. -95, -99, -103, -108, -111, -114, -999, -999,
  116594. -999, -999, -999, -999, -999, -999, -999, -999,
  116595. -999, -999, -999, -999, -999, -999, -999, -999,
  116596. -999, -999, -999, -999, -999, -999, -999, -999},
  116597. {-999, -999, -999, -999, -999, -999, -999, -999,
  116598. -999, -999, -103, -97, -90, -85, -76, -60,
  116599. -56, -54, -60, -62, -61, -56, -63, -65,
  116600. -73, -74, -77, -75, -78, -81, -86, -87,
  116601. -88, -91, -94, -98, -103, -110, -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, -999, -999, -999, -105,
  116605. -100, -97, -92, -86, -81, -79, -70, -57,
  116606. -51, -47, -51, -58, -60, -56, -53, -50,
  116607. -58, -52, -50, -50, -53, -55, -64, -69,
  116608. -71, -85, -82, -78, -81, -85, -95, -102,
  116609. -112, -999, -999, -999, -999, -999, -999, -999,
  116610. -999, -999, -999, -999, -999, -999, -999, -999},
  116611. {-999, -999, -999, -999, -999, -999, -999, -105,
  116612. -100, -97, -92, -85, -83, -79, -72, -49,
  116613. -40, -43, -43, -54, -56, -51, -50, -40,
  116614. -43, -38, -36, -35, -37, -38, -37, -44,
  116615. -54, -60, -57, -60, -70, -75, -84, -92,
  116616. -103, -112, -999, -999, -999, -999, -999, -999,
  116617. -999, -999, -999, -999, -999, -999, -999, -999}},
  116618. /* 2000 Hz */
  116619. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116620. -999, -999, -999, -110, -102, -95, -89, -82,
  116621. -83, -84, -90, -92, -99, -107, -113, -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, -999, -999, -999, -999, -999},
  116626. {-999, -999, -999, -999, -999, -999, -999, -999,
  116627. -999, -999, -107, -101, -95, -89, -83, -72,
  116628. -74, -78, -85, -88, -88, -90, -92, -98,
  116629. -105, -111, -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, -999, -999, -999, -999, -999},
  116633. {-999, -999, -999, -999, -999, -999, -999, -999,
  116634. -999, -109, -103, -97, -93, -87, -81, -70,
  116635. -70, -67, -75, -73, -76, -79, -81, -83,
  116636. -88, -89, -97, -103, -110, -999, -999, -999,
  116637. -999, -999, -999, -999, -999, -999, -999, -999,
  116638. -999, -999, -999, -999, -999, -999, -999, -999,
  116639. -999, -999, -999, -999, -999, -999, -999, -999},
  116640. {-999, -999, -999, -999, -999, -999, -999, -999,
  116641. -999, -107, -100, -94, -88, -83, -75, -63,
  116642. -59, -59, -63, -66, -60, -62, -67, -67,
  116643. -77, -76, -81, -88, -86, -92, -96, -102,
  116644. -109, -116, -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, -999, -999, -999,
  116648. -999, -105, -98, -92, -86, -81, -73, -56,
  116649. -52, -47, -55, -60, -58, -52, -51, -45,
  116650. -49, -50, -53, -54, -61, -71, -70, -69,
  116651. -78, -79, -87, -90, -96, -104, -112, -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, -999, -999, -999,
  116655. -999, -103, -96, -90, -86, -78, -70, -51,
  116656. -42, -47, -48, -55, -54, -54, -53, -42,
  116657. -35, -28, -33, -38, -37, -44, -47, -49,
  116658. -54, -63, -68, -78, -82, -89, -94, -99,
  116659. -104, -109, -114, -999, -999, -999, -999, -999,
  116660. -999, -999, -999, -999, -999, -999, -999, -999}},
  116661. /* 2828 Hz */
  116662. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116663. -999, -999, -999, -999, -110, -100, -90, -79,
  116664. -85, -81, -82, -82, -89, -94, -99, -103,
  116665. -109, -115, -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, -999, -999, -999, -999},
  116669. {-999, -999, -999, -999, -999, -999, -999, -999,
  116670. -999, -999, -999, -999, -105, -97, -85, -72,
  116671. -74, -70, -70, -70, -76, -85, -91, -93,
  116672. -97, -103, -109, -115, -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, -999, -999, -999, -999},
  116676. {-999, -999, -999, -999, -999, -999, -999, -999,
  116677. -999, -999, -999, -999, -112, -93, -81, -68,
  116678. -62, -60, -60, -57, -63, -70, -77, -82,
  116679. -90, -93, -98, -104, -109, -113, -999, -999,
  116680. -999, -999, -999, -999, -999, -999, -999, -999,
  116681. -999, -999, -999, -999, -999, -999, -999, -999,
  116682. -999, -999, -999, -999, -999, -999, -999, -999},
  116683. {-999, -999, -999, -999, -999, -999, -999, -999,
  116684. -999, -999, -999, -113, -100, -93, -84, -63,
  116685. -58, -48, -53, -54, -52, -52, -57, -64,
  116686. -66, -76, -83, -81, -85, -85, -90, -95,
  116687. -98, -101, -103, -106, -108, -111, -999, -999,
  116688. -999, -999, -999, -999, -999, -999, -999, -999,
  116689. -999, -999, -999, -999, -999, -999, -999, -999},
  116690. {-999, -999, -999, -999, -999, -999, -999, -999,
  116691. -999, -999, -999, -105, -95, -86, -74, -53,
  116692. -50, -38, -43, -49, -43, -42, -39, -39,
  116693. -46, -52, -57, -56, -72, -69, -74, -81,
  116694. -87, -92, -94, -97, -99, -102, -105, -108,
  116695. -999, -999, -999, -999, -999, -999, -999, -999,
  116696. -999, -999, -999, -999, -999, -999, -999, -999},
  116697. {-999, -999, -999, -999, -999, -999, -999, -999,
  116698. -999, -999, -108, -99, -90, -76, -66, -45,
  116699. -43, -41, -44, -47, -43, -47, -40, -30,
  116700. -31, -31, -39, -33, -40, -41, -43, -53,
  116701. -59, -70, -73, -77, -79, -82, -84, -87,
  116702. -999, -999, -999, -999, -999, -999, -999, -999,
  116703. -999, -999, -999, -999, -999, -999, -999, -999}},
  116704. /* 4000 Hz */
  116705. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116706. -999, -999, -999, -999, -999, -110, -91, -76,
  116707. -75, -85, -93, -98, -104, -110, -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, -999, -999, -999, -999, -999},
  116712. {-999, -999, -999, -999, -999, -999, -999, -999,
  116713. -999, -999, -999, -999, -999, -110, -91, -70,
  116714. -70, -75, -86, -89, -94, -98, -101, -106,
  116715. -110, -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, -999, -999, -999, -999, -999},
  116719. {-999, -999, -999, -999, -999, -999, -999, -999,
  116720. -999, -999, -999, -999, -110, -95, -80, -60,
  116721. -65, -64, -74, -83, -88, -91, -95, -99,
  116722. -103, -107, -110, -999, -999, -999, -999, -999,
  116723. -999, -999, -999, -999, -999, -999, -999, -999,
  116724. -999, -999, -999, -999, -999, -999, -999, -999,
  116725. -999, -999, -999, -999, -999, -999, -999, -999},
  116726. {-999, -999, -999, -999, -999, -999, -999, -999,
  116727. -999, -999, -999, -999, -110, -95, -80, -58,
  116728. -55, -49, -66, -68, -71, -78, -78, -80,
  116729. -88, -85, -89, -97, -100, -105, -110, -999,
  116730. -999, -999, -999, -999, -999, -999, -999, -999,
  116731. -999, -999, -999, -999, -999, -999, -999, -999,
  116732. -999, -999, -999, -999, -999, -999, -999, -999},
  116733. {-999, -999, -999, -999, -999, -999, -999, -999,
  116734. -999, -999, -999, -999, -110, -95, -80, -53,
  116735. -52, -41, -59, -59, -49, -58, -56, -63,
  116736. -86, -79, -90, -93, -98, -103, -107, -112,
  116737. -999, -999, -999, -999, -999, -999, -999, -999,
  116738. -999, -999, -999, -999, -999, -999, -999, -999,
  116739. -999, -999, -999, -999, -999, -999, -999, -999},
  116740. {-999, -999, -999, -999, -999, -999, -999, -999,
  116741. -999, -999, -999, -110, -97, -91, -73, -45,
  116742. -40, -33, -53, -61, -49, -54, -50, -50,
  116743. -60, -52, -67, -74, -81, -92, -96, -100,
  116744. -105, -110, -999, -999, -999, -999, -999, -999,
  116745. -999, -999, -999, -999, -999, -999, -999, -999,
  116746. -999, -999, -999, -999, -999, -999, -999, -999}},
  116747. /* 5657 Hz */
  116748. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116749. -999, -999, -999, -113, -106, -99, -92, -77,
  116750. -80, -88, -97, -106, -115, -999, -999, -999,
  116751. -999, -999, -999, -999, -999, -999, -999, -999,
  116752. -999, -999, -999, -999, -999, -999, -999, -999,
  116753. -999, -999, -999, -999, -999, -999, -999, -999,
  116754. -999, -999, -999, -999, -999, -999, -999, -999},
  116755. {-999, -999, -999, -999, -999, -999, -999, -999,
  116756. -999, -999, -116, -109, -102, -95, -89, -74,
  116757. -72, -88, -87, -95, -102, -109, -116, -999,
  116758. -999, -999, -999, -999, -999, -999, -999, -999,
  116759. -999, -999, -999, -999, -999, -999, -999, -999,
  116760. -999, -999, -999, -999, -999, -999, -999, -999,
  116761. -999, -999, -999, -999, -999, -999, -999, -999},
  116762. {-999, -999, -999, -999, -999, -999, -999, -999,
  116763. -999, -999, -116, -109, -102, -95, -89, -75,
  116764. -66, -74, -77, -78, -86, -87, -90, -96,
  116765. -105, -115, -999, -999, -999, -999, -999, -999,
  116766. -999, -999, -999, -999, -999, -999, -999, -999,
  116767. -999, -999, -999, -999, -999, -999, -999, -999,
  116768. -999, -999, -999, -999, -999, -999, -999, -999},
  116769. {-999, -999, -999, -999, -999, -999, -999, -999,
  116770. -999, -999, -115, -108, -101, -94, -88, -66,
  116771. -56, -61, -70, -65, -78, -72, -83, -84,
  116772. -93, -98, -105, -110, -999, -999, -999, -999,
  116773. -999, -999, -999, -999, -999, -999, -999, -999,
  116774. -999, -999, -999, -999, -999, -999, -999, -999,
  116775. -999, -999, -999, -999, -999, -999, -999, -999},
  116776. {-999, -999, -999, -999, -999, -999, -999, -999,
  116777. -999, -999, -110, -105, -95, -89, -82, -57,
  116778. -52, -52, -59, -56, -59, -58, -69, -67,
  116779. -88, -82, -82, -89, -94, -100, -108, -999,
  116780. -999, -999, -999, -999, -999, -999, -999, -999,
  116781. -999, -999, -999, -999, -999, -999, -999, -999,
  116782. -999, -999, -999, -999, -999, -999, -999, -999},
  116783. {-999, -999, -999, -999, -999, -999, -999, -999,
  116784. -999, -110, -101, -96, -90, -83, -77, -54,
  116785. -43, -38, -50, -48, -52, -48, -42, -42,
  116786. -51, -52, -53, -59, -65, -71, -78, -85,
  116787. -95, -999, -999, -999, -999, -999, -999, -999,
  116788. -999, -999, -999, -999, -999, -999, -999, -999,
  116789. -999, -999, -999, -999, -999, -999, -999, -999}},
  116790. /* 8000 Hz */
  116791. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116792. -999, -999, -999, -999, -120, -105, -86, -68,
  116793. -78, -79, -90, -100, -110, -999, -999, -999,
  116794. -999, -999, -999, -999, -999, -999, -999, -999,
  116795. -999, -999, -999, -999, -999, -999, -999, -999,
  116796. -999, -999, -999, -999, -999, -999, -999, -999,
  116797. -999, -999, -999, -999, -999, -999, -999, -999},
  116798. {-999, -999, -999, -999, -999, -999, -999, -999,
  116799. -999, -999, -999, -999, -120, -105, -86, -66,
  116800. -73, -77, -88, -96, -105, -115, -999, -999,
  116801. -999, -999, -999, -999, -999, -999, -999, -999,
  116802. -999, -999, -999, -999, -999, -999, -999, -999,
  116803. -999, -999, -999, -999, -999, -999, -999, -999,
  116804. -999, -999, -999, -999, -999, -999, -999, -999},
  116805. {-999, -999, -999, -999, -999, -999, -999, -999,
  116806. -999, -999, -999, -120, -105, -92, -80, -61,
  116807. -64, -68, -80, -87, -92, -100, -110, -999,
  116808. -999, -999, -999, -999, -999, -999, -999, -999,
  116809. -999, -999, -999, -999, -999, -999, -999, -999,
  116810. -999, -999, -999, -999, -999, -999, -999, -999,
  116811. -999, -999, -999, -999, -999, -999, -999, -999},
  116812. {-999, -999, -999, -999, -999, -999, -999, -999,
  116813. -999, -999, -999, -120, -104, -91, -79, -52,
  116814. -60, -54, -64, -69, -77, -80, -82, -84,
  116815. -85, -87, -88, -90, -999, -999, -999, -999,
  116816. -999, -999, -999, -999, -999, -999, -999, -999,
  116817. -999, -999, -999, -999, -999, -999, -999, -999,
  116818. -999, -999, -999, -999, -999, -999, -999, -999},
  116819. {-999, -999, -999, -999, -999, -999, -999, -999,
  116820. -999, -999, -999, -118, -100, -87, -77, -49,
  116821. -50, -44, -58, -61, -61, -67, -65, -62,
  116822. -62, -62, -65, -68, -999, -999, -999, -999,
  116823. -999, -999, -999, -999, -999, -999, -999, -999,
  116824. -999, -999, -999, -999, -999, -999, -999, -999,
  116825. -999, -999, -999, -999, -999, -999, -999, -999},
  116826. {-999, -999, -999, -999, -999, -999, -999, -999,
  116827. -999, -999, -999, -115, -98, -84, -62, -49,
  116828. -44, -38, -46, -49, -49, -46, -39, -37,
  116829. -39, -40, -42, -43, -999, -999, -999, -999,
  116830. -999, -999, -999, -999, -999, -999, -999, -999,
  116831. -999, -999, -999, -999, -999, -999, -999, -999,
  116832. -999, -999, -999, -999, -999, -999, -999, -999}},
  116833. /* 11314 Hz */
  116834. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116835. -999, -999, -999, -999, -999, -110, -88, -74,
  116836. -77, -82, -82, -85, -90, -94, -99, -104,
  116837. -999, -999, -999, -999, -999, -999, -999, -999,
  116838. -999, -999, -999, -999, -999, -999, -999, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999,
  116840. -999, -999, -999, -999, -999, -999, -999, -999},
  116841. {-999, -999, -999, -999, -999, -999, -999, -999,
  116842. -999, -999, -999, -999, -999, -110, -88, -66,
  116843. -70, -81, -80, -81, -84, -88, -91, -93,
  116844. -999, -999, -999, -999, -999, -999, -999, -999,
  116845. -999, -999, -999, -999, -999, -999, -999, -999,
  116846. -999, -999, -999, -999, -999, -999, -999, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999},
  116848. {-999, -999, -999, -999, -999, -999, -999, -999,
  116849. -999, -999, -999, -999, -999, -110, -88, -61,
  116850. -63, -70, -71, -74, -77, -80, -83, -85,
  116851. -999, -999, -999, -999, -999, -999, -999, -999,
  116852. -999, -999, -999, -999, -999, -999, -999, -999,
  116853. -999, -999, -999, -999, -999, -999, -999, -999,
  116854. -999, -999, -999, -999, -999, -999, -999, -999},
  116855. {-999, -999, -999, -999, -999, -999, -999, -999,
  116856. -999, -999, -999, -999, -999, -110, -86, -62,
  116857. -63, -62, -62, -58, -52, -50, -50, -52,
  116858. -54, -999, -999, -999, -999, -999, -999, -999,
  116859. -999, -999, -999, -999, -999, -999, -999, -999,
  116860. -999, -999, -999, -999, -999, -999, -999, -999,
  116861. -999, -999, -999, -999, -999, -999, -999, -999},
  116862. {-999, -999, -999, -999, -999, -999, -999, -999,
  116863. -999, -999, -999, -999, -118, -108, -84, -53,
  116864. -50, -50, -50, -55, -47, -45, -40, -40,
  116865. -40, -999, -999, -999, -999, -999, -999, -999,
  116866. -999, -999, -999, -999, -999, -999, -999, -999,
  116867. -999, -999, -999, -999, -999, -999, -999, -999,
  116868. -999, -999, -999, -999, -999, -999, -999, -999},
  116869. {-999, -999, -999, -999, -999, -999, -999, -999,
  116870. -999, -999, -999, -999, -118, -100, -73, -43,
  116871. -37, -42, -43, -53, -38, -37, -35, -35,
  116872. -38, -999, -999, -999, -999, -999, -999, -999,
  116873. -999, -999, -999, -999, -999, -999, -999, -999,
  116874. -999, -999, -999, -999, -999, -999, -999, -999,
  116875. -999, -999, -999, -999, -999, -999, -999, -999}},
  116876. /* 16000 Hz */
  116877. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116878. -999, -999, -999, -110, -100, -91, -84, -74,
  116879. -80, -80, -80, -80, -80, -999, -999, -999,
  116880. -999, -999, -999, -999, -999, -999, -999, -999,
  116881. -999, -999, -999, -999, -999, -999, -999, -999,
  116882. -999, -999, -999, -999, -999, -999, -999, -999,
  116883. -999, -999, -999, -999, -999, -999, -999, -999},
  116884. {-999, -999, -999, -999, -999, -999, -999, -999,
  116885. -999, -999, -999, -110, -100, -91, -84, -74,
  116886. -68, -68, -68, -68, -68, -999, -999, -999,
  116887. -999, -999, -999, -999, -999, -999, -999, -999,
  116888. -999, -999, -999, -999, -999, -999, -999, -999,
  116889. -999, -999, -999, -999, -999, -999, -999, -999,
  116890. -999, -999, -999, -999, -999, -999, -999, -999},
  116891. {-999, -999, -999, -999, -999, -999, -999, -999,
  116892. -999, -999, -999, -110, -100, -86, -78, -70,
  116893. -60, -45, -30, -21, -999, -999, -999, -999,
  116894. -999, -999, -999, -999, -999, -999, -999, -999,
  116895. -999, -999, -999, -999, -999, -999, -999, -999,
  116896. -999, -999, -999, -999, -999, -999, -999, -999,
  116897. -999, -999, -999, -999, -999, -999, -999, -999},
  116898. {-999, -999, -999, -999, -999, -999, -999, -999,
  116899. -999, -999, -999, -110, -100, -87, -78, -67,
  116900. -48, -38, -29, -21, -999, -999, -999, -999,
  116901. -999, -999, -999, -999, -999, -999, -999, -999,
  116902. -999, -999, -999, -999, -999, -999, -999, -999,
  116903. -999, -999, -999, -999, -999, -999, -999, -999,
  116904. -999, -999, -999, -999, -999, -999, -999, -999},
  116905. {-999, -999, -999, -999, -999, -999, -999, -999,
  116906. -999, -999, -999, -110, -100, -86, -69, -56,
  116907. -45, -35, -33, -29, -999, -999, -999, -999,
  116908. -999, -999, -999, -999, -999, -999, -999, -999,
  116909. -999, -999, -999, -999, -999, -999, -999, -999,
  116910. -999, -999, -999, -999, -999, -999, -999, -999,
  116911. -999, -999, -999, -999, -999, -999, -999, -999},
  116912. {-999, -999, -999, -999, -999, -999, -999, -999,
  116913. -999, -999, -999, -110, -100, -83, -71, -48,
  116914. -27, -38, -37, -34, -999, -999, -999, -999,
  116915. -999, -999, -999, -999, -999, -999, -999, -999,
  116916. -999, -999, -999, -999, -999, -999, -999, -999,
  116917. -999, -999, -999, -999, -999, -999, -999, -999,
  116918. -999, -999, -999, -999, -999, -999, -999, -999}}
  116919. };
  116920. #endif
  116921. /*** End of inlined file: masking.h ***/
  116922. #define NEGINF -9999.f
  116923. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116924. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116925. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116926. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116927. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116928. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116929. look->channels=vi->channels;
  116930. look->ampmax=-9999.;
  116931. look->gi=gi;
  116932. return(look);
  116933. }
  116934. void _vp_global_free(vorbis_look_psy_global *look){
  116935. if(look){
  116936. memset(look,0,sizeof(*look));
  116937. _ogg_free(look);
  116938. }
  116939. }
  116940. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116941. if(i){
  116942. memset(i,0,sizeof(*i));
  116943. _ogg_free(i);
  116944. }
  116945. }
  116946. void _vi_psy_free(vorbis_info_psy *i){
  116947. if(i){
  116948. memset(i,0,sizeof(*i));
  116949. _ogg_free(i);
  116950. }
  116951. }
  116952. static void min_curve(float *c,
  116953. float *c2){
  116954. int i;
  116955. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116956. }
  116957. static void max_curve(float *c,
  116958. float *c2){
  116959. int i;
  116960. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116961. }
  116962. static void attenuate_curve(float *c,float att){
  116963. int i;
  116964. for(i=0;i<EHMER_MAX;i++)
  116965. c[i]+=att;
  116966. }
  116967. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116968. float center_boost, float center_decay_rate){
  116969. int i,j,k,m;
  116970. float ath[EHMER_MAX];
  116971. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116972. float athc[P_LEVELS][EHMER_MAX];
  116973. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116974. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116975. memset(workc,0,sizeof(workc));
  116976. for(i=0;i<P_BANDS;i++){
  116977. /* we add back in the ATH to avoid low level curves falling off to
  116978. -infinity and unnecessarily cutting off high level curves in the
  116979. curve limiting (last step). */
  116980. /* A half-band's settings must be valid over the whole band, and
  116981. it's better to mask too little than too much */
  116982. int ath_offset=i*4;
  116983. for(j=0;j<EHMER_MAX;j++){
  116984. float min=999.;
  116985. for(k=0;k<4;k++)
  116986. if(j+k+ath_offset<MAX_ATH){
  116987. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116988. }else{
  116989. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116990. }
  116991. ath[j]=min;
  116992. }
  116993. /* copy curves into working space, replicate the 50dB curve to 30
  116994. and 40, replicate the 100dB curve to 110 */
  116995. for(j=0;j<6;j++)
  116996. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116997. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116998. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116999. /* apply centered curve boost/decay */
  117000. for(j=0;j<P_LEVELS;j++){
  117001. for(k=0;k<EHMER_MAX;k++){
  117002. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117003. if(adj<0. && center_boost>0)adj=0.;
  117004. if(adj>0. && center_boost<0)adj=0.;
  117005. workc[i][j][k]+=adj;
  117006. }
  117007. }
  117008. /* normalize curves so the driving amplitude is 0dB */
  117009. /* make temp curves with the ATH overlayed */
  117010. for(j=0;j<P_LEVELS;j++){
  117011. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117012. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117013. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117014. max_curve(athc[j],workc[i][j]);
  117015. }
  117016. /* Now limit the louder curves.
  117017. the idea is this: We don't know what the playback attenuation
  117018. will be; 0dB SL moves every time the user twiddles the volume
  117019. knob. So that means we have to use a single 'most pessimal' curve
  117020. for all masking amplitudes, right? Wrong. The *loudest* sound
  117021. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117022. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117023. etc... */
  117024. for(j=1;j<P_LEVELS;j++){
  117025. min_curve(athc[j],athc[j-1]);
  117026. min_curve(workc[i][j],athc[j]);
  117027. }
  117028. }
  117029. for(i=0;i<P_BANDS;i++){
  117030. int hi_curve,lo_curve,bin;
  117031. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117032. /* low frequency curves are measured with greater resolution than
  117033. the MDCT/FFT will actually give us; we want the curve applied
  117034. to the tone data to be pessimistic and thus apply the minimum
  117035. masking possible for a given bin. That means that a single bin
  117036. could span more than one octave and that the curve will be a
  117037. composite of multiple octaves. It also may mean that a single
  117038. bin may span > an eighth of an octave and that the eighth
  117039. octave values may also be composited. */
  117040. /* which octave curves will we be compositing? */
  117041. bin=floor(fromOC(i*.5)/binHz);
  117042. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117043. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117044. if(lo_curve>i)lo_curve=i;
  117045. if(lo_curve<0)lo_curve=0;
  117046. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117047. for(m=0;m<P_LEVELS;m++){
  117048. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117049. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117050. /* render the curve into bins, then pull values back into curve.
  117051. The point is that any inherent subsampling aliasing results in
  117052. a safe minimum */
  117053. for(k=lo_curve;k<=hi_curve;k++){
  117054. int l=0;
  117055. for(j=0;j<EHMER_MAX;j++){
  117056. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117057. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117058. if(lo_bin<0)lo_bin=0;
  117059. if(lo_bin>n)lo_bin=n;
  117060. if(lo_bin<l)l=lo_bin;
  117061. if(hi_bin<0)hi_bin=0;
  117062. if(hi_bin>n)hi_bin=n;
  117063. for(;l<hi_bin && l<n;l++)
  117064. if(brute_buffer[l]>workc[k][m][j])
  117065. brute_buffer[l]=workc[k][m][j];
  117066. }
  117067. for(;l<n;l++)
  117068. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117069. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117070. }
  117071. /* be equally paranoid about being valid up to next half ocatve */
  117072. if(i+1<P_BANDS){
  117073. int l=0;
  117074. k=i+1;
  117075. for(j=0;j<EHMER_MAX;j++){
  117076. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117077. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117078. if(lo_bin<0)lo_bin=0;
  117079. if(lo_bin>n)lo_bin=n;
  117080. if(lo_bin<l)l=lo_bin;
  117081. if(hi_bin<0)hi_bin=0;
  117082. if(hi_bin>n)hi_bin=n;
  117083. for(;l<hi_bin && l<n;l++)
  117084. if(brute_buffer[l]>workc[k][m][j])
  117085. brute_buffer[l]=workc[k][m][j];
  117086. }
  117087. for(;l<n;l++)
  117088. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117089. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117090. }
  117091. for(j=0;j<EHMER_MAX;j++){
  117092. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117093. if(bin<0){
  117094. ret[i][m][j+2]=-999.;
  117095. }else{
  117096. if(bin>=n){
  117097. ret[i][m][j+2]=-999.;
  117098. }else{
  117099. ret[i][m][j+2]=brute_buffer[bin];
  117100. }
  117101. }
  117102. }
  117103. /* add fenceposts */
  117104. for(j=0;j<EHMER_OFFSET;j++)
  117105. if(ret[i][m][j+2]>-200.f)break;
  117106. ret[i][m][0]=j;
  117107. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117108. if(ret[i][m][j+2]>-200.f)
  117109. break;
  117110. ret[i][m][1]=j;
  117111. }
  117112. }
  117113. return(ret);
  117114. }
  117115. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117116. vorbis_info_psy_global *gi,int n,long rate){
  117117. long i,j,lo=-99,hi=1;
  117118. long maxoc;
  117119. memset(p,0,sizeof(*p));
  117120. p->eighth_octave_lines=gi->eighth_octave_lines;
  117121. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117122. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117123. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117124. p->total_octave_lines=maxoc-p->firstoc+1;
  117125. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117126. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117127. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117128. p->vi=vi;
  117129. p->n=n;
  117130. p->rate=rate;
  117131. /* AoTuV HF weighting */
  117132. p->m_val = 1.;
  117133. if(rate < 26000) p->m_val = 0;
  117134. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117135. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117136. /* set up the lookups for a given blocksize and sample rate */
  117137. for(i=0,j=0;i<MAX_ATH-1;i++){
  117138. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117139. float base=ATH[i];
  117140. if(j<endpos){
  117141. float delta=(ATH[i+1]-base)/(endpos-j);
  117142. for(;j<endpos && j<n;j++){
  117143. p->ath[j]=base+100.;
  117144. base+=delta;
  117145. }
  117146. }
  117147. }
  117148. for(i=0;i<n;i++){
  117149. float bark=toBARK(rate/(2*n)*i);
  117150. for(;lo+vi->noisewindowlomin<i &&
  117151. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117152. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117153. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117154. p->bark[i]=((lo-1)<<16)+(hi-1);
  117155. }
  117156. for(i=0;i<n;i++)
  117157. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117158. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117159. vi->tone_centerboost,vi->tone_decay);
  117160. /* set up rolling noise median */
  117161. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117162. for(i=0;i<P_NOISECURVES;i++)
  117163. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117164. for(i=0;i<n;i++){
  117165. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117166. int inthalfoc;
  117167. float del;
  117168. if(halfoc<0)halfoc=0;
  117169. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117170. inthalfoc=(int)halfoc;
  117171. del=halfoc-inthalfoc;
  117172. for(j=0;j<P_NOISECURVES;j++)
  117173. p->noiseoffset[j][i]=
  117174. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117175. p->vi->noiseoff[j][inthalfoc+1]*del;
  117176. }
  117177. #if 0
  117178. {
  117179. static int ls=0;
  117180. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117181. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117182. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117183. }
  117184. #endif
  117185. }
  117186. void _vp_psy_clear(vorbis_look_psy *p){
  117187. int i,j;
  117188. if(p){
  117189. if(p->ath)_ogg_free(p->ath);
  117190. if(p->octave)_ogg_free(p->octave);
  117191. if(p->bark)_ogg_free(p->bark);
  117192. if(p->tonecurves){
  117193. for(i=0;i<P_BANDS;i++){
  117194. for(j=0;j<P_LEVELS;j++){
  117195. _ogg_free(p->tonecurves[i][j]);
  117196. }
  117197. _ogg_free(p->tonecurves[i]);
  117198. }
  117199. _ogg_free(p->tonecurves);
  117200. }
  117201. if(p->noiseoffset){
  117202. for(i=0;i<P_NOISECURVES;i++){
  117203. _ogg_free(p->noiseoffset[i]);
  117204. }
  117205. _ogg_free(p->noiseoffset);
  117206. }
  117207. memset(p,0,sizeof(*p));
  117208. }
  117209. }
  117210. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117211. static void seed_curve(float *seed,
  117212. const float **curves,
  117213. float amp,
  117214. int oc, int n,
  117215. int linesper,float dBoffset){
  117216. int i,post1;
  117217. int seedptr;
  117218. const float *posts,*curve;
  117219. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117220. choice=max(choice,0);
  117221. choice=min(choice,P_LEVELS-1);
  117222. posts=curves[choice];
  117223. curve=posts+2;
  117224. post1=(int)posts[1];
  117225. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117226. for(i=posts[0];i<post1;i++){
  117227. if(seedptr>0){
  117228. float lin=amp+curve[i];
  117229. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117230. }
  117231. seedptr+=linesper;
  117232. if(seedptr>=n)break;
  117233. }
  117234. }
  117235. static void seed_loop(vorbis_look_psy *p,
  117236. const float ***curves,
  117237. const float *f,
  117238. const float *flr,
  117239. float *seed,
  117240. float specmax){
  117241. vorbis_info_psy *vi=p->vi;
  117242. long n=p->n,i;
  117243. float dBoffset=vi->max_curve_dB-specmax;
  117244. /* prime the working vector with peak values */
  117245. for(i=0;i<n;i++){
  117246. float max=f[i];
  117247. long oc=p->octave[i];
  117248. while(i+1<n && p->octave[i+1]==oc){
  117249. i++;
  117250. if(f[i]>max)max=f[i];
  117251. }
  117252. if(max+6.f>flr[i]){
  117253. oc=oc>>p->shiftoc;
  117254. if(oc>=P_BANDS)oc=P_BANDS-1;
  117255. if(oc<0)oc=0;
  117256. seed_curve(seed,
  117257. curves[oc],
  117258. max,
  117259. p->octave[i]-p->firstoc,
  117260. p->total_octave_lines,
  117261. p->eighth_octave_lines,
  117262. dBoffset);
  117263. }
  117264. }
  117265. }
  117266. static void seed_chase(float *seeds, int linesper, long n){
  117267. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117268. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117269. long stack=0;
  117270. long pos=0;
  117271. long i;
  117272. for(i=0;i<n;i++){
  117273. if(stack<2){
  117274. posstack[stack]=i;
  117275. ampstack[stack++]=seeds[i];
  117276. }else{
  117277. while(1){
  117278. if(seeds[i]<ampstack[stack-1]){
  117279. posstack[stack]=i;
  117280. ampstack[stack++]=seeds[i];
  117281. break;
  117282. }else{
  117283. if(i<posstack[stack-1]+linesper){
  117284. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117285. i<posstack[stack-2]+linesper){
  117286. /* we completely overlap, making stack-1 irrelevant. pop it */
  117287. stack--;
  117288. continue;
  117289. }
  117290. }
  117291. posstack[stack]=i;
  117292. ampstack[stack++]=seeds[i];
  117293. break;
  117294. }
  117295. }
  117296. }
  117297. }
  117298. /* the stack now contains only the positions that are relevant. Scan
  117299. 'em straight through */
  117300. for(i=0;i<stack;i++){
  117301. long endpos;
  117302. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117303. endpos=posstack[i+1];
  117304. }else{
  117305. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117306. discarded in short frames */
  117307. }
  117308. if(endpos>n)endpos=n;
  117309. for(;pos<endpos;pos++)
  117310. seeds[pos]=ampstack[i];
  117311. }
  117312. /* there. Linear time. I now remember this was on a problem set I
  117313. had in Grad Skool... I didn't solve it at the time ;-) */
  117314. }
  117315. /* bleaugh, this is more complicated than it needs to be */
  117316. #include<stdio.h>
  117317. static void max_seeds(vorbis_look_psy *p,
  117318. float *seed,
  117319. float *flr){
  117320. long n=p->total_octave_lines;
  117321. int linesper=p->eighth_octave_lines;
  117322. long linpos=0;
  117323. long pos;
  117324. seed_chase(seed,linesper,n); /* for masking */
  117325. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117326. while(linpos+1<p->n){
  117327. float minV=seed[pos];
  117328. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117329. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117330. while(pos+1<=end){
  117331. pos++;
  117332. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117333. minV=seed[pos];
  117334. }
  117335. end=pos+p->firstoc;
  117336. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117337. if(flr[linpos]<minV)flr[linpos]=minV;
  117338. }
  117339. {
  117340. float minV=seed[p->total_octave_lines-1];
  117341. for(;linpos<p->n;linpos++)
  117342. if(flr[linpos]<minV)flr[linpos]=minV;
  117343. }
  117344. }
  117345. static void bark_noise_hybridmp(int n,const long *b,
  117346. const float *f,
  117347. float *noise,
  117348. const float offset,
  117349. const int fixed){
  117350. float *N=(float*) alloca(n*sizeof(*N));
  117351. float *X=(float*) alloca(n*sizeof(*N));
  117352. float *XX=(float*) alloca(n*sizeof(*N));
  117353. float *Y=(float*) alloca(n*sizeof(*N));
  117354. float *XY=(float*) alloca(n*sizeof(*N));
  117355. float tN, tX, tXX, tY, tXY;
  117356. int i;
  117357. int lo, hi;
  117358. float R, A, B, D;
  117359. float w, x, y;
  117360. tN = tX = tXX = tY = tXY = 0.f;
  117361. y = f[0] + offset;
  117362. if (y < 1.f) y = 1.f;
  117363. w = y * y * .5;
  117364. tN += w;
  117365. tX += w;
  117366. tY += w * y;
  117367. N[0] = tN;
  117368. X[0] = tX;
  117369. XX[0] = tXX;
  117370. Y[0] = tY;
  117371. XY[0] = tXY;
  117372. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117373. y = f[i] + offset;
  117374. if (y < 1.f) y = 1.f;
  117375. w = y * y;
  117376. tN += w;
  117377. tX += w * x;
  117378. tXX += w * x * x;
  117379. tY += w * y;
  117380. tXY += w * x * y;
  117381. N[i] = tN;
  117382. X[i] = tX;
  117383. XX[i] = tXX;
  117384. Y[i] = tY;
  117385. XY[i] = tXY;
  117386. }
  117387. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117388. lo = b[i] >> 16;
  117389. if( lo>=0 ) break;
  117390. hi = b[i] & 0xffff;
  117391. tN = N[hi] + N[-lo];
  117392. tX = X[hi] - X[-lo];
  117393. tXX = XX[hi] + XX[-lo];
  117394. tY = Y[hi] + Y[-lo];
  117395. tXY = XY[hi] - XY[-lo];
  117396. A = tY * tXX - tX * tXY;
  117397. B = tN * tXY - tX * tY;
  117398. D = tN * tXX - tX * tX;
  117399. R = (A + x * B) / D;
  117400. if (R < 0.f)
  117401. R = 0.f;
  117402. noise[i] = R - offset;
  117403. }
  117404. for ( ;; i++, x += 1.f) {
  117405. lo = b[i] >> 16;
  117406. hi = b[i] & 0xffff;
  117407. if(hi>=n)break;
  117408. tN = N[hi] - N[lo];
  117409. tX = X[hi] - X[lo];
  117410. tXX = XX[hi] - XX[lo];
  117411. tY = Y[hi] - Y[lo];
  117412. tXY = XY[hi] - XY[lo];
  117413. A = tY * tXX - tX * tXY;
  117414. B = tN * tXY - tX * tY;
  117415. D = tN * tXX - tX * tX;
  117416. R = (A + x * B) / D;
  117417. if (R < 0.f) R = 0.f;
  117418. noise[i] = R - offset;
  117419. }
  117420. for ( ; i < n; i++, x += 1.f) {
  117421. R = (A + x * B) / D;
  117422. if (R < 0.f) R = 0.f;
  117423. noise[i] = R - offset;
  117424. }
  117425. if (fixed <= 0) return;
  117426. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117427. hi = i + fixed / 2;
  117428. lo = hi - fixed;
  117429. if(lo>=0)break;
  117430. tN = N[hi] + N[-lo];
  117431. tX = X[hi] - X[-lo];
  117432. tXX = XX[hi] + XX[-lo];
  117433. tY = Y[hi] + Y[-lo];
  117434. tXY = XY[hi] - XY[-lo];
  117435. A = tY * tXX - tX * tXY;
  117436. B = tN * tXY - tX * tY;
  117437. D = tN * tXX - tX * tX;
  117438. R = (A + x * B) / D;
  117439. if (R - offset < noise[i]) noise[i] = R - offset;
  117440. }
  117441. for ( ;; i++, x += 1.f) {
  117442. hi = i + fixed / 2;
  117443. lo = hi - fixed;
  117444. if(hi>=n)break;
  117445. tN = N[hi] - N[lo];
  117446. tX = X[hi] - X[lo];
  117447. tXX = XX[hi] - XX[lo];
  117448. tY = Y[hi] - Y[lo];
  117449. tXY = XY[hi] - XY[lo];
  117450. A = tY * tXX - tX * tXY;
  117451. B = tN * tXY - tX * tY;
  117452. D = tN * tXX - tX * tX;
  117453. R = (A + x * B) / D;
  117454. if (R - offset < noise[i]) noise[i] = R - offset;
  117455. }
  117456. for ( ; i < n; i++, x += 1.f) {
  117457. R = (A + x * B) / D;
  117458. if (R - offset < noise[i]) noise[i] = R - offset;
  117459. }
  117460. }
  117461. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117462. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117463. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117464. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117465. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117466. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117467. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117468. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117469. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117470. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117471. 973377.F, 913981.F, 858210.F, 805842.F,
  117472. 756669.F, 710497.F, 667142.F, 626433.F,
  117473. 588208.F, 552316.F, 518613.F, 486967.F,
  117474. 457252.F, 429351.F, 403152.F, 378551.F,
  117475. 355452.F, 333762.F, 313396.F, 294273.F,
  117476. 276316.F, 259455.F, 243623.F, 228757.F,
  117477. 214798.F, 201691.F, 189384.F, 177828.F,
  117478. 166977.F, 156788.F, 147221.F, 138237.F,
  117479. 129802.F, 121881.F, 114444.F, 107461.F,
  117480. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117481. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117482. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117483. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117484. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117485. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117486. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117487. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117488. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117489. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117490. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117491. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117492. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117493. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117494. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117495. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117496. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117497. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117498. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117499. 842.910F, 791.475F, 743.179F, 697.830F,
  117500. 655.249F, 615.265F, 577.722F, 542.469F,
  117501. 509.367F, 478.286F, 449.101F, 421.696F,
  117502. 395.964F, 371.803F, 349.115F, 327.812F,
  117503. 307.809F, 289.026F, 271.390F, 254.830F,
  117504. 239.280F, 224.679F, 210.969F, 198.096F,
  117505. 186.008F, 174.658F, 164.000F, 153.993F,
  117506. 144.596F, 135.773F, 127.488F, 119.708F,
  117507. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117508. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117509. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117510. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117511. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117512. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117513. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117514. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117515. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117516. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117517. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117518. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117519. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117520. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117521. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117522. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117523. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117524. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117525. 1.20790F, 1.13419F, 1.06499F, 1.F
  117526. };
  117527. void _vp_remove_floor(vorbis_look_psy *p,
  117528. float *mdct,
  117529. int *codedflr,
  117530. float *residue,
  117531. int sliding_lowpass){
  117532. int i,n=p->n;
  117533. if(sliding_lowpass>n)sliding_lowpass=n;
  117534. for(i=0;i<sliding_lowpass;i++){
  117535. residue[i]=
  117536. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117537. }
  117538. for(;i<n;i++)
  117539. residue[i]=0.;
  117540. }
  117541. void _vp_noisemask(vorbis_look_psy *p,
  117542. float *logmdct,
  117543. float *logmask){
  117544. int i,n=p->n;
  117545. float *work=(float*) alloca(n*sizeof(*work));
  117546. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117547. 140.,-1);
  117548. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117549. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117550. p->vi->noisewindowfixed);
  117551. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117552. #if 0
  117553. {
  117554. static int seq=0;
  117555. float work2[n];
  117556. for(i=0;i<n;i++){
  117557. work2[i]=logmask[i]+work[i];
  117558. }
  117559. if(seq&1)
  117560. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117561. else
  117562. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117563. if(seq&1)
  117564. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117565. else
  117566. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117567. seq++;
  117568. }
  117569. #endif
  117570. for(i=0;i<n;i++){
  117571. int dB=logmask[i]+.5;
  117572. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117573. if(dB<0)dB=0;
  117574. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117575. }
  117576. }
  117577. void _vp_tonemask(vorbis_look_psy *p,
  117578. float *logfft,
  117579. float *logmask,
  117580. float global_specmax,
  117581. float local_specmax){
  117582. int i,n=p->n;
  117583. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117584. float att=local_specmax+p->vi->ath_adjatt;
  117585. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117586. /* set the ATH (floating below localmax, not global max by a
  117587. specified att) */
  117588. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117589. for(i=0;i<n;i++)
  117590. logmask[i]=p->ath[i]+att;
  117591. /* tone masking */
  117592. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117593. max_seeds(p,seed,logmask);
  117594. }
  117595. void _vp_offset_and_mix(vorbis_look_psy *p,
  117596. float *noise,
  117597. float *tone,
  117598. int offset_select,
  117599. float *logmask,
  117600. float *mdct,
  117601. float *logmdct){
  117602. int i,n=p->n;
  117603. float de, coeffi, cx;/* AoTuV */
  117604. float toneatt=p->vi->tone_masteratt[offset_select];
  117605. cx = p->m_val;
  117606. for(i=0;i<n;i++){
  117607. float val= noise[i]+p->noiseoffset[offset_select][i];
  117608. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117609. logmask[i]=max(val,tone[i]+toneatt);
  117610. /* AoTuV */
  117611. /** @ M1 **
  117612. The following codes improve a noise problem.
  117613. A fundamental idea uses the value of masking and carries out
  117614. the relative compensation of the MDCT.
  117615. However, this code is not perfect and all noise problems cannot be solved.
  117616. by Aoyumi @ 2004/04/18
  117617. */
  117618. if(offset_select == 1) {
  117619. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117620. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117621. if(val > coeffi){
  117622. /* mdct value is > -17.2 dB below floor */
  117623. de = 1.0-((val-coeffi)*0.005*cx);
  117624. /* pro-rated attenuation:
  117625. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117626. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117627. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117628. etc... */
  117629. if(de < 0) de = 0.0001;
  117630. }else
  117631. /* mdct value is <= -17.2 dB below floor */
  117632. de = 1.0-((val-coeffi)*0.0003*cx);
  117633. /* pro-rated attenuation:
  117634. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117635. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117636. etc... */
  117637. mdct[i] *= de;
  117638. }
  117639. }
  117640. }
  117641. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117642. vorbis_info *vi=vd->vi;
  117643. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117644. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117645. int n=ci->blocksizes[vd->W]/2;
  117646. float secs=(float)n/vi->rate;
  117647. amp+=secs*gi->ampmax_att_per_sec;
  117648. if(amp<-9999)amp=-9999;
  117649. return(amp);
  117650. }
  117651. static void couple_lossless(float A, float B,
  117652. float *qA, float *qB){
  117653. int test1=fabs(*qA)>fabs(*qB);
  117654. test1-= fabs(*qA)<fabs(*qB);
  117655. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117656. if(test1==1){
  117657. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117658. }else{
  117659. float temp=*qB;
  117660. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117661. *qA=temp;
  117662. }
  117663. if(*qB>fabs(*qA)*1.9999f){
  117664. *qB= -fabs(*qA)*2.f;
  117665. *qA= -*qA;
  117666. }
  117667. }
  117668. static float hypot_lookup[32]={
  117669. -0.009935, -0.011245, -0.012726, -0.014397,
  117670. -0.016282, -0.018407, -0.020800, -0.023494,
  117671. -0.026522, -0.029923, -0.033737, -0.038010,
  117672. -0.042787, -0.048121, -0.054064, -0.060671,
  117673. -0.068000, -0.076109, -0.085054, -0.094892,
  117674. -0.105675, -0.117451, -0.130260, -0.144134,
  117675. -0.159093, -0.175146, -0.192286, -0.210490,
  117676. -0.229718, -0.249913, -0.271001, -0.292893};
  117677. static void precomputed_couple_point(float premag,
  117678. int floorA,int floorB,
  117679. float *mag, float *ang){
  117680. int test=(floorA>floorB)-1;
  117681. int offset=31-abs(floorA-floorB);
  117682. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117683. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117684. *mag=premag*floormag;
  117685. *ang=0.f;
  117686. }
  117687. /* just like below, this is currently set up to only do
  117688. single-step-depth coupling. Otherwise, we'd have to do more
  117689. copying (which will be inevitable later) */
  117690. /* doing the real circular magnitude calculation is audibly superior
  117691. to (A+B)/sqrt(2) */
  117692. static float dipole_hypot(float a, float b){
  117693. if(a>0.){
  117694. if(b>0.)return sqrt(a*a+b*b);
  117695. if(a>-b)return sqrt(a*a-b*b);
  117696. return -sqrt(b*b-a*a);
  117697. }
  117698. if(b<0.)return -sqrt(a*a+b*b);
  117699. if(-a>b)return -sqrt(a*a-b*b);
  117700. return sqrt(b*b-a*a);
  117701. }
  117702. static float round_hypot(float a, float b){
  117703. if(a>0.){
  117704. if(b>0.)return sqrt(a*a+b*b);
  117705. if(a>-b)return sqrt(a*a+b*b);
  117706. return -sqrt(b*b+a*a);
  117707. }
  117708. if(b<0.)return -sqrt(a*a+b*b);
  117709. if(-a>b)return -sqrt(a*a+b*b);
  117710. return sqrt(b*b+a*a);
  117711. }
  117712. /* revert to round hypot for now */
  117713. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117714. vorbis_info_psy_global *g,
  117715. vorbis_look_psy *p,
  117716. vorbis_info_mapping0 *vi,
  117717. float **mdct){
  117718. int i,j,n=p->n;
  117719. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117720. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117721. for(i=0;i<vi->coupling_steps;i++){
  117722. float *mdctM=mdct[vi->coupling_mag[i]];
  117723. float *mdctA=mdct[vi->coupling_ang[i]];
  117724. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117725. for(j=0;j<limit;j++)
  117726. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117727. for(;j<n;j++)
  117728. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117729. }
  117730. return(ret);
  117731. }
  117732. /* this is for per-channel noise normalization */
  117733. static int JUCE_CDECL apsort(const void *a, const void *b){
  117734. float f1=fabs(**(float**)a);
  117735. float f2=fabs(**(float**)b);
  117736. return (f1<f2)-(f1>f2);
  117737. }
  117738. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117739. vorbis_look_psy *p,
  117740. vorbis_info_mapping0 *vi,
  117741. float **mags){
  117742. if(p->vi->normal_point_p){
  117743. int i,j,k,n=p->n;
  117744. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117745. int partition=p->vi->normal_partition;
  117746. float **work=(float**) alloca(sizeof(*work)*partition);
  117747. for(i=0;i<vi->coupling_steps;i++){
  117748. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117749. for(j=0;j<n;j+=partition){
  117750. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117751. qsort(work,partition,sizeof(*work),apsort);
  117752. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117753. }
  117754. }
  117755. return(ret);
  117756. }
  117757. return(NULL);
  117758. }
  117759. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117760. float *magnitudes,int *sortedindex){
  117761. int i,j,n=p->n;
  117762. vorbis_info_psy *vi=p->vi;
  117763. int partition=vi->normal_partition;
  117764. float **work=(float**) alloca(sizeof(*work)*partition);
  117765. int start=vi->normal_start;
  117766. for(j=start;j<n;j+=partition){
  117767. if(j+partition>n)partition=n-j;
  117768. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117769. qsort(work,partition,sizeof(*work),apsort);
  117770. for(i=0;i<partition;i++){
  117771. sortedindex[i+j-start]=work[i]-magnitudes;
  117772. }
  117773. }
  117774. }
  117775. void _vp_noise_normalize(vorbis_look_psy *p,
  117776. float *in,float *out,int *sortedindex){
  117777. int flag=0,i,j=0,n=p->n;
  117778. vorbis_info_psy *vi=p->vi;
  117779. int partition=vi->normal_partition;
  117780. int start=vi->normal_start;
  117781. if(start>n)start=n;
  117782. if(vi->normal_channel_p){
  117783. for(;j<start;j++)
  117784. out[j]=rint(in[j]);
  117785. for(;j+partition<=n;j+=partition){
  117786. float acc=0.;
  117787. int k;
  117788. for(i=j;i<j+partition;i++)
  117789. acc+=in[i]*in[i];
  117790. for(i=0;i<partition;i++){
  117791. k=sortedindex[i+j-start];
  117792. if(in[k]*in[k]>=.25f){
  117793. out[k]=rint(in[k]);
  117794. acc-=in[k]*in[k];
  117795. flag=1;
  117796. }else{
  117797. if(acc<vi->normal_thresh)break;
  117798. out[k]=unitnorm(in[k]);
  117799. acc-=1.;
  117800. }
  117801. }
  117802. for(;i<partition;i++){
  117803. k=sortedindex[i+j-start];
  117804. out[k]=0.;
  117805. }
  117806. }
  117807. }
  117808. for(;j<n;j++)
  117809. out[j]=rint(in[j]);
  117810. }
  117811. void _vp_couple(int blobno,
  117812. vorbis_info_psy_global *g,
  117813. vorbis_look_psy *p,
  117814. vorbis_info_mapping0 *vi,
  117815. float **res,
  117816. float **mag_memo,
  117817. int **mag_sort,
  117818. int **ifloor,
  117819. int *nonzero,
  117820. int sliding_lowpass){
  117821. int i,j,k,n=p->n;
  117822. /* perform any requested channel coupling */
  117823. /* point stereo can only be used in a first stage (in this encoder)
  117824. because of the dependency on floor lookups */
  117825. for(i=0;i<vi->coupling_steps;i++){
  117826. /* once we're doing multistage coupling in which a channel goes
  117827. through more than one coupling step, the floor vector
  117828. magnitudes will also have to be recalculated an propogated
  117829. along with PCM. Right now, we're not (that will wait until 5.1
  117830. most likely), so the code isn't here yet. The memory management
  117831. here is all assuming single depth couplings anyway. */
  117832. /* make sure coupling a zero and a nonzero channel results in two
  117833. nonzero channels. */
  117834. if(nonzero[vi->coupling_mag[i]] ||
  117835. nonzero[vi->coupling_ang[i]]){
  117836. float *rM=res[vi->coupling_mag[i]];
  117837. float *rA=res[vi->coupling_ang[i]];
  117838. float *qM=rM+n;
  117839. float *qA=rA+n;
  117840. int *floorM=ifloor[vi->coupling_mag[i]];
  117841. int *floorA=ifloor[vi->coupling_ang[i]];
  117842. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117843. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117844. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117845. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117846. int pointlimit=limit;
  117847. nonzero[vi->coupling_mag[i]]=1;
  117848. nonzero[vi->coupling_ang[i]]=1;
  117849. /* The threshold of a stereo is changed with the size of n */
  117850. if(n > 1000)
  117851. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117852. for(j=0;j<p->n;j+=partition){
  117853. float acc=0.f;
  117854. for(k=0;k<partition;k++){
  117855. int l=k+j;
  117856. if(l<sliding_lowpass){
  117857. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117858. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117859. precomputed_couple_point(mag_memo[i][l],
  117860. floorM[l],floorA[l],
  117861. qM+l,qA+l);
  117862. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117863. }else{
  117864. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117865. }
  117866. }else{
  117867. qM[l]=0.;
  117868. qA[l]=0.;
  117869. }
  117870. }
  117871. if(p->vi->normal_point_p){
  117872. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117873. int l=mag_sort[i][j+k];
  117874. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117875. qM[l]=unitnorm(qM[l]);
  117876. acc-=1.f;
  117877. }
  117878. }
  117879. }
  117880. }
  117881. }
  117882. }
  117883. }
  117884. /* AoTuV */
  117885. /** @ M2 **
  117886. The boost problem by the combination of noise normalization and point stereo is eased.
  117887. However, this is a temporary patch.
  117888. by Aoyumi @ 2004/04/18
  117889. */
  117890. void hf_reduction(vorbis_info_psy_global *g,
  117891. vorbis_look_psy *p,
  117892. vorbis_info_mapping0 *vi,
  117893. float **mdct){
  117894. int i,j,n=p->n, de=0.3*p->m_val;
  117895. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117896. for(i=0; i<vi->coupling_steps; i++){
  117897. /* for(j=start; j<limit; j++){} // ???*/
  117898. for(j=limit; j<n; j++)
  117899. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117900. }
  117901. }
  117902. #endif
  117903. /*** End of inlined file: psy.c ***/
  117904. /*** Start of inlined file: registry.c ***/
  117905. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117906. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117907. // tasks..
  117908. #if JUCE_MSVC
  117909. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117910. #endif
  117911. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117912. #if JUCE_USE_OGGVORBIS
  117913. /* seems like major overkill now; the backend numbers will grow into
  117914. the infrastructure soon enough */
  117915. extern vorbis_func_floor floor0_exportbundle;
  117916. extern vorbis_func_floor floor1_exportbundle;
  117917. extern vorbis_func_residue residue0_exportbundle;
  117918. extern vorbis_func_residue residue1_exportbundle;
  117919. extern vorbis_func_residue residue2_exportbundle;
  117920. extern vorbis_func_mapping mapping0_exportbundle;
  117921. vorbis_func_floor *_floor_P[]={
  117922. &floor0_exportbundle,
  117923. &floor1_exportbundle,
  117924. };
  117925. vorbis_func_residue *_residue_P[]={
  117926. &residue0_exportbundle,
  117927. &residue1_exportbundle,
  117928. &residue2_exportbundle,
  117929. };
  117930. vorbis_func_mapping *_mapping_P[]={
  117931. &mapping0_exportbundle,
  117932. };
  117933. #endif
  117934. /*** End of inlined file: registry.c ***/
  117935. /*** Start of inlined file: res0.c ***/
  117936. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117937. encode/decode loops are coded for clarity and performance is not
  117938. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117939. it's slow. */
  117940. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117941. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117942. // tasks..
  117943. #if JUCE_MSVC
  117944. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117945. #endif
  117946. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117947. #if JUCE_USE_OGGVORBIS
  117948. #include <stdlib.h>
  117949. #include <string.h>
  117950. #include <math.h>
  117951. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117952. #include <stdio.h>
  117953. #endif
  117954. typedef struct {
  117955. vorbis_info_residue0 *info;
  117956. int parts;
  117957. int stages;
  117958. codebook *fullbooks;
  117959. codebook *phrasebook;
  117960. codebook ***partbooks;
  117961. int partvals;
  117962. int **decodemap;
  117963. long postbits;
  117964. long phrasebits;
  117965. long frames;
  117966. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117967. int train_seq;
  117968. long *training_data[8][64];
  117969. float training_max[8][64];
  117970. float training_min[8][64];
  117971. float tmin;
  117972. float tmax;
  117973. #endif
  117974. } vorbis_look_residue0;
  117975. void res0_free_info(vorbis_info_residue *i){
  117976. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117977. if(info){
  117978. memset(info,0,sizeof(*info));
  117979. _ogg_free(info);
  117980. }
  117981. }
  117982. void res0_free_look(vorbis_look_residue *i){
  117983. int j;
  117984. if(i){
  117985. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117986. #ifdef TRAIN_RES
  117987. {
  117988. int j,k,l;
  117989. for(j=0;j<look->parts;j++){
  117990. /*fprintf(stderr,"partition %d: ",j);*/
  117991. for(k=0;k<8;k++)
  117992. if(look->training_data[k][j]){
  117993. char buffer[80];
  117994. FILE *of;
  117995. codebook *statebook=look->partbooks[j][k];
  117996. /* long and short into the same bucket by current convention */
  117997. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117998. of=fopen(buffer,"a");
  117999. for(l=0;l<statebook->entries;l++)
  118000. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118001. fclose(of);
  118002. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118003. look->training_min[k][j],look->training_max[k][j]);*/
  118004. _ogg_free(look->training_data[k][j]);
  118005. look->training_data[k][j]=NULL;
  118006. }
  118007. /*fprintf(stderr,"\n");*/
  118008. }
  118009. }
  118010. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118011. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118012. (float)look->phrasebits/look->frames,
  118013. (float)look->postbits/look->frames,
  118014. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118015. #endif
  118016. /*vorbis_info_residue0 *info=look->info;
  118017. fprintf(stderr,
  118018. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118019. "(%g/frame) \n",look->frames,look->phrasebits,
  118020. look->resbitsflat,
  118021. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118022. for(j=0;j<look->parts;j++){
  118023. long acc=0;
  118024. fprintf(stderr,"\t[%d] == ",j);
  118025. for(k=0;k<look->stages;k++)
  118026. if((info->secondstages[j]>>k)&1){
  118027. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118028. acc+=look->resbits[j][k];
  118029. }
  118030. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118031. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118032. }
  118033. fprintf(stderr,"\n");*/
  118034. for(j=0;j<look->parts;j++)
  118035. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118036. _ogg_free(look->partbooks);
  118037. for(j=0;j<look->partvals;j++)
  118038. _ogg_free(look->decodemap[j]);
  118039. _ogg_free(look->decodemap);
  118040. memset(look,0,sizeof(*look));
  118041. _ogg_free(look);
  118042. }
  118043. }
  118044. static int icount(unsigned int v){
  118045. int ret=0;
  118046. while(v){
  118047. ret+=v&1;
  118048. v>>=1;
  118049. }
  118050. return(ret);
  118051. }
  118052. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118053. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118054. int j,acc=0;
  118055. oggpack_write(opb,info->begin,24);
  118056. oggpack_write(opb,info->end,24);
  118057. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118058. code with a partitioned book */
  118059. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118060. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118061. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118062. bitmask of one indicates this partition class has bits to write
  118063. this pass */
  118064. for(j=0;j<info->partitions;j++){
  118065. if(ilog(info->secondstages[j])>3){
  118066. /* yes, this is a minor hack due to not thinking ahead */
  118067. oggpack_write(opb,info->secondstages[j],3);
  118068. oggpack_write(opb,1,1);
  118069. oggpack_write(opb,info->secondstages[j]>>3,5);
  118070. }else
  118071. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118072. acc+=icount(info->secondstages[j]);
  118073. }
  118074. for(j=0;j<acc;j++)
  118075. oggpack_write(opb,info->booklist[j],8);
  118076. }
  118077. /* vorbis_info is for range checking */
  118078. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118079. int j,acc=0;
  118080. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118081. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118082. info->begin=oggpack_read(opb,24);
  118083. info->end=oggpack_read(opb,24);
  118084. info->grouping=oggpack_read(opb,24)+1;
  118085. info->partitions=oggpack_read(opb,6)+1;
  118086. info->groupbook=oggpack_read(opb,8);
  118087. for(j=0;j<info->partitions;j++){
  118088. int cascade=oggpack_read(opb,3);
  118089. if(oggpack_read(opb,1))
  118090. cascade|=(oggpack_read(opb,5)<<3);
  118091. info->secondstages[j]=cascade;
  118092. acc+=icount(cascade);
  118093. }
  118094. for(j=0;j<acc;j++)
  118095. info->booklist[j]=oggpack_read(opb,8);
  118096. if(info->groupbook>=ci->books)goto errout;
  118097. for(j=0;j<acc;j++)
  118098. if(info->booklist[j]>=ci->books)goto errout;
  118099. return(info);
  118100. errout:
  118101. res0_free_info(info);
  118102. return(NULL);
  118103. }
  118104. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118105. vorbis_info_residue *vr){
  118106. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118107. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118108. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118109. int j,k,acc=0;
  118110. int dim;
  118111. int maxstage=0;
  118112. look->info=info;
  118113. look->parts=info->partitions;
  118114. look->fullbooks=ci->fullbooks;
  118115. look->phrasebook=ci->fullbooks+info->groupbook;
  118116. dim=look->phrasebook->dim;
  118117. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118118. for(j=0;j<look->parts;j++){
  118119. int stages=ilog(info->secondstages[j]);
  118120. if(stages){
  118121. if(stages>maxstage)maxstage=stages;
  118122. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118123. for(k=0;k<stages;k++)
  118124. if(info->secondstages[j]&(1<<k)){
  118125. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118126. #ifdef TRAIN_RES
  118127. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118128. sizeof(***look->training_data));
  118129. #endif
  118130. }
  118131. }
  118132. }
  118133. look->partvals=rint(pow((float)look->parts,(float)dim));
  118134. look->stages=maxstage;
  118135. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118136. for(j=0;j<look->partvals;j++){
  118137. long val=j;
  118138. long mult=look->partvals/look->parts;
  118139. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118140. for(k=0;k<dim;k++){
  118141. long deco=val/mult;
  118142. val-=deco*mult;
  118143. mult/=look->parts;
  118144. look->decodemap[j][k]=deco;
  118145. }
  118146. }
  118147. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118148. {
  118149. static int train_seq=0;
  118150. look->train_seq=train_seq++;
  118151. }
  118152. #endif
  118153. return(look);
  118154. }
  118155. /* break an abstraction and copy some code for performance purposes */
  118156. static int local_book_besterror(codebook *book,float *a){
  118157. int dim=book->dim,i,k,o;
  118158. int best=0;
  118159. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118160. /* find the quant val of each scalar */
  118161. for(k=0,o=dim;k<dim;++k){
  118162. float val=a[--o];
  118163. i=tt->threshvals>>1;
  118164. if(val<tt->quantthresh[i]){
  118165. if(val<tt->quantthresh[i-1]){
  118166. for(--i;i>0;--i)
  118167. if(val>=tt->quantthresh[i-1])
  118168. break;
  118169. }
  118170. }else{
  118171. for(++i;i<tt->threshvals-1;++i)
  118172. if(val<tt->quantthresh[i])break;
  118173. }
  118174. best=(best*tt->quantvals)+tt->quantmap[i];
  118175. }
  118176. /* regular lattices are easy :-) */
  118177. if(book->c->lengthlist[best]<=0){
  118178. const static_codebook *c=book->c;
  118179. int i,j;
  118180. float bestf=0.f;
  118181. float *e=book->valuelist;
  118182. best=-1;
  118183. for(i=0;i<book->entries;i++){
  118184. if(c->lengthlist[i]>0){
  118185. float thisx=0.f;
  118186. for(j=0;j<dim;j++){
  118187. float val=(e[j]-a[j]);
  118188. thisx+=val*val;
  118189. }
  118190. if(best==-1 || thisx<bestf){
  118191. bestf=thisx;
  118192. best=i;
  118193. }
  118194. }
  118195. e+=dim;
  118196. }
  118197. }
  118198. {
  118199. float *ptr=book->valuelist+best*dim;
  118200. for(i=0;i<dim;i++)
  118201. *a++ -= *ptr++;
  118202. }
  118203. return(best);
  118204. }
  118205. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118206. codebook *book,long *acc){
  118207. int i,bits=0;
  118208. int dim=book->dim;
  118209. int step=n/dim;
  118210. for(i=0;i<step;i++){
  118211. int entry=local_book_besterror(book,vec+i*dim);
  118212. #ifdef TRAIN_RES
  118213. acc[entry]++;
  118214. #endif
  118215. bits+=vorbis_book_encode(book,entry,opb);
  118216. }
  118217. return(bits);
  118218. }
  118219. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118220. float **in,int ch){
  118221. long i,j,k;
  118222. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118223. vorbis_info_residue0 *info=look->info;
  118224. /* move all this setup out later */
  118225. int samples_per_partition=info->grouping;
  118226. int possible_partitions=info->partitions;
  118227. int n=info->end-info->begin;
  118228. int partvals=n/samples_per_partition;
  118229. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118230. float scale=100./samples_per_partition;
  118231. /* we find the partition type for each partition of each
  118232. channel. We'll go back and do the interleaved encoding in a
  118233. bit. For now, clarity */
  118234. for(i=0;i<ch;i++){
  118235. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118236. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118237. }
  118238. for(i=0;i<partvals;i++){
  118239. int offset=i*samples_per_partition+info->begin;
  118240. for(j=0;j<ch;j++){
  118241. float max=0.;
  118242. float ent=0.;
  118243. for(k=0;k<samples_per_partition;k++){
  118244. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118245. ent+=fabs(rint(in[j][offset+k]));
  118246. }
  118247. ent*=scale;
  118248. for(k=0;k<possible_partitions-1;k++)
  118249. if(max<=info->classmetric1[k] &&
  118250. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118251. break;
  118252. partword[j][i]=k;
  118253. }
  118254. }
  118255. #ifdef TRAIN_RESAUX
  118256. {
  118257. FILE *of;
  118258. char buffer[80];
  118259. for(i=0;i<ch;i++){
  118260. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118261. of=fopen(buffer,"a");
  118262. for(j=0;j<partvals;j++)
  118263. fprintf(of,"%ld, ",partword[i][j]);
  118264. fprintf(of,"\n");
  118265. fclose(of);
  118266. }
  118267. }
  118268. #endif
  118269. look->frames++;
  118270. return(partword);
  118271. }
  118272. /* designed for stereo or other modes where the partition size is an
  118273. integer multiple of the number of channels encoded in the current
  118274. submap */
  118275. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118276. int ch){
  118277. long i,j,k,l;
  118278. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118279. vorbis_info_residue0 *info=look->info;
  118280. /* move all this setup out later */
  118281. int samples_per_partition=info->grouping;
  118282. int possible_partitions=info->partitions;
  118283. int n=info->end-info->begin;
  118284. int partvals=n/samples_per_partition;
  118285. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118286. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118287. FILE *of;
  118288. char buffer[80];
  118289. #endif
  118290. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118291. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118292. for(i=0,l=info->begin/ch;i<partvals;i++){
  118293. float magmax=0.f;
  118294. float angmax=0.f;
  118295. for(j=0;j<samples_per_partition;j+=ch){
  118296. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118297. for(k=1;k<ch;k++)
  118298. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118299. l++;
  118300. }
  118301. for(j=0;j<possible_partitions-1;j++)
  118302. if(magmax<=info->classmetric1[j] &&
  118303. angmax<=info->classmetric2[j])
  118304. break;
  118305. partword[0][i]=j;
  118306. }
  118307. #ifdef TRAIN_RESAUX
  118308. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118309. of=fopen(buffer,"a");
  118310. for(i=0;i<partvals;i++)
  118311. fprintf(of,"%ld, ",partword[0][i]);
  118312. fprintf(of,"\n");
  118313. fclose(of);
  118314. #endif
  118315. look->frames++;
  118316. return(partword);
  118317. }
  118318. static int _01forward(oggpack_buffer *opb,
  118319. vorbis_block *vb,vorbis_look_residue *vl,
  118320. float **in,int ch,
  118321. long **partword,
  118322. int (*encode)(oggpack_buffer *,float *,int,
  118323. codebook *,long *)){
  118324. long i,j,k,s;
  118325. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118326. vorbis_info_residue0 *info=look->info;
  118327. /* move all this setup out later */
  118328. int samples_per_partition=info->grouping;
  118329. int possible_partitions=info->partitions;
  118330. int partitions_per_word=look->phrasebook->dim;
  118331. int n=info->end-info->begin;
  118332. int partvals=n/samples_per_partition;
  118333. long resbits[128];
  118334. long resvals[128];
  118335. #ifdef TRAIN_RES
  118336. for(i=0;i<ch;i++)
  118337. for(j=info->begin;j<info->end;j++){
  118338. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118339. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118340. }
  118341. #endif
  118342. memset(resbits,0,sizeof(resbits));
  118343. memset(resvals,0,sizeof(resvals));
  118344. /* we code the partition words for each channel, then the residual
  118345. words for a partition per channel until we've written all the
  118346. residual words for that partition word. Then write the next
  118347. partition channel words... */
  118348. for(s=0;s<look->stages;s++){
  118349. for(i=0;i<partvals;){
  118350. /* first we encode a partition codeword for each channel */
  118351. if(s==0){
  118352. for(j=0;j<ch;j++){
  118353. long val=partword[j][i];
  118354. for(k=1;k<partitions_per_word;k++){
  118355. val*=possible_partitions;
  118356. if(i+k<partvals)
  118357. val+=partword[j][i+k];
  118358. }
  118359. /* training hack */
  118360. if(val<look->phrasebook->entries)
  118361. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118362. #if 0 /*def TRAIN_RES*/
  118363. else
  118364. fprintf(stderr,"!");
  118365. #endif
  118366. }
  118367. }
  118368. /* now we encode interleaved residual values for the partitions */
  118369. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118370. long offset=i*samples_per_partition+info->begin;
  118371. for(j=0;j<ch;j++){
  118372. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118373. if(info->secondstages[partword[j][i]]&(1<<s)){
  118374. codebook *statebook=look->partbooks[partword[j][i]][s];
  118375. if(statebook){
  118376. int ret;
  118377. long *accumulator=NULL;
  118378. #ifdef TRAIN_RES
  118379. accumulator=look->training_data[s][partword[j][i]];
  118380. {
  118381. int l;
  118382. float *samples=in[j]+offset;
  118383. for(l=0;l<samples_per_partition;l++){
  118384. if(samples[l]<look->training_min[s][partword[j][i]])
  118385. look->training_min[s][partword[j][i]]=samples[l];
  118386. if(samples[l]>look->training_max[s][partword[j][i]])
  118387. look->training_max[s][partword[j][i]]=samples[l];
  118388. }
  118389. }
  118390. #endif
  118391. ret=encode(opb,in[j]+offset,samples_per_partition,
  118392. statebook,accumulator);
  118393. look->postbits+=ret;
  118394. resbits[partword[j][i]]+=ret;
  118395. }
  118396. }
  118397. }
  118398. }
  118399. }
  118400. }
  118401. /*{
  118402. long total=0;
  118403. long totalbits=0;
  118404. fprintf(stderr,"%d :: ",vb->mode);
  118405. for(k=0;k<possible_partitions;k++){
  118406. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118407. total+=resvals[k];
  118408. totalbits+=resbits[k];
  118409. }
  118410. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118411. }*/
  118412. return(0);
  118413. }
  118414. /* a truncated packet here just means 'stop working'; it's not an error */
  118415. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118416. float **in,int ch,
  118417. long (*decodepart)(codebook *, float *,
  118418. oggpack_buffer *,int)){
  118419. long i,j,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***)alloca(ch*sizeof(*partword));
  118429. for(j=0;j<ch;j++)
  118430. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118431. for(s=0;s<look->stages;s++){
  118432. /* each loop decodes on partition codeword containing
  118433. partitions_pre_word partitions */
  118434. for(i=0,l=0;i<partvals;l++){
  118435. if(s==0){
  118436. /* fetch the partition word for each channel */
  118437. for(j=0;j<ch;j++){
  118438. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118439. if(temp==-1)goto eopbreak;
  118440. partword[j][l]=look->decodemap[temp];
  118441. if(partword[j][l]==NULL)goto errout;
  118442. }
  118443. }
  118444. /* now we decode residual values for the partitions */
  118445. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118446. for(j=0;j<ch;j++){
  118447. long offset=info->begin+i*samples_per_partition;
  118448. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118449. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118450. if(stagebook){
  118451. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118452. samples_per_partition)==-1)goto eopbreak;
  118453. }
  118454. }
  118455. }
  118456. }
  118457. }
  118458. errout:
  118459. eopbreak:
  118460. return(0);
  118461. }
  118462. #if 0
  118463. /* residue 0 and 1 are just slight variants of one another. 0 is
  118464. interleaved, 1 is not */
  118465. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118466. float **in,int *nonzero,int ch){
  118467. /* we encode only the nonzero parts of a bundle */
  118468. int i,used=0;
  118469. for(i=0;i<ch;i++)
  118470. if(nonzero[i])
  118471. in[used++]=in[i];
  118472. if(used)
  118473. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118474. return(_01class(vb,vl,in,used));
  118475. else
  118476. return(0);
  118477. }
  118478. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118479. float **in,float **out,int *nonzero,int ch,
  118480. long **partword){
  118481. /* we encode only the nonzero parts of a bundle */
  118482. int i,j,used=0,n=vb->pcmend/2;
  118483. for(i=0;i<ch;i++)
  118484. if(nonzero[i]){
  118485. if(out)
  118486. for(j=0;j<n;j++)
  118487. out[i][j]+=in[i][j];
  118488. in[used++]=in[i];
  118489. }
  118490. if(used){
  118491. int ret=_01forward(vb,vl,in,used,partword,
  118492. _interleaved_encodepart);
  118493. if(out){
  118494. used=0;
  118495. for(i=0;i<ch;i++)
  118496. if(nonzero[i]){
  118497. for(j=0;j<n;j++)
  118498. out[i][j]-=in[used][j];
  118499. used++;
  118500. }
  118501. }
  118502. return(ret);
  118503. }else{
  118504. return(0);
  118505. }
  118506. }
  118507. #endif
  118508. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118509. float **in,int *nonzero,int ch){
  118510. int i,used=0;
  118511. for(i=0;i<ch;i++)
  118512. if(nonzero[i])
  118513. in[used++]=in[i];
  118514. if(used)
  118515. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118516. else
  118517. return(0);
  118518. }
  118519. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118520. float **in,float **out,int *nonzero,int ch,
  118521. long **partword){
  118522. int i,j,used=0,n=vb->pcmend/2;
  118523. for(i=0;i<ch;i++)
  118524. if(nonzero[i]){
  118525. if(out)
  118526. for(j=0;j<n;j++)
  118527. out[i][j]+=in[i][j];
  118528. in[used++]=in[i];
  118529. }
  118530. if(used){
  118531. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118532. if(out){
  118533. used=0;
  118534. for(i=0;i<ch;i++)
  118535. if(nonzero[i]){
  118536. for(j=0;j<n;j++)
  118537. out[i][j]-=in[used][j];
  118538. used++;
  118539. }
  118540. }
  118541. return(ret);
  118542. }else{
  118543. return(0);
  118544. }
  118545. }
  118546. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118547. float **in,int *nonzero,int ch){
  118548. int i,used=0;
  118549. for(i=0;i<ch;i++)
  118550. if(nonzero[i])
  118551. in[used++]=in[i];
  118552. if(used)
  118553. return(_01class(vb,vl,in,used));
  118554. else
  118555. return(0);
  118556. }
  118557. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118558. float **in,int *nonzero,int ch){
  118559. int i,used=0;
  118560. for(i=0;i<ch;i++)
  118561. if(nonzero[i])
  118562. in[used++]=in[i];
  118563. if(used)
  118564. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118565. else
  118566. return(0);
  118567. }
  118568. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118569. float **in,int *nonzero,int ch){
  118570. int i,used=0;
  118571. for(i=0;i<ch;i++)
  118572. if(nonzero[i])used++;
  118573. if(used)
  118574. return(_2class(vb,vl,in,ch));
  118575. else
  118576. return(0);
  118577. }
  118578. /* res2 is slightly more different; all the channels are interleaved
  118579. into a single vector and encoded. */
  118580. int res2_forward(oggpack_buffer *opb,
  118581. vorbis_block *vb,vorbis_look_residue *vl,
  118582. float **in,float **out,int *nonzero,int ch,
  118583. long **partword){
  118584. long i,j,k,n=vb->pcmend/2,used=0;
  118585. /* don't duplicate the code; use a working vector hack for now and
  118586. reshape ourselves into a single channel res1 */
  118587. /* ugly; reallocs for each coupling pass :-( */
  118588. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118589. for(i=0;i<ch;i++){
  118590. float *pcm=in[i];
  118591. if(nonzero[i])used++;
  118592. for(j=0,k=i;j<n;j++,k+=ch)
  118593. work[k]=pcm[j];
  118594. }
  118595. if(used){
  118596. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118597. /* update the sofar vector */
  118598. if(out){
  118599. for(i=0;i<ch;i++){
  118600. float *pcm=in[i];
  118601. float *sofar=out[i];
  118602. for(j=0,k=i;j<n;j++,k+=ch)
  118603. sofar[j]+=pcm[j]-work[k];
  118604. }
  118605. }
  118606. return(ret);
  118607. }else{
  118608. return(0);
  118609. }
  118610. }
  118611. /* duplicate code here as speed is somewhat more important */
  118612. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118613. float **in,int *nonzero,int ch){
  118614. long i,k,l,s;
  118615. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118616. vorbis_info_residue0 *info=look->info;
  118617. /* move all this setup out later */
  118618. int samples_per_partition=info->grouping;
  118619. int partitions_per_word=look->phrasebook->dim;
  118620. int n=info->end-info->begin;
  118621. int partvals=n/samples_per_partition;
  118622. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118623. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118624. for(i=0;i<ch;i++)if(nonzero[i])break;
  118625. if(i==ch)return(0); /* no nonzero vectors */
  118626. for(s=0;s<look->stages;s++){
  118627. for(i=0,l=0;i<partvals;l++){
  118628. if(s==0){
  118629. /* fetch the partition word */
  118630. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118631. if(temp==-1)goto eopbreak;
  118632. partword[l]=look->decodemap[temp];
  118633. if(partword[l]==NULL)goto errout;
  118634. }
  118635. /* now we decode residual values for the partitions */
  118636. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118637. if(info->secondstages[partword[l][k]]&(1<<s)){
  118638. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118639. if(stagebook){
  118640. if(vorbis_book_decodevv_add(stagebook,in,
  118641. i*samples_per_partition+info->begin,ch,
  118642. &vb->opb,samples_per_partition)==-1)
  118643. goto eopbreak;
  118644. }
  118645. }
  118646. }
  118647. }
  118648. errout:
  118649. eopbreak:
  118650. return(0);
  118651. }
  118652. vorbis_func_residue residue0_exportbundle={
  118653. NULL,
  118654. &res0_unpack,
  118655. &res0_look,
  118656. &res0_free_info,
  118657. &res0_free_look,
  118658. NULL,
  118659. NULL,
  118660. &res0_inverse
  118661. };
  118662. vorbis_func_residue residue1_exportbundle={
  118663. &res0_pack,
  118664. &res0_unpack,
  118665. &res0_look,
  118666. &res0_free_info,
  118667. &res0_free_look,
  118668. &res1_class,
  118669. &res1_forward,
  118670. &res1_inverse
  118671. };
  118672. vorbis_func_residue residue2_exportbundle={
  118673. &res0_pack,
  118674. &res0_unpack,
  118675. &res0_look,
  118676. &res0_free_info,
  118677. &res0_free_look,
  118678. &res2_class,
  118679. &res2_forward,
  118680. &res2_inverse
  118681. };
  118682. #endif
  118683. /*** End of inlined file: res0.c ***/
  118684. /*** Start of inlined file: sharedbook.c ***/
  118685. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118686. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118687. // tasks..
  118688. #if JUCE_MSVC
  118689. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118690. #endif
  118691. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118692. #if JUCE_USE_OGGVORBIS
  118693. #include <stdlib.h>
  118694. #include <math.h>
  118695. #include <string.h>
  118696. /**** pack/unpack helpers ******************************************/
  118697. int _ilog(unsigned int v){
  118698. int ret=0;
  118699. while(v){
  118700. ret++;
  118701. v>>=1;
  118702. }
  118703. return(ret);
  118704. }
  118705. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118706. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118707. Why not IEEE? It's just not that important here. */
  118708. #define VQ_FEXP 10
  118709. #define VQ_FMAN 21
  118710. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118711. /* doesn't currently guard under/overflow */
  118712. long _float32_pack(float val){
  118713. int sign=0;
  118714. long exp;
  118715. long mant;
  118716. if(val<0){
  118717. sign=0x80000000;
  118718. val= -val;
  118719. }
  118720. exp= floor(log(val)/log(2.f));
  118721. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118722. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118723. return(sign|exp|mant);
  118724. }
  118725. float _float32_unpack(long val){
  118726. double mant=val&0x1fffff;
  118727. int sign=val&0x80000000;
  118728. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118729. if(sign)mant= -mant;
  118730. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118731. }
  118732. /* given a list of word lengths, generate a list of codewords. Works
  118733. for length ordered or unordered, always assigns the lowest valued
  118734. codewords first. Extended to handle unused entries (length 0) */
  118735. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118736. long i,j,count=0;
  118737. ogg_uint32_t marker[33];
  118738. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118739. memset(marker,0,sizeof(marker));
  118740. for(i=0;i<n;i++){
  118741. long length=l[i];
  118742. if(length>0){
  118743. ogg_uint32_t entry=marker[length];
  118744. /* when we claim a node for an entry, we also claim the nodes
  118745. below it (pruning off the imagined tree that may have dangled
  118746. from it) as well as blocking the use of any nodes directly
  118747. above for leaves */
  118748. /* update ourself */
  118749. if(length<32 && (entry>>length)){
  118750. /* error condition; the lengths must specify an overpopulated tree */
  118751. _ogg_free(r);
  118752. return(NULL);
  118753. }
  118754. r[count++]=entry;
  118755. /* Look to see if the next shorter marker points to the node
  118756. above. if so, update it and repeat. */
  118757. {
  118758. for(j=length;j>0;j--){
  118759. if(marker[j]&1){
  118760. /* have to jump branches */
  118761. if(j==1)
  118762. marker[1]++;
  118763. else
  118764. marker[j]=marker[j-1]<<1;
  118765. break; /* invariant says next upper marker would already
  118766. have been moved if it was on the same path */
  118767. }
  118768. marker[j]++;
  118769. }
  118770. }
  118771. /* prune the tree; the implicit invariant says all the longer
  118772. markers were dangling from our just-taken node. Dangle them
  118773. from our *new* node. */
  118774. for(j=length+1;j<33;j++)
  118775. if((marker[j]>>1) == entry){
  118776. entry=marker[j];
  118777. marker[j]=marker[j-1]<<1;
  118778. }else
  118779. break;
  118780. }else
  118781. if(sparsecount==0)count++;
  118782. }
  118783. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118784. endian */
  118785. for(i=0,count=0;i<n;i++){
  118786. ogg_uint32_t temp=0;
  118787. for(j=0;j<l[i];j++){
  118788. temp<<=1;
  118789. temp|=(r[count]>>j)&1;
  118790. }
  118791. if(sparsecount){
  118792. if(l[i])
  118793. r[count++]=temp;
  118794. }else
  118795. r[count++]=temp;
  118796. }
  118797. return(r);
  118798. }
  118799. /* there might be a straightforward one-line way to do the below
  118800. that's portable and totally safe against roundoff, but I haven't
  118801. thought of it. Therefore, we opt on the side of caution */
  118802. long _book_maptype1_quantvals(const static_codebook *b){
  118803. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118804. /* the above *should* be reliable, but we'll not assume that FP is
  118805. ever reliable when bitstream sync is at stake; verify via integer
  118806. means that vals really is the greatest value of dim for which
  118807. vals^b->bim <= b->entries */
  118808. /* treat the above as an initial guess */
  118809. while(1){
  118810. long acc=1;
  118811. long acc1=1;
  118812. int i;
  118813. for(i=0;i<b->dim;i++){
  118814. acc*=vals;
  118815. acc1*=vals+1;
  118816. }
  118817. if(acc<=b->entries && acc1>b->entries){
  118818. return(vals);
  118819. }else{
  118820. if(acc>b->entries){
  118821. vals--;
  118822. }else{
  118823. vals++;
  118824. }
  118825. }
  118826. }
  118827. }
  118828. /* unpack the quantized list of values for encode/decode ***********/
  118829. /* we need to deal with two map types: in map type 1, the values are
  118830. generated algorithmically (each column of the vector counts through
  118831. the values in the quant vector). in map type 2, all the values came
  118832. in in an explicit list. Both value lists must be unpacked */
  118833. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118834. long j,k,count=0;
  118835. if(b->maptype==1 || b->maptype==2){
  118836. int quantvals;
  118837. float mindel=_float32_unpack(b->q_min);
  118838. float delta=_float32_unpack(b->q_delta);
  118839. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118840. /* maptype 1 and 2 both use a quantized value vector, but
  118841. different sizes */
  118842. switch(b->maptype){
  118843. case 1:
  118844. /* most of the time, entries%dimensions == 0, but we need to be
  118845. well defined. We define that the possible vales at each
  118846. scalar is values == entries/dim. If entries%dim != 0, we'll
  118847. have 'too few' values (values*dim<entries), which means that
  118848. we'll have 'left over' entries; left over entries use zeroed
  118849. values (and are wasted). So don't generate codebooks like
  118850. that */
  118851. quantvals=_book_maptype1_quantvals(b);
  118852. for(j=0;j<b->entries;j++){
  118853. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118854. float last=0.f;
  118855. int indexdiv=1;
  118856. for(k=0;k<b->dim;k++){
  118857. int index= (j/indexdiv)%quantvals;
  118858. float val=b->quantlist[index];
  118859. val=fabs(val)*delta+mindel+last;
  118860. if(b->q_sequencep)last=val;
  118861. if(sparsemap)
  118862. r[sparsemap[count]*b->dim+k]=val;
  118863. else
  118864. r[count*b->dim+k]=val;
  118865. indexdiv*=quantvals;
  118866. }
  118867. count++;
  118868. }
  118869. }
  118870. break;
  118871. case 2:
  118872. for(j=0;j<b->entries;j++){
  118873. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118874. float last=0.f;
  118875. for(k=0;k<b->dim;k++){
  118876. float val=b->quantlist[j*b->dim+k];
  118877. val=fabs(val)*delta+mindel+last;
  118878. if(b->q_sequencep)last=val;
  118879. if(sparsemap)
  118880. r[sparsemap[count]*b->dim+k]=val;
  118881. else
  118882. r[count*b->dim+k]=val;
  118883. }
  118884. count++;
  118885. }
  118886. }
  118887. break;
  118888. }
  118889. return(r);
  118890. }
  118891. return(NULL);
  118892. }
  118893. void vorbis_staticbook_clear(static_codebook *b){
  118894. if(b->allocedp){
  118895. if(b->quantlist)_ogg_free(b->quantlist);
  118896. if(b->lengthlist)_ogg_free(b->lengthlist);
  118897. if(b->nearest_tree){
  118898. _ogg_free(b->nearest_tree->ptr0);
  118899. _ogg_free(b->nearest_tree->ptr1);
  118900. _ogg_free(b->nearest_tree->p);
  118901. _ogg_free(b->nearest_tree->q);
  118902. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118903. _ogg_free(b->nearest_tree);
  118904. }
  118905. if(b->thresh_tree){
  118906. _ogg_free(b->thresh_tree->quantthresh);
  118907. _ogg_free(b->thresh_tree->quantmap);
  118908. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118909. _ogg_free(b->thresh_tree);
  118910. }
  118911. memset(b,0,sizeof(*b));
  118912. }
  118913. }
  118914. void vorbis_staticbook_destroy(static_codebook *b){
  118915. if(b->allocedp){
  118916. vorbis_staticbook_clear(b);
  118917. _ogg_free(b);
  118918. }
  118919. }
  118920. void vorbis_book_clear(codebook *b){
  118921. /* static book is not cleared; we're likely called on the lookup and
  118922. the static codebook belongs to the info struct */
  118923. if(b->valuelist)_ogg_free(b->valuelist);
  118924. if(b->codelist)_ogg_free(b->codelist);
  118925. if(b->dec_index)_ogg_free(b->dec_index);
  118926. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118927. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118928. memset(b,0,sizeof(*b));
  118929. }
  118930. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118931. memset(c,0,sizeof(*c));
  118932. c->c=s;
  118933. c->entries=s->entries;
  118934. c->used_entries=s->entries;
  118935. c->dim=s->dim;
  118936. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118937. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118938. return(0);
  118939. }
  118940. static int JUCE_CDECL sort32a(const void *a,const void *b){
  118941. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118942. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118943. }
  118944. /* decode codebook arrangement is more heavily optimized than encode */
  118945. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118946. int i,j,n=0,tabn;
  118947. int *sortindex;
  118948. memset(c,0,sizeof(*c));
  118949. /* count actually used entries */
  118950. for(i=0;i<s->entries;i++)
  118951. if(s->lengthlist[i]>0)
  118952. n++;
  118953. c->entries=s->entries;
  118954. c->used_entries=n;
  118955. c->dim=s->dim;
  118956. /* two different remappings go on here.
  118957. First, we collapse the likely sparse codebook down only to
  118958. actually represented values/words. This collapsing needs to be
  118959. indexed as map-valueless books are used to encode original entry
  118960. positions as integers.
  118961. Second, we reorder all vectors, including the entry index above,
  118962. by sorted bitreversed codeword to allow treeless decode. */
  118963. {
  118964. /* perform sort */
  118965. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118966. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118967. if(codes==NULL)goto err_out;
  118968. for(i=0;i<n;i++){
  118969. codes[i]=ogg_bitreverse(codes[i]);
  118970. codep[i]=codes+i;
  118971. }
  118972. qsort(codep,n,sizeof(*codep),sort32a);
  118973. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118974. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118975. /* the index is a reverse index */
  118976. for(i=0;i<n;i++){
  118977. int position=codep[i]-codes;
  118978. sortindex[position]=i;
  118979. }
  118980. for(i=0;i<n;i++)
  118981. c->codelist[sortindex[i]]=codes[i];
  118982. _ogg_free(codes);
  118983. }
  118984. c->valuelist=_book_unquantize(s,n,sortindex);
  118985. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118986. for(n=0,i=0;i<s->entries;i++)
  118987. if(s->lengthlist[i]>0)
  118988. c->dec_index[sortindex[n++]]=i;
  118989. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118990. for(n=0,i=0;i<s->entries;i++)
  118991. if(s->lengthlist[i]>0)
  118992. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118993. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118994. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118995. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118996. tabn=1<<c->dec_firsttablen;
  118997. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118998. c->dec_maxlength=0;
  118999. for(i=0;i<n;i++){
  119000. if(c->dec_maxlength<c->dec_codelengths[i])
  119001. c->dec_maxlength=c->dec_codelengths[i];
  119002. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119003. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119004. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119005. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119006. }
  119007. }
  119008. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119009. hints for the non-direct-hits */
  119010. {
  119011. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119012. long lo=0,hi=0;
  119013. for(i=0;i<tabn;i++){
  119014. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119015. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119016. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119017. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119018. /* we only actually have 15 bits per hint to play with here.
  119019. In order to overflow gracefully (nothing breaks, efficiency
  119020. just drops), encode as the difference from the extremes. */
  119021. {
  119022. unsigned long loval=lo;
  119023. unsigned long hival=n-hi;
  119024. if(loval>0x7fff)loval=0x7fff;
  119025. if(hival>0x7fff)hival=0x7fff;
  119026. c->dec_firsttable[ogg_bitreverse(word)]=
  119027. 0x80000000UL | (loval<<15) | hival;
  119028. }
  119029. }
  119030. }
  119031. }
  119032. return(0);
  119033. err_out:
  119034. vorbis_book_clear(c);
  119035. return(-1);
  119036. }
  119037. static float _dist(int el,float *ref, float *b,int step){
  119038. int i;
  119039. float acc=0.f;
  119040. for(i=0;i<el;i++){
  119041. float val=(ref[i]-b[i*step]);
  119042. acc+=val*val;
  119043. }
  119044. return(acc);
  119045. }
  119046. int _best(codebook *book, float *a, int step){
  119047. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119048. #if 0
  119049. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119050. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119051. #endif
  119052. int dim=book->dim;
  119053. int k,o;
  119054. /*int savebest=-1;
  119055. float saverr;*/
  119056. /* do we have a threshhold encode hint? */
  119057. if(tt){
  119058. int index=0,i;
  119059. /* find the quant val of each scalar */
  119060. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119061. i=tt->threshvals>>1;
  119062. if(a[o]<tt->quantthresh[i]){
  119063. for(;i>0;i--)
  119064. if(a[o]>=tt->quantthresh[i-1])
  119065. break;
  119066. }else{
  119067. for(i++;i<tt->threshvals-1;i++)
  119068. if(a[o]<tt->quantthresh[i])break;
  119069. }
  119070. index=(index*tt->quantvals)+tt->quantmap[i];
  119071. }
  119072. /* regular lattices are easy :-) */
  119073. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119074. use a decision tree after all
  119075. and fall through*/
  119076. return(index);
  119077. }
  119078. #if 0
  119079. /* do we have a pigeonhole encode hint? */
  119080. if(pt){
  119081. const static_codebook *c=book->c;
  119082. int i,besti=-1;
  119083. float best=0.f;
  119084. int entry=0;
  119085. /* dealing with sequentialness is a pain in the ass */
  119086. if(c->q_sequencep){
  119087. int pv;
  119088. long mul=1;
  119089. float qlast=0;
  119090. for(k=0,o=0;k<dim;k++,o+=step){
  119091. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119092. if(pv<0 || pv>=pt->mapentries)break;
  119093. entry+=pt->pigeonmap[pv]*mul;
  119094. mul*=pt->quantvals;
  119095. qlast+=pv*pt->del+pt->min;
  119096. }
  119097. }else{
  119098. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119099. int pv=(int)((a[o]-pt->min)/pt->del);
  119100. if(pv<0 || pv>=pt->mapentries)break;
  119101. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119102. }
  119103. }
  119104. /* must be within the pigeonholable range; if we quant outside (or
  119105. in an entry that we define no list for), brute force it */
  119106. if(k==dim && pt->fitlength[entry]){
  119107. /* search the abbreviated list */
  119108. long *list=pt->fitlist+pt->fitmap[entry];
  119109. for(i=0;i<pt->fitlength[entry];i++){
  119110. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119111. if(besti==-1 || this<best){
  119112. best=this;
  119113. besti=list[i];
  119114. }
  119115. }
  119116. return(besti);
  119117. }
  119118. }
  119119. if(nt){
  119120. /* optimized using the decision tree */
  119121. while(1){
  119122. float c=0.f;
  119123. float *p=book->valuelist+nt->p[ptr];
  119124. float *q=book->valuelist+nt->q[ptr];
  119125. for(k=0,o=0;k<dim;k++,o+=step)
  119126. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119127. if(c>0.f) /* in A */
  119128. ptr= -nt->ptr0[ptr];
  119129. else /* in B */
  119130. ptr= -nt->ptr1[ptr];
  119131. if(ptr<=0)break;
  119132. }
  119133. return(-ptr);
  119134. }
  119135. #endif
  119136. /* brute force it! */
  119137. {
  119138. const static_codebook *c=book->c;
  119139. int i,besti=-1;
  119140. float best=0.f;
  119141. float *e=book->valuelist;
  119142. for(i=0;i<book->entries;i++){
  119143. if(c->lengthlist[i]>0){
  119144. float thisx=_dist(dim,e,a,step);
  119145. if(besti==-1 || thisx<best){
  119146. best=thisx;
  119147. besti=i;
  119148. }
  119149. }
  119150. e+=dim;
  119151. }
  119152. /*if(savebest!=-1 && savebest!=besti){
  119153. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119154. "original:");
  119155. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119156. fprintf(stderr,"\n"
  119157. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119158. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119159. (book->valuelist+savebest*dim)[i]);
  119160. fprintf(stderr,"\n"
  119161. "bruteforce (entry %d, err %g):",besti,best);
  119162. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119163. (book->valuelist+besti*dim)[i]);
  119164. fprintf(stderr,"\n");
  119165. }*/
  119166. return(besti);
  119167. }
  119168. }
  119169. long vorbis_book_codeword(codebook *book,int entry){
  119170. if(book->c) /* only use with encode; decode optimizations are
  119171. allowed to break this */
  119172. return book->codelist[entry];
  119173. return -1;
  119174. }
  119175. long vorbis_book_codelen(codebook *book,int entry){
  119176. if(book->c) /* only use with encode; decode optimizations are
  119177. allowed to break this */
  119178. return book->c->lengthlist[entry];
  119179. return -1;
  119180. }
  119181. #ifdef _V_SELFTEST
  119182. /* Unit tests of the dequantizer; this stuff will be OK
  119183. cross-platform, I simply want to be sure that special mapping cases
  119184. actually work properly; a bug could go unnoticed for a while */
  119185. #include <stdio.h>
  119186. /* cases:
  119187. no mapping
  119188. full, explicit mapping
  119189. algorithmic mapping
  119190. nonsequential
  119191. sequential
  119192. */
  119193. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119194. static long partial_quantlist1[]={0,7,2};
  119195. /* no mapping */
  119196. static_codebook test1={
  119197. 4,16,
  119198. NULL,
  119199. 0,
  119200. 0,0,0,0,
  119201. NULL,
  119202. NULL,NULL
  119203. };
  119204. static float *test1_result=NULL;
  119205. /* linear, full mapping, nonsequential */
  119206. static_codebook test2={
  119207. 4,3,
  119208. NULL,
  119209. 2,
  119210. -533200896,1611661312,4,0,
  119211. full_quantlist1,
  119212. NULL,NULL
  119213. };
  119214. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119215. /* linear, full mapping, sequential */
  119216. static_codebook test3={
  119217. 4,3,
  119218. NULL,
  119219. 2,
  119220. -533200896,1611661312,4,1,
  119221. full_quantlist1,
  119222. NULL,NULL
  119223. };
  119224. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119225. /* linear, algorithmic mapping, nonsequential */
  119226. static_codebook test4={
  119227. 3,27,
  119228. NULL,
  119229. 1,
  119230. -533200896,1611661312,4,0,
  119231. partial_quantlist1,
  119232. NULL,NULL
  119233. };
  119234. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119235. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119236. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119237. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119238. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119239. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119240. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119241. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119242. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119243. /* linear, algorithmic mapping, sequential */
  119244. static_codebook test5={
  119245. 3,27,
  119246. NULL,
  119247. 1,
  119248. -533200896,1611661312,4,1,
  119249. partial_quantlist1,
  119250. NULL,NULL
  119251. };
  119252. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119253. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119254. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119255. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119256. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119257. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119258. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119259. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119260. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119261. void run_test(static_codebook *b,float *comp){
  119262. float *out=_book_unquantize(b,b->entries,NULL);
  119263. int i;
  119264. if(comp){
  119265. if(!out){
  119266. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119267. exit(1);
  119268. }
  119269. for(i=0;i<b->entries*b->dim;i++)
  119270. if(fabs(out[i]-comp[i])>.0001){
  119271. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119272. "position %d, %g != %g\n",i,out[i],comp[i]);
  119273. exit(1);
  119274. }
  119275. }else{
  119276. if(out){
  119277. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119278. " correct result should have been NULL\n");
  119279. exit(1);
  119280. }
  119281. }
  119282. }
  119283. int main(){
  119284. /* run the nine dequant tests, and compare to the hand-rolled results */
  119285. fprintf(stderr,"Dequant test 1... ");
  119286. run_test(&test1,test1_result);
  119287. fprintf(stderr,"OK\nDequant test 2... ");
  119288. run_test(&test2,test2_result);
  119289. fprintf(stderr,"OK\nDequant test 3... ");
  119290. run_test(&test3,test3_result);
  119291. fprintf(stderr,"OK\nDequant test 4... ");
  119292. run_test(&test4,test4_result);
  119293. fprintf(stderr,"OK\nDequant test 5... ");
  119294. run_test(&test5,test5_result);
  119295. fprintf(stderr,"OK\n\n");
  119296. return(0);
  119297. }
  119298. #endif
  119299. #endif
  119300. /*** End of inlined file: sharedbook.c ***/
  119301. /*** Start of inlined file: smallft.c ***/
  119302. /* FFT implementation from OggSquish, minus cosine transforms,
  119303. * minus all but radix 2/4 case. In Vorbis we only need this
  119304. * cut-down version.
  119305. *
  119306. * To do more than just power-of-two sized vectors, see the full
  119307. * version I wrote for NetLib.
  119308. *
  119309. * Note that the packing is a little strange; rather than the FFT r/i
  119310. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119311. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119312. * FORTRAN version
  119313. */
  119314. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119315. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119316. // tasks..
  119317. #if JUCE_MSVC
  119318. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119319. #endif
  119320. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119321. #if JUCE_USE_OGGVORBIS
  119322. #include <stdlib.h>
  119323. #include <string.h>
  119324. #include <math.h>
  119325. static void drfti1(int n, float *wa, int *ifac){
  119326. static int ntryh[4] = { 4,2,3,5 };
  119327. static float tpi = 6.28318530717958648f;
  119328. float arg,argh,argld,fi;
  119329. int ntry=0,i,j=-1;
  119330. int k1, l1, l2, ib;
  119331. int ld, ii, ip, is, nq, nr;
  119332. int ido, ipm, nfm1;
  119333. int nl=n;
  119334. int nf=0;
  119335. L101:
  119336. j++;
  119337. if (j < 4)
  119338. ntry=ntryh[j];
  119339. else
  119340. ntry+=2;
  119341. L104:
  119342. nq=nl/ntry;
  119343. nr=nl-ntry*nq;
  119344. if (nr!=0) goto L101;
  119345. nf++;
  119346. ifac[nf+1]=ntry;
  119347. nl=nq;
  119348. if(ntry!=2)goto L107;
  119349. if(nf==1)goto L107;
  119350. for (i=1;i<nf;i++){
  119351. ib=nf-i+1;
  119352. ifac[ib+1]=ifac[ib];
  119353. }
  119354. ifac[2] = 2;
  119355. L107:
  119356. if(nl!=1)goto L104;
  119357. ifac[0]=n;
  119358. ifac[1]=nf;
  119359. argh=tpi/n;
  119360. is=0;
  119361. nfm1=nf-1;
  119362. l1=1;
  119363. if(nfm1==0)return;
  119364. for (k1=0;k1<nfm1;k1++){
  119365. ip=ifac[k1+2];
  119366. ld=0;
  119367. l2=l1*ip;
  119368. ido=n/l2;
  119369. ipm=ip-1;
  119370. for (j=0;j<ipm;j++){
  119371. ld+=l1;
  119372. i=is;
  119373. argld=(float)ld*argh;
  119374. fi=0.f;
  119375. for (ii=2;ii<ido;ii+=2){
  119376. fi+=1.f;
  119377. arg=fi*argld;
  119378. wa[i++]=cos(arg);
  119379. wa[i++]=sin(arg);
  119380. }
  119381. is+=ido;
  119382. }
  119383. l1=l2;
  119384. }
  119385. }
  119386. static void fdrffti(int n, float *wsave, int *ifac){
  119387. if (n == 1) return;
  119388. drfti1(n, wsave+n, ifac);
  119389. }
  119390. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119391. int i,k;
  119392. float ti2,tr2;
  119393. int t0,t1,t2,t3,t4,t5,t6;
  119394. t1=0;
  119395. t0=(t2=l1*ido);
  119396. t3=ido<<1;
  119397. for(k=0;k<l1;k++){
  119398. ch[t1<<1]=cc[t1]+cc[t2];
  119399. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119400. t1+=ido;
  119401. t2+=ido;
  119402. }
  119403. if(ido<2)return;
  119404. if(ido==2)goto L105;
  119405. t1=0;
  119406. t2=t0;
  119407. for(k=0;k<l1;k++){
  119408. t3=t2;
  119409. t4=(t1<<1)+(ido<<1);
  119410. t5=t1;
  119411. t6=t1+t1;
  119412. for(i=2;i<ido;i+=2){
  119413. t3+=2;
  119414. t4-=2;
  119415. t5+=2;
  119416. t6+=2;
  119417. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119418. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119419. ch[t6]=cc[t5]+ti2;
  119420. ch[t4]=ti2-cc[t5];
  119421. ch[t6-1]=cc[t5-1]+tr2;
  119422. ch[t4-1]=cc[t5-1]-tr2;
  119423. }
  119424. t1+=ido;
  119425. t2+=ido;
  119426. }
  119427. if(ido%2==1)return;
  119428. L105:
  119429. t3=(t2=(t1=ido)-1);
  119430. t2+=t0;
  119431. for(k=0;k<l1;k++){
  119432. ch[t1]=-cc[t2];
  119433. ch[t1-1]=cc[t3];
  119434. t1+=ido<<1;
  119435. t2+=ido;
  119436. t3+=ido;
  119437. }
  119438. }
  119439. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119440. float *wa2,float *wa3){
  119441. static float hsqt2 = .70710678118654752f;
  119442. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119443. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119444. t0=l1*ido;
  119445. t1=t0;
  119446. t4=t1<<1;
  119447. t2=t1+(t1<<1);
  119448. t3=0;
  119449. for(k=0;k<l1;k++){
  119450. tr1=cc[t1]+cc[t2];
  119451. tr2=cc[t3]+cc[t4];
  119452. ch[t5=t3<<2]=tr1+tr2;
  119453. ch[(ido<<2)+t5-1]=tr2-tr1;
  119454. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119455. ch[t5]=cc[t2]-cc[t1];
  119456. t1+=ido;
  119457. t2+=ido;
  119458. t3+=ido;
  119459. t4+=ido;
  119460. }
  119461. if(ido<2)return;
  119462. if(ido==2)goto L105;
  119463. t1=0;
  119464. for(k=0;k<l1;k++){
  119465. t2=t1;
  119466. t4=t1<<2;
  119467. t5=(t6=ido<<1)+t4;
  119468. for(i=2;i<ido;i+=2){
  119469. t3=(t2+=2);
  119470. t4+=2;
  119471. t5-=2;
  119472. t3+=t0;
  119473. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119474. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119475. t3+=t0;
  119476. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119477. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119478. t3+=t0;
  119479. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119480. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119481. tr1=cr2+cr4;
  119482. tr4=cr4-cr2;
  119483. ti1=ci2+ci4;
  119484. ti4=ci2-ci4;
  119485. ti2=cc[t2]+ci3;
  119486. ti3=cc[t2]-ci3;
  119487. tr2=cc[t2-1]+cr3;
  119488. tr3=cc[t2-1]-cr3;
  119489. ch[t4-1]=tr1+tr2;
  119490. ch[t4]=ti1+ti2;
  119491. ch[t5-1]=tr3-ti4;
  119492. ch[t5]=tr4-ti3;
  119493. ch[t4+t6-1]=ti4+tr3;
  119494. ch[t4+t6]=tr4+ti3;
  119495. ch[t5+t6-1]=tr2-tr1;
  119496. ch[t5+t6]=ti1-ti2;
  119497. }
  119498. t1+=ido;
  119499. }
  119500. if(ido&1)return;
  119501. L105:
  119502. t2=(t1=t0+ido-1)+(t0<<1);
  119503. t3=ido<<2;
  119504. t4=ido;
  119505. t5=ido<<1;
  119506. t6=ido;
  119507. for(k=0;k<l1;k++){
  119508. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119509. tr1=hsqt2*(cc[t1]-cc[t2]);
  119510. ch[t4-1]=tr1+cc[t6-1];
  119511. ch[t4+t5-1]=cc[t6-1]-tr1;
  119512. ch[t4]=ti1-cc[t1+t0];
  119513. ch[t4+t5]=ti1+cc[t1+t0];
  119514. t1+=ido;
  119515. t2+=ido;
  119516. t4+=t3;
  119517. t6+=ido;
  119518. }
  119519. }
  119520. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119521. float *c2,float *ch,float *ch2,float *wa){
  119522. static float tpi=6.283185307179586f;
  119523. int idij,ipph,i,j,k,l,ic,ik,is;
  119524. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119525. float dc2,ai1,ai2,ar1,ar2,ds2;
  119526. int nbd;
  119527. float dcp,arg,dsp,ar1h,ar2h;
  119528. int idp2,ipp2;
  119529. arg=tpi/(float)ip;
  119530. dcp=cos(arg);
  119531. dsp=sin(arg);
  119532. ipph=(ip+1)>>1;
  119533. ipp2=ip;
  119534. idp2=ido;
  119535. nbd=(ido-1)>>1;
  119536. t0=l1*ido;
  119537. t10=ip*ido;
  119538. if(ido==1)goto L119;
  119539. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119540. t1=0;
  119541. for(j=1;j<ip;j++){
  119542. t1+=t0;
  119543. t2=t1;
  119544. for(k=0;k<l1;k++){
  119545. ch[t2]=c1[t2];
  119546. t2+=ido;
  119547. }
  119548. }
  119549. is=-ido;
  119550. t1=0;
  119551. if(nbd>l1){
  119552. for(j=1;j<ip;j++){
  119553. t1+=t0;
  119554. is+=ido;
  119555. t2= -ido+t1;
  119556. for(k=0;k<l1;k++){
  119557. idij=is-1;
  119558. t2+=ido;
  119559. t3=t2;
  119560. for(i=2;i<ido;i+=2){
  119561. idij+=2;
  119562. t3+=2;
  119563. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119564. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119565. }
  119566. }
  119567. }
  119568. }else{
  119569. for(j=1;j<ip;j++){
  119570. is+=ido;
  119571. idij=is-1;
  119572. t1+=t0;
  119573. t2=t1;
  119574. for(i=2;i<ido;i+=2){
  119575. idij+=2;
  119576. t2+=2;
  119577. t3=t2;
  119578. for(k=0;k<l1;k++){
  119579. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119580. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119581. t3+=ido;
  119582. }
  119583. }
  119584. }
  119585. }
  119586. t1=0;
  119587. t2=ipp2*t0;
  119588. if(nbd<l1){
  119589. for(j=1;j<ipph;j++){
  119590. t1+=t0;
  119591. t2-=t0;
  119592. t3=t1;
  119593. t4=t2;
  119594. for(i=2;i<ido;i+=2){
  119595. t3+=2;
  119596. t4+=2;
  119597. t5=t3-ido;
  119598. t6=t4-ido;
  119599. for(k=0;k<l1;k++){
  119600. t5+=ido;
  119601. t6+=ido;
  119602. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119603. c1[t6-1]=ch[t5]-ch[t6];
  119604. c1[t5]=ch[t5]+ch[t6];
  119605. c1[t6]=ch[t6-1]-ch[t5-1];
  119606. }
  119607. }
  119608. }
  119609. }else{
  119610. for(j=1;j<ipph;j++){
  119611. t1+=t0;
  119612. t2-=t0;
  119613. t3=t1;
  119614. t4=t2;
  119615. for(k=0;k<l1;k++){
  119616. t5=t3;
  119617. t6=t4;
  119618. for(i=2;i<ido;i+=2){
  119619. t5+=2;
  119620. t6+=2;
  119621. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119622. c1[t6-1]=ch[t5]-ch[t6];
  119623. c1[t5]=ch[t5]+ch[t6];
  119624. c1[t6]=ch[t6-1]-ch[t5-1];
  119625. }
  119626. t3+=ido;
  119627. t4+=ido;
  119628. }
  119629. }
  119630. }
  119631. L119:
  119632. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119633. t1=0;
  119634. t2=ipp2*idl1;
  119635. for(j=1;j<ipph;j++){
  119636. t1+=t0;
  119637. t2-=t0;
  119638. t3=t1-ido;
  119639. t4=t2-ido;
  119640. for(k=0;k<l1;k++){
  119641. t3+=ido;
  119642. t4+=ido;
  119643. c1[t3]=ch[t3]+ch[t4];
  119644. c1[t4]=ch[t4]-ch[t3];
  119645. }
  119646. }
  119647. ar1=1.f;
  119648. ai1=0.f;
  119649. t1=0;
  119650. t2=ipp2*idl1;
  119651. t3=(ip-1)*idl1;
  119652. for(l=1;l<ipph;l++){
  119653. t1+=idl1;
  119654. t2-=idl1;
  119655. ar1h=dcp*ar1-dsp*ai1;
  119656. ai1=dcp*ai1+dsp*ar1;
  119657. ar1=ar1h;
  119658. t4=t1;
  119659. t5=t2;
  119660. t6=t3;
  119661. t7=idl1;
  119662. for(ik=0;ik<idl1;ik++){
  119663. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119664. ch2[t5++]=ai1*c2[t6++];
  119665. }
  119666. dc2=ar1;
  119667. ds2=ai1;
  119668. ar2=ar1;
  119669. ai2=ai1;
  119670. t4=idl1;
  119671. t5=(ipp2-1)*idl1;
  119672. for(j=2;j<ipph;j++){
  119673. t4+=idl1;
  119674. t5-=idl1;
  119675. ar2h=dc2*ar2-ds2*ai2;
  119676. ai2=dc2*ai2+ds2*ar2;
  119677. ar2=ar2h;
  119678. t6=t1;
  119679. t7=t2;
  119680. t8=t4;
  119681. t9=t5;
  119682. for(ik=0;ik<idl1;ik++){
  119683. ch2[t6++]+=ar2*c2[t8++];
  119684. ch2[t7++]+=ai2*c2[t9++];
  119685. }
  119686. }
  119687. }
  119688. t1=0;
  119689. for(j=1;j<ipph;j++){
  119690. t1+=idl1;
  119691. t2=t1;
  119692. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119693. }
  119694. if(ido<l1)goto L132;
  119695. t1=0;
  119696. t2=0;
  119697. for(k=0;k<l1;k++){
  119698. t3=t1;
  119699. t4=t2;
  119700. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119701. t1+=ido;
  119702. t2+=t10;
  119703. }
  119704. goto L135;
  119705. L132:
  119706. for(i=0;i<ido;i++){
  119707. t1=i;
  119708. t2=i;
  119709. for(k=0;k<l1;k++){
  119710. cc[t2]=ch[t1];
  119711. t1+=ido;
  119712. t2+=t10;
  119713. }
  119714. }
  119715. L135:
  119716. t1=0;
  119717. t2=ido<<1;
  119718. t3=0;
  119719. t4=ipp2*t0;
  119720. for(j=1;j<ipph;j++){
  119721. t1+=t2;
  119722. t3+=t0;
  119723. t4-=t0;
  119724. t5=t1;
  119725. t6=t3;
  119726. t7=t4;
  119727. for(k=0;k<l1;k++){
  119728. cc[t5-1]=ch[t6];
  119729. cc[t5]=ch[t7];
  119730. t5+=t10;
  119731. t6+=ido;
  119732. t7+=ido;
  119733. }
  119734. }
  119735. if(ido==1)return;
  119736. if(nbd<l1)goto L141;
  119737. t1=-ido;
  119738. t3=0;
  119739. t4=0;
  119740. t5=ipp2*t0;
  119741. for(j=1;j<ipph;j++){
  119742. t1+=t2;
  119743. t3+=t2;
  119744. t4+=t0;
  119745. t5-=t0;
  119746. t6=t1;
  119747. t7=t3;
  119748. t8=t4;
  119749. t9=t5;
  119750. for(k=0;k<l1;k++){
  119751. for(i=2;i<ido;i+=2){
  119752. ic=idp2-i;
  119753. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119754. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119755. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119756. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119757. }
  119758. t6+=t10;
  119759. t7+=t10;
  119760. t8+=ido;
  119761. t9+=ido;
  119762. }
  119763. }
  119764. return;
  119765. L141:
  119766. t1=-ido;
  119767. t3=0;
  119768. t4=0;
  119769. t5=ipp2*t0;
  119770. for(j=1;j<ipph;j++){
  119771. t1+=t2;
  119772. t3+=t2;
  119773. t4+=t0;
  119774. t5-=t0;
  119775. for(i=2;i<ido;i+=2){
  119776. t6=idp2+t1-i;
  119777. t7=i+t3;
  119778. t8=i+t4;
  119779. t9=i+t5;
  119780. for(k=0;k<l1;k++){
  119781. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119782. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119783. cc[t7]=ch[t8]+ch[t9];
  119784. cc[t6]=ch[t9]-ch[t8];
  119785. t6+=t10;
  119786. t7+=t10;
  119787. t8+=ido;
  119788. t9+=ido;
  119789. }
  119790. }
  119791. }
  119792. }
  119793. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119794. int i,k1,l1,l2;
  119795. int na,kh,nf;
  119796. int ip,iw,ido,idl1,ix2,ix3;
  119797. nf=ifac[1];
  119798. na=1;
  119799. l2=n;
  119800. iw=n;
  119801. for(k1=0;k1<nf;k1++){
  119802. kh=nf-k1;
  119803. ip=ifac[kh+1];
  119804. l1=l2/ip;
  119805. ido=n/l2;
  119806. idl1=ido*l1;
  119807. iw-=(ip-1)*ido;
  119808. na=1-na;
  119809. if(ip!=4)goto L102;
  119810. ix2=iw+ido;
  119811. ix3=ix2+ido;
  119812. if(na!=0)
  119813. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119814. else
  119815. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119816. goto L110;
  119817. L102:
  119818. if(ip!=2)goto L104;
  119819. if(na!=0)goto L103;
  119820. dradf2(ido,l1,c,ch,wa+iw-1);
  119821. goto L110;
  119822. L103:
  119823. dradf2(ido,l1,ch,c,wa+iw-1);
  119824. goto L110;
  119825. L104:
  119826. if(ido==1)na=1-na;
  119827. if(na!=0)goto L109;
  119828. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119829. na=1;
  119830. goto L110;
  119831. L109:
  119832. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119833. na=0;
  119834. L110:
  119835. l2=l1;
  119836. }
  119837. if(na==1)return;
  119838. for(i=0;i<n;i++)c[i]=ch[i];
  119839. }
  119840. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119841. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119842. float ti2,tr2;
  119843. t0=l1*ido;
  119844. t1=0;
  119845. t2=0;
  119846. t3=(ido<<1)-1;
  119847. for(k=0;k<l1;k++){
  119848. ch[t1]=cc[t2]+cc[t3+t2];
  119849. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119850. t2=(t1+=ido)<<1;
  119851. }
  119852. if(ido<2)return;
  119853. if(ido==2)goto L105;
  119854. t1=0;
  119855. t2=0;
  119856. for(k=0;k<l1;k++){
  119857. t3=t1;
  119858. t5=(t4=t2)+(ido<<1);
  119859. t6=t0+t1;
  119860. for(i=2;i<ido;i+=2){
  119861. t3+=2;
  119862. t4+=2;
  119863. t5-=2;
  119864. t6+=2;
  119865. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119866. tr2=cc[t4-1]-cc[t5-1];
  119867. ch[t3]=cc[t4]-cc[t5];
  119868. ti2=cc[t4]+cc[t5];
  119869. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119870. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119871. }
  119872. t2=(t1+=ido)<<1;
  119873. }
  119874. if(ido%2==1)return;
  119875. L105:
  119876. t1=ido-1;
  119877. t2=ido-1;
  119878. for(k=0;k<l1;k++){
  119879. ch[t1]=cc[t2]+cc[t2];
  119880. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119881. t1+=ido;
  119882. t2+=ido<<1;
  119883. }
  119884. }
  119885. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119886. float *wa2){
  119887. static float taur = -.5f;
  119888. static float taui = .8660254037844386f;
  119889. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119890. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119891. t0=l1*ido;
  119892. t1=0;
  119893. t2=t0<<1;
  119894. t3=ido<<1;
  119895. t4=ido+(ido<<1);
  119896. t5=0;
  119897. for(k=0;k<l1;k++){
  119898. tr2=cc[t3-1]+cc[t3-1];
  119899. cr2=cc[t5]+(taur*tr2);
  119900. ch[t1]=cc[t5]+tr2;
  119901. ci3=taui*(cc[t3]+cc[t3]);
  119902. ch[t1+t0]=cr2-ci3;
  119903. ch[t1+t2]=cr2+ci3;
  119904. t1+=ido;
  119905. t3+=t4;
  119906. t5+=t4;
  119907. }
  119908. if(ido==1)return;
  119909. t1=0;
  119910. t3=ido<<1;
  119911. for(k=0;k<l1;k++){
  119912. t7=t1+(t1<<1);
  119913. t6=(t5=t7+t3);
  119914. t8=t1;
  119915. t10=(t9=t1+t0)+t0;
  119916. for(i=2;i<ido;i+=2){
  119917. t5+=2;
  119918. t6-=2;
  119919. t7+=2;
  119920. t8+=2;
  119921. t9+=2;
  119922. t10+=2;
  119923. tr2=cc[t5-1]+cc[t6-1];
  119924. cr2=cc[t7-1]+(taur*tr2);
  119925. ch[t8-1]=cc[t7-1]+tr2;
  119926. ti2=cc[t5]-cc[t6];
  119927. ci2=cc[t7]+(taur*ti2);
  119928. ch[t8]=cc[t7]+ti2;
  119929. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119930. ci3=taui*(cc[t5]+cc[t6]);
  119931. dr2=cr2-ci3;
  119932. dr3=cr2+ci3;
  119933. di2=ci2+cr3;
  119934. di3=ci2-cr3;
  119935. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119936. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119937. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119938. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119939. }
  119940. t1+=ido;
  119941. }
  119942. }
  119943. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119944. float *wa2,float *wa3){
  119945. static float sqrt2=1.414213562373095f;
  119946. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119947. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119948. t0=l1*ido;
  119949. t1=0;
  119950. t2=ido<<2;
  119951. t3=0;
  119952. t6=ido<<1;
  119953. for(k=0;k<l1;k++){
  119954. t4=t3+t6;
  119955. t5=t1;
  119956. tr3=cc[t4-1]+cc[t4-1];
  119957. tr4=cc[t4]+cc[t4];
  119958. tr1=cc[t3]-cc[(t4+=t6)-1];
  119959. tr2=cc[t3]+cc[t4-1];
  119960. ch[t5]=tr2+tr3;
  119961. ch[t5+=t0]=tr1-tr4;
  119962. ch[t5+=t0]=tr2-tr3;
  119963. ch[t5+=t0]=tr1+tr4;
  119964. t1+=ido;
  119965. t3+=t2;
  119966. }
  119967. if(ido<2)return;
  119968. if(ido==2)goto L105;
  119969. t1=0;
  119970. for(k=0;k<l1;k++){
  119971. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119972. t7=t1;
  119973. for(i=2;i<ido;i+=2){
  119974. t2+=2;
  119975. t3+=2;
  119976. t4-=2;
  119977. t5-=2;
  119978. t7+=2;
  119979. ti1=cc[t2]+cc[t5];
  119980. ti2=cc[t2]-cc[t5];
  119981. ti3=cc[t3]-cc[t4];
  119982. tr4=cc[t3]+cc[t4];
  119983. tr1=cc[t2-1]-cc[t5-1];
  119984. tr2=cc[t2-1]+cc[t5-1];
  119985. ti4=cc[t3-1]-cc[t4-1];
  119986. tr3=cc[t3-1]+cc[t4-1];
  119987. ch[t7-1]=tr2+tr3;
  119988. cr3=tr2-tr3;
  119989. ch[t7]=ti2+ti3;
  119990. ci3=ti2-ti3;
  119991. cr2=tr1-tr4;
  119992. cr4=tr1+tr4;
  119993. ci2=ti1+ti4;
  119994. ci4=ti1-ti4;
  119995. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119996. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119997. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119998. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119999. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120000. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120001. }
  120002. t1+=ido;
  120003. }
  120004. if(ido%2 == 1)return;
  120005. L105:
  120006. t1=ido;
  120007. t2=ido<<2;
  120008. t3=ido-1;
  120009. t4=ido+(ido<<1);
  120010. for(k=0;k<l1;k++){
  120011. t5=t3;
  120012. ti1=cc[t1]+cc[t4];
  120013. ti2=cc[t4]-cc[t1];
  120014. tr1=cc[t1-1]-cc[t4-1];
  120015. tr2=cc[t1-1]+cc[t4-1];
  120016. ch[t5]=tr2+tr2;
  120017. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120018. ch[t5+=t0]=ti2+ti2;
  120019. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120020. t3+=ido;
  120021. t1+=t2;
  120022. t4+=t2;
  120023. }
  120024. }
  120025. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120026. float *c2,float *ch,float *ch2,float *wa){
  120027. static float tpi=6.283185307179586f;
  120028. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120029. t11,t12;
  120030. float dc2,ai1,ai2,ar1,ar2,ds2;
  120031. int nbd;
  120032. float dcp,arg,dsp,ar1h,ar2h;
  120033. int ipp2;
  120034. t10=ip*ido;
  120035. t0=l1*ido;
  120036. arg=tpi/(float)ip;
  120037. dcp=cos(arg);
  120038. dsp=sin(arg);
  120039. nbd=(ido-1)>>1;
  120040. ipp2=ip;
  120041. ipph=(ip+1)>>1;
  120042. if(ido<l1)goto L103;
  120043. t1=0;
  120044. t2=0;
  120045. for(k=0;k<l1;k++){
  120046. t3=t1;
  120047. t4=t2;
  120048. for(i=0;i<ido;i++){
  120049. ch[t3]=cc[t4];
  120050. t3++;
  120051. t4++;
  120052. }
  120053. t1+=ido;
  120054. t2+=t10;
  120055. }
  120056. goto L106;
  120057. L103:
  120058. t1=0;
  120059. for(i=0;i<ido;i++){
  120060. t2=t1;
  120061. t3=t1;
  120062. for(k=0;k<l1;k++){
  120063. ch[t2]=cc[t3];
  120064. t2+=ido;
  120065. t3+=t10;
  120066. }
  120067. t1++;
  120068. }
  120069. L106:
  120070. t1=0;
  120071. t2=ipp2*t0;
  120072. t7=(t5=ido<<1);
  120073. for(j=1;j<ipph;j++){
  120074. t1+=t0;
  120075. t2-=t0;
  120076. t3=t1;
  120077. t4=t2;
  120078. t6=t5;
  120079. for(k=0;k<l1;k++){
  120080. ch[t3]=cc[t6-1]+cc[t6-1];
  120081. ch[t4]=cc[t6]+cc[t6];
  120082. t3+=ido;
  120083. t4+=ido;
  120084. t6+=t10;
  120085. }
  120086. t5+=t7;
  120087. }
  120088. if (ido == 1)goto L116;
  120089. if(nbd<l1)goto L112;
  120090. t1=0;
  120091. t2=ipp2*t0;
  120092. t7=0;
  120093. for(j=1;j<ipph;j++){
  120094. t1+=t0;
  120095. t2-=t0;
  120096. t3=t1;
  120097. t4=t2;
  120098. t7+=(ido<<1);
  120099. t8=t7;
  120100. for(k=0;k<l1;k++){
  120101. t5=t3;
  120102. t6=t4;
  120103. t9=t8;
  120104. t11=t8;
  120105. for(i=2;i<ido;i+=2){
  120106. t5+=2;
  120107. t6+=2;
  120108. t9+=2;
  120109. t11-=2;
  120110. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120111. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120112. ch[t5]=cc[t9]-cc[t11];
  120113. ch[t6]=cc[t9]+cc[t11];
  120114. }
  120115. t3+=ido;
  120116. t4+=ido;
  120117. t8+=t10;
  120118. }
  120119. }
  120120. goto L116;
  120121. L112:
  120122. t1=0;
  120123. t2=ipp2*t0;
  120124. t7=0;
  120125. for(j=1;j<ipph;j++){
  120126. t1+=t0;
  120127. t2-=t0;
  120128. t3=t1;
  120129. t4=t2;
  120130. t7+=(ido<<1);
  120131. t8=t7;
  120132. t9=t7;
  120133. for(i=2;i<ido;i+=2){
  120134. t3+=2;
  120135. t4+=2;
  120136. t8+=2;
  120137. t9-=2;
  120138. t5=t3;
  120139. t6=t4;
  120140. t11=t8;
  120141. t12=t9;
  120142. for(k=0;k<l1;k++){
  120143. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120144. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120145. ch[t5]=cc[t11]-cc[t12];
  120146. ch[t6]=cc[t11]+cc[t12];
  120147. t5+=ido;
  120148. t6+=ido;
  120149. t11+=t10;
  120150. t12+=t10;
  120151. }
  120152. }
  120153. }
  120154. L116:
  120155. ar1=1.f;
  120156. ai1=0.f;
  120157. t1=0;
  120158. t9=(t2=ipp2*idl1);
  120159. t3=(ip-1)*idl1;
  120160. for(l=1;l<ipph;l++){
  120161. t1+=idl1;
  120162. t2-=idl1;
  120163. ar1h=dcp*ar1-dsp*ai1;
  120164. ai1=dcp*ai1+dsp*ar1;
  120165. ar1=ar1h;
  120166. t4=t1;
  120167. t5=t2;
  120168. t6=0;
  120169. t7=idl1;
  120170. t8=t3;
  120171. for(ik=0;ik<idl1;ik++){
  120172. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120173. c2[t5++]=ai1*ch2[t8++];
  120174. }
  120175. dc2=ar1;
  120176. ds2=ai1;
  120177. ar2=ar1;
  120178. ai2=ai1;
  120179. t6=idl1;
  120180. t7=t9-idl1;
  120181. for(j=2;j<ipph;j++){
  120182. t6+=idl1;
  120183. t7-=idl1;
  120184. ar2h=dc2*ar2-ds2*ai2;
  120185. ai2=dc2*ai2+ds2*ar2;
  120186. ar2=ar2h;
  120187. t4=t1;
  120188. t5=t2;
  120189. t11=t6;
  120190. t12=t7;
  120191. for(ik=0;ik<idl1;ik++){
  120192. c2[t4++]+=ar2*ch2[t11++];
  120193. c2[t5++]+=ai2*ch2[t12++];
  120194. }
  120195. }
  120196. }
  120197. t1=0;
  120198. for(j=1;j<ipph;j++){
  120199. t1+=idl1;
  120200. t2=t1;
  120201. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120202. }
  120203. t1=0;
  120204. t2=ipp2*t0;
  120205. for(j=1;j<ipph;j++){
  120206. t1+=t0;
  120207. t2-=t0;
  120208. t3=t1;
  120209. t4=t2;
  120210. for(k=0;k<l1;k++){
  120211. ch[t3]=c1[t3]-c1[t4];
  120212. ch[t4]=c1[t3]+c1[t4];
  120213. t3+=ido;
  120214. t4+=ido;
  120215. }
  120216. }
  120217. if(ido==1)goto L132;
  120218. if(nbd<l1)goto L128;
  120219. t1=0;
  120220. t2=ipp2*t0;
  120221. for(j=1;j<ipph;j++){
  120222. t1+=t0;
  120223. t2-=t0;
  120224. t3=t1;
  120225. t4=t2;
  120226. for(k=0;k<l1;k++){
  120227. t5=t3;
  120228. t6=t4;
  120229. for(i=2;i<ido;i+=2){
  120230. t5+=2;
  120231. t6+=2;
  120232. ch[t5-1]=c1[t5-1]-c1[t6];
  120233. ch[t6-1]=c1[t5-1]+c1[t6];
  120234. ch[t5]=c1[t5]+c1[t6-1];
  120235. ch[t6]=c1[t5]-c1[t6-1];
  120236. }
  120237. t3+=ido;
  120238. t4+=ido;
  120239. }
  120240. }
  120241. goto L132;
  120242. L128:
  120243. t1=0;
  120244. t2=ipp2*t0;
  120245. for(j=1;j<ipph;j++){
  120246. t1+=t0;
  120247. t2-=t0;
  120248. t3=t1;
  120249. t4=t2;
  120250. for(i=2;i<ido;i+=2){
  120251. t3+=2;
  120252. t4+=2;
  120253. t5=t3;
  120254. t6=t4;
  120255. for(k=0;k<l1;k++){
  120256. ch[t5-1]=c1[t5-1]-c1[t6];
  120257. ch[t6-1]=c1[t5-1]+c1[t6];
  120258. ch[t5]=c1[t5]+c1[t6-1];
  120259. ch[t6]=c1[t5]-c1[t6-1];
  120260. t5+=ido;
  120261. t6+=ido;
  120262. }
  120263. }
  120264. }
  120265. L132:
  120266. if(ido==1)return;
  120267. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120268. t1=0;
  120269. for(j=1;j<ip;j++){
  120270. t2=(t1+=t0);
  120271. for(k=0;k<l1;k++){
  120272. c1[t2]=ch[t2];
  120273. t2+=ido;
  120274. }
  120275. }
  120276. if(nbd>l1)goto L139;
  120277. is= -ido-1;
  120278. t1=0;
  120279. for(j=1;j<ip;j++){
  120280. is+=ido;
  120281. t1+=t0;
  120282. idij=is;
  120283. t2=t1;
  120284. for(i=2;i<ido;i+=2){
  120285. t2+=2;
  120286. idij+=2;
  120287. t3=t2;
  120288. for(k=0;k<l1;k++){
  120289. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120290. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120291. t3+=ido;
  120292. }
  120293. }
  120294. }
  120295. return;
  120296. L139:
  120297. is= -ido-1;
  120298. t1=0;
  120299. for(j=1;j<ip;j++){
  120300. is+=ido;
  120301. t1+=t0;
  120302. t2=t1;
  120303. for(k=0;k<l1;k++){
  120304. idij=is;
  120305. t3=t2;
  120306. for(i=2;i<ido;i+=2){
  120307. idij+=2;
  120308. t3+=2;
  120309. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120310. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120311. }
  120312. t2+=ido;
  120313. }
  120314. }
  120315. }
  120316. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120317. int i,k1,l1,l2;
  120318. int na;
  120319. int nf,ip,iw,ix2,ix3,ido,idl1;
  120320. nf=ifac[1];
  120321. na=0;
  120322. l1=1;
  120323. iw=1;
  120324. for(k1=0;k1<nf;k1++){
  120325. ip=ifac[k1 + 2];
  120326. l2=ip*l1;
  120327. ido=n/l2;
  120328. idl1=ido*l1;
  120329. if(ip!=4)goto L103;
  120330. ix2=iw+ido;
  120331. ix3=ix2+ido;
  120332. if(na!=0)
  120333. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120334. else
  120335. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120336. na=1-na;
  120337. goto L115;
  120338. L103:
  120339. if(ip!=2)goto L106;
  120340. if(na!=0)
  120341. dradb2(ido,l1,ch,c,wa+iw-1);
  120342. else
  120343. dradb2(ido,l1,c,ch,wa+iw-1);
  120344. na=1-na;
  120345. goto L115;
  120346. L106:
  120347. if(ip!=3)goto L109;
  120348. ix2=iw+ido;
  120349. if(na!=0)
  120350. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120351. else
  120352. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120353. na=1-na;
  120354. goto L115;
  120355. L109:
  120356. /* The radix five case can be translated later..... */
  120357. /* if(ip!=5)goto L112;
  120358. ix2=iw+ido;
  120359. ix3=ix2+ido;
  120360. ix4=ix3+ido;
  120361. if(na!=0)
  120362. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120363. else
  120364. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120365. na=1-na;
  120366. goto L115;
  120367. L112:*/
  120368. if(na!=0)
  120369. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120370. else
  120371. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120372. if(ido==1)na=1-na;
  120373. L115:
  120374. l1=l2;
  120375. iw+=(ip-1)*ido;
  120376. }
  120377. if(na==0)return;
  120378. for(i=0;i<n;i++)c[i]=ch[i];
  120379. }
  120380. void drft_forward(drft_lookup *l,float *data){
  120381. if(l->n==1)return;
  120382. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120383. }
  120384. void drft_backward(drft_lookup *l,float *data){
  120385. if (l->n==1)return;
  120386. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120387. }
  120388. void drft_init(drft_lookup *l,int n){
  120389. l->n=n;
  120390. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120391. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120392. fdrffti(n, l->trigcache, l->splitcache);
  120393. }
  120394. void drft_clear(drft_lookup *l){
  120395. if(l){
  120396. if(l->trigcache)_ogg_free(l->trigcache);
  120397. if(l->splitcache)_ogg_free(l->splitcache);
  120398. memset(l,0,sizeof(*l));
  120399. }
  120400. }
  120401. #endif
  120402. /*** End of inlined file: smallft.c ***/
  120403. /*** Start of inlined file: synthesis.c ***/
  120404. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120405. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120406. // tasks..
  120407. #if JUCE_MSVC
  120408. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120409. #endif
  120410. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120411. #if JUCE_USE_OGGVORBIS
  120412. #include <stdio.h>
  120413. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120414. vorbis_dsp_state *vd=vb->vd;
  120415. private_state *b=(private_state*)vd->backend_state;
  120416. vorbis_info *vi=vd->vi;
  120417. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120418. oggpack_buffer *opb=&vb->opb;
  120419. int type,mode,i;
  120420. /* first things first. Make sure decode is ready */
  120421. _vorbis_block_ripcord(vb);
  120422. oggpack_readinit(opb,op->packet,op->bytes);
  120423. /* Check the packet type */
  120424. if(oggpack_read(opb,1)!=0){
  120425. /* Oops. This is not an audio data packet */
  120426. return(OV_ENOTAUDIO);
  120427. }
  120428. /* read our mode and pre/post windowsize */
  120429. mode=oggpack_read(opb,b->modebits);
  120430. if(mode==-1)return(OV_EBADPACKET);
  120431. vb->mode=mode;
  120432. vb->W=ci->mode_param[mode]->blockflag;
  120433. if(vb->W){
  120434. /* this doesn;t get mapped through mode selection as it's used
  120435. only for window selection */
  120436. vb->lW=oggpack_read(opb,1);
  120437. vb->nW=oggpack_read(opb,1);
  120438. if(vb->nW==-1) return(OV_EBADPACKET);
  120439. }else{
  120440. vb->lW=0;
  120441. vb->nW=0;
  120442. }
  120443. /* more setup */
  120444. vb->granulepos=op->granulepos;
  120445. vb->sequence=op->packetno;
  120446. vb->eofflag=op->e_o_s;
  120447. /* alloc pcm passback storage */
  120448. vb->pcmend=ci->blocksizes[vb->W];
  120449. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120450. for(i=0;i<vi->channels;i++)
  120451. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120452. /* unpack_header enforces range checking */
  120453. type=ci->map_type[ci->mode_param[mode]->mapping];
  120454. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120455. mapping]));
  120456. }
  120457. /* used to track pcm position without actually performing decode.
  120458. Useful for sequential 'fast forward' */
  120459. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120460. vorbis_dsp_state *vd=vb->vd;
  120461. private_state *b=(private_state*)vd->backend_state;
  120462. vorbis_info *vi=vd->vi;
  120463. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120464. oggpack_buffer *opb=&vb->opb;
  120465. int mode;
  120466. /* first things first. Make sure decode is ready */
  120467. _vorbis_block_ripcord(vb);
  120468. oggpack_readinit(opb,op->packet,op->bytes);
  120469. /* Check the packet type */
  120470. if(oggpack_read(opb,1)!=0){
  120471. /* Oops. This is not an audio data packet */
  120472. return(OV_ENOTAUDIO);
  120473. }
  120474. /* read our mode and pre/post windowsize */
  120475. mode=oggpack_read(opb,b->modebits);
  120476. if(mode==-1)return(OV_EBADPACKET);
  120477. vb->mode=mode;
  120478. vb->W=ci->mode_param[mode]->blockflag;
  120479. if(vb->W){
  120480. vb->lW=oggpack_read(opb,1);
  120481. vb->nW=oggpack_read(opb,1);
  120482. if(vb->nW==-1) return(OV_EBADPACKET);
  120483. }else{
  120484. vb->lW=0;
  120485. vb->nW=0;
  120486. }
  120487. /* more setup */
  120488. vb->granulepos=op->granulepos;
  120489. vb->sequence=op->packetno;
  120490. vb->eofflag=op->e_o_s;
  120491. /* no pcm */
  120492. vb->pcmend=0;
  120493. vb->pcm=NULL;
  120494. return(0);
  120495. }
  120496. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120497. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120498. oggpack_buffer opb;
  120499. int mode;
  120500. oggpack_readinit(&opb,op->packet,op->bytes);
  120501. /* Check the packet type */
  120502. if(oggpack_read(&opb,1)!=0){
  120503. /* Oops. This is not an audio data packet */
  120504. return(OV_ENOTAUDIO);
  120505. }
  120506. {
  120507. int modebits=0;
  120508. int v=ci->modes;
  120509. while(v>1){
  120510. modebits++;
  120511. v>>=1;
  120512. }
  120513. /* read our mode and pre/post windowsize */
  120514. mode=oggpack_read(&opb,modebits);
  120515. }
  120516. if(mode==-1)return(OV_EBADPACKET);
  120517. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120518. }
  120519. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120520. /* set / clear half-sample-rate mode */
  120521. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120522. /* right now, our MDCT can't handle < 64 sample windows. */
  120523. if(ci->blocksizes[0]<=64 && flag)return -1;
  120524. ci->halfrate_flag=(flag?1:0);
  120525. return 0;
  120526. }
  120527. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120528. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120529. return ci->halfrate_flag;
  120530. }
  120531. #endif
  120532. /*** End of inlined file: synthesis.c ***/
  120533. /*** Start of inlined file: vorbisenc.c ***/
  120534. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120535. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120536. // tasks..
  120537. #if JUCE_MSVC
  120538. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120539. #endif
  120540. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120541. #if JUCE_USE_OGGVORBIS
  120542. #include <stdlib.h>
  120543. #include <string.h>
  120544. #include <math.h>
  120545. /* careful with this; it's using static array sizing to make managing
  120546. all the modes a little less annoying. If we use a residue backend
  120547. with > 12 partition types, or a different division of iteration,
  120548. this needs to be updated. */
  120549. typedef struct {
  120550. static_codebook *books[12][3];
  120551. } static_bookblock;
  120552. typedef struct {
  120553. int res_type;
  120554. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120555. vorbis_info_residue0 *res;
  120556. static_codebook *book_aux;
  120557. static_codebook *book_aux_managed;
  120558. static_bookblock *books_base;
  120559. static_bookblock *books_base_managed;
  120560. } vorbis_residue_template;
  120561. typedef struct {
  120562. vorbis_info_mapping0 *map;
  120563. vorbis_residue_template *res;
  120564. } vorbis_mapping_template;
  120565. typedef struct vp_adjblock{
  120566. int block[P_BANDS];
  120567. } vp_adjblock;
  120568. typedef struct {
  120569. int data[NOISE_COMPAND_LEVELS];
  120570. } compandblock;
  120571. /* high level configuration information for setting things up
  120572. step-by-step with the detailed vorbis_encode_ctl interface.
  120573. There's a fair amount of redundancy such that interactive setup
  120574. does not directly deal with any vorbis_info or codec_setup_info
  120575. initialization; it's all stored (until full init) in this highlevel
  120576. setup, then flushed out to the real codec setup structs later. */
  120577. typedef struct {
  120578. int att[P_NOISECURVES];
  120579. float boost;
  120580. float decay;
  120581. } att3;
  120582. typedef struct { int data[P_NOISECURVES]; } adj3;
  120583. typedef struct {
  120584. int pre[PACKETBLOBS];
  120585. int post[PACKETBLOBS];
  120586. float kHz[PACKETBLOBS];
  120587. float lowpasskHz[PACKETBLOBS];
  120588. } adj_stereo;
  120589. typedef struct {
  120590. int lo;
  120591. int hi;
  120592. int fixed;
  120593. } noiseguard;
  120594. typedef struct {
  120595. int data[P_NOISECURVES][17];
  120596. } noise3;
  120597. typedef struct {
  120598. int mappings;
  120599. double *rate_mapping;
  120600. double *quality_mapping;
  120601. int coupling_restriction;
  120602. long samplerate_min_restriction;
  120603. long samplerate_max_restriction;
  120604. int *blocksize_short;
  120605. int *blocksize_long;
  120606. att3 *psy_tone_masteratt;
  120607. int *psy_tone_0dB;
  120608. int *psy_tone_dBsuppress;
  120609. vp_adjblock *psy_tone_adj_impulse;
  120610. vp_adjblock *psy_tone_adj_long;
  120611. vp_adjblock *psy_tone_adj_other;
  120612. noiseguard *psy_noiseguards;
  120613. noise3 *psy_noise_bias_impulse;
  120614. noise3 *psy_noise_bias_padding;
  120615. noise3 *psy_noise_bias_trans;
  120616. noise3 *psy_noise_bias_long;
  120617. int *psy_noise_dBsuppress;
  120618. compandblock *psy_noise_compand;
  120619. double *psy_noise_compand_short_mapping;
  120620. double *psy_noise_compand_long_mapping;
  120621. int *psy_noise_normal_start[2];
  120622. int *psy_noise_normal_partition[2];
  120623. double *psy_noise_normal_thresh;
  120624. int *psy_ath_float;
  120625. int *psy_ath_abs;
  120626. double *psy_lowpass;
  120627. vorbis_info_psy_global *global_params;
  120628. double *global_mapping;
  120629. adj_stereo *stereo_modes;
  120630. static_codebook ***floor_books;
  120631. vorbis_info_floor1 *floor_params;
  120632. int *floor_short_mapping;
  120633. int *floor_long_mapping;
  120634. vorbis_mapping_template *maps;
  120635. } ve_setup_data_template;
  120636. /* a few static coder conventions */
  120637. static vorbis_info_mode _mode_template[2]={
  120638. {0,0,0,0},
  120639. {1,0,0,1}
  120640. };
  120641. static vorbis_info_mapping0 _map_nominal[2]={
  120642. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120643. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120644. };
  120645. /*** Start of inlined file: setup_44.h ***/
  120646. /*** Start of inlined file: floor_all.h ***/
  120647. /*** Start of inlined file: floor_books.h ***/
  120648. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120649. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120650. };
  120651. static static_codebook _huff_book_line_256x7_0sub1 = {
  120652. 1, 9,
  120653. _huff_lengthlist_line_256x7_0sub1,
  120654. 0, 0, 0, 0, 0,
  120655. NULL,
  120656. NULL,
  120657. NULL,
  120658. NULL,
  120659. 0
  120660. };
  120661. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120663. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120664. };
  120665. static static_codebook _huff_book_line_256x7_0sub2 = {
  120666. 1, 25,
  120667. _huff_lengthlist_line_256x7_0sub2,
  120668. 0, 0, 0, 0, 0,
  120669. NULL,
  120670. NULL,
  120671. NULL,
  120672. NULL,
  120673. 0
  120674. };
  120675. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120678. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120679. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120680. };
  120681. static static_codebook _huff_book_line_256x7_0sub3 = {
  120682. 1, 64,
  120683. _huff_lengthlist_line_256x7_0sub3,
  120684. 0, 0, 0, 0, 0,
  120685. NULL,
  120686. NULL,
  120687. NULL,
  120688. NULL,
  120689. 0
  120690. };
  120691. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120692. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120693. };
  120694. static static_codebook _huff_book_line_256x7_1sub1 = {
  120695. 1, 9,
  120696. _huff_lengthlist_line_256x7_1sub1,
  120697. 0, 0, 0, 0, 0,
  120698. NULL,
  120699. NULL,
  120700. NULL,
  120701. NULL,
  120702. 0
  120703. };
  120704. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120706. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120707. };
  120708. static static_codebook _huff_book_line_256x7_1sub2 = {
  120709. 1, 25,
  120710. _huff_lengthlist_line_256x7_1sub2,
  120711. 0, 0, 0, 0, 0,
  120712. NULL,
  120713. NULL,
  120714. NULL,
  120715. NULL,
  120716. 0
  120717. };
  120718. static long _huff_lengthlist_line_256x7_1sub3[] = {
  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, 3, 2, 4, 3, 6, 3, 7,
  120721. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120722. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120723. };
  120724. static static_codebook _huff_book_line_256x7_1sub3 = {
  120725. 1, 64,
  120726. _huff_lengthlist_line_256x7_1sub3,
  120727. 0, 0, 0, 0, 0,
  120728. NULL,
  120729. NULL,
  120730. NULL,
  120731. NULL,
  120732. 0
  120733. };
  120734. static long _huff_lengthlist_line_256x7_class0[] = {
  120735. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120736. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120737. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120738. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120739. };
  120740. static static_codebook _huff_book_line_256x7_class0 = {
  120741. 1, 64,
  120742. _huff_lengthlist_line_256x7_class0,
  120743. 0, 0, 0, 0, 0,
  120744. NULL,
  120745. NULL,
  120746. NULL,
  120747. NULL,
  120748. 0
  120749. };
  120750. static long _huff_lengthlist_line_256x7_class1[] = {
  120751. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120752. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120753. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120754. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120755. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120756. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120757. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120758. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120759. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120760. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120761. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120762. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120763. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120764. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120765. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120766. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120767. };
  120768. static static_codebook _huff_book_line_256x7_class1 = {
  120769. 1, 256,
  120770. _huff_lengthlist_line_256x7_class1,
  120771. 0, 0, 0, 0, 0,
  120772. NULL,
  120773. NULL,
  120774. NULL,
  120775. NULL,
  120776. 0
  120777. };
  120778. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120779. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120780. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120781. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120782. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120783. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120784. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120785. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120786. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120787. };
  120788. static static_codebook _huff_book_line_512x17_0sub0 = {
  120789. 1, 128,
  120790. _huff_lengthlist_line_512x17_0sub0,
  120791. 0, 0, 0, 0, 0,
  120792. NULL,
  120793. NULL,
  120794. NULL,
  120795. NULL,
  120796. 0
  120797. };
  120798. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120799. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120800. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120801. };
  120802. static static_codebook _huff_book_line_512x17_1sub0 = {
  120803. 1, 32,
  120804. _huff_lengthlist_line_512x17_1sub0,
  120805. 0, 0, 0, 0, 0,
  120806. NULL,
  120807. NULL,
  120808. NULL,
  120809. NULL,
  120810. 0
  120811. };
  120812. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120815. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120816. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120817. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120818. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120819. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120820. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120821. };
  120822. static static_codebook _huff_book_line_512x17_1sub1 = {
  120823. 1, 128,
  120824. _huff_lengthlist_line_512x17_1sub1,
  120825. 0, 0, 0, 0, 0,
  120826. NULL,
  120827. NULL,
  120828. NULL,
  120829. NULL,
  120830. 0
  120831. };
  120832. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120833. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120834. 5, 3,
  120835. };
  120836. static static_codebook _huff_book_line_512x17_2sub1 = {
  120837. 1, 18,
  120838. _huff_lengthlist_line_512x17_2sub1,
  120839. 0, 0, 0, 0, 0,
  120840. NULL,
  120841. NULL,
  120842. NULL,
  120843. NULL,
  120844. 0
  120845. };
  120846. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120848. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120849. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120850. 9, 8,
  120851. };
  120852. static static_codebook _huff_book_line_512x17_2sub2 = {
  120853. 1, 50,
  120854. _huff_lengthlist_line_512x17_2sub2,
  120855. 0, 0, 0, 0, 0,
  120856. NULL,
  120857. NULL,
  120858. NULL,
  120859. NULL,
  120860. 0
  120861. };
  120862. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120866. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120867. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120868. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120869. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120871. };
  120872. static static_codebook _huff_book_line_512x17_2sub3 = {
  120873. 1, 128,
  120874. _huff_lengthlist_line_512x17_2sub3,
  120875. 0, 0, 0, 0, 0,
  120876. NULL,
  120877. NULL,
  120878. NULL,
  120879. NULL,
  120880. 0
  120881. };
  120882. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120883. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120884. 5, 5,
  120885. };
  120886. static static_codebook _huff_book_line_512x17_3sub1 = {
  120887. 1, 18,
  120888. _huff_lengthlist_line_512x17_3sub1,
  120889. 0, 0, 0, 0, 0,
  120890. NULL,
  120891. NULL,
  120892. NULL,
  120893. NULL,
  120894. 0
  120895. };
  120896. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120898. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120899. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120900. 11,14,
  120901. };
  120902. static static_codebook _huff_book_line_512x17_3sub2 = {
  120903. 1, 50,
  120904. _huff_lengthlist_line_512x17_3sub2,
  120905. 0, 0, 0, 0, 0,
  120906. NULL,
  120907. NULL,
  120908. NULL,
  120909. NULL,
  120910. 0
  120911. };
  120912. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120916. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120917. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120918. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120919. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120920. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120921. };
  120922. static static_codebook _huff_book_line_512x17_3sub3 = {
  120923. 1, 128,
  120924. _huff_lengthlist_line_512x17_3sub3,
  120925. 0, 0, 0, 0, 0,
  120926. NULL,
  120927. NULL,
  120928. NULL,
  120929. NULL,
  120930. 0
  120931. };
  120932. static long _huff_lengthlist_line_512x17_class1[] = {
  120933. 1, 2, 3, 6, 5, 4, 7, 7,
  120934. };
  120935. static static_codebook _huff_book_line_512x17_class1 = {
  120936. 1, 8,
  120937. _huff_lengthlist_line_512x17_class1,
  120938. 0, 0, 0, 0, 0,
  120939. NULL,
  120940. NULL,
  120941. NULL,
  120942. NULL,
  120943. 0
  120944. };
  120945. static long _huff_lengthlist_line_512x17_class2[] = {
  120946. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120947. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120948. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120949. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120950. };
  120951. static static_codebook _huff_book_line_512x17_class2 = {
  120952. 1, 64,
  120953. _huff_lengthlist_line_512x17_class2,
  120954. 0, 0, 0, 0, 0,
  120955. NULL,
  120956. NULL,
  120957. NULL,
  120958. NULL,
  120959. 0
  120960. };
  120961. static long _huff_lengthlist_line_512x17_class3[] = {
  120962. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120963. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120964. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120965. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120966. };
  120967. static static_codebook _huff_book_line_512x17_class3 = {
  120968. 1, 64,
  120969. _huff_lengthlist_line_512x17_class3,
  120970. 0, 0, 0, 0, 0,
  120971. NULL,
  120972. NULL,
  120973. NULL,
  120974. NULL,
  120975. 0
  120976. };
  120977. static long _huff_lengthlist_line_128x4_class0[] = {
  120978. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120979. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120980. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120981. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120982. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120983. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120984. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120985. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120986. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120987. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120988. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120989. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120990. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120991. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120992. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120993. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120994. };
  120995. static static_codebook _huff_book_line_128x4_class0 = {
  120996. 1, 256,
  120997. _huff_lengthlist_line_128x4_class0,
  120998. 0, 0, 0, 0, 0,
  120999. NULL,
  121000. NULL,
  121001. NULL,
  121002. NULL,
  121003. 0
  121004. };
  121005. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121006. 2, 2, 2, 2,
  121007. };
  121008. static static_codebook _huff_book_line_128x4_0sub0 = {
  121009. 1, 4,
  121010. _huff_lengthlist_line_128x4_0sub0,
  121011. 0, 0, 0, 0, 0,
  121012. NULL,
  121013. NULL,
  121014. NULL,
  121015. NULL,
  121016. 0
  121017. };
  121018. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121019. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121020. };
  121021. static static_codebook _huff_book_line_128x4_0sub1 = {
  121022. 1, 10,
  121023. _huff_lengthlist_line_128x4_0sub1,
  121024. 0, 0, 0, 0, 0,
  121025. NULL,
  121026. NULL,
  121027. NULL,
  121028. NULL,
  121029. 0
  121030. };
  121031. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121033. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121034. };
  121035. static static_codebook _huff_book_line_128x4_0sub2 = {
  121036. 1, 25,
  121037. _huff_lengthlist_line_128x4_0sub2,
  121038. 0, 0, 0, 0, 0,
  121039. NULL,
  121040. NULL,
  121041. NULL,
  121042. NULL,
  121043. 0
  121044. };
  121045. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121048. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121049. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121050. };
  121051. static static_codebook _huff_book_line_128x4_0sub3 = {
  121052. 1, 64,
  121053. _huff_lengthlist_line_128x4_0sub3,
  121054. 0, 0, 0, 0, 0,
  121055. NULL,
  121056. NULL,
  121057. NULL,
  121058. NULL,
  121059. 0
  121060. };
  121061. static long _huff_lengthlist_line_256x4_class0[] = {
  121062. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121063. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121064. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121065. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121066. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121067. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121068. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121069. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121070. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121071. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121072. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121073. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121074. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121075. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121076. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121077. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121078. };
  121079. static static_codebook _huff_book_line_256x4_class0 = {
  121080. 1, 256,
  121081. _huff_lengthlist_line_256x4_class0,
  121082. 0, 0, 0, 0, 0,
  121083. NULL,
  121084. NULL,
  121085. NULL,
  121086. NULL,
  121087. 0
  121088. };
  121089. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121090. 2, 2, 2, 2,
  121091. };
  121092. static static_codebook _huff_book_line_256x4_0sub0 = {
  121093. 1, 4,
  121094. _huff_lengthlist_line_256x4_0sub0,
  121095. 0, 0, 0, 0, 0,
  121096. NULL,
  121097. NULL,
  121098. NULL,
  121099. NULL,
  121100. 0
  121101. };
  121102. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121103. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121104. };
  121105. static static_codebook _huff_book_line_256x4_0sub1 = {
  121106. 1, 10,
  121107. _huff_lengthlist_line_256x4_0sub1,
  121108. 0, 0, 0, 0, 0,
  121109. NULL,
  121110. NULL,
  121111. NULL,
  121112. NULL,
  121113. 0
  121114. };
  121115. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121117. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121118. };
  121119. static static_codebook _huff_book_line_256x4_0sub2 = {
  121120. 1, 25,
  121121. _huff_lengthlist_line_256x4_0sub2,
  121122. 0, 0, 0, 0, 0,
  121123. NULL,
  121124. NULL,
  121125. NULL,
  121126. NULL,
  121127. 0
  121128. };
  121129. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121132. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121133. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121134. };
  121135. static static_codebook _huff_book_line_256x4_0sub3 = {
  121136. 1, 64,
  121137. _huff_lengthlist_line_256x4_0sub3,
  121138. 0, 0, 0, 0, 0,
  121139. NULL,
  121140. NULL,
  121141. NULL,
  121142. NULL,
  121143. 0
  121144. };
  121145. static long _huff_lengthlist_line_128x7_class0[] = {
  121146. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121147. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121148. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121149. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121150. };
  121151. static static_codebook _huff_book_line_128x7_class0 = {
  121152. 1, 64,
  121153. _huff_lengthlist_line_128x7_class0,
  121154. 0, 0, 0, 0, 0,
  121155. NULL,
  121156. NULL,
  121157. NULL,
  121158. NULL,
  121159. 0
  121160. };
  121161. static long _huff_lengthlist_line_128x7_class1[] = {
  121162. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121163. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121164. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121165. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121166. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121167. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121168. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121169. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121170. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121171. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121172. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121173. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121174. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121175. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121176. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121177. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121178. };
  121179. static static_codebook _huff_book_line_128x7_class1 = {
  121180. 1, 256,
  121181. _huff_lengthlist_line_128x7_class1,
  121182. 0, 0, 0, 0, 0,
  121183. NULL,
  121184. NULL,
  121185. NULL,
  121186. NULL,
  121187. 0
  121188. };
  121189. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121190. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121191. };
  121192. static static_codebook _huff_book_line_128x7_0sub1 = {
  121193. 1, 9,
  121194. _huff_lengthlist_line_128x7_0sub1,
  121195. 0, 0, 0, 0, 0,
  121196. NULL,
  121197. NULL,
  121198. NULL,
  121199. NULL,
  121200. 0
  121201. };
  121202. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121204. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121205. };
  121206. static static_codebook _huff_book_line_128x7_0sub2 = {
  121207. 1, 25,
  121208. _huff_lengthlist_line_128x7_0sub2,
  121209. 0, 0, 0, 0, 0,
  121210. NULL,
  121211. NULL,
  121212. NULL,
  121213. NULL,
  121214. 0
  121215. };
  121216. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121219. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121220. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121221. };
  121222. static static_codebook _huff_book_line_128x7_0sub3 = {
  121223. 1, 64,
  121224. _huff_lengthlist_line_128x7_0sub3,
  121225. 0, 0, 0, 0, 0,
  121226. NULL,
  121227. NULL,
  121228. NULL,
  121229. NULL,
  121230. 0
  121231. };
  121232. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121233. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121234. };
  121235. static static_codebook _huff_book_line_128x7_1sub1 = {
  121236. 1, 9,
  121237. _huff_lengthlist_line_128x7_1sub1,
  121238. 0, 0, 0, 0, 0,
  121239. NULL,
  121240. NULL,
  121241. NULL,
  121242. NULL,
  121243. 0
  121244. };
  121245. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121247. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121248. };
  121249. static static_codebook _huff_book_line_128x7_1sub2 = {
  121250. 1, 25,
  121251. _huff_lengthlist_line_128x7_1sub2,
  121252. 0, 0, 0, 0, 0,
  121253. NULL,
  121254. NULL,
  121255. NULL,
  121256. NULL,
  121257. 0
  121258. };
  121259. static long _huff_lengthlist_line_128x7_1sub3[] = {
  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, 1, 7, 2, 7, 3, 8, 4,
  121262. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121263. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121264. };
  121265. static static_codebook _huff_book_line_128x7_1sub3 = {
  121266. 1, 64,
  121267. _huff_lengthlist_line_128x7_1sub3,
  121268. 0, 0, 0, 0, 0,
  121269. NULL,
  121270. NULL,
  121271. NULL,
  121272. NULL,
  121273. 0
  121274. };
  121275. static long _huff_lengthlist_line_128x11_class1[] = {
  121276. 1, 6, 3, 7, 2, 4, 5, 7,
  121277. };
  121278. static static_codebook _huff_book_line_128x11_class1 = {
  121279. 1, 8,
  121280. _huff_lengthlist_line_128x11_class1,
  121281. 0, 0, 0, 0, 0,
  121282. NULL,
  121283. NULL,
  121284. NULL,
  121285. NULL,
  121286. 0
  121287. };
  121288. static long _huff_lengthlist_line_128x11_class2[] = {
  121289. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121290. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121291. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121292. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121293. };
  121294. static static_codebook _huff_book_line_128x11_class2 = {
  121295. 1, 64,
  121296. _huff_lengthlist_line_128x11_class2,
  121297. 0, 0, 0, 0, 0,
  121298. NULL,
  121299. NULL,
  121300. NULL,
  121301. NULL,
  121302. 0
  121303. };
  121304. static long _huff_lengthlist_line_128x11_class3[] = {
  121305. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121306. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121307. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121308. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121309. };
  121310. static static_codebook _huff_book_line_128x11_class3 = {
  121311. 1, 64,
  121312. _huff_lengthlist_line_128x11_class3,
  121313. 0, 0, 0, 0, 0,
  121314. NULL,
  121315. NULL,
  121316. NULL,
  121317. NULL,
  121318. 0
  121319. };
  121320. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121321. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121322. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121323. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121324. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121325. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121326. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121327. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121328. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121329. };
  121330. static static_codebook _huff_book_line_128x11_0sub0 = {
  121331. 1, 128,
  121332. _huff_lengthlist_line_128x11_0sub0,
  121333. 0, 0, 0, 0, 0,
  121334. NULL,
  121335. NULL,
  121336. NULL,
  121337. NULL,
  121338. 0
  121339. };
  121340. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121341. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121342. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121343. };
  121344. static static_codebook _huff_book_line_128x11_1sub0 = {
  121345. 1, 32,
  121346. _huff_lengthlist_line_128x11_1sub0,
  121347. 0, 0, 0, 0, 0,
  121348. NULL,
  121349. NULL,
  121350. NULL,
  121351. NULL,
  121352. 0
  121353. };
  121354. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121357. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121358. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121359. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121360. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121361. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121362. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121363. };
  121364. static static_codebook _huff_book_line_128x11_1sub1 = {
  121365. 1, 128,
  121366. _huff_lengthlist_line_128x11_1sub1,
  121367. 0, 0, 0, 0, 0,
  121368. NULL,
  121369. NULL,
  121370. NULL,
  121371. NULL,
  121372. 0
  121373. };
  121374. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121375. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121376. 5, 5,
  121377. };
  121378. static static_codebook _huff_book_line_128x11_2sub1 = {
  121379. 1, 18,
  121380. _huff_lengthlist_line_128x11_2sub1,
  121381. 0, 0, 0, 0, 0,
  121382. NULL,
  121383. NULL,
  121384. NULL,
  121385. NULL,
  121386. 0
  121387. };
  121388. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121390. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121391. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121392. 8,11,
  121393. };
  121394. static static_codebook _huff_book_line_128x11_2sub2 = {
  121395. 1, 50,
  121396. _huff_lengthlist_line_128x11_2sub2,
  121397. 0, 0, 0, 0, 0,
  121398. NULL,
  121399. NULL,
  121400. NULL,
  121401. NULL,
  121402. 0
  121403. };
  121404. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121408. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121409. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121410. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121411. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121412. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121413. };
  121414. static static_codebook _huff_book_line_128x11_2sub3 = {
  121415. 1, 128,
  121416. _huff_lengthlist_line_128x11_2sub3,
  121417. 0, 0, 0, 0, 0,
  121418. NULL,
  121419. NULL,
  121420. NULL,
  121421. NULL,
  121422. 0
  121423. };
  121424. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121425. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121426. 5, 4,
  121427. };
  121428. static static_codebook _huff_book_line_128x11_3sub1 = {
  121429. 1, 18,
  121430. _huff_lengthlist_line_128x11_3sub1,
  121431. 0, 0, 0, 0, 0,
  121432. NULL,
  121433. NULL,
  121434. NULL,
  121435. NULL,
  121436. 0
  121437. };
  121438. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121440. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121441. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121442. 12, 6,
  121443. };
  121444. static static_codebook _huff_book_line_128x11_3sub2 = {
  121445. 1, 50,
  121446. _huff_lengthlist_line_128x11_3sub2,
  121447. 0, 0, 0, 0, 0,
  121448. NULL,
  121449. NULL,
  121450. NULL,
  121451. NULL,
  121452. 0
  121453. };
  121454. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121458. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121459. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121460. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121461. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121462. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121463. };
  121464. static static_codebook _huff_book_line_128x11_3sub3 = {
  121465. 1, 128,
  121466. _huff_lengthlist_line_128x11_3sub3,
  121467. 0, 0, 0, 0, 0,
  121468. NULL,
  121469. NULL,
  121470. NULL,
  121471. NULL,
  121472. 0
  121473. };
  121474. static long _huff_lengthlist_line_128x17_class1[] = {
  121475. 1, 3, 4, 7, 2, 5, 6, 7,
  121476. };
  121477. static static_codebook _huff_book_line_128x17_class1 = {
  121478. 1, 8,
  121479. _huff_lengthlist_line_128x17_class1,
  121480. 0, 0, 0, 0, 0,
  121481. NULL,
  121482. NULL,
  121483. NULL,
  121484. NULL,
  121485. 0
  121486. };
  121487. static long _huff_lengthlist_line_128x17_class2[] = {
  121488. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121489. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121490. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121491. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121492. };
  121493. static static_codebook _huff_book_line_128x17_class2 = {
  121494. 1, 64,
  121495. _huff_lengthlist_line_128x17_class2,
  121496. 0, 0, 0, 0, 0,
  121497. NULL,
  121498. NULL,
  121499. NULL,
  121500. NULL,
  121501. 0
  121502. };
  121503. static long _huff_lengthlist_line_128x17_class3[] = {
  121504. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121505. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121506. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121507. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121508. };
  121509. static static_codebook _huff_book_line_128x17_class3 = {
  121510. 1, 64,
  121511. _huff_lengthlist_line_128x17_class3,
  121512. 0, 0, 0, 0, 0,
  121513. NULL,
  121514. NULL,
  121515. NULL,
  121516. NULL,
  121517. 0
  121518. };
  121519. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121520. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121521. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121522. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121523. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121524. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121525. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121526. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121527. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121528. };
  121529. static static_codebook _huff_book_line_128x17_0sub0 = {
  121530. 1, 128,
  121531. _huff_lengthlist_line_128x17_0sub0,
  121532. 0, 0, 0, 0, 0,
  121533. NULL,
  121534. NULL,
  121535. NULL,
  121536. NULL,
  121537. 0
  121538. };
  121539. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121540. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121541. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121542. };
  121543. static static_codebook _huff_book_line_128x17_1sub0 = {
  121544. 1, 32,
  121545. _huff_lengthlist_line_128x17_1sub0,
  121546. 0, 0, 0, 0, 0,
  121547. NULL,
  121548. NULL,
  121549. NULL,
  121550. NULL,
  121551. 0
  121552. };
  121553. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121556. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121557. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121558. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121559. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121560. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121561. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121562. };
  121563. static static_codebook _huff_book_line_128x17_1sub1 = {
  121564. 1, 128,
  121565. _huff_lengthlist_line_128x17_1sub1,
  121566. 0, 0, 0, 0, 0,
  121567. NULL,
  121568. NULL,
  121569. NULL,
  121570. NULL,
  121571. 0
  121572. };
  121573. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121574. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121575. 9, 4,
  121576. };
  121577. static static_codebook _huff_book_line_128x17_2sub1 = {
  121578. 1, 18,
  121579. _huff_lengthlist_line_128x17_2sub1,
  121580. 0, 0, 0, 0, 0,
  121581. NULL,
  121582. NULL,
  121583. NULL,
  121584. NULL,
  121585. 0
  121586. };
  121587. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121589. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121590. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121591. 13,13,
  121592. };
  121593. static static_codebook _huff_book_line_128x17_2sub2 = {
  121594. 1, 50,
  121595. _huff_lengthlist_line_128x17_2sub2,
  121596. 0, 0, 0, 0, 0,
  121597. NULL,
  121598. NULL,
  121599. NULL,
  121600. NULL,
  121601. 0
  121602. };
  121603. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121607. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121608. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121609. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121610. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121611. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121612. };
  121613. static static_codebook _huff_book_line_128x17_2sub3 = {
  121614. 1, 128,
  121615. _huff_lengthlist_line_128x17_2sub3,
  121616. 0, 0, 0, 0, 0,
  121617. NULL,
  121618. NULL,
  121619. NULL,
  121620. NULL,
  121621. 0
  121622. };
  121623. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121624. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121625. 6, 4,
  121626. };
  121627. static static_codebook _huff_book_line_128x17_3sub1 = {
  121628. 1, 18,
  121629. _huff_lengthlist_line_128x17_3sub1,
  121630. 0, 0, 0, 0, 0,
  121631. NULL,
  121632. NULL,
  121633. NULL,
  121634. NULL,
  121635. 0
  121636. };
  121637. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121639. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121640. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121641. 10, 8,
  121642. };
  121643. static static_codebook _huff_book_line_128x17_3sub2 = {
  121644. 1, 50,
  121645. _huff_lengthlist_line_128x17_3sub2,
  121646. 0, 0, 0, 0, 0,
  121647. NULL,
  121648. NULL,
  121649. NULL,
  121650. NULL,
  121651. 0
  121652. };
  121653. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121657. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121658. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121659. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121660. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121661. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121662. };
  121663. static static_codebook _huff_book_line_128x17_3sub3 = {
  121664. 1, 128,
  121665. _huff_lengthlist_line_128x17_3sub3,
  121666. 0, 0, 0, 0, 0,
  121667. NULL,
  121668. NULL,
  121669. NULL,
  121670. NULL,
  121671. 0
  121672. };
  121673. static long _huff_lengthlist_line_1024x27_class1[] = {
  121674. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121675. };
  121676. static static_codebook _huff_book_line_1024x27_class1 = {
  121677. 1, 16,
  121678. _huff_lengthlist_line_1024x27_class1,
  121679. 0, 0, 0, 0, 0,
  121680. NULL,
  121681. NULL,
  121682. NULL,
  121683. NULL,
  121684. 0
  121685. };
  121686. static long _huff_lengthlist_line_1024x27_class2[] = {
  121687. 1, 4, 2, 6, 3, 7, 5, 7,
  121688. };
  121689. static static_codebook _huff_book_line_1024x27_class2 = {
  121690. 1, 8,
  121691. _huff_lengthlist_line_1024x27_class2,
  121692. 0, 0, 0, 0, 0,
  121693. NULL,
  121694. NULL,
  121695. NULL,
  121696. NULL,
  121697. 0
  121698. };
  121699. static long _huff_lengthlist_line_1024x27_class3[] = {
  121700. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121701. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121702. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121703. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121704. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121705. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121706. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121707. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121708. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121709. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121710. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121711. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121712. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121713. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121714. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121715. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121716. };
  121717. static static_codebook _huff_book_line_1024x27_class3 = {
  121718. 1, 256,
  121719. _huff_lengthlist_line_1024x27_class3,
  121720. 0, 0, 0, 0, 0,
  121721. NULL,
  121722. NULL,
  121723. NULL,
  121724. NULL,
  121725. 0
  121726. };
  121727. static long _huff_lengthlist_line_1024x27_class4[] = {
  121728. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121729. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121730. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121731. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121732. };
  121733. static static_codebook _huff_book_line_1024x27_class4 = {
  121734. 1, 64,
  121735. _huff_lengthlist_line_1024x27_class4,
  121736. 0, 0, 0, 0, 0,
  121737. NULL,
  121738. NULL,
  121739. NULL,
  121740. NULL,
  121741. 0
  121742. };
  121743. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121744. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121745. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121746. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121747. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121748. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121749. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121750. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121751. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121752. };
  121753. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121754. 1, 128,
  121755. _huff_lengthlist_line_1024x27_0sub0,
  121756. 0, 0, 0, 0, 0,
  121757. NULL,
  121758. NULL,
  121759. NULL,
  121760. NULL,
  121761. 0
  121762. };
  121763. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121764. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121765. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121766. };
  121767. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121768. 1, 32,
  121769. _huff_lengthlist_line_1024x27_1sub0,
  121770. 0, 0, 0, 0, 0,
  121771. NULL,
  121772. NULL,
  121773. NULL,
  121774. NULL,
  121775. 0
  121776. };
  121777. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121780. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121781. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121782. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121783. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121784. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121785. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121786. };
  121787. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121788. 1, 128,
  121789. _huff_lengthlist_line_1024x27_1sub1,
  121790. 0, 0, 0, 0, 0,
  121791. NULL,
  121792. NULL,
  121793. NULL,
  121794. NULL,
  121795. 0
  121796. };
  121797. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121798. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121799. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121800. };
  121801. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121802. 1, 32,
  121803. _huff_lengthlist_line_1024x27_2sub0,
  121804. 0, 0, 0, 0, 0,
  121805. NULL,
  121806. NULL,
  121807. NULL,
  121808. NULL,
  121809. 0
  121810. };
  121811. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121814. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121815. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121816. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121817. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121818. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121819. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121820. };
  121821. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121822. 1, 128,
  121823. _huff_lengthlist_line_1024x27_2sub1,
  121824. 0, 0, 0, 0, 0,
  121825. NULL,
  121826. NULL,
  121827. NULL,
  121828. NULL,
  121829. 0
  121830. };
  121831. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121832. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121833. 5, 5,
  121834. };
  121835. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121836. 1, 18,
  121837. _huff_lengthlist_line_1024x27_3sub1,
  121838. 0, 0, 0, 0, 0,
  121839. NULL,
  121840. NULL,
  121841. NULL,
  121842. NULL,
  121843. 0
  121844. };
  121845. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121847. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121848. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121849. 9,11,
  121850. };
  121851. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121852. 1, 50,
  121853. _huff_lengthlist_line_1024x27_3sub2,
  121854. 0, 0, 0, 0, 0,
  121855. NULL,
  121856. NULL,
  121857. NULL,
  121858. NULL,
  121859. 0
  121860. };
  121861. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121865. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121866. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121867. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121868. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121869. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121870. };
  121871. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121872. 1, 128,
  121873. _huff_lengthlist_line_1024x27_3sub3,
  121874. 0, 0, 0, 0, 0,
  121875. NULL,
  121876. NULL,
  121877. NULL,
  121878. NULL,
  121879. 0
  121880. };
  121881. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121882. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121883. 5, 4,
  121884. };
  121885. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121886. 1, 18,
  121887. _huff_lengthlist_line_1024x27_4sub1,
  121888. 0, 0, 0, 0, 0,
  121889. NULL,
  121890. NULL,
  121891. NULL,
  121892. NULL,
  121893. 0
  121894. };
  121895. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121897. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121898. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121899. 9,12,
  121900. };
  121901. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121902. 1, 50,
  121903. _huff_lengthlist_line_1024x27_4sub2,
  121904. 0, 0, 0, 0, 0,
  121905. NULL,
  121906. NULL,
  121907. NULL,
  121908. NULL,
  121909. 0
  121910. };
  121911. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121915. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121916. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121918. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121919. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121920. };
  121921. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121922. 1, 128,
  121923. _huff_lengthlist_line_1024x27_4sub3,
  121924. 0, 0, 0, 0, 0,
  121925. NULL,
  121926. NULL,
  121927. NULL,
  121928. NULL,
  121929. 0
  121930. };
  121931. static long _huff_lengthlist_line_2048x27_class1[] = {
  121932. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121933. };
  121934. static static_codebook _huff_book_line_2048x27_class1 = {
  121935. 1, 16,
  121936. _huff_lengthlist_line_2048x27_class1,
  121937. 0, 0, 0, 0, 0,
  121938. NULL,
  121939. NULL,
  121940. NULL,
  121941. NULL,
  121942. 0
  121943. };
  121944. static long _huff_lengthlist_line_2048x27_class2[] = {
  121945. 1, 2, 3, 6, 4, 7, 5, 7,
  121946. };
  121947. static static_codebook _huff_book_line_2048x27_class2 = {
  121948. 1, 8,
  121949. _huff_lengthlist_line_2048x27_class2,
  121950. 0, 0, 0, 0, 0,
  121951. NULL,
  121952. NULL,
  121953. NULL,
  121954. NULL,
  121955. 0
  121956. };
  121957. static long _huff_lengthlist_line_2048x27_class3[] = {
  121958. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121959. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121960. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121961. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121962. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121963. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121964. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121965. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121966. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121967. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121968. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121969. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121970. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121971. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121972. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121973. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121974. };
  121975. static static_codebook _huff_book_line_2048x27_class3 = {
  121976. 1, 256,
  121977. _huff_lengthlist_line_2048x27_class3,
  121978. 0, 0, 0, 0, 0,
  121979. NULL,
  121980. NULL,
  121981. NULL,
  121982. NULL,
  121983. 0
  121984. };
  121985. static long _huff_lengthlist_line_2048x27_class4[] = {
  121986. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121987. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121988. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121989. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121990. };
  121991. static static_codebook _huff_book_line_2048x27_class4 = {
  121992. 1, 64,
  121993. _huff_lengthlist_line_2048x27_class4,
  121994. 0, 0, 0, 0, 0,
  121995. NULL,
  121996. NULL,
  121997. NULL,
  121998. NULL,
  121999. 0
  122000. };
  122001. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122002. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122003. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122004. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122005. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122006. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122007. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122008. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122009. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122010. };
  122011. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122012. 1, 128,
  122013. _huff_lengthlist_line_2048x27_0sub0,
  122014. 0, 0, 0, 0, 0,
  122015. NULL,
  122016. NULL,
  122017. NULL,
  122018. NULL,
  122019. 0
  122020. };
  122021. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122022. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122023. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122024. };
  122025. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122026. 1, 32,
  122027. _huff_lengthlist_line_2048x27_1sub0,
  122028. 0, 0, 0, 0, 0,
  122029. NULL,
  122030. NULL,
  122031. NULL,
  122032. NULL,
  122033. 0
  122034. };
  122035. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122038. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122039. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122040. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122041. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122042. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122043. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122044. };
  122045. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122046. 1, 128,
  122047. _huff_lengthlist_line_2048x27_1sub1,
  122048. 0, 0, 0, 0, 0,
  122049. NULL,
  122050. NULL,
  122051. NULL,
  122052. NULL,
  122053. 0
  122054. };
  122055. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122056. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122057. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122058. };
  122059. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122060. 1, 32,
  122061. _huff_lengthlist_line_2048x27_2sub0,
  122062. 0, 0, 0, 0, 0,
  122063. NULL,
  122064. NULL,
  122065. NULL,
  122066. NULL,
  122067. 0
  122068. };
  122069. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122072. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122073. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122074. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122075. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122076. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122077. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122078. };
  122079. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122080. 1, 128,
  122081. _huff_lengthlist_line_2048x27_2sub1,
  122082. 0, 0, 0, 0, 0,
  122083. NULL,
  122084. NULL,
  122085. NULL,
  122086. NULL,
  122087. 0
  122088. };
  122089. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122090. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122091. 5, 5,
  122092. };
  122093. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122094. 1, 18,
  122095. _huff_lengthlist_line_2048x27_3sub1,
  122096. 0, 0, 0, 0, 0,
  122097. NULL,
  122098. NULL,
  122099. NULL,
  122100. NULL,
  122101. 0
  122102. };
  122103. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122105. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122106. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122107. 10,12,
  122108. };
  122109. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122110. 1, 50,
  122111. _huff_lengthlist_line_2048x27_3sub2,
  122112. 0, 0, 0, 0, 0,
  122113. NULL,
  122114. NULL,
  122115. NULL,
  122116. NULL,
  122117. 0
  122118. };
  122119. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122123. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122124. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122125. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122126. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122127. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122128. };
  122129. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122130. 1, 128,
  122131. _huff_lengthlist_line_2048x27_3sub3,
  122132. 0, 0, 0, 0, 0,
  122133. NULL,
  122134. NULL,
  122135. NULL,
  122136. NULL,
  122137. 0
  122138. };
  122139. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122140. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122141. 4, 5,
  122142. };
  122143. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122144. 1, 18,
  122145. _huff_lengthlist_line_2048x27_4sub1,
  122146. 0, 0, 0, 0, 0,
  122147. NULL,
  122148. NULL,
  122149. NULL,
  122150. NULL,
  122151. 0
  122152. };
  122153. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122155. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122156. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122157. 10,10,
  122158. };
  122159. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122160. 1, 50,
  122161. _huff_lengthlist_line_2048x27_4sub2,
  122162. 0, 0, 0, 0, 0,
  122163. NULL,
  122164. NULL,
  122165. NULL,
  122166. NULL,
  122167. 0
  122168. };
  122169. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122173. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122174. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122175. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122176. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122177. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122178. };
  122179. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122180. 1, 128,
  122181. _huff_lengthlist_line_2048x27_4sub3,
  122182. 0, 0, 0, 0, 0,
  122183. NULL,
  122184. NULL,
  122185. NULL,
  122186. NULL,
  122187. 0
  122188. };
  122189. static long _huff_lengthlist_line_256x4low_class0[] = {
  122190. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122191. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122192. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122193. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122194. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122195. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122196. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122197. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122198. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122199. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122200. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122201. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122202. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122203. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122204. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122205. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122206. };
  122207. static static_codebook _huff_book_line_256x4low_class0 = {
  122208. 1, 256,
  122209. _huff_lengthlist_line_256x4low_class0,
  122210. 0, 0, 0, 0, 0,
  122211. NULL,
  122212. NULL,
  122213. NULL,
  122214. NULL,
  122215. 0
  122216. };
  122217. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122218. 1, 3, 2, 3,
  122219. };
  122220. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122221. 1, 4,
  122222. _huff_lengthlist_line_256x4low_0sub0,
  122223. 0, 0, 0, 0, 0,
  122224. NULL,
  122225. NULL,
  122226. NULL,
  122227. NULL,
  122228. 0
  122229. };
  122230. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122231. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122232. };
  122233. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122234. 1, 10,
  122235. _huff_lengthlist_line_256x4low_0sub1,
  122236. 0, 0, 0, 0, 0,
  122237. NULL,
  122238. NULL,
  122239. NULL,
  122240. NULL,
  122241. 0
  122242. };
  122243. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122245. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122246. };
  122247. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122248. 1, 25,
  122249. _huff_lengthlist_line_256x4low_0sub2,
  122250. 0, 0, 0, 0, 0,
  122251. NULL,
  122252. NULL,
  122253. NULL,
  122254. NULL,
  122255. 0
  122256. };
  122257. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122260. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122261. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122262. };
  122263. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122264. 1, 64,
  122265. _huff_lengthlist_line_256x4low_0sub3,
  122266. 0, 0, 0, 0, 0,
  122267. NULL,
  122268. NULL,
  122269. NULL,
  122270. NULL,
  122271. 0
  122272. };
  122273. /*** End of inlined file: floor_books.h ***/
  122274. static static_codebook *_floor_128x4_books[]={
  122275. &_huff_book_line_128x4_class0,
  122276. &_huff_book_line_128x4_0sub0,
  122277. &_huff_book_line_128x4_0sub1,
  122278. &_huff_book_line_128x4_0sub2,
  122279. &_huff_book_line_128x4_0sub3,
  122280. };
  122281. static static_codebook *_floor_256x4_books[]={
  122282. &_huff_book_line_256x4_class0,
  122283. &_huff_book_line_256x4_0sub0,
  122284. &_huff_book_line_256x4_0sub1,
  122285. &_huff_book_line_256x4_0sub2,
  122286. &_huff_book_line_256x4_0sub3,
  122287. };
  122288. static static_codebook *_floor_128x7_books[]={
  122289. &_huff_book_line_128x7_class0,
  122290. &_huff_book_line_128x7_class1,
  122291. &_huff_book_line_128x7_0sub1,
  122292. &_huff_book_line_128x7_0sub2,
  122293. &_huff_book_line_128x7_0sub3,
  122294. &_huff_book_line_128x7_1sub1,
  122295. &_huff_book_line_128x7_1sub2,
  122296. &_huff_book_line_128x7_1sub3,
  122297. };
  122298. static static_codebook *_floor_256x7_books[]={
  122299. &_huff_book_line_256x7_class0,
  122300. &_huff_book_line_256x7_class1,
  122301. &_huff_book_line_256x7_0sub1,
  122302. &_huff_book_line_256x7_0sub2,
  122303. &_huff_book_line_256x7_0sub3,
  122304. &_huff_book_line_256x7_1sub1,
  122305. &_huff_book_line_256x7_1sub2,
  122306. &_huff_book_line_256x7_1sub3,
  122307. };
  122308. static static_codebook *_floor_128x11_books[]={
  122309. &_huff_book_line_128x11_class1,
  122310. &_huff_book_line_128x11_class2,
  122311. &_huff_book_line_128x11_class3,
  122312. &_huff_book_line_128x11_0sub0,
  122313. &_huff_book_line_128x11_1sub0,
  122314. &_huff_book_line_128x11_1sub1,
  122315. &_huff_book_line_128x11_2sub1,
  122316. &_huff_book_line_128x11_2sub2,
  122317. &_huff_book_line_128x11_2sub3,
  122318. &_huff_book_line_128x11_3sub1,
  122319. &_huff_book_line_128x11_3sub2,
  122320. &_huff_book_line_128x11_3sub3,
  122321. };
  122322. static static_codebook *_floor_128x17_books[]={
  122323. &_huff_book_line_128x17_class1,
  122324. &_huff_book_line_128x17_class2,
  122325. &_huff_book_line_128x17_class3,
  122326. &_huff_book_line_128x17_0sub0,
  122327. &_huff_book_line_128x17_1sub0,
  122328. &_huff_book_line_128x17_1sub1,
  122329. &_huff_book_line_128x17_2sub1,
  122330. &_huff_book_line_128x17_2sub2,
  122331. &_huff_book_line_128x17_2sub3,
  122332. &_huff_book_line_128x17_3sub1,
  122333. &_huff_book_line_128x17_3sub2,
  122334. &_huff_book_line_128x17_3sub3,
  122335. };
  122336. static static_codebook *_floor_256x4low_books[]={
  122337. &_huff_book_line_256x4low_class0,
  122338. &_huff_book_line_256x4low_0sub0,
  122339. &_huff_book_line_256x4low_0sub1,
  122340. &_huff_book_line_256x4low_0sub2,
  122341. &_huff_book_line_256x4low_0sub3,
  122342. };
  122343. static static_codebook *_floor_1024x27_books[]={
  122344. &_huff_book_line_1024x27_class1,
  122345. &_huff_book_line_1024x27_class2,
  122346. &_huff_book_line_1024x27_class3,
  122347. &_huff_book_line_1024x27_class4,
  122348. &_huff_book_line_1024x27_0sub0,
  122349. &_huff_book_line_1024x27_1sub0,
  122350. &_huff_book_line_1024x27_1sub1,
  122351. &_huff_book_line_1024x27_2sub0,
  122352. &_huff_book_line_1024x27_2sub1,
  122353. &_huff_book_line_1024x27_3sub1,
  122354. &_huff_book_line_1024x27_3sub2,
  122355. &_huff_book_line_1024x27_3sub3,
  122356. &_huff_book_line_1024x27_4sub1,
  122357. &_huff_book_line_1024x27_4sub2,
  122358. &_huff_book_line_1024x27_4sub3,
  122359. };
  122360. static static_codebook *_floor_2048x27_books[]={
  122361. &_huff_book_line_2048x27_class1,
  122362. &_huff_book_line_2048x27_class2,
  122363. &_huff_book_line_2048x27_class3,
  122364. &_huff_book_line_2048x27_class4,
  122365. &_huff_book_line_2048x27_0sub0,
  122366. &_huff_book_line_2048x27_1sub0,
  122367. &_huff_book_line_2048x27_1sub1,
  122368. &_huff_book_line_2048x27_2sub0,
  122369. &_huff_book_line_2048x27_2sub1,
  122370. &_huff_book_line_2048x27_3sub1,
  122371. &_huff_book_line_2048x27_3sub2,
  122372. &_huff_book_line_2048x27_3sub3,
  122373. &_huff_book_line_2048x27_4sub1,
  122374. &_huff_book_line_2048x27_4sub2,
  122375. &_huff_book_line_2048x27_4sub3,
  122376. };
  122377. static static_codebook *_floor_512x17_books[]={
  122378. &_huff_book_line_512x17_class1,
  122379. &_huff_book_line_512x17_class2,
  122380. &_huff_book_line_512x17_class3,
  122381. &_huff_book_line_512x17_0sub0,
  122382. &_huff_book_line_512x17_1sub0,
  122383. &_huff_book_line_512x17_1sub1,
  122384. &_huff_book_line_512x17_2sub1,
  122385. &_huff_book_line_512x17_2sub2,
  122386. &_huff_book_line_512x17_2sub3,
  122387. &_huff_book_line_512x17_3sub1,
  122388. &_huff_book_line_512x17_3sub2,
  122389. &_huff_book_line_512x17_3sub3,
  122390. };
  122391. static static_codebook **_floor_books[10]={
  122392. _floor_128x4_books,
  122393. _floor_256x4_books,
  122394. _floor_128x7_books,
  122395. _floor_256x7_books,
  122396. _floor_128x11_books,
  122397. _floor_128x17_books,
  122398. _floor_256x4low_books,
  122399. _floor_1024x27_books,
  122400. _floor_2048x27_books,
  122401. _floor_512x17_books,
  122402. };
  122403. static vorbis_info_floor1 _floor[10]={
  122404. /* 128 x 4 */
  122405. {
  122406. 1,{0},{4},{2},{0},
  122407. {{1,2,3,4}},
  122408. 4,{0,128, 33,8,16,70},
  122409. 60,30,500, 1.,18., -1
  122410. },
  122411. /* 256 x 4 */
  122412. {
  122413. 1,{0},{4},{2},{0},
  122414. {{1,2,3,4}},
  122415. 4,{0,256, 66,16,32,140},
  122416. 60,30,500, 1.,18., -1
  122417. },
  122418. /* 128 x 7 */
  122419. {
  122420. 2,{0,1},{3,4},{2,2},{0,1},
  122421. {{-1,2,3,4},{-1,5,6,7}},
  122422. 4,{0,128, 14,4,58, 2,8,28,90},
  122423. 60,30,500, 1.,18., -1
  122424. },
  122425. /* 256 x 7 */
  122426. {
  122427. 2,{0,1},{3,4},{2,2},{0,1},
  122428. {{-1,2,3,4},{-1,5,6,7}},
  122429. 4,{0,256, 28,8,116, 4,16,56,180},
  122430. 60,30,500, 1.,18., -1
  122431. },
  122432. /* 128 x 11 */
  122433. {
  122434. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122435. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122436. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122437. 60,30,500, 1,18., -1
  122438. },
  122439. /* 128 x 17 */
  122440. {
  122441. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122442. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122443. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122444. 60,30,500, 1,18., -1
  122445. },
  122446. /* 256 x 4 (low bitrate version) */
  122447. {
  122448. 1,{0},{4},{2},{0},
  122449. {{1,2,3,4}},
  122450. 4,{0,256, 66,16,32,140},
  122451. 60,30,500, 1.,18., -1
  122452. },
  122453. /* 1024 x 27 */
  122454. {
  122455. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122456. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122457. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122458. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122459. 60,30,500, 3,18., -1 /* lowpass */
  122460. },
  122461. /* 2048 x 27 */
  122462. {
  122463. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122464. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122465. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122466. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122467. 60,30,500, 3,18., -1 /* lowpass */
  122468. },
  122469. /* 512 x 17 */
  122470. {
  122471. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122472. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122473. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122474. 7,23,39, 55,79,110, 156,232,360},
  122475. 60,30,500, 1,18., -1 /* lowpass! */
  122476. },
  122477. };
  122478. /*** End of inlined file: floor_all.h ***/
  122479. /*** Start of inlined file: residue_44.h ***/
  122480. /*** Start of inlined file: res_books_stereo.h ***/
  122481. static long _vq_quantlist__16c0_s_p1_0[] = {
  122482. 1,
  122483. 0,
  122484. 2,
  122485. };
  122486. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122487. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122488. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122493. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122498. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  122533. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  122538. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  122543. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122579. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122584. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122589. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0,
  122898. };
  122899. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122900. -0.5, 0.5,
  122901. };
  122902. static long _vq_quantmap__16c0_s_p1_0[] = {
  122903. 1, 0, 2,
  122904. };
  122905. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122906. _vq_quantthresh__16c0_s_p1_0,
  122907. _vq_quantmap__16c0_s_p1_0,
  122908. 3,
  122909. 3
  122910. };
  122911. static static_codebook _16c0_s_p1_0 = {
  122912. 8, 6561,
  122913. _vq_lengthlist__16c0_s_p1_0,
  122914. 1, -535822336, 1611661312, 2, 0,
  122915. _vq_quantlist__16c0_s_p1_0,
  122916. NULL,
  122917. &_vq_auxt__16c0_s_p1_0,
  122918. NULL,
  122919. 0
  122920. };
  122921. static long _vq_quantlist__16c0_s_p2_0[] = {
  122922. 2,
  122923. 1,
  122924. 3,
  122925. 0,
  122926. 4,
  122927. };
  122928. static long _vq_lengthlist__16c0_s_p2_0[] = {
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0,
  122969. };
  122970. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122971. -1.5, -0.5, 0.5, 1.5,
  122972. };
  122973. static long _vq_quantmap__16c0_s_p2_0[] = {
  122974. 3, 1, 0, 2, 4,
  122975. };
  122976. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122977. _vq_quantthresh__16c0_s_p2_0,
  122978. _vq_quantmap__16c0_s_p2_0,
  122979. 5,
  122980. 5
  122981. };
  122982. static static_codebook _16c0_s_p2_0 = {
  122983. 4, 625,
  122984. _vq_lengthlist__16c0_s_p2_0,
  122985. 1, -533725184, 1611661312, 3, 0,
  122986. _vq_quantlist__16c0_s_p2_0,
  122987. NULL,
  122988. &_vq_auxt__16c0_s_p2_0,
  122989. NULL,
  122990. 0
  122991. };
  122992. static long _vq_quantlist__16c0_s_p3_0[] = {
  122993. 2,
  122994. 1,
  122995. 3,
  122996. 0,
  122997. 4,
  122998. };
  122999. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123000. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0,
  123040. };
  123041. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123042. -1.5, -0.5, 0.5, 1.5,
  123043. };
  123044. static long _vq_quantmap__16c0_s_p3_0[] = {
  123045. 3, 1, 0, 2, 4,
  123046. };
  123047. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123048. _vq_quantthresh__16c0_s_p3_0,
  123049. _vq_quantmap__16c0_s_p3_0,
  123050. 5,
  123051. 5
  123052. };
  123053. static static_codebook _16c0_s_p3_0 = {
  123054. 4, 625,
  123055. _vq_lengthlist__16c0_s_p3_0,
  123056. 1, -533725184, 1611661312, 3, 0,
  123057. _vq_quantlist__16c0_s_p3_0,
  123058. NULL,
  123059. &_vq_auxt__16c0_s_p3_0,
  123060. NULL,
  123061. 0
  123062. };
  123063. static long _vq_quantlist__16c0_s_p4_0[] = {
  123064. 4,
  123065. 3,
  123066. 5,
  123067. 2,
  123068. 6,
  123069. 1,
  123070. 7,
  123071. 0,
  123072. 8,
  123073. };
  123074. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123075. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123076. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123077. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123078. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123079. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0,
  123081. };
  123082. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123083. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123084. };
  123085. static long _vq_quantmap__16c0_s_p4_0[] = {
  123086. 7, 5, 3, 1, 0, 2, 4, 6,
  123087. 8,
  123088. };
  123089. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123090. _vq_quantthresh__16c0_s_p4_0,
  123091. _vq_quantmap__16c0_s_p4_0,
  123092. 9,
  123093. 9
  123094. };
  123095. static static_codebook _16c0_s_p4_0 = {
  123096. 2, 81,
  123097. _vq_lengthlist__16c0_s_p4_0,
  123098. 1, -531628032, 1611661312, 4, 0,
  123099. _vq_quantlist__16c0_s_p4_0,
  123100. NULL,
  123101. &_vq_auxt__16c0_s_p4_0,
  123102. NULL,
  123103. 0
  123104. };
  123105. static long _vq_quantlist__16c0_s_p5_0[] = {
  123106. 4,
  123107. 3,
  123108. 5,
  123109. 2,
  123110. 6,
  123111. 1,
  123112. 7,
  123113. 0,
  123114. 8,
  123115. };
  123116. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123117. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123118. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123119. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123120. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123121. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123122. 10,
  123123. };
  123124. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123125. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123126. };
  123127. static long _vq_quantmap__16c0_s_p5_0[] = {
  123128. 7, 5, 3, 1, 0, 2, 4, 6,
  123129. 8,
  123130. };
  123131. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123132. _vq_quantthresh__16c0_s_p5_0,
  123133. _vq_quantmap__16c0_s_p5_0,
  123134. 9,
  123135. 9
  123136. };
  123137. static static_codebook _16c0_s_p5_0 = {
  123138. 2, 81,
  123139. _vq_lengthlist__16c0_s_p5_0,
  123140. 1, -531628032, 1611661312, 4, 0,
  123141. _vq_quantlist__16c0_s_p5_0,
  123142. NULL,
  123143. &_vq_auxt__16c0_s_p5_0,
  123144. NULL,
  123145. 0
  123146. };
  123147. static long _vq_quantlist__16c0_s_p6_0[] = {
  123148. 8,
  123149. 7,
  123150. 9,
  123151. 6,
  123152. 10,
  123153. 5,
  123154. 11,
  123155. 4,
  123156. 12,
  123157. 3,
  123158. 13,
  123159. 2,
  123160. 14,
  123161. 1,
  123162. 15,
  123163. 0,
  123164. 16,
  123165. };
  123166. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123167. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123168. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123169. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123170. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123171. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123172. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123173. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123174. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123175. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123176. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123177. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123178. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123179. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123180. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123181. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123182. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123183. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123185. 14,
  123186. };
  123187. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123188. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123189. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123190. };
  123191. static long _vq_quantmap__16c0_s_p6_0[] = {
  123192. 15, 13, 11, 9, 7, 5, 3, 1,
  123193. 0, 2, 4, 6, 8, 10, 12, 14,
  123194. 16,
  123195. };
  123196. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123197. _vq_quantthresh__16c0_s_p6_0,
  123198. _vq_quantmap__16c0_s_p6_0,
  123199. 17,
  123200. 17
  123201. };
  123202. static static_codebook _16c0_s_p6_0 = {
  123203. 2, 289,
  123204. _vq_lengthlist__16c0_s_p6_0,
  123205. 1, -529530880, 1611661312, 5, 0,
  123206. _vq_quantlist__16c0_s_p6_0,
  123207. NULL,
  123208. &_vq_auxt__16c0_s_p6_0,
  123209. NULL,
  123210. 0
  123211. };
  123212. static long _vq_quantlist__16c0_s_p7_0[] = {
  123213. 1,
  123214. 0,
  123215. 2,
  123216. };
  123217. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123218. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123219. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123220. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123221. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123222. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123223. 13,
  123224. };
  123225. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123226. -5.5, 5.5,
  123227. };
  123228. static long _vq_quantmap__16c0_s_p7_0[] = {
  123229. 1, 0, 2,
  123230. };
  123231. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123232. _vq_quantthresh__16c0_s_p7_0,
  123233. _vq_quantmap__16c0_s_p7_0,
  123234. 3,
  123235. 3
  123236. };
  123237. static static_codebook _16c0_s_p7_0 = {
  123238. 4, 81,
  123239. _vq_lengthlist__16c0_s_p7_0,
  123240. 1, -529137664, 1618345984, 2, 0,
  123241. _vq_quantlist__16c0_s_p7_0,
  123242. NULL,
  123243. &_vq_auxt__16c0_s_p7_0,
  123244. NULL,
  123245. 0
  123246. };
  123247. static long _vq_quantlist__16c0_s_p7_1[] = {
  123248. 5,
  123249. 4,
  123250. 6,
  123251. 3,
  123252. 7,
  123253. 2,
  123254. 8,
  123255. 1,
  123256. 9,
  123257. 0,
  123258. 10,
  123259. };
  123260. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123261. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123262. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123263. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123264. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123265. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123266. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123267. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123268. 11,11,11, 9, 9, 9, 9,10,10,
  123269. };
  123270. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123271. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123272. 3.5, 4.5,
  123273. };
  123274. static long _vq_quantmap__16c0_s_p7_1[] = {
  123275. 9, 7, 5, 3, 1, 0, 2, 4,
  123276. 6, 8, 10,
  123277. };
  123278. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123279. _vq_quantthresh__16c0_s_p7_1,
  123280. _vq_quantmap__16c0_s_p7_1,
  123281. 11,
  123282. 11
  123283. };
  123284. static static_codebook _16c0_s_p7_1 = {
  123285. 2, 121,
  123286. _vq_lengthlist__16c0_s_p7_1,
  123287. 1, -531365888, 1611661312, 4, 0,
  123288. _vq_quantlist__16c0_s_p7_1,
  123289. NULL,
  123290. &_vq_auxt__16c0_s_p7_1,
  123291. NULL,
  123292. 0
  123293. };
  123294. static long _vq_quantlist__16c0_s_p8_0[] = {
  123295. 6,
  123296. 5,
  123297. 7,
  123298. 4,
  123299. 8,
  123300. 3,
  123301. 9,
  123302. 2,
  123303. 10,
  123304. 1,
  123305. 11,
  123306. 0,
  123307. 12,
  123308. };
  123309. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123310. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123311. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123312. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123313. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123314. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123315. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123316. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123317. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123318. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123319. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123320. 0,12,13,13,12,13,14,14,14,
  123321. };
  123322. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123323. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123324. 12.5, 17.5, 22.5, 27.5,
  123325. };
  123326. static long _vq_quantmap__16c0_s_p8_0[] = {
  123327. 11, 9, 7, 5, 3, 1, 0, 2,
  123328. 4, 6, 8, 10, 12,
  123329. };
  123330. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123331. _vq_quantthresh__16c0_s_p8_0,
  123332. _vq_quantmap__16c0_s_p8_0,
  123333. 13,
  123334. 13
  123335. };
  123336. static static_codebook _16c0_s_p8_0 = {
  123337. 2, 169,
  123338. _vq_lengthlist__16c0_s_p8_0,
  123339. 1, -526516224, 1616117760, 4, 0,
  123340. _vq_quantlist__16c0_s_p8_0,
  123341. NULL,
  123342. &_vq_auxt__16c0_s_p8_0,
  123343. NULL,
  123344. 0
  123345. };
  123346. static long _vq_quantlist__16c0_s_p8_1[] = {
  123347. 2,
  123348. 1,
  123349. 3,
  123350. 0,
  123351. 4,
  123352. };
  123353. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123354. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123355. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123356. };
  123357. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123358. -1.5, -0.5, 0.5, 1.5,
  123359. };
  123360. static long _vq_quantmap__16c0_s_p8_1[] = {
  123361. 3, 1, 0, 2, 4,
  123362. };
  123363. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123364. _vq_quantthresh__16c0_s_p8_1,
  123365. _vq_quantmap__16c0_s_p8_1,
  123366. 5,
  123367. 5
  123368. };
  123369. static static_codebook _16c0_s_p8_1 = {
  123370. 2, 25,
  123371. _vq_lengthlist__16c0_s_p8_1,
  123372. 1, -533725184, 1611661312, 3, 0,
  123373. _vq_quantlist__16c0_s_p8_1,
  123374. NULL,
  123375. &_vq_auxt__16c0_s_p8_1,
  123376. NULL,
  123377. 0
  123378. };
  123379. static long _vq_quantlist__16c0_s_p9_0[] = {
  123380. 1,
  123381. 0,
  123382. 2,
  123383. };
  123384. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123385. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123386. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123387. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123388. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123389. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123390. 7,
  123391. };
  123392. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123393. -157.5, 157.5,
  123394. };
  123395. static long _vq_quantmap__16c0_s_p9_0[] = {
  123396. 1, 0, 2,
  123397. };
  123398. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123399. _vq_quantthresh__16c0_s_p9_0,
  123400. _vq_quantmap__16c0_s_p9_0,
  123401. 3,
  123402. 3
  123403. };
  123404. static static_codebook _16c0_s_p9_0 = {
  123405. 4, 81,
  123406. _vq_lengthlist__16c0_s_p9_0,
  123407. 1, -518803456, 1628680192, 2, 0,
  123408. _vq_quantlist__16c0_s_p9_0,
  123409. NULL,
  123410. &_vq_auxt__16c0_s_p9_0,
  123411. NULL,
  123412. 0
  123413. };
  123414. static long _vq_quantlist__16c0_s_p9_1[] = {
  123415. 7,
  123416. 6,
  123417. 8,
  123418. 5,
  123419. 9,
  123420. 4,
  123421. 10,
  123422. 3,
  123423. 11,
  123424. 2,
  123425. 12,
  123426. 1,
  123427. 13,
  123428. 0,
  123429. 14,
  123430. };
  123431. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123432. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123433. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123434. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123435. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123436. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123437. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123438. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123439. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123440. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123441. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123442. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123443. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123444. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123445. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123446. 10,
  123447. };
  123448. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123449. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123450. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123451. };
  123452. static long _vq_quantmap__16c0_s_p9_1[] = {
  123453. 13, 11, 9, 7, 5, 3, 1, 0,
  123454. 2, 4, 6, 8, 10, 12, 14,
  123455. };
  123456. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123457. _vq_quantthresh__16c0_s_p9_1,
  123458. _vq_quantmap__16c0_s_p9_1,
  123459. 15,
  123460. 15
  123461. };
  123462. static static_codebook _16c0_s_p9_1 = {
  123463. 2, 225,
  123464. _vq_lengthlist__16c0_s_p9_1,
  123465. 1, -520986624, 1620377600, 4, 0,
  123466. _vq_quantlist__16c0_s_p9_1,
  123467. NULL,
  123468. &_vq_auxt__16c0_s_p9_1,
  123469. NULL,
  123470. 0
  123471. };
  123472. static long _vq_quantlist__16c0_s_p9_2[] = {
  123473. 10,
  123474. 9,
  123475. 11,
  123476. 8,
  123477. 12,
  123478. 7,
  123479. 13,
  123480. 6,
  123481. 14,
  123482. 5,
  123483. 15,
  123484. 4,
  123485. 16,
  123486. 3,
  123487. 17,
  123488. 2,
  123489. 18,
  123490. 1,
  123491. 19,
  123492. 0,
  123493. 20,
  123494. };
  123495. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123496. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123497. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123498. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123499. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123500. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123501. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123502. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123503. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123504. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123505. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123506. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123507. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123508. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123509. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123510. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123511. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123512. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123513. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123514. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123515. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123516. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123517. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123518. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123519. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123520. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123521. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123522. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123523. 10,11,10,10,11, 9,10,10,10,
  123524. };
  123525. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123526. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123527. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123528. 6.5, 7.5, 8.5, 9.5,
  123529. };
  123530. static long _vq_quantmap__16c0_s_p9_2[] = {
  123531. 19, 17, 15, 13, 11, 9, 7, 5,
  123532. 3, 1, 0, 2, 4, 6, 8, 10,
  123533. 12, 14, 16, 18, 20,
  123534. };
  123535. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123536. _vq_quantthresh__16c0_s_p9_2,
  123537. _vq_quantmap__16c0_s_p9_2,
  123538. 21,
  123539. 21
  123540. };
  123541. static static_codebook _16c0_s_p9_2 = {
  123542. 2, 441,
  123543. _vq_lengthlist__16c0_s_p9_2,
  123544. 1, -529268736, 1611661312, 5, 0,
  123545. _vq_quantlist__16c0_s_p9_2,
  123546. NULL,
  123547. &_vq_auxt__16c0_s_p9_2,
  123548. NULL,
  123549. 0
  123550. };
  123551. static long _huff_lengthlist__16c0_s_single[] = {
  123552. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123553. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123554. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123555. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123556. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123557. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123558. 16,16,18,18,
  123559. };
  123560. static static_codebook _huff_book__16c0_s_single = {
  123561. 2, 100,
  123562. _huff_lengthlist__16c0_s_single,
  123563. 0, 0, 0, 0, 0,
  123564. NULL,
  123565. NULL,
  123566. NULL,
  123567. NULL,
  123568. 0
  123569. };
  123570. static long _huff_lengthlist__16c1_s_long[] = {
  123571. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123572. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123573. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123574. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123575. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123576. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123577. 12,11,11,13,
  123578. };
  123579. static static_codebook _huff_book__16c1_s_long = {
  123580. 2, 100,
  123581. _huff_lengthlist__16c1_s_long,
  123582. 0, 0, 0, 0, 0,
  123583. NULL,
  123584. NULL,
  123585. NULL,
  123586. NULL,
  123587. 0
  123588. };
  123589. static long _vq_quantlist__16c1_s_p1_0[] = {
  123590. 1,
  123591. 0,
  123592. 2,
  123593. };
  123594. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123595. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123596. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123601. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123606. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  123641. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  123646. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  123651. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123687. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123692. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123697. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0,
  124006. };
  124007. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124008. -0.5, 0.5,
  124009. };
  124010. static long _vq_quantmap__16c1_s_p1_0[] = {
  124011. 1, 0, 2,
  124012. };
  124013. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124014. _vq_quantthresh__16c1_s_p1_0,
  124015. _vq_quantmap__16c1_s_p1_0,
  124016. 3,
  124017. 3
  124018. };
  124019. static static_codebook _16c1_s_p1_0 = {
  124020. 8, 6561,
  124021. _vq_lengthlist__16c1_s_p1_0,
  124022. 1, -535822336, 1611661312, 2, 0,
  124023. _vq_quantlist__16c1_s_p1_0,
  124024. NULL,
  124025. &_vq_auxt__16c1_s_p1_0,
  124026. NULL,
  124027. 0
  124028. };
  124029. static long _vq_quantlist__16c1_s_p2_0[] = {
  124030. 2,
  124031. 1,
  124032. 3,
  124033. 0,
  124034. 4,
  124035. };
  124036. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0,
  124077. };
  124078. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124079. -1.5, -0.5, 0.5, 1.5,
  124080. };
  124081. static long _vq_quantmap__16c1_s_p2_0[] = {
  124082. 3, 1, 0, 2, 4,
  124083. };
  124084. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124085. _vq_quantthresh__16c1_s_p2_0,
  124086. _vq_quantmap__16c1_s_p2_0,
  124087. 5,
  124088. 5
  124089. };
  124090. static static_codebook _16c1_s_p2_0 = {
  124091. 4, 625,
  124092. _vq_lengthlist__16c1_s_p2_0,
  124093. 1, -533725184, 1611661312, 3, 0,
  124094. _vq_quantlist__16c1_s_p2_0,
  124095. NULL,
  124096. &_vq_auxt__16c1_s_p2_0,
  124097. NULL,
  124098. 0
  124099. };
  124100. static long _vq_quantlist__16c1_s_p3_0[] = {
  124101. 2,
  124102. 1,
  124103. 3,
  124104. 0,
  124105. 4,
  124106. };
  124107. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124108. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0,
  124148. };
  124149. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124150. -1.5, -0.5, 0.5, 1.5,
  124151. };
  124152. static long _vq_quantmap__16c1_s_p3_0[] = {
  124153. 3, 1, 0, 2, 4,
  124154. };
  124155. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124156. _vq_quantthresh__16c1_s_p3_0,
  124157. _vq_quantmap__16c1_s_p3_0,
  124158. 5,
  124159. 5
  124160. };
  124161. static static_codebook _16c1_s_p3_0 = {
  124162. 4, 625,
  124163. _vq_lengthlist__16c1_s_p3_0,
  124164. 1, -533725184, 1611661312, 3, 0,
  124165. _vq_quantlist__16c1_s_p3_0,
  124166. NULL,
  124167. &_vq_auxt__16c1_s_p3_0,
  124168. NULL,
  124169. 0
  124170. };
  124171. static long _vq_quantlist__16c1_s_p4_0[] = {
  124172. 4,
  124173. 3,
  124174. 5,
  124175. 2,
  124176. 6,
  124177. 1,
  124178. 7,
  124179. 0,
  124180. 8,
  124181. };
  124182. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124183. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124184. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124185. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124186. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124187. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0,
  124189. };
  124190. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124191. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124192. };
  124193. static long _vq_quantmap__16c1_s_p4_0[] = {
  124194. 7, 5, 3, 1, 0, 2, 4, 6,
  124195. 8,
  124196. };
  124197. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124198. _vq_quantthresh__16c1_s_p4_0,
  124199. _vq_quantmap__16c1_s_p4_0,
  124200. 9,
  124201. 9
  124202. };
  124203. static static_codebook _16c1_s_p4_0 = {
  124204. 2, 81,
  124205. _vq_lengthlist__16c1_s_p4_0,
  124206. 1, -531628032, 1611661312, 4, 0,
  124207. _vq_quantlist__16c1_s_p4_0,
  124208. NULL,
  124209. &_vq_auxt__16c1_s_p4_0,
  124210. NULL,
  124211. 0
  124212. };
  124213. static long _vq_quantlist__16c1_s_p5_0[] = {
  124214. 4,
  124215. 3,
  124216. 5,
  124217. 2,
  124218. 6,
  124219. 1,
  124220. 7,
  124221. 0,
  124222. 8,
  124223. };
  124224. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124225. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124226. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124227. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124228. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124229. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124230. 10,
  124231. };
  124232. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124233. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124234. };
  124235. static long _vq_quantmap__16c1_s_p5_0[] = {
  124236. 7, 5, 3, 1, 0, 2, 4, 6,
  124237. 8,
  124238. };
  124239. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124240. _vq_quantthresh__16c1_s_p5_0,
  124241. _vq_quantmap__16c1_s_p5_0,
  124242. 9,
  124243. 9
  124244. };
  124245. static static_codebook _16c1_s_p5_0 = {
  124246. 2, 81,
  124247. _vq_lengthlist__16c1_s_p5_0,
  124248. 1, -531628032, 1611661312, 4, 0,
  124249. _vq_quantlist__16c1_s_p5_0,
  124250. NULL,
  124251. &_vq_auxt__16c1_s_p5_0,
  124252. NULL,
  124253. 0
  124254. };
  124255. static long _vq_quantlist__16c1_s_p6_0[] = {
  124256. 8,
  124257. 7,
  124258. 9,
  124259. 6,
  124260. 10,
  124261. 5,
  124262. 11,
  124263. 4,
  124264. 12,
  124265. 3,
  124266. 13,
  124267. 2,
  124268. 14,
  124269. 1,
  124270. 15,
  124271. 0,
  124272. 16,
  124273. };
  124274. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124275. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124276. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124277. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124278. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124279. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124280. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124281. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124282. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124283. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124284. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124285. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124286. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124287. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124288. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124289. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124290. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124291. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124292. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124293. 14,
  124294. };
  124295. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124296. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124297. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124298. };
  124299. static long _vq_quantmap__16c1_s_p6_0[] = {
  124300. 15, 13, 11, 9, 7, 5, 3, 1,
  124301. 0, 2, 4, 6, 8, 10, 12, 14,
  124302. 16,
  124303. };
  124304. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124305. _vq_quantthresh__16c1_s_p6_0,
  124306. _vq_quantmap__16c1_s_p6_0,
  124307. 17,
  124308. 17
  124309. };
  124310. static static_codebook _16c1_s_p6_0 = {
  124311. 2, 289,
  124312. _vq_lengthlist__16c1_s_p6_0,
  124313. 1, -529530880, 1611661312, 5, 0,
  124314. _vq_quantlist__16c1_s_p6_0,
  124315. NULL,
  124316. &_vq_auxt__16c1_s_p6_0,
  124317. NULL,
  124318. 0
  124319. };
  124320. static long _vq_quantlist__16c1_s_p7_0[] = {
  124321. 1,
  124322. 0,
  124323. 2,
  124324. };
  124325. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124326. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124327. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124328. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124329. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124330. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124331. 11,
  124332. };
  124333. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124334. -5.5, 5.5,
  124335. };
  124336. static long _vq_quantmap__16c1_s_p7_0[] = {
  124337. 1, 0, 2,
  124338. };
  124339. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124340. _vq_quantthresh__16c1_s_p7_0,
  124341. _vq_quantmap__16c1_s_p7_0,
  124342. 3,
  124343. 3
  124344. };
  124345. static static_codebook _16c1_s_p7_0 = {
  124346. 4, 81,
  124347. _vq_lengthlist__16c1_s_p7_0,
  124348. 1, -529137664, 1618345984, 2, 0,
  124349. _vq_quantlist__16c1_s_p7_0,
  124350. NULL,
  124351. &_vq_auxt__16c1_s_p7_0,
  124352. NULL,
  124353. 0
  124354. };
  124355. static long _vq_quantlist__16c1_s_p7_1[] = {
  124356. 5,
  124357. 4,
  124358. 6,
  124359. 3,
  124360. 7,
  124361. 2,
  124362. 8,
  124363. 1,
  124364. 9,
  124365. 0,
  124366. 10,
  124367. };
  124368. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124369. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124370. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124371. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124372. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124373. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124374. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124375. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124376. 10,10,10, 8, 8, 8, 8, 9, 9,
  124377. };
  124378. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124379. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124380. 3.5, 4.5,
  124381. };
  124382. static long _vq_quantmap__16c1_s_p7_1[] = {
  124383. 9, 7, 5, 3, 1, 0, 2, 4,
  124384. 6, 8, 10,
  124385. };
  124386. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124387. _vq_quantthresh__16c1_s_p7_1,
  124388. _vq_quantmap__16c1_s_p7_1,
  124389. 11,
  124390. 11
  124391. };
  124392. static static_codebook _16c1_s_p7_1 = {
  124393. 2, 121,
  124394. _vq_lengthlist__16c1_s_p7_1,
  124395. 1, -531365888, 1611661312, 4, 0,
  124396. _vq_quantlist__16c1_s_p7_1,
  124397. NULL,
  124398. &_vq_auxt__16c1_s_p7_1,
  124399. NULL,
  124400. 0
  124401. };
  124402. static long _vq_quantlist__16c1_s_p8_0[] = {
  124403. 6,
  124404. 5,
  124405. 7,
  124406. 4,
  124407. 8,
  124408. 3,
  124409. 9,
  124410. 2,
  124411. 10,
  124412. 1,
  124413. 11,
  124414. 0,
  124415. 12,
  124416. };
  124417. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124418. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124419. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124420. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124421. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124422. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124423. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124424. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124425. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124426. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124427. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124428. 0,12,12,12,12,13,13,14,15,
  124429. };
  124430. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124431. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124432. 12.5, 17.5, 22.5, 27.5,
  124433. };
  124434. static long _vq_quantmap__16c1_s_p8_0[] = {
  124435. 11, 9, 7, 5, 3, 1, 0, 2,
  124436. 4, 6, 8, 10, 12,
  124437. };
  124438. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124439. _vq_quantthresh__16c1_s_p8_0,
  124440. _vq_quantmap__16c1_s_p8_0,
  124441. 13,
  124442. 13
  124443. };
  124444. static static_codebook _16c1_s_p8_0 = {
  124445. 2, 169,
  124446. _vq_lengthlist__16c1_s_p8_0,
  124447. 1, -526516224, 1616117760, 4, 0,
  124448. _vq_quantlist__16c1_s_p8_0,
  124449. NULL,
  124450. &_vq_auxt__16c1_s_p8_0,
  124451. NULL,
  124452. 0
  124453. };
  124454. static long _vq_quantlist__16c1_s_p8_1[] = {
  124455. 2,
  124456. 1,
  124457. 3,
  124458. 0,
  124459. 4,
  124460. };
  124461. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124462. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124463. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124464. };
  124465. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124466. -1.5, -0.5, 0.5, 1.5,
  124467. };
  124468. static long _vq_quantmap__16c1_s_p8_1[] = {
  124469. 3, 1, 0, 2, 4,
  124470. };
  124471. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124472. _vq_quantthresh__16c1_s_p8_1,
  124473. _vq_quantmap__16c1_s_p8_1,
  124474. 5,
  124475. 5
  124476. };
  124477. static static_codebook _16c1_s_p8_1 = {
  124478. 2, 25,
  124479. _vq_lengthlist__16c1_s_p8_1,
  124480. 1, -533725184, 1611661312, 3, 0,
  124481. _vq_quantlist__16c1_s_p8_1,
  124482. NULL,
  124483. &_vq_auxt__16c1_s_p8_1,
  124484. NULL,
  124485. 0
  124486. };
  124487. static long _vq_quantlist__16c1_s_p9_0[] = {
  124488. 6,
  124489. 5,
  124490. 7,
  124491. 4,
  124492. 8,
  124493. 3,
  124494. 9,
  124495. 2,
  124496. 10,
  124497. 1,
  124498. 11,
  124499. 0,
  124500. 12,
  124501. };
  124502. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124503. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124504. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124505. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124506. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124507. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124508. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124509. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124510. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124511. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124512. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124513. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124514. };
  124515. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124516. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124517. 787.5, 1102.5, 1417.5, 1732.5,
  124518. };
  124519. static long _vq_quantmap__16c1_s_p9_0[] = {
  124520. 11, 9, 7, 5, 3, 1, 0, 2,
  124521. 4, 6, 8, 10, 12,
  124522. };
  124523. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124524. _vq_quantthresh__16c1_s_p9_0,
  124525. _vq_quantmap__16c1_s_p9_0,
  124526. 13,
  124527. 13
  124528. };
  124529. static static_codebook _16c1_s_p9_0 = {
  124530. 2, 169,
  124531. _vq_lengthlist__16c1_s_p9_0,
  124532. 1, -513964032, 1628680192, 4, 0,
  124533. _vq_quantlist__16c1_s_p9_0,
  124534. NULL,
  124535. &_vq_auxt__16c1_s_p9_0,
  124536. NULL,
  124537. 0
  124538. };
  124539. static long _vq_quantlist__16c1_s_p9_1[] = {
  124540. 7,
  124541. 6,
  124542. 8,
  124543. 5,
  124544. 9,
  124545. 4,
  124546. 10,
  124547. 3,
  124548. 11,
  124549. 2,
  124550. 12,
  124551. 1,
  124552. 13,
  124553. 0,
  124554. 14,
  124555. };
  124556. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124557. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124558. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124559. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124560. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124561. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124562. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124563. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124564. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124565. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124566. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124567. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124568. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124569. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124570. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124571. 13,
  124572. };
  124573. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124574. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124575. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124576. };
  124577. static long _vq_quantmap__16c1_s_p9_1[] = {
  124578. 13, 11, 9, 7, 5, 3, 1, 0,
  124579. 2, 4, 6, 8, 10, 12, 14,
  124580. };
  124581. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124582. _vq_quantthresh__16c1_s_p9_1,
  124583. _vq_quantmap__16c1_s_p9_1,
  124584. 15,
  124585. 15
  124586. };
  124587. static static_codebook _16c1_s_p9_1 = {
  124588. 2, 225,
  124589. _vq_lengthlist__16c1_s_p9_1,
  124590. 1, -520986624, 1620377600, 4, 0,
  124591. _vq_quantlist__16c1_s_p9_1,
  124592. NULL,
  124593. &_vq_auxt__16c1_s_p9_1,
  124594. NULL,
  124595. 0
  124596. };
  124597. static long _vq_quantlist__16c1_s_p9_2[] = {
  124598. 10,
  124599. 9,
  124600. 11,
  124601. 8,
  124602. 12,
  124603. 7,
  124604. 13,
  124605. 6,
  124606. 14,
  124607. 5,
  124608. 15,
  124609. 4,
  124610. 16,
  124611. 3,
  124612. 17,
  124613. 2,
  124614. 18,
  124615. 1,
  124616. 19,
  124617. 0,
  124618. 20,
  124619. };
  124620. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124621. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124622. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124623. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124624. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124625. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124626. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124627. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124628. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124629. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124630. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124631. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124632. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124633. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124634. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124635. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124636. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124637. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124638. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124639. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124640. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124641. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124642. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124643. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124644. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124645. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124646. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124647. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124648. 11,11,11,11,12,11,11,12,11,
  124649. };
  124650. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124651. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124652. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124653. 6.5, 7.5, 8.5, 9.5,
  124654. };
  124655. static long _vq_quantmap__16c1_s_p9_2[] = {
  124656. 19, 17, 15, 13, 11, 9, 7, 5,
  124657. 3, 1, 0, 2, 4, 6, 8, 10,
  124658. 12, 14, 16, 18, 20,
  124659. };
  124660. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124661. _vq_quantthresh__16c1_s_p9_2,
  124662. _vq_quantmap__16c1_s_p9_2,
  124663. 21,
  124664. 21
  124665. };
  124666. static static_codebook _16c1_s_p9_2 = {
  124667. 2, 441,
  124668. _vq_lengthlist__16c1_s_p9_2,
  124669. 1, -529268736, 1611661312, 5, 0,
  124670. _vq_quantlist__16c1_s_p9_2,
  124671. NULL,
  124672. &_vq_auxt__16c1_s_p9_2,
  124673. NULL,
  124674. 0
  124675. };
  124676. static long _huff_lengthlist__16c1_s_short[] = {
  124677. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124678. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124679. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124680. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124681. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124682. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124683. 9, 9,10,13,
  124684. };
  124685. static static_codebook _huff_book__16c1_s_short = {
  124686. 2, 100,
  124687. _huff_lengthlist__16c1_s_short,
  124688. 0, 0, 0, 0, 0,
  124689. NULL,
  124690. NULL,
  124691. NULL,
  124692. NULL,
  124693. 0
  124694. };
  124695. static long _huff_lengthlist__16c2_s_long[] = {
  124696. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124697. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124698. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124699. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124700. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124701. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124702. 14,14,16,18,
  124703. };
  124704. static static_codebook _huff_book__16c2_s_long = {
  124705. 2, 100,
  124706. _huff_lengthlist__16c2_s_long,
  124707. 0, 0, 0, 0, 0,
  124708. NULL,
  124709. NULL,
  124710. NULL,
  124711. NULL,
  124712. 0
  124713. };
  124714. static long _vq_quantlist__16c2_s_p1_0[] = {
  124715. 1,
  124716. 0,
  124717. 2,
  124718. };
  124719. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124720. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124721. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124725. 0,
  124726. };
  124727. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124728. -0.5, 0.5,
  124729. };
  124730. static long _vq_quantmap__16c2_s_p1_0[] = {
  124731. 1, 0, 2,
  124732. };
  124733. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124734. _vq_quantthresh__16c2_s_p1_0,
  124735. _vq_quantmap__16c2_s_p1_0,
  124736. 3,
  124737. 3
  124738. };
  124739. static static_codebook _16c2_s_p1_0 = {
  124740. 4, 81,
  124741. _vq_lengthlist__16c2_s_p1_0,
  124742. 1, -535822336, 1611661312, 2, 0,
  124743. _vq_quantlist__16c2_s_p1_0,
  124744. NULL,
  124745. &_vq_auxt__16c2_s_p1_0,
  124746. NULL,
  124747. 0
  124748. };
  124749. static long _vq_quantlist__16c2_s_p2_0[] = {
  124750. 2,
  124751. 1,
  124752. 3,
  124753. 0,
  124754. 4,
  124755. };
  124756. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124757. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124758. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124759. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124760. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124761. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124762. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124763. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124764. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124769. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124770. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124771. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124772. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124777. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124778. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124779. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124780. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124785. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124786. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124787. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124788. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124793. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124794. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124795. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124796. 13,
  124797. };
  124798. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124799. -1.5, -0.5, 0.5, 1.5,
  124800. };
  124801. static long _vq_quantmap__16c2_s_p2_0[] = {
  124802. 3, 1, 0, 2, 4,
  124803. };
  124804. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124805. _vq_quantthresh__16c2_s_p2_0,
  124806. _vq_quantmap__16c2_s_p2_0,
  124807. 5,
  124808. 5
  124809. };
  124810. static static_codebook _16c2_s_p2_0 = {
  124811. 4, 625,
  124812. _vq_lengthlist__16c2_s_p2_0,
  124813. 1, -533725184, 1611661312, 3, 0,
  124814. _vq_quantlist__16c2_s_p2_0,
  124815. NULL,
  124816. &_vq_auxt__16c2_s_p2_0,
  124817. NULL,
  124818. 0
  124819. };
  124820. static long _vq_quantlist__16c2_s_p3_0[] = {
  124821. 4,
  124822. 3,
  124823. 5,
  124824. 2,
  124825. 6,
  124826. 1,
  124827. 7,
  124828. 0,
  124829. 8,
  124830. };
  124831. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124832. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124833. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124834. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124835. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124837. 0,
  124838. };
  124839. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124840. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124841. };
  124842. static long _vq_quantmap__16c2_s_p3_0[] = {
  124843. 7, 5, 3, 1, 0, 2, 4, 6,
  124844. 8,
  124845. };
  124846. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124847. _vq_quantthresh__16c2_s_p3_0,
  124848. _vq_quantmap__16c2_s_p3_0,
  124849. 9,
  124850. 9
  124851. };
  124852. static static_codebook _16c2_s_p3_0 = {
  124853. 2, 81,
  124854. _vq_lengthlist__16c2_s_p3_0,
  124855. 1, -531628032, 1611661312, 4, 0,
  124856. _vq_quantlist__16c2_s_p3_0,
  124857. NULL,
  124858. &_vq_auxt__16c2_s_p3_0,
  124859. NULL,
  124860. 0
  124861. };
  124862. static long _vq_quantlist__16c2_s_p4_0[] = {
  124863. 8,
  124864. 7,
  124865. 9,
  124866. 6,
  124867. 10,
  124868. 5,
  124869. 11,
  124870. 4,
  124871. 12,
  124872. 3,
  124873. 13,
  124874. 2,
  124875. 14,
  124876. 1,
  124877. 15,
  124878. 0,
  124879. 16,
  124880. };
  124881. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124882. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124883. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124884. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124885. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124886. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124887. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124888. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124889. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124890. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124891. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124900. 0,
  124901. };
  124902. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124903. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124904. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124905. };
  124906. static long _vq_quantmap__16c2_s_p4_0[] = {
  124907. 15, 13, 11, 9, 7, 5, 3, 1,
  124908. 0, 2, 4, 6, 8, 10, 12, 14,
  124909. 16,
  124910. };
  124911. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124912. _vq_quantthresh__16c2_s_p4_0,
  124913. _vq_quantmap__16c2_s_p4_0,
  124914. 17,
  124915. 17
  124916. };
  124917. static static_codebook _16c2_s_p4_0 = {
  124918. 2, 289,
  124919. _vq_lengthlist__16c2_s_p4_0,
  124920. 1, -529530880, 1611661312, 5, 0,
  124921. _vq_quantlist__16c2_s_p4_0,
  124922. NULL,
  124923. &_vq_auxt__16c2_s_p4_0,
  124924. NULL,
  124925. 0
  124926. };
  124927. static long _vq_quantlist__16c2_s_p5_0[] = {
  124928. 1,
  124929. 0,
  124930. 2,
  124931. };
  124932. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124933. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124934. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124935. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124936. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124937. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124938. 12,
  124939. };
  124940. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124941. -5.5, 5.5,
  124942. };
  124943. static long _vq_quantmap__16c2_s_p5_0[] = {
  124944. 1, 0, 2,
  124945. };
  124946. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124947. _vq_quantthresh__16c2_s_p5_0,
  124948. _vq_quantmap__16c2_s_p5_0,
  124949. 3,
  124950. 3
  124951. };
  124952. static static_codebook _16c2_s_p5_0 = {
  124953. 4, 81,
  124954. _vq_lengthlist__16c2_s_p5_0,
  124955. 1, -529137664, 1618345984, 2, 0,
  124956. _vq_quantlist__16c2_s_p5_0,
  124957. NULL,
  124958. &_vq_auxt__16c2_s_p5_0,
  124959. NULL,
  124960. 0
  124961. };
  124962. static long _vq_quantlist__16c2_s_p5_1[] = {
  124963. 5,
  124964. 4,
  124965. 6,
  124966. 3,
  124967. 7,
  124968. 2,
  124969. 8,
  124970. 1,
  124971. 9,
  124972. 0,
  124973. 10,
  124974. };
  124975. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124976. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124977. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124978. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124979. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124980. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124981. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124982. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124983. 11,11,11, 7, 7, 8, 8, 8, 8,
  124984. };
  124985. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124986. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124987. 3.5, 4.5,
  124988. };
  124989. static long _vq_quantmap__16c2_s_p5_1[] = {
  124990. 9, 7, 5, 3, 1, 0, 2, 4,
  124991. 6, 8, 10,
  124992. };
  124993. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124994. _vq_quantthresh__16c2_s_p5_1,
  124995. _vq_quantmap__16c2_s_p5_1,
  124996. 11,
  124997. 11
  124998. };
  124999. static static_codebook _16c2_s_p5_1 = {
  125000. 2, 121,
  125001. _vq_lengthlist__16c2_s_p5_1,
  125002. 1, -531365888, 1611661312, 4, 0,
  125003. _vq_quantlist__16c2_s_p5_1,
  125004. NULL,
  125005. &_vq_auxt__16c2_s_p5_1,
  125006. NULL,
  125007. 0
  125008. };
  125009. static long _vq_quantlist__16c2_s_p6_0[] = {
  125010. 6,
  125011. 5,
  125012. 7,
  125013. 4,
  125014. 8,
  125015. 3,
  125016. 9,
  125017. 2,
  125018. 10,
  125019. 1,
  125020. 11,
  125021. 0,
  125022. 12,
  125023. };
  125024. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125025. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125026. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125027. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125028. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125029. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125030. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125035. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125036. };
  125037. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125038. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125039. 12.5, 17.5, 22.5, 27.5,
  125040. };
  125041. static long _vq_quantmap__16c2_s_p6_0[] = {
  125042. 11, 9, 7, 5, 3, 1, 0, 2,
  125043. 4, 6, 8, 10, 12,
  125044. };
  125045. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125046. _vq_quantthresh__16c2_s_p6_0,
  125047. _vq_quantmap__16c2_s_p6_0,
  125048. 13,
  125049. 13
  125050. };
  125051. static static_codebook _16c2_s_p6_0 = {
  125052. 2, 169,
  125053. _vq_lengthlist__16c2_s_p6_0,
  125054. 1, -526516224, 1616117760, 4, 0,
  125055. _vq_quantlist__16c2_s_p6_0,
  125056. NULL,
  125057. &_vq_auxt__16c2_s_p6_0,
  125058. NULL,
  125059. 0
  125060. };
  125061. static long _vq_quantlist__16c2_s_p6_1[] = {
  125062. 2,
  125063. 1,
  125064. 3,
  125065. 0,
  125066. 4,
  125067. };
  125068. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125069. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125070. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125071. };
  125072. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125073. -1.5, -0.5, 0.5, 1.5,
  125074. };
  125075. static long _vq_quantmap__16c2_s_p6_1[] = {
  125076. 3, 1, 0, 2, 4,
  125077. };
  125078. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125079. _vq_quantthresh__16c2_s_p6_1,
  125080. _vq_quantmap__16c2_s_p6_1,
  125081. 5,
  125082. 5
  125083. };
  125084. static static_codebook _16c2_s_p6_1 = {
  125085. 2, 25,
  125086. _vq_lengthlist__16c2_s_p6_1,
  125087. 1, -533725184, 1611661312, 3, 0,
  125088. _vq_quantlist__16c2_s_p6_1,
  125089. NULL,
  125090. &_vq_auxt__16c2_s_p6_1,
  125091. NULL,
  125092. 0
  125093. };
  125094. static long _vq_quantlist__16c2_s_p7_0[] = {
  125095. 6,
  125096. 5,
  125097. 7,
  125098. 4,
  125099. 8,
  125100. 3,
  125101. 9,
  125102. 2,
  125103. 10,
  125104. 1,
  125105. 11,
  125106. 0,
  125107. 12,
  125108. };
  125109. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125110. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125111. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125112. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125113. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125114. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125115. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125116. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125117. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125118. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125119. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125120. 18,13,14,13,13,14,13,15,14,
  125121. };
  125122. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125123. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125124. 27.5, 38.5, 49.5, 60.5,
  125125. };
  125126. static long _vq_quantmap__16c2_s_p7_0[] = {
  125127. 11, 9, 7, 5, 3, 1, 0, 2,
  125128. 4, 6, 8, 10, 12,
  125129. };
  125130. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125131. _vq_quantthresh__16c2_s_p7_0,
  125132. _vq_quantmap__16c2_s_p7_0,
  125133. 13,
  125134. 13
  125135. };
  125136. static static_codebook _16c2_s_p7_0 = {
  125137. 2, 169,
  125138. _vq_lengthlist__16c2_s_p7_0,
  125139. 1, -523206656, 1618345984, 4, 0,
  125140. _vq_quantlist__16c2_s_p7_0,
  125141. NULL,
  125142. &_vq_auxt__16c2_s_p7_0,
  125143. NULL,
  125144. 0
  125145. };
  125146. static long _vq_quantlist__16c2_s_p7_1[] = {
  125147. 5,
  125148. 4,
  125149. 6,
  125150. 3,
  125151. 7,
  125152. 2,
  125153. 8,
  125154. 1,
  125155. 9,
  125156. 0,
  125157. 10,
  125158. };
  125159. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125160. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125161. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125162. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125163. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125164. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125165. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125166. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125167. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125168. };
  125169. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125170. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125171. 3.5, 4.5,
  125172. };
  125173. static long _vq_quantmap__16c2_s_p7_1[] = {
  125174. 9, 7, 5, 3, 1, 0, 2, 4,
  125175. 6, 8, 10,
  125176. };
  125177. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125178. _vq_quantthresh__16c2_s_p7_1,
  125179. _vq_quantmap__16c2_s_p7_1,
  125180. 11,
  125181. 11
  125182. };
  125183. static static_codebook _16c2_s_p7_1 = {
  125184. 2, 121,
  125185. _vq_lengthlist__16c2_s_p7_1,
  125186. 1, -531365888, 1611661312, 4, 0,
  125187. _vq_quantlist__16c2_s_p7_1,
  125188. NULL,
  125189. &_vq_auxt__16c2_s_p7_1,
  125190. NULL,
  125191. 0
  125192. };
  125193. static long _vq_quantlist__16c2_s_p8_0[] = {
  125194. 7,
  125195. 6,
  125196. 8,
  125197. 5,
  125198. 9,
  125199. 4,
  125200. 10,
  125201. 3,
  125202. 11,
  125203. 2,
  125204. 12,
  125205. 1,
  125206. 13,
  125207. 0,
  125208. 14,
  125209. };
  125210. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125211. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125212. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125213. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125214. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125215. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125216. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125217. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125218. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125219. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125220. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125221. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125222. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125223. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125224. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125225. 13,
  125226. };
  125227. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125228. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125229. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125230. };
  125231. static long _vq_quantmap__16c2_s_p8_0[] = {
  125232. 13, 11, 9, 7, 5, 3, 1, 0,
  125233. 2, 4, 6, 8, 10, 12, 14,
  125234. };
  125235. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125236. _vq_quantthresh__16c2_s_p8_0,
  125237. _vq_quantmap__16c2_s_p8_0,
  125238. 15,
  125239. 15
  125240. };
  125241. static static_codebook _16c2_s_p8_0 = {
  125242. 2, 225,
  125243. _vq_lengthlist__16c2_s_p8_0,
  125244. 1, -520986624, 1620377600, 4, 0,
  125245. _vq_quantlist__16c2_s_p8_0,
  125246. NULL,
  125247. &_vq_auxt__16c2_s_p8_0,
  125248. NULL,
  125249. 0
  125250. };
  125251. static long _vq_quantlist__16c2_s_p8_1[] = {
  125252. 10,
  125253. 9,
  125254. 11,
  125255. 8,
  125256. 12,
  125257. 7,
  125258. 13,
  125259. 6,
  125260. 14,
  125261. 5,
  125262. 15,
  125263. 4,
  125264. 16,
  125265. 3,
  125266. 17,
  125267. 2,
  125268. 18,
  125269. 1,
  125270. 19,
  125271. 0,
  125272. 20,
  125273. };
  125274. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125275. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125276. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125277. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125278. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125279. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125280. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125281. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125282. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125283. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125284. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125285. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125286. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125287. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125288. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125289. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125290. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125291. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125292. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125293. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125294. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125295. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125296. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125297. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125298. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125299. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125300. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125301. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125302. 10,11,10,10,10,10,10,10,10,
  125303. };
  125304. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125305. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125306. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125307. 6.5, 7.5, 8.5, 9.5,
  125308. };
  125309. static long _vq_quantmap__16c2_s_p8_1[] = {
  125310. 19, 17, 15, 13, 11, 9, 7, 5,
  125311. 3, 1, 0, 2, 4, 6, 8, 10,
  125312. 12, 14, 16, 18, 20,
  125313. };
  125314. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125315. _vq_quantthresh__16c2_s_p8_1,
  125316. _vq_quantmap__16c2_s_p8_1,
  125317. 21,
  125318. 21
  125319. };
  125320. static static_codebook _16c2_s_p8_1 = {
  125321. 2, 441,
  125322. _vq_lengthlist__16c2_s_p8_1,
  125323. 1, -529268736, 1611661312, 5, 0,
  125324. _vq_quantlist__16c2_s_p8_1,
  125325. NULL,
  125326. &_vq_auxt__16c2_s_p8_1,
  125327. NULL,
  125328. 0
  125329. };
  125330. static long _vq_quantlist__16c2_s_p9_0[] = {
  125331. 6,
  125332. 5,
  125333. 7,
  125334. 4,
  125335. 8,
  125336. 3,
  125337. 9,
  125338. 2,
  125339. 10,
  125340. 1,
  125341. 11,
  125342. 0,
  125343. 12,
  125344. };
  125345. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125346. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125347. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125348. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125349. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125350. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125351. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125352. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125353. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125354. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125355. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125356. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125357. };
  125358. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125359. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125360. 2327.5, 3258.5, 4189.5, 5120.5,
  125361. };
  125362. static long _vq_quantmap__16c2_s_p9_0[] = {
  125363. 11, 9, 7, 5, 3, 1, 0, 2,
  125364. 4, 6, 8, 10, 12,
  125365. };
  125366. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125367. _vq_quantthresh__16c2_s_p9_0,
  125368. _vq_quantmap__16c2_s_p9_0,
  125369. 13,
  125370. 13
  125371. };
  125372. static static_codebook _16c2_s_p9_0 = {
  125373. 2, 169,
  125374. _vq_lengthlist__16c2_s_p9_0,
  125375. 1, -510275072, 1631393792, 4, 0,
  125376. _vq_quantlist__16c2_s_p9_0,
  125377. NULL,
  125378. &_vq_auxt__16c2_s_p9_0,
  125379. NULL,
  125380. 0
  125381. };
  125382. static long _vq_quantlist__16c2_s_p9_1[] = {
  125383. 8,
  125384. 7,
  125385. 9,
  125386. 6,
  125387. 10,
  125388. 5,
  125389. 11,
  125390. 4,
  125391. 12,
  125392. 3,
  125393. 13,
  125394. 2,
  125395. 14,
  125396. 1,
  125397. 15,
  125398. 0,
  125399. 16,
  125400. };
  125401. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125402. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125403. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125404. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125405. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125406. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125407. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125408. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125409. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125410. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125411. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125412. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125413. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125414. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125415. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125416. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125417. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125418. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125419. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125420. 10,
  125421. };
  125422. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125423. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125424. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125425. };
  125426. static long _vq_quantmap__16c2_s_p9_1[] = {
  125427. 15, 13, 11, 9, 7, 5, 3, 1,
  125428. 0, 2, 4, 6, 8, 10, 12, 14,
  125429. 16,
  125430. };
  125431. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125432. _vq_quantthresh__16c2_s_p9_1,
  125433. _vq_quantmap__16c2_s_p9_1,
  125434. 17,
  125435. 17
  125436. };
  125437. static static_codebook _16c2_s_p9_1 = {
  125438. 2, 289,
  125439. _vq_lengthlist__16c2_s_p9_1,
  125440. 1, -518488064, 1622704128, 5, 0,
  125441. _vq_quantlist__16c2_s_p9_1,
  125442. NULL,
  125443. &_vq_auxt__16c2_s_p9_1,
  125444. NULL,
  125445. 0
  125446. };
  125447. static long _vq_quantlist__16c2_s_p9_2[] = {
  125448. 13,
  125449. 12,
  125450. 14,
  125451. 11,
  125452. 15,
  125453. 10,
  125454. 16,
  125455. 9,
  125456. 17,
  125457. 8,
  125458. 18,
  125459. 7,
  125460. 19,
  125461. 6,
  125462. 20,
  125463. 5,
  125464. 21,
  125465. 4,
  125466. 22,
  125467. 3,
  125468. 23,
  125469. 2,
  125470. 24,
  125471. 1,
  125472. 25,
  125473. 0,
  125474. 26,
  125475. };
  125476. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125477. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125478. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125479. };
  125480. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125481. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125482. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125483. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125484. 11.5, 12.5,
  125485. };
  125486. static long _vq_quantmap__16c2_s_p9_2[] = {
  125487. 25, 23, 21, 19, 17, 15, 13, 11,
  125488. 9, 7, 5, 3, 1, 0, 2, 4,
  125489. 6, 8, 10, 12, 14, 16, 18, 20,
  125490. 22, 24, 26,
  125491. };
  125492. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125493. _vq_quantthresh__16c2_s_p9_2,
  125494. _vq_quantmap__16c2_s_p9_2,
  125495. 27,
  125496. 27
  125497. };
  125498. static static_codebook _16c2_s_p9_2 = {
  125499. 1, 27,
  125500. _vq_lengthlist__16c2_s_p9_2,
  125501. 1, -528875520, 1611661312, 5, 0,
  125502. _vq_quantlist__16c2_s_p9_2,
  125503. NULL,
  125504. &_vq_auxt__16c2_s_p9_2,
  125505. NULL,
  125506. 0
  125507. };
  125508. static long _huff_lengthlist__16c2_s_short[] = {
  125509. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125510. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125511. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125512. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125513. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125514. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125515. 15,12,14,14,
  125516. };
  125517. static static_codebook _huff_book__16c2_s_short = {
  125518. 2, 100,
  125519. _huff_lengthlist__16c2_s_short,
  125520. 0, 0, 0, 0, 0,
  125521. NULL,
  125522. NULL,
  125523. NULL,
  125524. NULL,
  125525. 0
  125526. };
  125527. static long _vq_quantlist__8c0_s_p1_0[] = {
  125528. 1,
  125529. 0,
  125530. 2,
  125531. };
  125532. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125533. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125534. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125539. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125544. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  125579. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125584. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  125589. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125625. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125630. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125635. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0,
  125944. };
  125945. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125946. -0.5, 0.5,
  125947. };
  125948. static long _vq_quantmap__8c0_s_p1_0[] = {
  125949. 1, 0, 2,
  125950. };
  125951. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125952. _vq_quantthresh__8c0_s_p1_0,
  125953. _vq_quantmap__8c0_s_p1_0,
  125954. 3,
  125955. 3
  125956. };
  125957. static static_codebook _8c0_s_p1_0 = {
  125958. 8, 6561,
  125959. _vq_lengthlist__8c0_s_p1_0,
  125960. 1, -535822336, 1611661312, 2, 0,
  125961. _vq_quantlist__8c0_s_p1_0,
  125962. NULL,
  125963. &_vq_auxt__8c0_s_p1_0,
  125964. NULL,
  125965. 0
  125966. };
  125967. static long _vq_quantlist__8c0_s_p2_0[] = {
  125968. 2,
  125969. 1,
  125970. 3,
  125971. 0,
  125972. 4,
  125973. };
  125974. static long _vq_lengthlist__8c0_s_p2_0[] = {
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0,
  126015. };
  126016. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126017. -1.5, -0.5, 0.5, 1.5,
  126018. };
  126019. static long _vq_quantmap__8c0_s_p2_0[] = {
  126020. 3, 1, 0, 2, 4,
  126021. };
  126022. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126023. _vq_quantthresh__8c0_s_p2_0,
  126024. _vq_quantmap__8c0_s_p2_0,
  126025. 5,
  126026. 5
  126027. };
  126028. static static_codebook _8c0_s_p2_0 = {
  126029. 4, 625,
  126030. _vq_lengthlist__8c0_s_p2_0,
  126031. 1, -533725184, 1611661312, 3, 0,
  126032. _vq_quantlist__8c0_s_p2_0,
  126033. NULL,
  126034. &_vq_auxt__8c0_s_p2_0,
  126035. NULL,
  126036. 0
  126037. };
  126038. static long _vq_quantlist__8c0_s_p3_0[] = {
  126039. 2,
  126040. 1,
  126041. 3,
  126042. 0,
  126043. 4,
  126044. };
  126045. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126046. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0,
  126086. };
  126087. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126088. -1.5, -0.5, 0.5, 1.5,
  126089. };
  126090. static long _vq_quantmap__8c0_s_p3_0[] = {
  126091. 3, 1, 0, 2, 4,
  126092. };
  126093. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126094. _vq_quantthresh__8c0_s_p3_0,
  126095. _vq_quantmap__8c0_s_p3_0,
  126096. 5,
  126097. 5
  126098. };
  126099. static static_codebook _8c0_s_p3_0 = {
  126100. 4, 625,
  126101. _vq_lengthlist__8c0_s_p3_0,
  126102. 1, -533725184, 1611661312, 3, 0,
  126103. _vq_quantlist__8c0_s_p3_0,
  126104. NULL,
  126105. &_vq_auxt__8c0_s_p3_0,
  126106. NULL,
  126107. 0
  126108. };
  126109. static long _vq_quantlist__8c0_s_p4_0[] = {
  126110. 4,
  126111. 3,
  126112. 5,
  126113. 2,
  126114. 6,
  126115. 1,
  126116. 7,
  126117. 0,
  126118. 8,
  126119. };
  126120. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126121. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126122. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126123. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126124. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126125. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0,
  126127. };
  126128. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126129. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126130. };
  126131. static long _vq_quantmap__8c0_s_p4_0[] = {
  126132. 7, 5, 3, 1, 0, 2, 4, 6,
  126133. 8,
  126134. };
  126135. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126136. _vq_quantthresh__8c0_s_p4_0,
  126137. _vq_quantmap__8c0_s_p4_0,
  126138. 9,
  126139. 9
  126140. };
  126141. static static_codebook _8c0_s_p4_0 = {
  126142. 2, 81,
  126143. _vq_lengthlist__8c0_s_p4_0,
  126144. 1, -531628032, 1611661312, 4, 0,
  126145. _vq_quantlist__8c0_s_p4_0,
  126146. NULL,
  126147. &_vq_auxt__8c0_s_p4_0,
  126148. NULL,
  126149. 0
  126150. };
  126151. static long _vq_quantlist__8c0_s_p5_0[] = {
  126152. 4,
  126153. 3,
  126154. 5,
  126155. 2,
  126156. 6,
  126157. 1,
  126158. 7,
  126159. 0,
  126160. 8,
  126161. };
  126162. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126163. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126164. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126165. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126166. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126167. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126168. 10,
  126169. };
  126170. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126171. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126172. };
  126173. static long _vq_quantmap__8c0_s_p5_0[] = {
  126174. 7, 5, 3, 1, 0, 2, 4, 6,
  126175. 8,
  126176. };
  126177. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126178. _vq_quantthresh__8c0_s_p5_0,
  126179. _vq_quantmap__8c0_s_p5_0,
  126180. 9,
  126181. 9
  126182. };
  126183. static static_codebook _8c0_s_p5_0 = {
  126184. 2, 81,
  126185. _vq_lengthlist__8c0_s_p5_0,
  126186. 1, -531628032, 1611661312, 4, 0,
  126187. _vq_quantlist__8c0_s_p5_0,
  126188. NULL,
  126189. &_vq_auxt__8c0_s_p5_0,
  126190. NULL,
  126191. 0
  126192. };
  126193. static long _vq_quantlist__8c0_s_p6_0[] = {
  126194. 8,
  126195. 7,
  126196. 9,
  126197. 6,
  126198. 10,
  126199. 5,
  126200. 11,
  126201. 4,
  126202. 12,
  126203. 3,
  126204. 13,
  126205. 2,
  126206. 14,
  126207. 1,
  126208. 15,
  126209. 0,
  126210. 16,
  126211. };
  126212. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126213. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126214. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126215. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126216. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126217. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126218. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126219. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126220. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126221. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126222. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126223. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126224. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126225. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126226. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126227. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126228. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126229. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126231. 14,
  126232. };
  126233. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126234. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126235. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126236. };
  126237. static long _vq_quantmap__8c0_s_p6_0[] = {
  126238. 15, 13, 11, 9, 7, 5, 3, 1,
  126239. 0, 2, 4, 6, 8, 10, 12, 14,
  126240. 16,
  126241. };
  126242. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126243. _vq_quantthresh__8c0_s_p6_0,
  126244. _vq_quantmap__8c0_s_p6_0,
  126245. 17,
  126246. 17
  126247. };
  126248. static static_codebook _8c0_s_p6_0 = {
  126249. 2, 289,
  126250. _vq_lengthlist__8c0_s_p6_0,
  126251. 1, -529530880, 1611661312, 5, 0,
  126252. _vq_quantlist__8c0_s_p6_0,
  126253. NULL,
  126254. &_vq_auxt__8c0_s_p6_0,
  126255. NULL,
  126256. 0
  126257. };
  126258. static long _vq_quantlist__8c0_s_p7_0[] = {
  126259. 1,
  126260. 0,
  126261. 2,
  126262. };
  126263. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126264. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126265. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126266. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126267. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126268. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126269. 10,
  126270. };
  126271. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126272. -5.5, 5.5,
  126273. };
  126274. static long _vq_quantmap__8c0_s_p7_0[] = {
  126275. 1, 0, 2,
  126276. };
  126277. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126278. _vq_quantthresh__8c0_s_p7_0,
  126279. _vq_quantmap__8c0_s_p7_0,
  126280. 3,
  126281. 3
  126282. };
  126283. static static_codebook _8c0_s_p7_0 = {
  126284. 4, 81,
  126285. _vq_lengthlist__8c0_s_p7_0,
  126286. 1, -529137664, 1618345984, 2, 0,
  126287. _vq_quantlist__8c0_s_p7_0,
  126288. NULL,
  126289. &_vq_auxt__8c0_s_p7_0,
  126290. NULL,
  126291. 0
  126292. };
  126293. static long _vq_quantlist__8c0_s_p7_1[] = {
  126294. 5,
  126295. 4,
  126296. 6,
  126297. 3,
  126298. 7,
  126299. 2,
  126300. 8,
  126301. 1,
  126302. 9,
  126303. 0,
  126304. 10,
  126305. };
  126306. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126307. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126308. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126309. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126310. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126311. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126312. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126313. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126314. 10,10,10, 9, 9, 9,10,10,10,
  126315. };
  126316. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126317. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126318. 3.5, 4.5,
  126319. };
  126320. static long _vq_quantmap__8c0_s_p7_1[] = {
  126321. 9, 7, 5, 3, 1, 0, 2, 4,
  126322. 6, 8, 10,
  126323. };
  126324. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126325. _vq_quantthresh__8c0_s_p7_1,
  126326. _vq_quantmap__8c0_s_p7_1,
  126327. 11,
  126328. 11
  126329. };
  126330. static static_codebook _8c0_s_p7_1 = {
  126331. 2, 121,
  126332. _vq_lengthlist__8c0_s_p7_1,
  126333. 1, -531365888, 1611661312, 4, 0,
  126334. _vq_quantlist__8c0_s_p7_1,
  126335. NULL,
  126336. &_vq_auxt__8c0_s_p7_1,
  126337. NULL,
  126338. 0
  126339. };
  126340. static long _vq_quantlist__8c0_s_p8_0[] = {
  126341. 6,
  126342. 5,
  126343. 7,
  126344. 4,
  126345. 8,
  126346. 3,
  126347. 9,
  126348. 2,
  126349. 10,
  126350. 1,
  126351. 11,
  126352. 0,
  126353. 12,
  126354. };
  126355. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126356. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126357. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126358. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126359. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126360. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126361. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126362. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126363. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126364. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126365. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126366. 0, 0,13,13,11,13,13,11,12,
  126367. };
  126368. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126369. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126370. 12.5, 17.5, 22.5, 27.5,
  126371. };
  126372. static long _vq_quantmap__8c0_s_p8_0[] = {
  126373. 11, 9, 7, 5, 3, 1, 0, 2,
  126374. 4, 6, 8, 10, 12,
  126375. };
  126376. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126377. _vq_quantthresh__8c0_s_p8_0,
  126378. _vq_quantmap__8c0_s_p8_0,
  126379. 13,
  126380. 13
  126381. };
  126382. static static_codebook _8c0_s_p8_0 = {
  126383. 2, 169,
  126384. _vq_lengthlist__8c0_s_p8_0,
  126385. 1, -526516224, 1616117760, 4, 0,
  126386. _vq_quantlist__8c0_s_p8_0,
  126387. NULL,
  126388. &_vq_auxt__8c0_s_p8_0,
  126389. NULL,
  126390. 0
  126391. };
  126392. static long _vq_quantlist__8c0_s_p8_1[] = {
  126393. 2,
  126394. 1,
  126395. 3,
  126396. 0,
  126397. 4,
  126398. };
  126399. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126400. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126401. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126402. };
  126403. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126404. -1.5, -0.5, 0.5, 1.5,
  126405. };
  126406. static long _vq_quantmap__8c0_s_p8_1[] = {
  126407. 3, 1, 0, 2, 4,
  126408. };
  126409. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126410. _vq_quantthresh__8c0_s_p8_1,
  126411. _vq_quantmap__8c0_s_p8_1,
  126412. 5,
  126413. 5
  126414. };
  126415. static static_codebook _8c0_s_p8_1 = {
  126416. 2, 25,
  126417. _vq_lengthlist__8c0_s_p8_1,
  126418. 1, -533725184, 1611661312, 3, 0,
  126419. _vq_quantlist__8c0_s_p8_1,
  126420. NULL,
  126421. &_vq_auxt__8c0_s_p8_1,
  126422. NULL,
  126423. 0
  126424. };
  126425. static long _vq_quantlist__8c0_s_p9_0[] = {
  126426. 1,
  126427. 0,
  126428. 2,
  126429. };
  126430. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126431. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126432. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126433. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126434. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126435. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126436. 7,
  126437. };
  126438. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126439. -157.5, 157.5,
  126440. };
  126441. static long _vq_quantmap__8c0_s_p9_0[] = {
  126442. 1, 0, 2,
  126443. };
  126444. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126445. _vq_quantthresh__8c0_s_p9_0,
  126446. _vq_quantmap__8c0_s_p9_0,
  126447. 3,
  126448. 3
  126449. };
  126450. static static_codebook _8c0_s_p9_0 = {
  126451. 4, 81,
  126452. _vq_lengthlist__8c0_s_p9_0,
  126453. 1, -518803456, 1628680192, 2, 0,
  126454. _vq_quantlist__8c0_s_p9_0,
  126455. NULL,
  126456. &_vq_auxt__8c0_s_p9_0,
  126457. NULL,
  126458. 0
  126459. };
  126460. static long _vq_quantlist__8c0_s_p9_1[] = {
  126461. 7,
  126462. 6,
  126463. 8,
  126464. 5,
  126465. 9,
  126466. 4,
  126467. 10,
  126468. 3,
  126469. 11,
  126470. 2,
  126471. 12,
  126472. 1,
  126473. 13,
  126474. 0,
  126475. 14,
  126476. };
  126477. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126478. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126479. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126480. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126481. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126482. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126483. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126487. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126492. 11,
  126493. };
  126494. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126495. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126496. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126497. };
  126498. static long _vq_quantmap__8c0_s_p9_1[] = {
  126499. 13, 11, 9, 7, 5, 3, 1, 0,
  126500. 2, 4, 6, 8, 10, 12, 14,
  126501. };
  126502. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126503. _vq_quantthresh__8c0_s_p9_1,
  126504. _vq_quantmap__8c0_s_p9_1,
  126505. 15,
  126506. 15
  126507. };
  126508. static static_codebook _8c0_s_p9_1 = {
  126509. 2, 225,
  126510. _vq_lengthlist__8c0_s_p9_1,
  126511. 1, -520986624, 1620377600, 4, 0,
  126512. _vq_quantlist__8c0_s_p9_1,
  126513. NULL,
  126514. &_vq_auxt__8c0_s_p9_1,
  126515. NULL,
  126516. 0
  126517. };
  126518. static long _vq_quantlist__8c0_s_p9_2[] = {
  126519. 10,
  126520. 9,
  126521. 11,
  126522. 8,
  126523. 12,
  126524. 7,
  126525. 13,
  126526. 6,
  126527. 14,
  126528. 5,
  126529. 15,
  126530. 4,
  126531. 16,
  126532. 3,
  126533. 17,
  126534. 2,
  126535. 18,
  126536. 1,
  126537. 19,
  126538. 0,
  126539. 20,
  126540. };
  126541. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126542. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126543. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126544. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126545. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126546. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126547. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126548. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126549. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126550. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126551. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126552. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126553. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126554. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126555. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126556. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126557. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126558. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126559. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126560. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126561. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126562. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126563. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126564. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126565. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126566. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126567. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126568. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126569. 10,11, 9,11,10, 9,10, 9,10,
  126570. };
  126571. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126572. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126573. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126574. 6.5, 7.5, 8.5, 9.5,
  126575. };
  126576. static long _vq_quantmap__8c0_s_p9_2[] = {
  126577. 19, 17, 15, 13, 11, 9, 7, 5,
  126578. 3, 1, 0, 2, 4, 6, 8, 10,
  126579. 12, 14, 16, 18, 20,
  126580. };
  126581. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126582. _vq_quantthresh__8c0_s_p9_2,
  126583. _vq_quantmap__8c0_s_p9_2,
  126584. 21,
  126585. 21
  126586. };
  126587. static static_codebook _8c0_s_p9_2 = {
  126588. 2, 441,
  126589. _vq_lengthlist__8c0_s_p9_2,
  126590. 1, -529268736, 1611661312, 5, 0,
  126591. _vq_quantlist__8c0_s_p9_2,
  126592. NULL,
  126593. &_vq_auxt__8c0_s_p9_2,
  126594. NULL,
  126595. 0
  126596. };
  126597. static long _huff_lengthlist__8c0_s_single[] = {
  126598. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126599. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126600. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126601. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126602. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126603. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126604. 17,16,17,17,
  126605. };
  126606. static static_codebook _huff_book__8c0_s_single = {
  126607. 2, 100,
  126608. _huff_lengthlist__8c0_s_single,
  126609. 0, 0, 0, 0, 0,
  126610. NULL,
  126611. NULL,
  126612. NULL,
  126613. NULL,
  126614. 0
  126615. };
  126616. static long _vq_quantlist__8c1_s_p1_0[] = {
  126617. 1,
  126618. 0,
  126619. 2,
  126620. };
  126621. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126622. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126623. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126628. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126633. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  126668. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  126673. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  126678. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126714. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126719. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126724. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0,
  127033. };
  127034. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127035. -0.5, 0.5,
  127036. };
  127037. static long _vq_quantmap__8c1_s_p1_0[] = {
  127038. 1, 0, 2,
  127039. };
  127040. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127041. _vq_quantthresh__8c1_s_p1_0,
  127042. _vq_quantmap__8c1_s_p1_0,
  127043. 3,
  127044. 3
  127045. };
  127046. static static_codebook _8c1_s_p1_0 = {
  127047. 8, 6561,
  127048. _vq_lengthlist__8c1_s_p1_0,
  127049. 1, -535822336, 1611661312, 2, 0,
  127050. _vq_quantlist__8c1_s_p1_0,
  127051. NULL,
  127052. &_vq_auxt__8c1_s_p1_0,
  127053. NULL,
  127054. 0
  127055. };
  127056. static long _vq_quantlist__8c1_s_p2_0[] = {
  127057. 2,
  127058. 1,
  127059. 3,
  127060. 0,
  127061. 4,
  127062. };
  127063. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0,
  127104. };
  127105. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127106. -1.5, -0.5, 0.5, 1.5,
  127107. };
  127108. static long _vq_quantmap__8c1_s_p2_0[] = {
  127109. 3, 1, 0, 2, 4,
  127110. };
  127111. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127112. _vq_quantthresh__8c1_s_p2_0,
  127113. _vq_quantmap__8c1_s_p2_0,
  127114. 5,
  127115. 5
  127116. };
  127117. static static_codebook _8c1_s_p2_0 = {
  127118. 4, 625,
  127119. _vq_lengthlist__8c1_s_p2_0,
  127120. 1, -533725184, 1611661312, 3, 0,
  127121. _vq_quantlist__8c1_s_p2_0,
  127122. NULL,
  127123. &_vq_auxt__8c1_s_p2_0,
  127124. NULL,
  127125. 0
  127126. };
  127127. static long _vq_quantlist__8c1_s_p3_0[] = {
  127128. 2,
  127129. 1,
  127130. 3,
  127131. 0,
  127132. 4,
  127133. };
  127134. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127135. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0,
  127175. };
  127176. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127177. -1.5, -0.5, 0.5, 1.5,
  127178. };
  127179. static long _vq_quantmap__8c1_s_p3_0[] = {
  127180. 3, 1, 0, 2, 4,
  127181. };
  127182. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127183. _vq_quantthresh__8c1_s_p3_0,
  127184. _vq_quantmap__8c1_s_p3_0,
  127185. 5,
  127186. 5
  127187. };
  127188. static static_codebook _8c1_s_p3_0 = {
  127189. 4, 625,
  127190. _vq_lengthlist__8c1_s_p3_0,
  127191. 1, -533725184, 1611661312, 3, 0,
  127192. _vq_quantlist__8c1_s_p3_0,
  127193. NULL,
  127194. &_vq_auxt__8c1_s_p3_0,
  127195. NULL,
  127196. 0
  127197. };
  127198. static long _vq_quantlist__8c1_s_p4_0[] = {
  127199. 4,
  127200. 3,
  127201. 5,
  127202. 2,
  127203. 6,
  127204. 1,
  127205. 7,
  127206. 0,
  127207. 8,
  127208. };
  127209. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127210. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127211. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127212. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127213. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127214. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0,
  127216. };
  127217. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127218. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127219. };
  127220. static long _vq_quantmap__8c1_s_p4_0[] = {
  127221. 7, 5, 3, 1, 0, 2, 4, 6,
  127222. 8,
  127223. };
  127224. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127225. _vq_quantthresh__8c1_s_p4_0,
  127226. _vq_quantmap__8c1_s_p4_0,
  127227. 9,
  127228. 9
  127229. };
  127230. static static_codebook _8c1_s_p4_0 = {
  127231. 2, 81,
  127232. _vq_lengthlist__8c1_s_p4_0,
  127233. 1, -531628032, 1611661312, 4, 0,
  127234. _vq_quantlist__8c1_s_p4_0,
  127235. NULL,
  127236. &_vq_auxt__8c1_s_p4_0,
  127237. NULL,
  127238. 0
  127239. };
  127240. static long _vq_quantlist__8c1_s_p5_0[] = {
  127241. 4,
  127242. 3,
  127243. 5,
  127244. 2,
  127245. 6,
  127246. 1,
  127247. 7,
  127248. 0,
  127249. 8,
  127250. };
  127251. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127252. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127253. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127254. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127255. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127256. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127257. 10,
  127258. };
  127259. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127260. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127261. };
  127262. static long _vq_quantmap__8c1_s_p5_0[] = {
  127263. 7, 5, 3, 1, 0, 2, 4, 6,
  127264. 8,
  127265. };
  127266. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127267. _vq_quantthresh__8c1_s_p5_0,
  127268. _vq_quantmap__8c1_s_p5_0,
  127269. 9,
  127270. 9
  127271. };
  127272. static static_codebook _8c1_s_p5_0 = {
  127273. 2, 81,
  127274. _vq_lengthlist__8c1_s_p5_0,
  127275. 1, -531628032, 1611661312, 4, 0,
  127276. _vq_quantlist__8c1_s_p5_0,
  127277. NULL,
  127278. &_vq_auxt__8c1_s_p5_0,
  127279. NULL,
  127280. 0
  127281. };
  127282. static long _vq_quantlist__8c1_s_p6_0[] = {
  127283. 8,
  127284. 7,
  127285. 9,
  127286. 6,
  127287. 10,
  127288. 5,
  127289. 11,
  127290. 4,
  127291. 12,
  127292. 3,
  127293. 13,
  127294. 2,
  127295. 14,
  127296. 1,
  127297. 15,
  127298. 0,
  127299. 16,
  127300. };
  127301. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127302. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127303. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127304. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127305. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127306. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127307. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127308. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127309. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127310. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127311. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127312. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127313. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127314. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127315. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127316. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127317. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127318. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127320. 14,
  127321. };
  127322. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127323. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127324. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127325. };
  127326. static long _vq_quantmap__8c1_s_p6_0[] = {
  127327. 15, 13, 11, 9, 7, 5, 3, 1,
  127328. 0, 2, 4, 6, 8, 10, 12, 14,
  127329. 16,
  127330. };
  127331. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127332. _vq_quantthresh__8c1_s_p6_0,
  127333. _vq_quantmap__8c1_s_p6_0,
  127334. 17,
  127335. 17
  127336. };
  127337. static static_codebook _8c1_s_p6_0 = {
  127338. 2, 289,
  127339. _vq_lengthlist__8c1_s_p6_0,
  127340. 1, -529530880, 1611661312, 5, 0,
  127341. _vq_quantlist__8c1_s_p6_0,
  127342. NULL,
  127343. &_vq_auxt__8c1_s_p6_0,
  127344. NULL,
  127345. 0
  127346. };
  127347. static long _vq_quantlist__8c1_s_p7_0[] = {
  127348. 1,
  127349. 0,
  127350. 2,
  127351. };
  127352. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127353. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127354. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127355. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127356. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127357. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127358. 9,
  127359. };
  127360. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127361. -5.5, 5.5,
  127362. };
  127363. static long _vq_quantmap__8c1_s_p7_0[] = {
  127364. 1, 0, 2,
  127365. };
  127366. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127367. _vq_quantthresh__8c1_s_p7_0,
  127368. _vq_quantmap__8c1_s_p7_0,
  127369. 3,
  127370. 3
  127371. };
  127372. static static_codebook _8c1_s_p7_0 = {
  127373. 4, 81,
  127374. _vq_lengthlist__8c1_s_p7_0,
  127375. 1, -529137664, 1618345984, 2, 0,
  127376. _vq_quantlist__8c1_s_p7_0,
  127377. NULL,
  127378. &_vq_auxt__8c1_s_p7_0,
  127379. NULL,
  127380. 0
  127381. };
  127382. static long _vq_quantlist__8c1_s_p7_1[] = {
  127383. 5,
  127384. 4,
  127385. 6,
  127386. 3,
  127387. 7,
  127388. 2,
  127389. 8,
  127390. 1,
  127391. 9,
  127392. 0,
  127393. 10,
  127394. };
  127395. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127396. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127397. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127398. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127399. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127400. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127401. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127402. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127403. 10,10,10, 8, 8, 8, 8, 8, 8,
  127404. };
  127405. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127406. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127407. 3.5, 4.5,
  127408. };
  127409. static long _vq_quantmap__8c1_s_p7_1[] = {
  127410. 9, 7, 5, 3, 1, 0, 2, 4,
  127411. 6, 8, 10,
  127412. };
  127413. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127414. _vq_quantthresh__8c1_s_p7_1,
  127415. _vq_quantmap__8c1_s_p7_1,
  127416. 11,
  127417. 11
  127418. };
  127419. static static_codebook _8c1_s_p7_1 = {
  127420. 2, 121,
  127421. _vq_lengthlist__8c1_s_p7_1,
  127422. 1, -531365888, 1611661312, 4, 0,
  127423. _vq_quantlist__8c1_s_p7_1,
  127424. NULL,
  127425. &_vq_auxt__8c1_s_p7_1,
  127426. NULL,
  127427. 0
  127428. };
  127429. static long _vq_quantlist__8c1_s_p8_0[] = {
  127430. 6,
  127431. 5,
  127432. 7,
  127433. 4,
  127434. 8,
  127435. 3,
  127436. 9,
  127437. 2,
  127438. 10,
  127439. 1,
  127440. 11,
  127441. 0,
  127442. 12,
  127443. };
  127444. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127445. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127446. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127447. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127448. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127449. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127450. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127451. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127452. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127453. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127454. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127455. 0,12,12,11,10,12,11,13,12,
  127456. };
  127457. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127458. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127459. 12.5, 17.5, 22.5, 27.5,
  127460. };
  127461. static long _vq_quantmap__8c1_s_p8_0[] = {
  127462. 11, 9, 7, 5, 3, 1, 0, 2,
  127463. 4, 6, 8, 10, 12,
  127464. };
  127465. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127466. _vq_quantthresh__8c1_s_p8_0,
  127467. _vq_quantmap__8c1_s_p8_0,
  127468. 13,
  127469. 13
  127470. };
  127471. static static_codebook _8c1_s_p8_0 = {
  127472. 2, 169,
  127473. _vq_lengthlist__8c1_s_p8_0,
  127474. 1, -526516224, 1616117760, 4, 0,
  127475. _vq_quantlist__8c1_s_p8_0,
  127476. NULL,
  127477. &_vq_auxt__8c1_s_p8_0,
  127478. NULL,
  127479. 0
  127480. };
  127481. static long _vq_quantlist__8c1_s_p8_1[] = {
  127482. 2,
  127483. 1,
  127484. 3,
  127485. 0,
  127486. 4,
  127487. };
  127488. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127489. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127490. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127491. };
  127492. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127493. -1.5, -0.5, 0.5, 1.5,
  127494. };
  127495. static long _vq_quantmap__8c1_s_p8_1[] = {
  127496. 3, 1, 0, 2, 4,
  127497. };
  127498. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127499. _vq_quantthresh__8c1_s_p8_1,
  127500. _vq_quantmap__8c1_s_p8_1,
  127501. 5,
  127502. 5
  127503. };
  127504. static static_codebook _8c1_s_p8_1 = {
  127505. 2, 25,
  127506. _vq_lengthlist__8c1_s_p8_1,
  127507. 1, -533725184, 1611661312, 3, 0,
  127508. _vq_quantlist__8c1_s_p8_1,
  127509. NULL,
  127510. &_vq_auxt__8c1_s_p8_1,
  127511. NULL,
  127512. 0
  127513. };
  127514. static long _vq_quantlist__8c1_s_p9_0[] = {
  127515. 6,
  127516. 5,
  127517. 7,
  127518. 4,
  127519. 8,
  127520. 3,
  127521. 9,
  127522. 2,
  127523. 10,
  127524. 1,
  127525. 11,
  127526. 0,
  127527. 12,
  127528. };
  127529. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127530. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127531. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127532. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127533. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127534. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127535. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127536. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127537. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127538. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127539. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127540. 10,10,10,10,10, 9, 9, 9, 9,
  127541. };
  127542. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127543. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127544. 787.5, 1102.5, 1417.5, 1732.5,
  127545. };
  127546. static long _vq_quantmap__8c1_s_p9_0[] = {
  127547. 11, 9, 7, 5, 3, 1, 0, 2,
  127548. 4, 6, 8, 10, 12,
  127549. };
  127550. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127551. _vq_quantthresh__8c1_s_p9_0,
  127552. _vq_quantmap__8c1_s_p9_0,
  127553. 13,
  127554. 13
  127555. };
  127556. static static_codebook _8c1_s_p9_0 = {
  127557. 2, 169,
  127558. _vq_lengthlist__8c1_s_p9_0,
  127559. 1, -513964032, 1628680192, 4, 0,
  127560. _vq_quantlist__8c1_s_p9_0,
  127561. NULL,
  127562. &_vq_auxt__8c1_s_p9_0,
  127563. NULL,
  127564. 0
  127565. };
  127566. static long _vq_quantlist__8c1_s_p9_1[] = {
  127567. 7,
  127568. 6,
  127569. 8,
  127570. 5,
  127571. 9,
  127572. 4,
  127573. 10,
  127574. 3,
  127575. 11,
  127576. 2,
  127577. 12,
  127578. 1,
  127579. 13,
  127580. 0,
  127581. 14,
  127582. };
  127583. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127584. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127585. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127586. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127587. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127588. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127589. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127590. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127591. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127592. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127593. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127594. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127595. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127596. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127597. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127598. 15,
  127599. };
  127600. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127601. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127602. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127603. };
  127604. static long _vq_quantmap__8c1_s_p9_1[] = {
  127605. 13, 11, 9, 7, 5, 3, 1, 0,
  127606. 2, 4, 6, 8, 10, 12, 14,
  127607. };
  127608. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127609. _vq_quantthresh__8c1_s_p9_1,
  127610. _vq_quantmap__8c1_s_p9_1,
  127611. 15,
  127612. 15
  127613. };
  127614. static static_codebook _8c1_s_p9_1 = {
  127615. 2, 225,
  127616. _vq_lengthlist__8c1_s_p9_1,
  127617. 1, -520986624, 1620377600, 4, 0,
  127618. _vq_quantlist__8c1_s_p9_1,
  127619. NULL,
  127620. &_vq_auxt__8c1_s_p9_1,
  127621. NULL,
  127622. 0
  127623. };
  127624. static long _vq_quantlist__8c1_s_p9_2[] = {
  127625. 10,
  127626. 9,
  127627. 11,
  127628. 8,
  127629. 12,
  127630. 7,
  127631. 13,
  127632. 6,
  127633. 14,
  127634. 5,
  127635. 15,
  127636. 4,
  127637. 16,
  127638. 3,
  127639. 17,
  127640. 2,
  127641. 18,
  127642. 1,
  127643. 19,
  127644. 0,
  127645. 20,
  127646. };
  127647. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127648. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127649. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127650. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127651. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127652. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127653. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127654. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127655. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127656. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127657. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127658. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127659. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127660. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127661. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127662. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127663. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127664. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127665. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127666. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127667. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127668. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127669. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127670. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127671. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127672. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127673. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127674. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127675. 10,10,10,10,10,10,10,10,10,
  127676. };
  127677. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127678. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127679. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127680. 6.5, 7.5, 8.5, 9.5,
  127681. };
  127682. static long _vq_quantmap__8c1_s_p9_2[] = {
  127683. 19, 17, 15, 13, 11, 9, 7, 5,
  127684. 3, 1, 0, 2, 4, 6, 8, 10,
  127685. 12, 14, 16, 18, 20,
  127686. };
  127687. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127688. _vq_quantthresh__8c1_s_p9_2,
  127689. _vq_quantmap__8c1_s_p9_2,
  127690. 21,
  127691. 21
  127692. };
  127693. static static_codebook _8c1_s_p9_2 = {
  127694. 2, 441,
  127695. _vq_lengthlist__8c1_s_p9_2,
  127696. 1, -529268736, 1611661312, 5, 0,
  127697. _vq_quantlist__8c1_s_p9_2,
  127698. NULL,
  127699. &_vq_auxt__8c1_s_p9_2,
  127700. NULL,
  127701. 0
  127702. };
  127703. static long _huff_lengthlist__8c1_s_single[] = {
  127704. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127705. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127706. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127707. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127708. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127709. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127710. 9, 7, 7, 8,
  127711. };
  127712. static static_codebook _huff_book__8c1_s_single = {
  127713. 2, 100,
  127714. _huff_lengthlist__8c1_s_single,
  127715. 0, 0, 0, 0, 0,
  127716. NULL,
  127717. NULL,
  127718. NULL,
  127719. NULL,
  127720. 0
  127721. };
  127722. static long _huff_lengthlist__44c2_s_long[] = {
  127723. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127724. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127725. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127726. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127727. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127728. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127729. 10, 8, 8, 9,
  127730. };
  127731. static static_codebook _huff_book__44c2_s_long = {
  127732. 2, 100,
  127733. _huff_lengthlist__44c2_s_long,
  127734. 0, 0, 0, 0, 0,
  127735. NULL,
  127736. NULL,
  127737. NULL,
  127738. NULL,
  127739. 0
  127740. };
  127741. static long _vq_quantlist__44c2_s_p1_0[] = {
  127742. 1,
  127743. 0,
  127744. 2,
  127745. };
  127746. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127747. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127748. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127753. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127758. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  127793. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  127798. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  127803. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127839. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127844. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127849. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0,
  128158. };
  128159. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128160. -0.5, 0.5,
  128161. };
  128162. static long _vq_quantmap__44c2_s_p1_0[] = {
  128163. 1, 0, 2,
  128164. };
  128165. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128166. _vq_quantthresh__44c2_s_p1_0,
  128167. _vq_quantmap__44c2_s_p1_0,
  128168. 3,
  128169. 3
  128170. };
  128171. static static_codebook _44c2_s_p1_0 = {
  128172. 8, 6561,
  128173. _vq_lengthlist__44c2_s_p1_0,
  128174. 1, -535822336, 1611661312, 2, 0,
  128175. _vq_quantlist__44c2_s_p1_0,
  128176. NULL,
  128177. &_vq_auxt__44c2_s_p1_0,
  128178. NULL,
  128179. 0
  128180. };
  128181. static long _vq_quantlist__44c2_s_p2_0[] = {
  128182. 2,
  128183. 1,
  128184. 3,
  128185. 0,
  128186. 4,
  128187. };
  128188. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128189. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128190. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128191. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128192. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128193. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128199. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128200. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128201. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128207. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128208. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128215. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128216. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0,
  128229. };
  128230. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128231. -1.5, -0.5, 0.5, 1.5,
  128232. };
  128233. static long _vq_quantmap__44c2_s_p2_0[] = {
  128234. 3, 1, 0, 2, 4,
  128235. };
  128236. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128237. _vq_quantthresh__44c2_s_p2_0,
  128238. _vq_quantmap__44c2_s_p2_0,
  128239. 5,
  128240. 5
  128241. };
  128242. static static_codebook _44c2_s_p2_0 = {
  128243. 4, 625,
  128244. _vq_lengthlist__44c2_s_p2_0,
  128245. 1, -533725184, 1611661312, 3, 0,
  128246. _vq_quantlist__44c2_s_p2_0,
  128247. NULL,
  128248. &_vq_auxt__44c2_s_p2_0,
  128249. NULL,
  128250. 0
  128251. };
  128252. static long _vq_quantlist__44c2_s_p3_0[] = {
  128253. 2,
  128254. 1,
  128255. 3,
  128256. 0,
  128257. 4,
  128258. };
  128259. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128260. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0,
  128300. };
  128301. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128302. -1.5, -0.5, 0.5, 1.5,
  128303. };
  128304. static long _vq_quantmap__44c2_s_p3_0[] = {
  128305. 3, 1, 0, 2, 4,
  128306. };
  128307. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128308. _vq_quantthresh__44c2_s_p3_0,
  128309. _vq_quantmap__44c2_s_p3_0,
  128310. 5,
  128311. 5
  128312. };
  128313. static static_codebook _44c2_s_p3_0 = {
  128314. 4, 625,
  128315. _vq_lengthlist__44c2_s_p3_0,
  128316. 1, -533725184, 1611661312, 3, 0,
  128317. _vq_quantlist__44c2_s_p3_0,
  128318. NULL,
  128319. &_vq_auxt__44c2_s_p3_0,
  128320. NULL,
  128321. 0
  128322. };
  128323. static long _vq_quantlist__44c2_s_p4_0[] = {
  128324. 4,
  128325. 3,
  128326. 5,
  128327. 2,
  128328. 6,
  128329. 1,
  128330. 7,
  128331. 0,
  128332. 8,
  128333. };
  128334. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128335. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128336. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128337. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128338. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128339. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0,
  128341. };
  128342. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128343. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128344. };
  128345. static long _vq_quantmap__44c2_s_p4_0[] = {
  128346. 7, 5, 3, 1, 0, 2, 4, 6,
  128347. 8,
  128348. };
  128349. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128350. _vq_quantthresh__44c2_s_p4_0,
  128351. _vq_quantmap__44c2_s_p4_0,
  128352. 9,
  128353. 9
  128354. };
  128355. static static_codebook _44c2_s_p4_0 = {
  128356. 2, 81,
  128357. _vq_lengthlist__44c2_s_p4_0,
  128358. 1, -531628032, 1611661312, 4, 0,
  128359. _vq_quantlist__44c2_s_p4_0,
  128360. NULL,
  128361. &_vq_auxt__44c2_s_p4_0,
  128362. NULL,
  128363. 0
  128364. };
  128365. static long _vq_quantlist__44c2_s_p5_0[] = {
  128366. 4,
  128367. 3,
  128368. 5,
  128369. 2,
  128370. 6,
  128371. 1,
  128372. 7,
  128373. 0,
  128374. 8,
  128375. };
  128376. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128377. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128378. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128379. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128380. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128381. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128382. 11,
  128383. };
  128384. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128385. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128386. };
  128387. static long _vq_quantmap__44c2_s_p5_0[] = {
  128388. 7, 5, 3, 1, 0, 2, 4, 6,
  128389. 8,
  128390. };
  128391. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128392. _vq_quantthresh__44c2_s_p5_0,
  128393. _vq_quantmap__44c2_s_p5_0,
  128394. 9,
  128395. 9
  128396. };
  128397. static static_codebook _44c2_s_p5_0 = {
  128398. 2, 81,
  128399. _vq_lengthlist__44c2_s_p5_0,
  128400. 1, -531628032, 1611661312, 4, 0,
  128401. _vq_quantlist__44c2_s_p5_0,
  128402. NULL,
  128403. &_vq_auxt__44c2_s_p5_0,
  128404. NULL,
  128405. 0
  128406. };
  128407. static long _vq_quantlist__44c2_s_p6_0[] = {
  128408. 8,
  128409. 7,
  128410. 9,
  128411. 6,
  128412. 10,
  128413. 5,
  128414. 11,
  128415. 4,
  128416. 12,
  128417. 3,
  128418. 13,
  128419. 2,
  128420. 14,
  128421. 1,
  128422. 15,
  128423. 0,
  128424. 16,
  128425. };
  128426. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128427. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128428. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128429. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128430. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128431. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128432. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128433. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128434. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128435. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128436. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128437. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128438. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128439. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128440. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128441. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128442. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128443. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128445. 14,
  128446. };
  128447. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128448. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128449. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128450. };
  128451. static long _vq_quantmap__44c2_s_p6_0[] = {
  128452. 15, 13, 11, 9, 7, 5, 3, 1,
  128453. 0, 2, 4, 6, 8, 10, 12, 14,
  128454. 16,
  128455. };
  128456. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128457. _vq_quantthresh__44c2_s_p6_0,
  128458. _vq_quantmap__44c2_s_p6_0,
  128459. 17,
  128460. 17
  128461. };
  128462. static static_codebook _44c2_s_p6_0 = {
  128463. 2, 289,
  128464. _vq_lengthlist__44c2_s_p6_0,
  128465. 1, -529530880, 1611661312, 5, 0,
  128466. _vq_quantlist__44c2_s_p6_0,
  128467. NULL,
  128468. &_vq_auxt__44c2_s_p6_0,
  128469. NULL,
  128470. 0
  128471. };
  128472. static long _vq_quantlist__44c2_s_p7_0[] = {
  128473. 1,
  128474. 0,
  128475. 2,
  128476. };
  128477. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128478. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128479. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128480. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128481. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128482. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128483. 11,
  128484. };
  128485. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128486. -5.5, 5.5,
  128487. };
  128488. static long _vq_quantmap__44c2_s_p7_0[] = {
  128489. 1, 0, 2,
  128490. };
  128491. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128492. _vq_quantthresh__44c2_s_p7_0,
  128493. _vq_quantmap__44c2_s_p7_0,
  128494. 3,
  128495. 3
  128496. };
  128497. static static_codebook _44c2_s_p7_0 = {
  128498. 4, 81,
  128499. _vq_lengthlist__44c2_s_p7_0,
  128500. 1, -529137664, 1618345984, 2, 0,
  128501. _vq_quantlist__44c2_s_p7_0,
  128502. NULL,
  128503. &_vq_auxt__44c2_s_p7_0,
  128504. NULL,
  128505. 0
  128506. };
  128507. static long _vq_quantlist__44c2_s_p7_1[] = {
  128508. 5,
  128509. 4,
  128510. 6,
  128511. 3,
  128512. 7,
  128513. 2,
  128514. 8,
  128515. 1,
  128516. 9,
  128517. 0,
  128518. 10,
  128519. };
  128520. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128521. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128522. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128523. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128524. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128525. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128526. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128527. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128528. 10,10,10, 8, 8, 8, 8, 8, 8,
  128529. };
  128530. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128531. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128532. 3.5, 4.5,
  128533. };
  128534. static long _vq_quantmap__44c2_s_p7_1[] = {
  128535. 9, 7, 5, 3, 1, 0, 2, 4,
  128536. 6, 8, 10,
  128537. };
  128538. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128539. _vq_quantthresh__44c2_s_p7_1,
  128540. _vq_quantmap__44c2_s_p7_1,
  128541. 11,
  128542. 11
  128543. };
  128544. static static_codebook _44c2_s_p7_1 = {
  128545. 2, 121,
  128546. _vq_lengthlist__44c2_s_p7_1,
  128547. 1, -531365888, 1611661312, 4, 0,
  128548. _vq_quantlist__44c2_s_p7_1,
  128549. NULL,
  128550. &_vq_auxt__44c2_s_p7_1,
  128551. NULL,
  128552. 0
  128553. };
  128554. static long _vq_quantlist__44c2_s_p8_0[] = {
  128555. 6,
  128556. 5,
  128557. 7,
  128558. 4,
  128559. 8,
  128560. 3,
  128561. 9,
  128562. 2,
  128563. 10,
  128564. 1,
  128565. 11,
  128566. 0,
  128567. 12,
  128568. };
  128569. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128570. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128571. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128572. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128573. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128574. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128575. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128576. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128577. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128578. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128579. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128580. 0,12,12,12,12,13,12,14,14,
  128581. };
  128582. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128583. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128584. 12.5, 17.5, 22.5, 27.5,
  128585. };
  128586. static long _vq_quantmap__44c2_s_p8_0[] = {
  128587. 11, 9, 7, 5, 3, 1, 0, 2,
  128588. 4, 6, 8, 10, 12,
  128589. };
  128590. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128591. _vq_quantthresh__44c2_s_p8_0,
  128592. _vq_quantmap__44c2_s_p8_0,
  128593. 13,
  128594. 13
  128595. };
  128596. static static_codebook _44c2_s_p8_0 = {
  128597. 2, 169,
  128598. _vq_lengthlist__44c2_s_p8_0,
  128599. 1, -526516224, 1616117760, 4, 0,
  128600. _vq_quantlist__44c2_s_p8_0,
  128601. NULL,
  128602. &_vq_auxt__44c2_s_p8_0,
  128603. NULL,
  128604. 0
  128605. };
  128606. static long _vq_quantlist__44c2_s_p8_1[] = {
  128607. 2,
  128608. 1,
  128609. 3,
  128610. 0,
  128611. 4,
  128612. };
  128613. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128614. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128615. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128616. };
  128617. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128618. -1.5, -0.5, 0.5, 1.5,
  128619. };
  128620. static long _vq_quantmap__44c2_s_p8_1[] = {
  128621. 3, 1, 0, 2, 4,
  128622. };
  128623. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128624. _vq_quantthresh__44c2_s_p8_1,
  128625. _vq_quantmap__44c2_s_p8_1,
  128626. 5,
  128627. 5
  128628. };
  128629. static static_codebook _44c2_s_p8_1 = {
  128630. 2, 25,
  128631. _vq_lengthlist__44c2_s_p8_1,
  128632. 1, -533725184, 1611661312, 3, 0,
  128633. _vq_quantlist__44c2_s_p8_1,
  128634. NULL,
  128635. &_vq_auxt__44c2_s_p8_1,
  128636. NULL,
  128637. 0
  128638. };
  128639. static long _vq_quantlist__44c2_s_p9_0[] = {
  128640. 6,
  128641. 5,
  128642. 7,
  128643. 4,
  128644. 8,
  128645. 3,
  128646. 9,
  128647. 2,
  128648. 10,
  128649. 1,
  128650. 11,
  128651. 0,
  128652. 12,
  128653. };
  128654. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128655. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128656. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128657. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128658. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128659. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128660. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128661. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128662. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128663. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128664. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128665. 11,11,11,11,11,11,11,11,11,
  128666. };
  128667. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128668. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128669. 552.5, 773.5, 994.5, 1215.5,
  128670. };
  128671. static long _vq_quantmap__44c2_s_p9_0[] = {
  128672. 11, 9, 7, 5, 3, 1, 0, 2,
  128673. 4, 6, 8, 10, 12,
  128674. };
  128675. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128676. _vq_quantthresh__44c2_s_p9_0,
  128677. _vq_quantmap__44c2_s_p9_0,
  128678. 13,
  128679. 13
  128680. };
  128681. static static_codebook _44c2_s_p9_0 = {
  128682. 2, 169,
  128683. _vq_lengthlist__44c2_s_p9_0,
  128684. 1, -514541568, 1627103232, 4, 0,
  128685. _vq_quantlist__44c2_s_p9_0,
  128686. NULL,
  128687. &_vq_auxt__44c2_s_p9_0,
  128688. NULL,
  128689. 0
  128690. };
  128691. static long _vq_quantlist__44c2_s_p9_1[] = {
  128692. 6,
  128693. 5,
  128694. 7,
  128695. 4,
  128696. 8,
  128697. 3,
  128698. 9,
  128699. 2,
  128700. 10,
  128701. 1,
  128702. 11,
  128703. 0,
  128704. 12,
  128705. };
  128706. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128707. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128708. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128709. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128710. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128711. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128712. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128713. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128714. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128715. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128716. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128717. 17,13,12,12,10,13,11,14,14,
  128718. };
  128719. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128720. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128721. 42.5, 59.5, 76.5, 93.5,
  128722. };
  128723. static long _vq_quantmap__44c2_s_p9_1[] = {
  128724. 11, 9, 7, 5, 3, 1, 0, 2,
  128725. 4, 6, 8, 10, 12,
  128726. };
  128727. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128728. _vq_quantthresh__44c2_s_p9_1,
  128729. _vq_quantmap__44c2_s_p9_1,
  128730. 13,
  128731. 13
  128732. };
  128733. static static_codebook _44c2_s_p9_1 = {
  128734. 2, 169,
  128735. _vq_lengthlist__44c2_s_p9_1,
  128736. 1, -522616832, 1620115456, 4, 0,
  128737. _vq_quantlist__44c2_s_p9_1,
  128738. NULL,
  128739. &_vq_auxt__44c2_s_p9_1,
  128740. NULL,
  128741. 0
  128742. };
  128743. static long _vq_quantlist__44c2_s_p9_2[] = {
  128744. 8,
  128745. 7,
  128746. 9,
  128747. 6,
  128748. 10,
  128749. 5,
  128750. 11,
  128751. 4,
  128752. 12,
  128753. 3,
  128754. 13,
  128755. 2,
  128756. 14,
  128757. 1,
  128758. 15,
  128759. 0,
  128760. 16,
  128761. };
  128762. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128763. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128764. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128765. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128766. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128767. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128768. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128769. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128770. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128771. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128772. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128773. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128774. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128775. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128776. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128777. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128778. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128779. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128780. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128781. 10,
  128782. };
  128783. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128784. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128785. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128786. };
  128787. static long _vq_quantmap__44c2_s_p9_2[] = {
  128788. 15, 13, 11, 9, 7, 5, 3, 1,
  128789. 0, 2, 4, 6, 8, 10, 12, 14,
  128790. 16,
  128791. };
  128792. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128793. _vq_quantthresh__44c2_s_p9_2,
  128794. _vq_quantmap__44c2_s_p9_2,
  128795. 17,
  128796. 17
  128797. };
  128798. static static_codebook _44c2_s_p9_2 = {
  128799. 2, 289,
  128800. _vq_lengthlist__44c2_s_p9_2,
  128801. 1, -529530880, 1611661312, 5, 0,
  128802. _vq_quantlist__44c2_s_p9_2,
  128803. NULL,
  128804. &_vq_auxt__44c2_s_p9_2,
  128805. NULL,
  128806. 0
  128807. };
  128808. static long _huff_lengthlist__44c2_s_short[] = {
  128809. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128810. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128811. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128812. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128813. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128814. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128815. 6, 8, 9,12,
  128816. };
  128817. static static_codebook _huff_book__44c2_s_short = {
  128818. 2, 100,
  128819. _huff_lengthlist__44c2_s_short,
  128820. 0, 0, 0, 0, 0,
  128821. NULL,
  128822. NULL,
  128823. NULL,
  128824. NULL,
  128825. 0
  128826. };
  128827. static long _huff_lengthlist__44c3_s_long[] = {
  128828. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128829. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128830. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128831. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128832. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128833. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128834. 9, 8, 8, 8,
  128835. };
  128836. static static_codebook _huff_book__44c3_s_long = {
  128837. 2, 100,
  128838. _huff_lengthlist__44c3_s_long,
  128839. 0, 0, 0, 0, 0,
  128840. NULL,
  128841. NULL,
  128842. NULL,
  128843. NULL,
  128844. 0
  128845. };
  128846. static long _vq_quantlist__44c3_s_p1_0[] = {
  128847. 1,
  128848. 0,
  128849. 2,
  128850. };
  128851. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128852. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128853. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128858. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128863. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  128898. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  128903. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  128908. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128944. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128949. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128954. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0,
  129263. };
  129264. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129265. -0.5, 0.5,
  129266. };
  129267. static long _vq_quantmap__44c3_s_p1_0[] = {
  129268. 1, 0, 2,
  129269. };
  129270. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129271. _vq_quantthresh__44c3_s_p1_0,
  129272. _vq_quantmap__44c3_s_p1_0,
  129273. 3,
  129274. 3
  129275. };
  129276. static static_codebook _44c3_s_p1_0 = {
  129277. 8, 6561,
  129278. _vq_lengthlist__44c3_s_p1_0,
  129279. 1, -535822336, 1611661312, 2, 0,
  129280. _vq_quantlist__44c3_s_p1_0,
  129281. NULL,
  129282. &_vq_auxt__44c3_s_p1_0,
  129283. NULL,
  129284. 0
  129285. };
  129286. static long _vq_quantlist__44c3_s_p2_0[] = {
  129287. 2,
  129288. 1,
  129289. 3,
  129290. 0,
  129291. 4,
  129292. };
  129293. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129294. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129295. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129296. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129297. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129298. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129304. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129305. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129306. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129312. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129313. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129320. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129321. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0,
  129334. };
  129335. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129336. -1.5, -0.5, 0.5, 1.5,
  129337. };
  129338. static long _vq_quantmap__44c3_s_p2_0[] = {
  129339. 3, 1, 0, 2, 4,
  129340. };
  129341. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129342. _vq_quantthresh__44c3_s_p2_0,
  129343. _vq_quantmap__44c3_s_p2_0,
  129344. 5,
  129345. 5
  129346. };
  129347. static static_codebook _44c3_s_p2_0 = {
  129348. 4, 625,
  129349. _vq_lengthlist__44c3_s_p2_0,
  129350. 1, -533725184, 1611661312, 3, 0,
  129351. _vq_quantlist__44c3_s_p2_0,
  129352. NULL,
  129353. &_vq_auxt__44c3_s_p2_0,
  129354. NULL,
  129355. 0
  129356. };
  129357. static long _vq_quantlist__44c3_s_p3_0[] = {
  129358. 2,
  129359. 1,
  129360. 3,
  129361. 0,
  129362. 4,
  129363. };
  129364. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129365. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0,
  129405. };
  129406. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129407. -1.5, -0.5, 0.5, 1.5,
  129408. };
  129409. static long _vq_quantmap__44c3_s_p3_0[] = {
  129410. 3, 1, 0, 2, 4,
  129411. };
  129412. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129413. _vq_quantthresh__44c3_s_p3_0,
  129414. _vq_quantmap__44c3_s_p3_0,
  129415. 5,
  129416. 5
  129417. };
  129418. static static_codebook _44c3_s_p3_0 = {
  129419. 4, 625,
  129420. _vq_lengthlist__44c3_s_p3_0,
  129421. 1, -533725184, 1611661312, 3, 0,
  129422. _vq_quantlist__44c3_s_p3_0,
  129423. NULL,
  129424. &_vq_auxt__44c3_s_p3_0,
  129425. NULL,
  129426. 0
  129427. };
  129428. static long _vq_quantlist__44c3_s_p4_0[] = {
  129429. 4,
  129430. 3,
  129431. 5,
  129432. 2,
  129433. 6,
  129434. 1,
  129435. 7,
  129436. 0,
  129437. 8,
  129438. };
  129439. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129440. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129441. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129442. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129443. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129444. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0,
  129446. };
  129447. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129448. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129449. };
  129450. static long _vq_quantmap__44c3_s_p4_0[] = {
  129451. 7, 5, 3, 1, 0, 2, 4, 6,
  129452. 8,
  129453. };
  129454. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129455. _vq_quantthresh__44c3_s_p4_0,
  129456. _vq_quantmap__44c3_s_p4_0,
  129457. 9,
  129458. 9
  129459. };
  129460. static static_codebook _44c3_s_p4_0 = {
  129461. 2, 81,
  129462. _vq_lengthlist__44c3_s_p4_0,
  129463. 1, -531628032, 1611661312, 4, 0,
  129464. _vq_quantlist__44c3_s_p4_0,
  129465. NULL,
  129466. &_vq_auxt__44c3_s_p4_0,
  129467. NULL,
  129468. 0
  129469. };
  129470. static long _vq_quantlist__44c3_s_p5_0[] = {
  129471. 4,
  129472. 3,
  129473. 5,
  129474. 2,
  129475. 6,
  129476. 1,
  129477. 7,
  129478. 0,
  129479. 8,
  129480. };
  129481. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129482. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129483. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129484. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129485. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129486. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129487. 11,
  129488. };
  129489. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129490. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129491. };
  129492. static long _vq_quantmap__44c3_s_p5_0[] = {
  129493. 7, 5, 3, 1, 0, 2, 4, 6,
  129494. 8,
  129495. };
  129496. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129497. _vq_quantthresh__44c3_s_p5_0,
  129498. _vq_quantmap__44c3_s_p5_0,
  129499. 9,
  129500. 9
  129501. };
  129502. static static_codebook _44c3_s_p5_0 = {
  129503. 2, 81,
  129504. _vq_lengthlist__44c3_s_p5_0,
  129505. 1, -531628032, 1611661312, 4, 0,
  129506. _vq_quantlist__44c3_s_p5_0,
  129507. NULL,
  129508. &_vq_auxt__44c3_s_p5_0,
  129509. NULL,
  129510. 0
  129511. };
  129512. static long _vq_quantlist__44c3_s_p6_0[] = {
  129513. 8,
  129514. 7,
  129515. 9,
  129516. 6,
  129517. 10,
  129518. 5,
  129519. 11,
  129520. 4,
  129521. 12,
  129522. 3,
  129523. 13,
  129524. 2,
  129525. 14,
  129526. 1,
  129527. 15,
  129528. 0,
  129529. 16,
  129530. };
  129531. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129532. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129533. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129534. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129535. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129536. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129537. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129538. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129539. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129540. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129541. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129542. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129543. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129544. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129545. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129546. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129547. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129548. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129550. 13,
  129551. };
  129552. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129553. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129554. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129555. };
  129556. static long _vq_quantmap__44c3_s_p6_0[] = {
  129557. 15, 13, 11, 9, 7, 5, 3, 1,
  129558. 0, 2, 4, 6, 8, 10, 12, 14,
  129559. 16,
  129560. };
  129561. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129562. _vq_quantthresh__44c3_s_p6_0,
  129563. _vq_quantmap__44c3_s_p6_0,
  129564. 17,
  129565. 17
  129566. };
  129567. static static_codebook _44c3_s_p6_0 = {
  129568. 2, 289,
  129569. _vq_lengthlist__44c3_s_p6_0,
  129570. 1, -529530880, 1611661312, 5, 0,
  129571. _vq_quantlist__44c3_s_p6_0,
  129572. NULL,
  129573. &_vq_auxt__44c3_s_p6_0,
  129574. NULL,
  129575. 0
  129576. };
  129577. static long _vq_quantlist__44c3_s_p7_0[] = {
  129578. 1,
  129579. 0,
  129580. 2,
  129581. };
  129582. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129583. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129584. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129585. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129586. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129587. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129588. 10,
  129589. };
  129590. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129591. -5.5, 5.5,
  129592. };
  129593. static long _vq_quantmap__44c3_s_p7_0[] = {
  129594. 1, 0, 2,
  129595. };
  129596. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129597. _vq_quantthresh__44c3_s_p7_0,
  129598. _vq_quantmap__44c3_s_p7_0,
  129599. 3,
  129600. 3
  129601. };
  129602. static static_codebook _44c3_s_p7_0 = {
  129603. 4, 81,
  129604. _vq_lengthlist__44c3_s_p7_0,
  129605. 1, -529137664, 1618345984, 2, 0,
  129606. _vq_quantlist__44c3_s_p7_0,
  129607. NULL,
  129608. &_vq_auxt__44c3_s_p7_0,
  129609. NULL,
  129610. 0
  129611. };
  129612. static long _vq_quantlist__44c3_s_p7_1[] = {
  129613. 5,
  129614. 4,
  129615. 6,
  129616. 3,
  129617. 7,
  129618. 2,
  129619. 8,
  129620. 1,
  129621. 9,
  129622. 0,
  129623. 10,
  129624. };
  129625. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129626. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129627. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129628. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129629. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129630. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129631. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129632. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129633. 10,10,10, 8, 8, 8, 8, 8, 8,
  129634. };
  129635. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129636. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129637. 3.5, 4.5,
  129638. };
  129639. static long _vq_quantmap__44c3_s_p7_1[] = {
  129640. 9, 7, 5, 3, 1, 0, 2, 4,
  129641. 6, 8, 10,
  129642. };
  129643. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129644. _vq_quantthresh__44c3_s_p7_1,
  129645. _vq_quantmap__44c3_s_p7_1,
  129646. 11,
  129647. 11
  129648. };
  129649. static static_codebook _44c3_s_p7_1 = {
  129650. 2, 121,
  129651. _vq_lengthlist__44c3_s_p7_1,
  129652. 1, -531365888, 1611661312, 4, 0,
  129653. _vq_quantlist__44c3_s_p7_1,
  129654. NULL,
  129655. &_vq_auxt__44c3_s_p7_1,
  129656. NULL,
  129657. 0
  129658. };
  129659. static long _vq_quantlist__44c3_s_p8_0[] = {
  129660. 6,
  129661. 5,
  129662. 7,
  129663. 4,
  129664. 8,
  129665. 3,
  129666. 9,
  129667. 2,
  129668. 10,
  129669. 1,
  129670. 11,
  129671. 0,
  129672. 12,
  129673. };
  129674. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129675. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129676. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129677. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129678. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129679. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129680. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129681. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129682. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129683. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129684. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129685. 0,13,13,12,12,13,12,14,13,
  129686. };
  129687. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129688. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129689. 12.5, 17.5, 22.5, 27.5,
  129690. };
  129691. static long _vq_quantmap__44c3_s_p8_0[] = {
  129692. 11, 9, 7, 5, 3, 1, 0, 2,
  129693. 4, 6, 8, 10, 12,
  129694. };
  129695. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129696. _vq_quantthresh__44c3_s_p8_0,
  129697. _vq_quantmap__44c3_s_p8_0,
  129698. 13,
  129699. 13
  129700. };
  129701. static static_codebook _44c3_s_p8_0 = {
  129702. 2, 169,
  129703. _vq_lengthlist__44c3_s_p8_0,
  129704. 1, -526516224, 1616117760, 4, 0,
  129705. _vq_quantlist__44c3_s_p8_0,
  129706. NULL,
  129707. &_vq_auxt__44c3_s_p8_0,
  129708. NULL,
  129709. 0
  129710. };
  129711. static long _vq_quantlist__44c3_s_p8_1[] = {
  129712. 2,
  129713. 1,
  129714. 3,
  129715. 0,
  129716. 4,
  129717. };
  129718. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129719. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129720. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129721. };
  129722. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129723. -1.5, -0.5, 0.5, 1.5,
  129724. };
  129725. static long _vq_quantmap__44c3_s_p8_1[] = {
  129726. 3, 1, 0, 2, 4,
  129727. };
  129728. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129729. _vq_quantthresh__44c3_s_p8_1,
  129730. _vq_quantmap__44c3_s_p8_1,
  129731. 5,
  129732. 5
  129733. };
  129734. static static_codebook _44c3_s_p8_1 = {
  129735. 2, 25,
  129736. _vq_lengthlist__44c3_s_p8_1,
  129737. 1, -533725184, 1611661312, 3, 0,
  129738. _vq_quantlist__44c3_s_p8_1,
  129739. NULL,
  129740. &_vq_auxt__44c3_s_p8_1,
  129741. NULL,
  129742. 0
  129743. };
  129744. static long _vq_quantlist__44c3_s_p9_0[] = {
  129745. 6,
  129746. 5,
  129747. 7,
  129748. 4,
  129749. 8,
  129750. 3,
  129751. 9,
  129752. 2,
  129753. 10,
  129754. 1,
  129755. 11,
  129756. 0,
  129757. 12,
  129758. };
  129759. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129760. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129761. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129762. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129763. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129764. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129765. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129766. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129767. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129768. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129769. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129770. 11,11,11,11,11,11,11,11,11,
  129771. };
  129772. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129773. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129774. 637.5, 892.5, 1147.5, 1402.5,
  129775. };
  129776. static long _vq_quantmap__44c3_s_p9_0[] = {
  129777. 11, 9, 7, 5, 3, 1, 0, 2,
  129778. 4, 6, 8, 10, 12,
  129779. };
  129780. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129781. _vq_quantthresh__44c3_s_p9_0,
  129782. _vq_quantmap__44c3_s_p9_0,
  129783. 13,
  129784. 13
  129785. };
  129786. static static_codebook _44c3_s_p9_0 = {
  129787. 2, 169,
  129788. _vq_lengthlist__44c3_s_p9_0,
  129789. 1, -514332672, 1627381760, 4, 0,
  129790. _vq_quantlist__44c3_s_p9_0,
  129791. NULL,
  129792. &_vq_auxt__44c3_s_p9_0,
  129793. NULL,
  129794. 0
  129795. };
  129796. static long _vq_quantlist__44c3_s_p9_1[] = {
  129797. 7,
  129798. 6,
  129799. 8,
  129800. 5,
  129801. 9,
  129802. 4,
  129803. 10,
  129804. 3,
  129805. 11,
  129806. 2,
  129807. 12,
  129808. 1,
  129809. 13,
  129810. 0,
  129811. 14,
  129812. };
  129813. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129814. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129815. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129816. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129817. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129818. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129819. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129820. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129821. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129822. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129823. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129824. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129825. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129826. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129827. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129828. 15,
  129829. };
  129830. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129831. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129832. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129833. };
  129834. static long _vq_quantmap__44c3_s_p9_1[] = {
  129835. 13, 11, 9, 7, 5, 3, 1, 0,
  129836. 2, 4, 6, 8, 10, 12, 14,
  129837. };
  129838. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129839. _vq_quantthresh__44c3_s_p9_1,
  129840. _vq_quantmap__44c3_s_p9_1,
  129841. 15,
  129842. 15
  129843. };
  129844. static static_codebook _44c3_s_p9_1 = {
  129845. 2, 225,
  129846. _vq_lengthlist__44c3_s_p9_1,
  129847. 1, -522338304, 1620115456, 4, 0,
  129848. _vq_quantlist__44c3_s_p9_1,
  129849. NULL,
  129850. &_vq_auxt__44c3_s_p9_1,
  129851. NULL,
  129852. 0
  129853. };
  129854. static long _vq_quantlist__44c3_s_p9_2[] = {
  129855. 8,
  129856. 7,
  129857. 9,
  129858. 6,
  129859. 10,
  129860. 5,
  129861. 11,
  129862. 4,
  129863. 12,
  129864. 3,
  129865. 13,
  129866. 2,
  129867. 14,
  129868. 1,
  129869. 15,
  129870. 0,
  129871. 16,
  129872. };
  129873. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129874. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129875. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129876. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129877. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129878. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129879. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129880. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129881. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129882. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129883. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129884. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129885. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129886. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129887. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129888. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129889. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129890. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129891. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129892. 10,
  129893. };
  129894. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129895. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129896. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129897. };
  129898. static long _vq_quantmap__44c3_s_p9_2[] = {
  129899. 15, 13, 11, 9, 7, 5, 3, 1,
  129900. 0, 2, 4, 6, 8, 10, 12, 14,
  129901. 16,
  129902. };
  129903. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129904. _vq_quantthresh__44c3_s_p9_2,
  129905. _vq_quantmap__44c3_s_p9_2,
  129906. 17,
  129907. 17
  129908. };
  129909. static static_codebook _44c3_s_p9_2 = {
  129910. 2, 289,
  129911. _vq_lengthlist__44c3_s_p9_2,
  129912. 1, -529530880, 1611661312, 5, 0,
  129913. _vq_quantlist__44c3_s_p9_2,
  129914. NULL,
  129915. &_vq_auxt__44c3_s_p9_2,
  129916. NULL,
  129917. 0
  129918. };
  129919. static long _huff_lengthlist__44c3_s_short[] = {
  129920. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129921. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129922. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129923. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129924. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129925. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129926. 6, 8, 9,11,
  129927. };
  129928. static static_codebook _huff_book__44c3_s_short = {
  129929. 2, 100,
  129930. _huff_lengthlist__44c3_s_short,
  129931. 0, 0, 0, 0, 0,
  129932. NULL,
  129933. NULL,
  129934. NULL,
  129935. NULL,
  129936. 0
  129937. };
  129938. static long _huff_lengthlist__44c4_s_long[] = {
  129939. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129940. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129941. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129942. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129943. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129944. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129945. 9, 8, 7, 7,
  129946. };
  129947. static static_codebook _huff_book__44c4_s_long = {
  129948. 2, 100,
  129949. _huff_lengthlist__44c4_s_long,
  129950. 0, 0, 0, 0, 0,
  129951. NULL,
  129952. NULL,
  129953. NULL,
  129954. NULL,
  129955. 0
  129956. };
  129957. static long _vq_quantlist__44c4_s_p1_0[] = {
  129958. 1,
  129959. 0,
  129960. 2,
  129961. };
  129962. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129963. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129964. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129969. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129974. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  130009. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  130014. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  130019. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130055. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130060. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130065. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0,
  130374. };
  130375. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130376. -0.5, 0.5,
  130377. };
  130378. static long _vq_quantmap__44c4_s_p1_0[] = {
  130379. 1, 0, 2,
  130380. };
  130381. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130382. _vq_quantthresh__44c4_s_p1_0,
  130383. _vq_quantmap__44c4_s_p1_0,
  130384. 3,
  130385. 3
  130386. };
  130387. static static_codebook _44c4_s_p1_0 = {
  130388. 8, 6561,
  130389. _vq_lengthlist__44c4_s_p1_0,
  130390. 1, -535822336, 1611661312, 2, 0,
  130391. _vq_quantlist__44c4_s_p1_0,
  130392. NULL,
  130393. &_vq_auxt__44c4_s_p1_0,
  130394. NULL,
  130395. 0
  130396. };
  130397. static long _vq_quantlist__44c4_s_p2_0[] = {
  130398. 2,
  130399. 1,
  130400. 3,
  130401. 0,
  130402. 4,
  130403. };
  130404. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130405. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130406. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130407. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130408. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130409. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130415. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130416. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130417. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130423. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130424. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130431. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130432. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0,
  130445. };
  130446. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130447. -1.5, -0.5, 0.5, 1.5,
  130448. };
  130449. static long _vq_quantmap__44c4_s_p2_0[] = {
  130450. 3, 1, 0, 2, 4,
  130451. };
  130452. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130453. _vq_quantthresh__44c4_s_p2_0,
  130454. _vq_quantmap__44c4_s_p2_0,
  130455. 5,
  130456. 5
  130457. };
  130458. static static_codebook _44c4_s_p2_0 = {
  130459. 4, 625,
  130460. _vq_lengthlist__44c4_s_p2_0,
  130461. 1, -533725184, 1611661312, 3, 0,
  130462. _vq_quantlist__44c4_s_p2_0,
  130463. NULL,
  130464. &_vq_auxt__44c4_s_p2_0,
  130465. NULL,
  130466. 0
  130467. };
  130468. static long _vq_quantlist__44c4_s_p3_0[] = {
  130469. 2,
  130470. 1,
  130471. 3,
  130472. 0,
  130473. 4,
  130474. };
  130475. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130476. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0,
  130516. };
  130517. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130518. -1.5, -0.5, 0.5, 1.5,
  130519. };
  130520. static long _vq_quantmap__44c4_s_p3_0[] = {
  130521. 3, 1, 0, 2, 4,
  130522. };
  130523. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130524. _vq_quantthresh__44c4_s_p3_0,
  130525. _vq_quantmap__44c4_s_p3_0,
  130526. 5,
  130527. 5
  130528. };
  130529. static static_codebook _44c4_s_p3_0 = {
  130530. 4, 625,
  130531. _vq_lengthlist__44c4_s_p3_0,
  130532. 1, -533725184, 1611661312, 3, 0,
  130533. _vq_quantlist__44c4_s_p3_0,
  130534. NULL,
  130535. &_vq_auxt__44c4_s_p3_0,
  130536. NULL,
  130537. 0
  130538. };
  130539. static long _vq_quantlist__44c4_s_p4_0[] = {
  130540. 4,
  130541. 3,
  130542. 5,
  130543. 2,
  130544. 6,
  130545. 1,
  130546. 7,
  130547. 0,
  130548. 8,
  130549. };
  130550. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130551. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130552. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130553. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130554. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130555. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0,
  130557. };
  130558. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130559. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130560. };
  130561. static long _vq_quantmap__44c4_s_p4_0[] = {
  130562. 7, 5, 3, 1, 0, 2, 4, 6,
  130563. 8,
  130564. };
  130565. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130566. _vq_quantthresh__44c4_s_p4_0,
  130567. _vq_quantmap__44c4_s_p4_0,
  130568. 9,
  130569. 9
  130570. };
  130571. static static_codebook _44c4_s_p4_0 = {
  130572. 2, 81,
  130573. _vq_lengthlist__44c4_s_p4_0,
  130574. 1, -531628032, 1611661312, 4, 0,
  130575. _vq_quantlist__44c4_s_p4_0,
  130576. NULL,
  130577. &_vq_auxt__44c4_s_p4_0,
  130578. NULL,
  130579. 0
  130580. };
  130581. static long _vq_quantlist__44c4_s_p5_0[] = {
  130582. 4,
  130583. 3,
  130584. 5,
  130585. 2,
  130586. 6,
  130587. 1,
  130588. 7,
  130589. 0,
  130590. 8,
  130591. };
  130592. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130593. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130594. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130595. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130596. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130597. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130598. 10,
  130599. };
  130600. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130601. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130602. };
  130603. static long _vq_quantmap__44c4_s_p5_0[] = {
  130604. 7, 5, 3, 1, 0, 2, 4, 6,
  130605. 8,
  130606. };
  130607. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130608. _vq_quantthresh__44c4_s_p5_0,
  130609. _vq_quantmap__44c4_s_p5_0,
  130610. 9,
  130611. 9
  130612. };
  130613. static static_codebook _44c4_s_p5_0 = {
  130614. 2, 81,
  130615. _vq_lengthlist__44c4_s_p5_0,
  130616. 1, -531628032, 1611661312, 4, 0,
  130617. _vq_quantlist__44c4_s_p5_0,
  130618. NULL,
  130619. &_vq_auxt__44c4_s_p5_0,
  130620. NULL,
  130621. 0
  130622. };
  130623. static long _vq_quantlist__44c4_s_p6_0[] = {
  130624. 8,
  130625. 7,
  130626. 9,
  130627. 6,
  130628. 10,
  130629. 5,
  130630. 11,
  130631. 4,
  130632. 12,
  130633. 3,
  130634. 13,
  130635. 2,
  130636. 14,
  130637. 1,
  130638. 15,
  130639. 0,
  130640. 16,
  130641. };
  130642. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130643. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130644. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130645. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130646. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130647. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130648. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130649. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130650. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130651. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130652. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130653. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130654. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130655. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130656. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130657. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130658. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130659. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130661. 13,
  130662. };
  130663. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130664. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130665. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130666. };
  130667. static long _vq_quantmap__44c4_s_p6_0[] = {
  130668. 15, 13, 11, 9, 7, 5, 3, 1,
  130669. 0, 2, 4, 6, 8, 10, 12, 14,
  130670. 16,
  130671. };
  130672. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130673. _vq_quantthresh__44c4_s_p6_0,
  130674. _vq_quantmap__44c4_s_p6_0,
  130675. 17,
  130676. 17
  130677. };
  130678. static static_codebook _44c4_s_p6_0 = {
  130679. 2, 289,
  130680. _vq_lengthlist__44c4_s_p6_0,
  130681. 1, -529530880, 1611661312, 5, 0,
  130682. _vq_quantlist__44c4_s_p6_0,
  130683. NULL,
  130684. &_vq_auxt__44c4_s_p6_0,
  130685. NULL,
  130686. 0
  130687. };
  130688. static long _vq_quantlist__44c4_s_p7_0[] = {
  130689. 1,
  130690. 0,
  130691. 2,
  130692. };
  130693. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130694. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130695. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130696. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130697. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130698. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130699. 10,
  130700. };
  130701. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130702. -5.5, 5.5,
  130703. };
  130704. static long _vq_quantmap__44c4_s_p7_0[] = {
  130705. 1, 0, 2,
  130706. };
  130707. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130708. _vq_quantthresh__44c4_s_p7_0,
  130709. _vq_quantmap__44c4_s_p7_0,
  130710. 3,
  130711. 3
  130712. };
  130713. static static_codebook _44c4_s_p7_0 = {
  130714. 4, 81,
  130715. _vq_lengthlist__44c4_s_p7_0,
  130716. 1, -529137664, 1618345984, 2, 0,
  130717. _vq_quantlist__44c4_s_p7_0,
  130718. NULL,
  130719. &_vq_auxt__44c4_s_p7_0,
  130720. NULL,
  130721. 0
  130722. };
  130723. static long _vq_quantlist__44c4_s_p7_1[] = {
  130724. 5,
  130725. 4,
  130726. 6,
  130727. 3,
  130728. 7,
  130729. 2,
  130730. 8,
  130731. 1,
  130732. 9,
  130733. 0,
  130734. 10,
  130735. };
  130736. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130737. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130738. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130739. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130740. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130741. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130742. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130743. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130744. 10,10,10, 8, 8, 8, 8, 9, 9,
  130745. };
  130746. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130747. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130748. 3.5, 4.5,
  130749. };
  130750. static long _vq_quantmap__44c4_s_p7_1[] = {
  130751. 9, 7, 5, 3, 1, 0, 2, 4,
  130752. 6, 8, 10,
  130753. };
  130754. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130755. _vq_quantthresh__44c4_s_p7_1,
  130756. _vq_quantmap__44c4_s_p7_1,
  130757. 11,
  130758. 11
  130759. };
  130760. static static_codebook _44c4_s_p7_1 = {
  130761. 2, 121,
  130762. _vq_lengthlist__44c4_s_p7_1,
  130763. 1, -531365888, 1611661312, 4, 0,
  130764. _vq_quantlist__44c4_s_p7_1,
  130765. NULL,
  130766. &_vq_auxt__44c4_s_p7_1,
  130767. NULL,
  130768. 0
  130769. };
  130770. static long _vq_quantlist__44c4_s_p8_0[] = {
  130771. 6,
  130772. 5,
  130773. 7,
  130774. 4,
  130775. 8,
  130776. 3,
  130777. 9,
  130778. 2,
  130779. 10,
  130780. 1,
  130781. 11,
  130782. 0,
  130783. 12,
  130784. };
  130785. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130786. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130787. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130788. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130789. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130790. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130791. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130792. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130793. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130794. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130795. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130796. 0,13,12,12,12,12,12,13,13,
  130797. };
  130798. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130799. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130800. 12.5, 17.5, 22.5, 27.5,
  130801. };
  130802. static long _vq_quantmap__44c4_s_p8_0[] = {
  130803. 11, 9, 7, 5, 3, 1, 0, 2,
  130804. 4, 6, 8, 10, 12,
  130805. };
  130806. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130807. _vq_quantthresh__44c4_s_p8_0,
  130808. _vq_quantmap__44c4_s_p8_0,
  130809. 13,
  130810. 13
  130811. };
  130812. static static_codebook _44c4_s_p8_0 = {
  130813. 2, 169,
  130814. _vq_lengthlist__44c4_s_p8_0,
  130815. 1, -526516224, 1616117760, 4, 0,
  130816. _vq_quantlist__44c4_s_p8_0,
  130817. NULL,
  130818. &_vq_auxt__44c4_s_p8_0,
  130819. NULL,
  130820. 0
  130821. };
  130822. static long _vq_quantlist__44c4_s_p8_1[] = {
  130823. 2,
  130824. 1,
  130825. 3,
  130826. 0,
  130827. 4,
  130828. };
  130829. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130830. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130831. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130832. };
  130833. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130834. -1.5, -0.5, 0.5, 1.5,
  130835. };
  130836. static long _vq_quantmap__44c4_s_p8_1[] = {
  130837. 3, 1, 0, 2, 4,
  130838. };
  130839. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130840. _vq_quantthresh__44c4_s_p8_1,
  130841. _vq_quantmap__44c4_s_p8_1,
  130842. 5,
  130843. 5
  130844. };
  130845. static static_codebook _44c4_s_p8_1 = {
  130846. 2, 25,
  130847. _vq_lengthlist__44c4_s_p8_1,
  130848. 1, -533725184, 1611661312, 3, 0,
  130849. _vq_quantlist__44c4_s_p8_1,
  130850. NULL,
  130851. &_vq_auxt__44c4_s_p8_1,
  130852. NULL,
  130853. 0
  130854. };
  130855. static long _vq_quantlist__44c4_s_p9_0[] = {
  130856. 6,
  130857. 5,
  130858. 7,
  130859. 4,
  130860. 8,
  130861. 3,
  130862. 9,
  130863. 2,
  130864. 10,
  130865. 1,
  130866. 11,
  130867. 0,
  130868. 12,
  130869. };
  130870. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130871. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130872. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130873. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130874. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130875. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130876. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130877. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130878. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130879. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130880. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130881. 12,12,12,12,12,12,12,12,12,
  130882. };
  130883. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130884. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130885. 787.5, 1102.5, 1417.5, 1732.5,
  130886. };
  130887. static long _vq_quantmap__44c4_s_p9_0[] = {
  130888. 11, 9, 7, 5, 3, 1, 0, 2,
  130889. 4, 6, 8, 10, 12,
  130890. };
  130891. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130892. _vq_quantthresh__44c4_s_p9_0,
  130893. _vq_quantmap__44c4_s_p9_0,
  130894. 13,
  130895. 13
  130896. };
  130897. static static_codebook _44c4_s_p9_0 = {
  130898. 2, 169,
  130899. _vq_lengthlist__44c4_s_p9_0,
  130900. 1, -513964032, 1628680192, 4, 0,
  130901. _vq_quantlist__44c4_s_p9_0,
  130902. NULL,
  130903. &_vq_auxt__44c4_s_p9_0,
  130904. NULL,
  130905. 0
  130906. };
  130907. static long _vq_quantlist__44c4_s_p9_1[] = {
  130908. 7,
  130909. 6,
  130910. 8,
  130911. 5,
  130912. 9,
  130913. 4,
  130914. 10,
  130915. 3,
  130916. 11,
  130917. 2,
  130918. 12,
  130919. 1,
  130920. 13,
  130921. 0,
  130922. 14,
  130923. };
  130924. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130925. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130926. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130927. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130928. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130929. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130930. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130931. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130932. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130933. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130934. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130935. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130936. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130937. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130938. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130939. 15,
  130940. };
  130941. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130942. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130943. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130944. };
  130945. static long _vq_quantmap__44c4_s_p9_1[] = {
  130946. 13, 11, 9, 7, 5, 3, 1, 0,
  130947. 2, 4, 6, 8, 10, 12, 14,
  130948. };
  130949. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130950. _vq_quantthresh__44c4_s_p9_1,
  130951. _vq_quantmap__44c4_s_p9_1,
  130952. 15,
  130953. 15
  130954. };
  130955. static static_codebook _44c4_s_p9_1 = {
  130956. 2, 225,
  130957. _vq_lengthlist__44c4_s_p9_1,
  130958. 1, -520986624, 1620377600, 4, 0,
  130959. _vq_quantlist__44c4_s_p9_1,
  130960. NULL,
  130961. &_vq_auxt__44c4_s_p9_1,
  130962. NULL,
  130963. 0
  130964. };
  130965. static long _vq_quantlist__44c4_s_p9_2[] = {
  130966. 10,
  130967. 9,
  130968. 11,
  130969. 8,
  130970. 12,
  130971. 7,
  130972. 13,
  130973. 6,
  130974. 14,
  130975. 5,
  130976. 15,
  130977. 4,
  130978. 16,
  130979. 3,
  130980. 17,
  130981. 2,
  130982. 18,
  130983. 1,
  130984. 19,
  130985. 0,
  130986. 20,
  130987. };
  130988. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130989. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130990. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130991. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130992. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130993. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130994. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130995. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130996. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130997. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130998. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130999. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131000. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131001. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131002. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131003. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131004. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131005. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131006. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131007. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131008. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131009. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131010. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131011. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131012. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131013. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131014. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131015. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131016. 10,10,10,10,10,10,10,10,10,
  131017. };
  131018. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131019. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131020. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131021. 6.5, 7.5, 8.5, 9.5,
  131022. };
  131023. static long _vq_quantmap__44c4_s_p9_2[] = {
  131024. 19, 17, 15, 13, 11, 9, 7, 5,
  131025. 3, 1, 0, 2, 4, 6, 8, 10,
  131026. 12, 14, 16, 18, 20,
  131027. };
  131028. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131029. _vq_quantthresh__44c4_s_p9_2,
  131030. _vq_quantmap__44c4_s_p9_2,
  131031. 21,
  131032. 21
  131033. };
  131034. static static_codebook _44c4_s_p9_2 = {
  131035. 2, 441,
  131036. _vq_lengthlist__44c4_s_p9_2,
  131037. 1, -529268736, 1611661312, 5, 0,
  131038. _vq_quantlist__44c4_s_p9_2,
  131039. NULL,
  131040. &_vq_auxt__44c4_s_p9_2,
  131041. NULL,
  131042. 0
  131043. };
  131044. static long _huff_lengthlist__44c4_s_short[] = {
  131045. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131046. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131047. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131048. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131049. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131050. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131051. 7, 9,12,17,
  131052. };
  131053. static static_codebook _huff_book__44c4_s_short = {
  131054. 2, 100,
  131055. _huff_lengthlist__44c4_s_short,
  131056. 0, 0, 0, 0, 0,
  131057. NULL,
  131058. NULL,
  131059. NULL,
  131060. NULL,
  131061. 0
  131062. };
  131063. static long _huff_lengthlist__44c5_s_long[] = {
  131064. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131065. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131066. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131067. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131068. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131069. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131070. 9, 8, 7, 7,
  131071. };
  131072. static static_codebook _huff_book__44c5_s_long = {
  131073. 2, 100,
  131074. _huff_lengthlist__44c5_s_long,
  131075. 0, 0, 0, 0, 0,
  131076. NULL,
  131077. NULL,
  131078. NULL,
  131079. NULL,
  131080. 0
  131081. };
  131082. static long _vq_quantlist__44c5_s_p1_0[] = {
  131083. 1,
  131084. 0,
  131085. 2,
  131086. };
  131087. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131088. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131089. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131094. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131099. 0, 0, 0, 0, 7, 9, 9, 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, 4, 7, 7, 0, 0, 0, 0,
  131134. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  131139. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  131144. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131180. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131185. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131190. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0,
  131499. };
  131500. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131501. -0.5, 0.5,
  131502. };
  131503. static long _vq_quantmap__44c5_s_p1_0[] = {
  131504. 1, 0, 2,
  131505. };
  131506. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131507. _vq_quantthresh__44c5_s_p1_0,
  131508. _vq_quantmap__44c5_s_p1_0,
  131509. 3,
  131510. 3
  131511. };
  131512. static static_codebook _44c5_s_p1_0 = {
  131513. 8, 6561,
  131514. _vq_lengthlist__44c5_s_p1_0,
  131515. 1, -535822336, 1611661312, 2, 0,
  131516. _vq_quantlist__44c5_s_p1_0,
  131517. NULL,
  131518. &_vq_auxt__44c5_s_p1_0,
  131519. NULL,
  131520. 0
  131521. };
  131522. static long _vq_quantlist__44c5_s_p2_0[] = {
  131523. 2,
  131524. 1,
  131525. 3,
  131526. 0,
  131527. 4,
  131528. };
  131529. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131530. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131531. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131532. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131533. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131534. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131540. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131541. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131542. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131548. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131549. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131556. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131557. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0,
  131570. };
  131571. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131572. -1.5, -0.5, 0.5, 1.5,
  131573. };
  131574. static long _vq_quantmap__44c5_s_p2_0[] = {
  131575. 3, 1, 0, 2, 4,
  131576. };
  131577. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131578. _vq_quantthresh__44c5_s_p2_0,
  131579. _vq_quantmap__44c5_s_p2_0,
  131580. 5,
  131581. 5
  131582. };
  131583. static static_codebook _44c5_s_p2_0 = {
  131584. 4, 625,
  131585. _vq_lengthlist__44c5_s_p2_0,
  131586. 1, -533725184, 1611661312, 3, 0,
  131587. _vq_quantlist__44c5_s_p2_0,
  131588. NULL,
  131589. &_vq_auxt__44c5_s_p2_0,
  131590. NULL,
  131591. 0
  131592. };
  131593. static long _vq_quantlist__44c5_s_p3_0[] = {
  131594. 2,
  131595. 1,
  131596. 3,
  131597. 0,
  131598. 4,
  131599. };
  131600. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131601. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0,
  131641. };
  131642. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131643. -1.5, -0.5, 0.5, 1.5,
  131644. };
  131645. static long _vq_quantmap__44c5_s_p3_0[] = {
  131646. 3, 1, 0, 2, 4,
  131647. };
  131648. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131649. _vq_quantthresh__44c5_s_p3_0,
  131650. _vq_quantmap__44c5_s_p3_0,
  131651. 5,
  131652. 5
  131653. };
  131654. static static_codebook _44c5_s_p3_0 = {
  131655. 4, 625,
  131656. _vq_lengthlist__44c5_s_p3_0,
  131657. 1, -533725184, 1611661312, 3, 0,
  131658. _vq_quantlist__44c5_s_p3_0,
  131659. NULL,
  131660. &_vq_auxt__44c5_s_p3_0,
  131661. NULL,
  131662. 0
  131663. };
  131664. static long _vq_quantlist__44c5_s_p4_0[] = {
  131665. 4,
  131666. 3,
  131667. 5,
  131668. 2,
  131669. 6,
  131670. 1,
  131671. 7,
  131672. 0,
  131673. 8,
  131674. };
  131675. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131676. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131677. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131678. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131679. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131680. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0,
  131682. };
  131683. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131684. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131685. };
  131686. static long _vq_quantmap__44c5_s_p4_0[] = {
  131687. 7, 5, 3, 1, 0, 2, 4, 6,
  131688. 8,
  131689. };
  131690. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131691. _vq_quantthresh__44c5_s_p4_0,
  131692. _vq_quantmap__44c5_s_p4_0,
  131693. 9,
  131694. 9
  131695. };
  131696. static static_codebook _44c5_s_p4_0 = {
  131697. 2, 81,
  131698. _vq_lengthlist__44c5_s_p4_0,
  131699. 1, -531628032, 1611661312, 4, 0,
  131700. _vq_quantlist__44c5_s_p4_0,
  131701. NULL,
  131702. &_vq_auxt__44c5_s_p4_0,
  131703. NULL,
  131704. 0
  131705. };
  131706. static long _vq_quantlist__44c5_s_p5_0[] = {
  131707. 4,
  131708. 3,
  131709. 5,
  131710. 2,
  131711. 6,
  131712. 1,
  131713. 7,
  131714. 0,
  131715. 8,
  131716. };
  131717. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131718. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131719. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131720. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131721. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131722. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131723. 10,
  131724. };
  131725. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131726. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131727. };
  131728. static long _vq_quantmap__44c5_s_p5_0[] = {
  131729. 7, 5, 3, 1, 0, 2, 4, 6,
  131730. 8,
  131731. };
  131732. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131733. _vq_quantthresh__44c5_s_p5_0,
  131734. _vq_quantmap__44c5_s_p5_0,
  131735. 9,
  131736. 9
  131737. };
  131738. static static_codebook _44c5_s_p5_0 = {
  131739. 2, 81,
  131740. _vq_lengthlist__44c5_s_p5_0,
  131741. 1, -531628032, 1611661312, 4, 0,
  131742. _vq_quantlist__44c5_s_p5_0,
  131743. NULL,
  131744. &_vq_auxt__44c5_s_p5_0,
  131745. NULL,
  131746. 0
  131747. };
  131748. static long _vq_quantlist__44c5_s_p6_0[] = {
  131749. 8,
  131750. 7,
  131751. 9,
  131752. 6,
  131753. 10,
  131754. 5,
  131755. 11,
  131756. 4,
  131757. 12,
  131758. 3,
  131759. 13,
  131760. 2,
  131761. 14,
  131762. 1,
  131763. 15,
  131764. 0,
  131765. 16,
  131766. };
  131767. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131768. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131769. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131770. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131771. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131772. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131773. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131774. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131775. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131776. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131777. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131778. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131779. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131780. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131781. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131782. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131783. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131784. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131786. 13,
  131787. };
  131788. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131789. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131790. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131791. };
  131792. static long _vq_quantmap__44c5_s_p6_0[] = {
  131793. 15, 13, 11, 9, 7, 5, 3, 1,
  131794. 0, 2, 4, 6, 8, 10, 12, 14,
  131795. 16,
  131796. };
  131797. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131798. _vq_quantthresh__44c5_s_p6_0,
  131799. _vq_quantmap__44c5_s_p6_0,
  131800. 17,
  131801. 17
  131802. };
  131803. static static_codebook _44c5_s_p6_0 = {
  131804. 2, 289,
  131805. _vq_lengthlist__44c5_s_p6_0,
  131806. 1, -529530880, 1611661312, 5, 0,
  131807. _vq_quantlist__44c5_s_p6_0,
  131808. NULL,
  131809. &_vq_auxt__44c5_s_p6_0,
  131810. NULL,
  131811. 0
  131812. };
  131813. static long _vq_quantlist__44c5_s_p7_0[] = {
  131814. 1,
  131815. 0,
  131816. 2,
  131817. };
  131818. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131819. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131820. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131821. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131822. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131823. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131824. 10,
  131825. };
  131826. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131827. -5.5, 5.5,
  131828. };
  131829. static long _vq_quantmap__44c5_s_p7_0[] = {
  131830. 1, 0, 2,
  131831. };
  131832. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131833. _vq_quantthresh__44c5_s_p7_0,
  131834. _vq_quantmap__44c5_s_p7_0,
  131835. 3,
  131836. 3
  131837. };
  131838. static static_codebook _44c5_s_p7_0 = {
  131839. 4, 81,
  131840. _vq_lengthlist__44c5_s_p7_0,
  131841. 1, -529137664, 1618345984, 2, 0,
  131842. _vq_quantlist__44c5_s_p7_0,
  131843. NULL,
  131844. &_vq_auxt__44c5_s_p7_0,
  131845. NULL,
  131846. 0
  131847. };
  131848. static long _vq_quantlist__44c5_s_p7_1[] = {
  131849. 5,
  131850. 4,
  131851. 6,
  131852. 3,
  131853. 7,
  131854. 2,
  131855. 8,
  131856. 1,
  131857. 9,
  131858. 0,
  131859. 10,
  131860. };
  131861. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131862. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131863. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131864. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131865. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131866. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131867. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131868. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131869. 10,10,10, 8, 8, 8, 8, 8, 8,
  131870. };
  131871. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131872. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131873. 3.5, 4.5,
  131874. };
  131875. static long _vq_quantmap__44c5_s_p7_1[] = {
  131876. 9, 7, 5, 3, 1, 0, 2, 4,
  131877. 6, 8, 10,
  131878. };
  131879. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131880. _vq_quantthresh__44c5_s_p7_1,
  131881. _vq_quantmap__44c5_s_p7_1,
  131882. 11,
  131883. 11
  131884. };
  131885. static static_codebook _44c5_s_p7_1 = {
  131886. 2, 121,
  131887. _vq_lengthlist__44c5_s_p7_1,
  131888. 1, -531365888, 1611661312, 4, 0,
  131889. _vq_quantlist__44c5_s_p7_1,
  131890. NULL,
  131891. &_vq_auxt__44c5_s_p7_1,
  131892. NULL,
  131893. 0
  131894. };
  131895. static long _vq_quantlist__44c5_s_p8_0[] = {
  131896. 6,
  131897. 5,
  131898. 7,
  131899. 4,
  131900. 8,
  131901. 3,
  131902. 9,
  131903. 2,
  131904. 10,
  131905. 1,
  131906. 11,
  131907. 0,
  131908. 12,
  131909. };
  131910. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131911. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131912. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131913. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131914. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131915. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131916. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131917. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131918. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131919. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131920. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131921. 0,12,12,12,12,12,12,13,13,
  131922. };
  131923. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131924. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131925. 12.5, 17.5, 22.5, 27.5,
  131926. };
  131927. static long _vq_quantmap__44c5_s_p8_0[] = {
  131928. 11, 9, 7, 5, 3, 1, 0, 2,
  131929. 4, 6, 8, 10, 12,
  131930. };
  131931. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131932. _vq_quantthresh__44c5_s_p8_0,
  131933. _vq_quantmap__44c5_s_p8_0,
  131934. 13,
  131935. 13
  131936. };
  131937. static static_codebook _44c5_s_p8_0 = {
  131938. 2, 169,
  131939. _vq_lengthlist__44c5_s_p8_0,
  131940. 1, -526516224, 1616117760, 4, 0,
  131941. _vq_quantlist__44c5_s_p8_0,
  131942. NULL,
  131943. &_vq_auxt__44c5_s_p8_0,
  131944. NULL,
  131945. 0
  131946. };
  131947. static long _vq_quantlist__44c5_s_p8_1[] = {
  131948. 2,
  131949. 1,
  131950. 3,
  131951. 0,
  131952. 4,
  131953. };
  131954. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131955. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131956. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131957. };
  131958. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131959. -1.5, -0.5, 0.5, 1.5,
  131960. };
  131961. static long _vq_quantmap__44c5_s_p8_1[] = {
  131962. 3, 1, 0, 2, 4,
  131963. };
  131964. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131965. _vq_quantthresh__44c5_s_p8_1,
  131966. _vq_quantmap__44c5_s_p8_1,
  131967. 5,
  131968. 5
  131969. };
  131970. static static_codebook _44c5_s_p8_1 = {
  131971. 2, 25,
  131972. _vq_lengthlist__44c5_s_p8_1,
  131973. 1, -533725184, 1611661312, 3, 0,
  131974. _vq_quantlist__44c5_s_p8_1,
  131975. NULL,
  131976. &_vq_auxt__44c5_s_p8_1,
  131977. NULL,
  131978. 0
  131979. };
  131980. static long _vq_quantlist__44c5_s_p9_0[] = {
  131981. 7,
  131982. 6,
  131983. 8,
  131984. 5,
  131985. 9,
  131986. 4,
  131987. 10,
  131988. 3,
  131989. 11,
  131990. 2,
  131991. 12,
  131992. 1,
  131993. 13,
  131994. 0,
  131995. 14,
  131996. };
  131997. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131998. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131999. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132000. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132001. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132002. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132003. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132004. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132005. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132006. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132007. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132008. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132009. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132010. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132011. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132012. 12,
  132013. };
  132014. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132015. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132016. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132017. };
  132018. static long _vq_quantmap__44c5_s_p9_0[] = {
  132019. 13, 11, 9, 7, 5, 3, 1, 0,
  132020. 2, 4, 6, 8, 10, 12, 14,
  132021. };
  132022. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132023. _vq_quantthresh__44c5_s_p9_0,
  132024. _vq_quantmap__44c5_s_p9_0,
  132025. 15,
  132026. 15
  132027. };
  132028. static static_codebook _44c5_s_p9_0 = {
  132029. 2, 225,
  132030. _vq_lengthlist__44c5_s_p9_0,
  132031. 1, -512522752, 1628852224, 4, 0,
  132032. _vq_quantlist__44c5_s_p9_0,
  132033. NULL,
  132034. &_vq_auxt__44c5_s_p9_0,
  132035. NULL,
  132036. 0
  132037. };
  132038. static long _vq_quantlist__44c5_s_p9_1[] = {
  132039. 8,
  132040. 7,
  132041. 9,
  132042. 6,
  132043. 10,
  132044. 5,
  132045. 11,
  132046. 4,
  132047. 12,
  132048. 3,
  132049. 13,
  132050. 2,
  132051. 14,
  132052. 1,
  132053. 15,
  132054. 0,
  132055. 16,
  132056. };
  132057. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132058. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132059. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132060. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132061. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132062. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132063. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132064. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132065. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132066. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132067. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132068. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132069. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132070. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132071. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132072. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132073. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132074. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132075. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132076. 15,
  132077. };
  132078. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132079. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132080. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132081. };
  132082. static long _vq_quantmap__44c5_s_p9_1[] = {
  132083. 15, 13, 11, 9, 7, 5, 3, 1,
  132084. 0, 2, 4, 6, 8, 10, 12, 14,
  132085. 16,
  132086. };
  132087. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132088. _vq_quantthresh__44c5_s_p9_1,
  132089. _vq_quantmap__44c5_s_p9_1,
  132090. 17,
  132091. 17
  132092. };
  132093. static static_codebook _44c5_s_p9_1 = {
  132094. 2, 289,
  132095. _vq_lengthlist__44c5_s_p9_1,
  132096. 1, -520814592, 1620377600, 5, 0,
  132097. _vq_quantlist__44c5_s_p9_1,
  132098. NULL,
  132099. &_vq_auxt__44c5_s_p9_1,
  132100. NULL,
  132101. 0
  132102. };
  132103. static long _vq_quantlist__44c5_s_p9_2[] = {
  132104. 10,
  132105. 9,
  132106. 11,
  132107. 8,
  132108. 12,
  132109. 7,
  132110. 13,
  132111. 6,
  132112. 14,
  132113. 5,
  132114. 15,
  132115. 4,
  132116. 16,
  132117. 3,
  132118. 17,
  132119. 2,
  132120. 18,
  132121. 1,
  132122. 19,
  132123. 0,
  132124. 20,
  132125. };
  132126. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132127. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132128. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132129. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132130. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132131. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132132. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132133. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132134. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132135. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132136. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132137. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132138. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132139. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132140. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132141. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132142. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132143. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132144. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132145. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132146. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132147. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132148. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132149. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132150. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132151. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132152. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132153. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132154. 10,10,10,10,10,10,10,10,10,
  132155. };
  132156. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132157. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132158. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132159. 6.5, 7.5, 8.5, 9.5,
  132160. };
  132161. static long _vq_quantmap__44c5_s_p9_2[] = {
  132162. 19, 17, 15, 13, 11, 9, 7, 5,
  132163. 3, 1, 0, 2, 4, 6, 8, 10,
  132164. 12, 14, 16, 18, 20,
  132165. };
  132166. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132167. _vq_quantthresh__44c5_s_p9_2,
  132168. _vq_quantmap__44c5_s_p9_2,
  132169. 21,
  132170. 21
  132171. };
  132172. static static_codebook _44c5_s_p9_2 = {
  132173. 2, 441,
  132174. _vq_lengthlist__44c5_s_p9_2,
  132175. 1, -529268736, 1611661312, 5, 0,
  132176. _vq_quantlist__44c5_s_p9_2,
  132177. NULL,
  132178. &_vq_auxt__44c5_s_p9_2,
  132179. NULL,
  132180. 0
  132181. };
  132182. static long _huff_lengthlist__44c5_s_short[] = {
  132183. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132184. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132185. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132186. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132187. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132188. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132189. 6, 8,11,16,
  132190. };
  132191. static static_codebook _huff_book__44c5_s_short = {
  132192. 2, 100,
  132193. _huff_lengthlist__44c5_s_short,
  132194. 0, 0, 0, 0, 0,
  132195. NULL,
  132196. NULL,
  132197. NULL,
  132198. NULL,
  132199. 0
  132200. };
  132201. static long _huff_lengthlist__44c6_s_long[] = {
  132202. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132203. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132204. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132205. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132206. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132207. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132208. 11,10,10,12,
  132209. };
  132210. static static_codebook _huff_book__44c6_s_long = {
  132211. 2, 100,
  132212. _huff_lengthlist__44c6_s_long,
  132213. 0, 0, 0, 0, 0,
  132214. NULL,
  132215. NULL,
  132216. NULL,
  132217. NULL,
  132218. 0
  132219. };
  132220. static long _vq_quantlist__44c6_s_p1_0[] = {
  132221. 1,
  132222. 0,
  132223. 2,
  132224. };
  132225. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132226. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132227. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132228. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132229. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132230. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132231. 8,
  132232. };
  132233. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132234. -0.5, 0.5,
  132235. };
  132236. static long _vq_quantmap__44c6_s_p1_0[] = {
  132237. 1, 0, 2,
  132238. };
  132239. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132240. _vq_quantthresh__44c6_s_p1_0,
  132241. _vq_quantmap__44c6_s_p1_0,
  132242. 3,
  132243. 3
  132244. };
  132245. static static_codebook _44c6_s_p1_0 = {
  132246. 4, 81,
  132247. _vq_lengthlist__44c6_s_p1_0,
  132248. 1, -535822336, 1611661312, 2, 0,
  132249. _vq_quantlist__44c6_s_p1_0,
  132250. NULL,
  132251. &_vq_auxt__44c6_s_p1_0,
  132252. NULL,
  132253. 0
  132254. };
  132255. static long _vq_quantlist__44c6_s_p2_0[] = {
  132256. 2,
  132257. 1,
  132258. 3,
  132259. 0,
  132260. 4,
  132261. };
  132262. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132263. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132264. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132265. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132266. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132267. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132268. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132269. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132270. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132272. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132273. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132274. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132275. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132276. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132277. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132278. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132280. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132281. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132282. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132283. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132284. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132285. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132286. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132288. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132289. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132290. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132291. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132292. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132293. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132294. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132299. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132300. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132301. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132302. 13,
  132303. };
  132304. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132305. -1.5, -0.5, 0.5, 1.5,
  132306. };
  132307. static long _vq_quantmap__44c6_s_p2_0[] = {
  132308. 3, 1, 0, 2, 4,
  132309. };
  132310. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132311. _vq_quantthresh__44c6_s_p2_0,
  132312. _vq_quantmap__44c6_s_p2_0,
  132313. 5,
  132314. 5
  132315. };
  132316. static static_codebook _44c6_s_p2_0 = {
  132317. 4, 625,
  132318. _vq_lengthlist__44c6_s_p2_0,
  132319. 1, -533725184, 1611661312, 3, 0,
  132320. _vq_quantlist__44c6_s_p2_0,
  132321. NULL,
  132322. &_vq_auxt__44c6_s_p2_0,
  132323. NULL,
  132324. 0
  132325. };
  132326. static long _vq_quantlist__44c6_s_p3_0[] = {
  132327. 4,
  132328. 3,
  132329. 5,
  132330. 2,
  132331. 6,
  132332. 1,
  132333. 7,
  132334. 0,
  132335. 8,
  132336. };
  132337. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132338. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132339. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132340. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132341. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132343. 0,
  132344. };
  132345. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132346. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132347. };
  132348. static long _vq_quantmap__44c6_s_p3_0[] = {
  132349. 7, 5, 3, 1, 0, 2, 4, 6,
  132350. 8,
  132351. };
  132352. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132353. _vq_quantthresh__44c6_s_p3_0,
  132354. _vq_quantmap__44c6_s_p3_0,
  132355. 9,
  132356. 9
  132357. };
  132358. static static_codebook _44c6_s_p3_0 = {
  132359. 2, 81,
  132360. _vq_lengthlist__44c6_s_p3_0,
  132361. 1, -531628032, 1611661312, 4, 0,
  132362. _vq_quantlist__44c6_s_p3_0,
  132363. NULL,
  132364. &_vq_auxt__44c6_s_p3_0,
  132365. NULL,
  132366. 0
  132367. };
  132368. static long _vq_quantlist__44c6_s_p4_0[] = {
  132369. 8,
  132370. 7,
  132371. 9,
  132372. 6,
  132373. 10,
  132374. 5,
  132375. 11,
  132376. 4,
  132377. 12,
  132378. 3,
  132379. 13,
  132380. 2,
  132381. 14,
  132382. 1,
  132383. 15,
  132384. 0,
  132385. 16,
  132386. };
  132387. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132388. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132389. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132390. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132391. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132392. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132393. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132394. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132395. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132396. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132397. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132406. 0,
  132407. };
  132408. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132409. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132410. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132411. };
  132412. static long _vq_quantmap__44c6_s_p4_0[] = {
  132413. 15, 13, 11, 9, 7, 5, 3, 1,
  132414. 0, 2, 4, 6, 8, 10, 12, 14,
  132415. 16,
  132416. };
  132417. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132418. _vq_quantthresh__44c6_s_p4_0,
  132419. _vq_quantmap__44c6_s_p4_0,
  132420. 17,
  132421. 17
  132422. };
  132423. static static_codebook _44c6_s_p4_0 = {
  132424. 2, 289,
  132425. _vq_lengthlist__44c6_s_p4_0,
  132426. 1, -529530880, 1611661312, 5, 0,
  132427. _vq_quantlist__44c6_s_p4_0,
  132428. NULL,
  132429. &_vq_auxt__44c6_s_p4_0,
  132430. NULL,
  132431. 0
  132432. };
  132433. static long _vq_quantlist__44c6_s_p5_0[] = {
  132434. 1,
  132435. 0,
  132436. 2,
  132437. };
  132438. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132439. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132440. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132441. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132442. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132443. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132444. 12,
  132445. };
  132446. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132447. -5.5, 5.5,
  132448. };
  132449. static long _vq_quantmap__44c6_s_p5_0[] = {
  132450. 1, 0, 2,
  132451. };
  132452. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132453. _vq_quantthresh__44c6_s_p5_0,
  132454. _vq_quantmap__44c6_s_p5_0,
  132455. 3,
  132456. 3
  132457. };
  132458. static static_codebook _44c6_s_p5_0 = {
  132459. 4, 81,
  132460. _vq_lengthlist__44c6_s_p5_0,
  132461. 1, -529137664, 1618345984, 2, 0,
  132462. _vq_quantlist__44c6_s_p5_0,
  132463. NULL,
  132464. &_vq_auxt__44c6_s_p5_0,
  132465. NULL,
  132466. 0
  132467. };
  132468. static long _vq_quantlist__44c6_s_p5_1[] = {
  132469. 5,
  132470. 4,
  132471. 6,
  132472. 3,
  132473. 7,
  132474. 2,
  132475. 8,
  132476. 1,
  132477. 9,
  132478. 0,
  132479. 10,
  132480. };
  132481. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132482. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132483. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132484. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132485. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132486. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132487. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132488. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132489. 11,10,10, 7, 7, 8, 8, 8, 8,
  132490. };
  132491. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132492. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132493. 3.5, 4.5,
  132494. };
  132495. static long _vq_quantmap__44c6_s_p5_1[] = {
  132496. 9, 7, 5, 3, 1, 0, 2, 4,
  132497. 6, 8, 10,
  132498. };
  132499. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132500. _vq_quantthresh__44c6_s_p5_1,
  132501. _vq_quantmap__44c6_s_p5_1,
  132502. 11,
  132503. 11
  132504. };
  132505. static static_codebook _44c6_s_p5_1 = {
  132506. 2, 121,
  132507. _vq_lengthlist__44c6_s_p5_1,
  132508. 1, -531365888, 1611661312, 4, 0,
  132509. _vq_quantlist__44c6_s_p5_1,
  132510. NULL,
  132511. &_vq_auxt__44c6_s_p5_1,
  132512. NULL,
  132513. 0
  132514. };
  132515. static long _vq_quantlist__44c6_s_p6_0[] = {
  132516. 6,
  132517. 5,
  132518. 7,
  132519. 4,
  132520. 8,
  132521. 3,
  132522. 9,
  132523. 2,
  132524. 10,
  132525. 1,
  132526. 11,
  132527. 0,
  132528. 12,
  132529. };
  132530. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132531. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132532. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132533. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132534. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132535. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132536. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132541. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132542. };
  132543. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132544. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132545. 12.5, 17.5, 22.5, 27.5,
  132546. };
  132547. static long _vq_quantmap__44c6_s_p6_0[] = {
  132548. 11, 9, 7, 5, 3, 1, 0, 2,
  132549. 4, 6, 8, 10, 12,
  132550. };
  132551. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132552. _vq_quantthresh__44c6_s_p6_0,
  132553. _vq_quantmap__44c6_s_p6_0,
  132554. 13,
  132555. 13
  132556. };
  132557. static static_codebook _44c6_s_p6_0 = {
  132558. 2, 169,
  132559. _vq_lengthlist__44c6_s_p6_0,
  132560. 1, -526516224, 1616117760, 4, 0,
  132561. _vq_quantlist__44c6_s_p6_0,
  132562. NULL,
  132563. &_vq_auxt__44c6_s_p6_0,
  132564. NULL,
  132565. 0
  132566. };
  132567. static long _vq_quantlist__44c6_s_p6_1[] = {
  132568. 2,
  132569. 1,
  132570. 3,
  132571. 0,
  132572. 4,
  132573. };
  132574. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132575. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132576. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132577. };
  132578. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132579. -1.5, -0.5, 0.5, 1.5,
  132580. };
  132581. static long _vq_quantmap__44c6_s_p6_1[] = {
  132582. 3, 1, 0, 2, 4,
  132583. };
  132584. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132585. _vq_quantthresh__44c6_s_p6_1,
  132586. _vq_quantmap__44c6_s_p6_1,
  132587. 5,
  132588. 5
  132589. };
  132590. static static_codebook _44c6_s_p6_1 = {
  132591. 2, 25,
  132592. _vq_lengthlist__44c6_s_p6_1,
  132593. 1, -533725184, 1611661312, 3, 0,
  132594. _vq_quantlist__44c6_s_p6_1,
  132595. NULL,
  132596. &_vq_auxt__44c6_s_p6_1,
  132597. NULL,
  132598. 0
  132599. };
  132600. static long _vq_quantlist__44c6_s_p7_0[] = {
  132601. 6,
  132602. 5,
  132603. 7,
  132604. 4,
  132605. 8,
  132606. 3,
  132607. 9,
  132608. 2,
  132609. 10,
  132610. 1,
  132611. 11,
  132612. 0,
  132613. 12,
  132614. };
  132615. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132616. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132617. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132618. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132619. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132620. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132621. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132622. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132623. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132624. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132625. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132626. 20,13,13,13,13,13,13,14,14,
  132627. };
  132628. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132629. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132630. 27.5, 38.5, 49.5, 60.5,
  132631. };
  132632. static long _vq_quantmap__44c6_s_p7_0[] = {
  132633. 11, 9, 7, 5, 3, 1, 0, 2,
  132634. 4, 6, 8, 10, 12,
  132635. };
  132636. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132637. _vq_quantthresh__44c6_s_p7_0,
  132638. _vq_quantmap__44c6_s_p7_0,
  132639. 13,
  132640. 13
  132641. };
  132642. static static_codebook _44c6_s_p7_0 = {
  132643. 2, 169,
  132644. _vq_lengthlist__44c6_s_p7_0,
  132645. 1, -523206656, 1618345984, 4, 0,
  132646. _vq_quantlist__44c6_s_p7_0,
  132647. NULL,
  132648. &_vq_auxt__44c6_s_p7_0,
  132649. NULL,
  132650. 0
  132651. };
  132652. static long _vq_quantlist__44c6_s_p7_1[] = {
  132653. 5,
  132654. 4,
  132655. 6,
  132656. 3,
  132657. 7,
  132658. 2,
  132659. 8,
  132660. 1,
  132661. 9,
  132662. 0,
  132663. 10,
  132664. };
  132665. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132666. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132667. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132668. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132669. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132670. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132671. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132672. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132673. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132674. };
  132675. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132676. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132677. 3.5, 4.5,
  132678. };
  132679. static long _vq_quantmap__44c6_s_p7_1[] = {
  132680. 9, 7, 5, 3, 1, 0, 2, 4,
  132681. 6, 8, 10,
  132682. };
  132683. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132684. _vq_quantthresh__44c6_s_p7_1,
  132685. _vq_quantmap__44c6_s_p7_1,
  132686. 11,
  132687. 11
  132688. };
  132689. static static_codebook _44c6_s_p7_1 = {
  132690. 2, 121,
  132691. _vq_lengthlist__44c6_s_p7_1,
  132692. 1, -531365888, 1611661312, 4, 0,
  132693. _vq_quantlist__44c6_s_p7_1,
  132694. NULL,
  132695. &_vq_auxt__44c6_s_p7_1,
  132696. NULL,
  132697. 0
  132698. };
  132699. static long _vq_quantlist__44c6_s_p8_0[] = {
  132700. 7,
  132701. 6,
  132702. 8,
  132703. 5,
  132704. 9,
  132705. 4,
  132706. 10,
  132707. 3,
  132708. 11,
  132709. 2,
  132710. 12,
  132711. 1,
  132712. 13,
  132713. 0,
  132714. 14,
  132715. };
  132716. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132717. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132718. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132719. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132720. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132721. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132722. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132723. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132724. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132725. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132726. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132727. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132728. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132729. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132730. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132731. 14,
  132732. };
  132733. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132734. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132735. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132736. };
  132737. static long _vq_quantmap__44c6_s_p8_0[] = {
  132738. 13, 11, 9, 7, 5, 3, 1, 0,
  132739. 2, 4, 6, 8, 10, 12, 14,
  132740. };
  132741. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132742. _vq_quantthresh__44c6_s_p8_0,
  132743. _vq_quantmap__44c6_s_p8_0,
  132744. 15,
  132745. 15
  132746. };
  132747. static static_codebook _44c6_s_p8_0 = {
  132748. 2, 225,
  132749. _vq_lengthlist__44c6_s_p8_0,
  132750. 1, -520986624, 1620377600, 4, 0,
  132751. _vq_quantlist__44c6_s_p8_0,
  132752. NULL,
  132753. &_vq_auxt__44c6_s_p8_0,
  132754. NULL,
  132755. 0
  132756. };
  132757. static long _vq_quantlist__44c6_s_p8_1[] = {
  132758. 10,
  132759. 9,
  132760. 11,
  132761. 8,
  132762. 12,
  132763. 7,
  132764. 13,
  132765. 6,
  132766. 14,
  132767. 5,
  132768. 15,
  132769. 4,
  132770. 16,
  132771. 3,
  132772. 17,
  132773. 2,
  132774. 18,
  132775. 1,
  132776. 19,
  132777. 0,
  132778. 20,
  132779. };
  132780. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132781. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132782. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132783. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132784. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132785. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132786. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132787. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132788. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132789. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132790. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132791. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132792. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132793. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132794. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132795. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132796. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132797. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132798. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132799. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132800. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132801. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132802. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132803. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132804. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132805. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132806. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132807. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132808. 10,10,10,10,10,10,10,10,10,
  132809. };
  132810. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132811. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132812. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132813. 6.5, 7.5, 8.5, 9.5,
  132814. };
  132815. static long _vq_quantmap__44c6_s_p8_1[] = {
  132816. 19, 17, 15, 13, 11, 9, 7, 5,
  132817. 3, 1, 0, 2, 4, 6, 8, 10,
  132818. 12, 14, 16, 18, 20,
  132819. };
  132820. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132821. _vq_quantthresh__44c6_s_p8_1,
  132822. _vq_quantmap__44c6_s_p8_1,
  132823. 21,
  132824. 21
  132825. };
  132826. static static_codebook _44c6_s_p8_1 = {
  132827. 2, 441,
  132828. _vq_lengthlist__44c6_s_p8_1,
  132829. 1, -529268736, 1611661312, 5, 0,
  132830. _vq_quantlist__44c6_s_p8_1,
  132831. NULL,
  132832. &_vq_auxt__44c6_s_p8_1,
  132833. NULL,
  132834. 0
  132835. };
  132836. static long _vq_quantlist__44c6_s_p9_0[] = {
  132837. 6,
  132838. 5,
  132839. 7,
  132840. 4,
  132841. 8,
  132842. 3,
  132843. 9,
  132844. 2,
  132845. 10,
  132846. 1,
  132847. 11,
  132848. 0,
  132849. 12,
  132850. };
  132851. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132852. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132853. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132854. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132855. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132856. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132857. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132858. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132859. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132860. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132861. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132862. 10,10,10,10,10,10,10,10,10,
  132863. };
  132864. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132865. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132866. 1592.5, 2229.5, 2866.5, 3503.5,
  132867. };
  132868. static long _vq_quantmap__44c6_s_p9_0[] = {
  132869. 11, 9, 7, 5, 3, 1, 0, 2,
  132870. 4, 6, 8, 10, 12,
  132871. };
  132872. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132873. _vq_quantthresh__44c6_s_p9_0,
  132874. _vq_quantmap__44c6_s_p9_0,
  132875. 13,
  132876. 13
  132877. };
  132878. static static_codebook _44c6_s_p9_0 = {
  132879. 2, 169,
  132880. _vq_lengthlist__44c6_s_p9_0,
  132881. 1, -511845376, 1630791680, 4, 0,
  132882. _vq_quantlist__44c6_s_p9_0,
  132883. NULL,
  132884. &_vq_auxt__44c6_s_p9_0,
  132885. NULL,
  132886. 0
  132887. };
  132888. static long _vq_quantlist__44c6_s_p9_1[] = {
  132889. 6,
  132890. 5,
  132891. 7,
  132892. 4,
  132893. 8,
  132894. 3,
  132895. 9,
  132896. 2,
  132897. 10,
  132898. 1,
  132899. 11,
  132900. 0,
  132901. 12,
  132902. };
  132903. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132904. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132905. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132906. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132907. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132908. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132909. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132910. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132911. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132912. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132913. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132914. 15,12,10,11,11,13,11,12,13,
  132915. };
  132916. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132917. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132918. 122.5, 171.5, 220.5, 269.5,
  132919. };
  132920. static long _vq_quantmap__44c6_s_p9_1[] = {
  132921. 11, 9, 7, 5, 3, 1, 0, 2,
  132922. 4, 6, 8, 10, 12,
  132923. };
  132924. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132925. _vq_quantthresh__44c6_s_p9_1,
  132926. _vq_quantmap__44c6_s_p9_1,
  132927. 13,
  132928. 13
  132929. };
  132930. static static_codebook _44c6_s_p9_1 = {
  132931. 2, 169,
  132932. _vq_lengthlist__44c6_s_p9_1,
  132933. 1, -518889472, 1622704128, 4, 0,
  132934. _vq_quantlist__44c6_s_p9_1,
  132935. NULL,
  132936. &_vq_auxt__44c6_s_p9_1,
  132937. NULL,
  132938. 0
  132939. };
  132940. static long _vq_quantlist__44c6_s_p9_2[] = {
  132941. 24,
  132942. 23,
  132943. 25,
  132944. 22,
  132945. 26,
  132946. 21,
  132947. 27,
  132948. 20,
  132949. 28,
  132950. 19,
  132951. 29,
  132952. 18,
  132953. 30,
  132954. 17,
  132955. 31,
  132956. 16,
  132957. 32,
  132958. 15,
  132959. 33,
  132960. 14,
  132961. 34,
  132962. 13,
  132963. 35,
  132964. 12,
  132965. 36,
  132966. 11,
  132967. 37,
  132968. 10,
  132969. 38,
  132970. 9,
  132971. 39,
  132972. 8,
  132973. 40,
  132974. 7,
  132975. 41,
  132976. 6,
  132977. 42,
  132978. 5,
  132979. 43,
  132980. 4,
  132981. 44,
  132982. 3,
  132983. 45,
  132984. 2,
  132985. 46,
  132986. 1,
  132987. 47,
  132988. 0,
  132989. 48,
  132990. };
  132991. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132992. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132993. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132994. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132995. 7,
  132996. };
  132997. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132998. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132999. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133000. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133001. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133002. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133003. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133004. };
  133005. static long _vq_quantmap__44c6_s_p9_2[] = {
  133006. 47, 45, 43, 41, 39, 37, 35, 33,
  133007. 31, 29, 27, 25, 23, 21, 19, 17,
  133008. 15, 13, 11, 9, 7, 5, 3, 1,
  133009. 0, 2, 4, 6, 8, 10, 12, 14,
  133010. 16, 18, 20, 22, 24, 26, 28, 30,
  133011. 32, 34, 36, 38, 40, 42, 44, 46,
  133012. 48,
  133013. };
  133014. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133015. _vq_quantthresh__44c6_s_p9_2,
  133016. _vq_quantmap__44c6_s_p9_2,
  133017. 49,
  133018. 49
  133019. };
  133020. static static_codebook _44c6_s_p9_2 = {
  133021. 1, 49,
  133022. _vq_lengthlist__44c6_s_p9_2,
  133023. 1, -526909440, 1611661312, 6, 0,
  133024. _vq_quantlist__44c6_s_p9_2,
  133025. NULL,
  133026. &_vq_auxt__44c6_s_p9_2,
  133027. NULL,
  133028. 0
  133029. };
  133030. static long _huff_lengthlist__44c6_s_short[] = {
  133031. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133032. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133033. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133034. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133035. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133036. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133037. 9,10,17,18,
  133038. };
  133039. static static_codebook _huff_book__44c6_s_short = {
  133040. 2, 100,
  133041. _huff_lengthlist__44c6_s_short,
  133042. 0, 0, 0, 0, 0,
  133043. NULL,
  133044. NULL,
  133045. NULL,
  133046. NULL,
  133047. 0
  133048. };
  133049. static long _huff_lengthlist__44c7_s_long[] = {
  133050. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133051. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133052. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133053. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133054. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133055. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133056. 11,10,10,12,
  133057. };
  133058. static static_codebook _huff_book__44c7_s_long = {
  133059. 2, 100,
  133060. _huff_lengthlist__44c7_s_long,
  133061. 0, 0, 0, 0, 0,
  133062. NULL,
  133063. NULL,
  133064. NULL,
  133065. NULL,
  133066. 0
  133067. };
  133068. static long _vq_quantlist__44c7_s_p1_0[] = {
  133069. 1,
  133070. 0,
  133071. 2,
  133072. };
  133073. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133074. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133075. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133076. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133077. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133078. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133079. 8,
  133080. };
  133081. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133082. -0.5, 0.5,
  133083. };
  133084. static long _vq_quantmap__44c7_s_p1_0[] = {
  133085. 1, 0, 2,
  133086. };
  133087. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133088. _vq_quantthresh__44c7_s_p1_0,
  133089. _vq_quantmap__44c7_s_p1_0,
  133090. 3,
  133091. 3
  133092. };
  133093. static static_codebook _44c7_s_p1_0 = {
  133094. 4, 81,
  133095. _vq_lengthlist__44c7_s_p1_0,
  133096. 1, -535822336, 1611661312, 2, 0,
  133097. _vq_quantlist__44c7_s_p1_0,
  133098. NULL,
  133099. &_vq_auxt__44c7_s_p1_0,
  133100. NULL,
  133101. 0
  133102. };
  133103. static long _vq_quantlist__44c7_s_p2_0[] = {
  133104. 2,
  133105. 1,
  133106. 3,
  133107. 0,
  133108. 4,
  133109. };
  133110. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133111. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133112. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133113. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133114. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133115. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133116. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133117. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133118. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133120. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133121. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133122. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133123. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133124. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133125. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133126. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133128. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133129. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133130. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133131. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133132. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133133. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133134. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133136. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133137. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133138. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133139. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133140. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133141. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133142. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133147. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133148. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133149. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133150. 13,
  133151. };
  133152. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133153. -1.5, -0.5, 0.5, 1.5,
  133154. };
  133155. static long _vq_quantmap__44c7_s_p2_0[] = {
  133156. 3, 1, 0, 2, 4,
  133157. };
  133158. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133159. _vq_quantthresh__44c7_s_p2_0,
  133160. _vq_quantmap__44c7_s_p2_0,
  133161. 5,
  133162. 5
  133163. };
  133164. static static_codebook _44c7_s_p2_0 = {
  133165. 4, 625,
  133166. _vq_lengthlist__44c7_s_p2_0,
  133167. 1, -533725184, 1611661312, 3, 0,
  133168. _vq_quantlist__44c7_s_p2_0,
  133169. NULL,
  133170. &_vq_auxt__44c7_s_p2_0,
  133171. NULL,
  133172. 0
  133173. };
  133174. static long _vq_quantlist__44c7_s_p3_0[] = {
  133175. 4,
  133176. 3,
  133177. 5,
  133178. 2,
  133179. 6,
  133180. 1,
  133181. 7,
  133182. 0,
  133183. 8,
  133184. };
  133185. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133186. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133187. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133188. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133189. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133191. 0,
  133192. };
  133193. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133194. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133195. };
  133196. static long _vq_quantmap__44c7_s_p3_0[] = {
  133197. 7, 5, 3, 1, 0, 2, 4, 6,
  133198. 8,
  133199. };
  133200. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133201. _vq_quantthresh__44c7_s_p3_0,
  133202. _vq_quantmap__44c7_s_p3_0,
  133203. 9,
  133204. 9
  133205. };
  133206. static static_codebook _44c7_s_p3_0 = {
  133207. 2, 81,
  133208. _vq_lengthlist__44c7_s_p3_0,
  133209. 1, -531628032, 1611661312, 4, 0,
  133210. _vq_quantlist__44c7_s_p3_0,
  133211. NULL,
  133212. &_vq_auxt__44c7_s_p3_0,
  133213. NULL,
  133214. 0
  133215. };
  133216. static long _vq_quantlist__44c7_s_p4_0[] = {
  133217. 8,
  133218. 7,
  133219. 9,
  133220. 6,
  133221. 10,
  133222. 5,
  133223. 11,
  133224. 4,
  133225. 12,
  133226. 3,
  133227. 13,
  133228. 2,
  133229. 14,
  133230. 1,
  133231. 15,
  133232. 0,
  133233. 16,
  133234. };
  133235. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133236. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133237. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133238. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133239. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133240. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133241. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133242. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133243. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133244. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133245. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133254. 0,
  133255. };
  133256. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133257. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133258. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133259. };
  133260. static long _vq_quantmap__44c7_s_p4_0[] = {
  133261. 15, 13, 11, 9, 7, 5, 3, 1,
  133262. 0, 2, 4, 6, 8, 10, 12, 14,
  133263. 16,
  133264. };
  133265. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133266. _vq_quantthresh__44c7_s_p4_0,
  133267. _vq_quantmap__44c7_s_p4_0,
  133268. 17,
  133269. 17
  133270. };
  133271. static static_codebook _44c7_s_p4_0 = {
  133272. 2, 289,
  133273. _vq_lengthlist__44c7_s_p4_0,
  133274. 1, -529530880, 1611661312, 5, 0,
  133275. _vq_quantlist__44c7_s_p4_0,
  133276. NULL,
  133277. &_vq_auxt__44c7_s_p4_0,
  133278. NULL,
  133279. 0
  133280. };
  133281. static long _vq_quantlist__44c7_s_p5_0[] = {
  133282. 1,
  133283. 0,
  133284. 2,
  133285. };
  133286. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133287. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133288. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133289. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133290. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133291. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133292. 12,
  133293. };
  133294. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133295. -5.5, 5.5,
  133296. };
  133297. static long _vq_quantmap__44c7_s_p5_0[] = {
  133298. 1, 0, 2,
  133299. };
  133300. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133301. _vq_quantthresh__44c7_s_p5_0,
  133302. _vq_quantmap__44c7_s_p5_0,
  133303. 3,
  133304. 3
  133305. };
  133306. static static_codebook _44c7_s_p5_0 = {
  133307. 4, 81,
  133308. _vq_lengthlist__44c7_s_p5_0,
  133309. 1, -529137664, 1618345984, 2, 0,
  133310. _vq_quantlist__44c7_s_p5_0,
  133311. NULL,
  133312. &_vq_auxt__44c7_s_p5_0,
  133313. NULL,
  133314. 0
  133315. };
  133316. static long _vq_quantlist__44c7_s_p5_1[] = {
  133317. 5,
  133318. 4,
  133319. 6,
  133320. 3,
  133321. 7,
  133322. 2,
  133323. 8,
  133324. 1,
  133325. 9,
  133326. 0,
  133327. 10,
  133328. };
  133329. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133330. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133331. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133332. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133333. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133334. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133335. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133336. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133337. 11,11,11, 7, 7, 8, 8, 8, 8,
  133338. };
  133339. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133340. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133341. 3.5, 4.5,
  133342. };
  133343. static long _vq_quantmap__44c7_s_p5_1[] = {
  133344. 9, 7, 5, 3, 1, 0, 2, 4,
  133345. 6, 8, 10,
  133346. };
  133347. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133348. _vq_quantthresh__44c7_s_p5_1,
  133349. _vq_quantmap__44c7_s_p5_1,
  133350. 11,
  133351. 11
  133352. };
  133353. static static_codebook _44c7_s_p5_1 = {
  133354. 2, 121,
  133355. _vq_lengthlist__44c7_s_p5_1,
  133356. 1, -531365888, 1611661312, 4, 0,
  133357. _vq_quantlist__44c7_s_p5_1,
  133358. NULL,
  133359. &_vq_auxt__44c7_s_p5_1,
  133360. NULL,
  133361. 0
  133362. };
  133363. static long _vq_quantlist__44c7_s_p6_0[] = {
  133364. 6,
  133365. 5,
  133366. 7,
  133367. 4,
  133368. 8,
  133369. 3,
  133370. 9,
  133371. 2,
  133372. 10,
  133373. 1,
  133374. 11,
  133375. 0,
  133376. 12,
  133377. };
  133378. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133379. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133380. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133381. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133382. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133383. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133384. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133389. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133390. };
  133391. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133392. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133393. 12.5, 17.5, 22.5, 27.5,
  133394. };
  133395. static long _vq_quantmap__44c7_s_p6_0[] = {
  133396. 11, 9, 7, 5, 3, 1, 0, 2,
  133397. 4, 6, 8, 10, 12,
  133398. };
  133399. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133400. _vq_quantthresh__44c7_s_p6_0,
  133401. _vq_quantmap__44c7_s_p6_0,
  133402. 13,
  133403. 13
  133404. };
  133405. static static_codebook _44c7_s_p6_0 = {
  133406. 2, 169,
  133407. _vq_lengthlist__44c7_s_p6_0,
  133408. 1, -526516224, 1616117760, 4, 0,
  133409. _vq_quantlist__44c7_s_p6_0,
  133410. NULL,
  133411. &_vq_auxt__44c7_s_p6_0,
  133412. NULL,
  133413. 0
  133414. };
  133415. static long _vq_quantlist__44c7_s_p6_1[] = {
  133416. 2,
  133417. 1,
  133418. 3,
  133419. 0,
  133420. 4,
  133421. };
  133422. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133423. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133424. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133425. };
  133426. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133427. -1.5, -0.5, 0.5, 1.5,
  133428. };
  133429. static long _vq_quantmap__44c7_s_p6_1[] = {
  133430. 3, 1, 0, 2, 4,
  133431. };
  133432. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133433. _vq_quantthresh__44c7_s_p6_1,
  133434. _vq_quantmap__44c7_s_p6_1,
  133435. 5,
  133436. 5
  133437. };
  133438. static static_codebook _44c7_s_p6_1 = {
  133439. 2, 25,
  133440. _vq_lengthlist__44c7_s_p6_1,
  133441. 1, -533725184, 1611661312, 3, 0,
  133442. _vq_quantlist__44c7_s_p6_1,
  133443. NULL,
  133444. &_vq_auxt__44c7_s_p6_1,
  133445. NULL,
  133446. 0
  133447. };
  133448. static long _vq_quantlist__44c7_s_p7_0[] = {
  133449. 6,
  133450. 5,
  133451. 7,
  133452. 4,
  133453. 8,
  133454. 3,
  133455. 9,
  133456. 2,
  133457. 10,
  133458. 1,
  133459. 11,
  133460. 0,
  133461. 12,
  133462. };
  133463. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133464. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133465. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133466. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133467. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133468. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133469. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133470. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133471. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133472. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133473. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133474. 19,13,13,13,13,14,14,15,15,
  133475. };
  133476. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133477. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133478. 27.5, 38.5, 49.5, 60.5,
  133479. };
  133480. static long _vq_quantmap__44c7_s_p7_0[] = {
  133481. 11, 9, 7, 5, 3, 1, 0, 2,
  133482. 4, 6, 8, 10, 12,
  133483. };
  133484. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133485. _vq_quantthresh__44c7_s_p7_0,
  133486. _vq_quantmap__44c7_s_p7_0,
  133487. 13,
  133488. 13
  133489. };
  133490. static static_codebook _44c7_s_p7_0 = {
  133491. 2, 169,
  133492. _vq_lengthlist__44c7_s_p7_0,
  133493. 1, -523206656, 1618345984, 4, 0,
  133494. _vq_quantlist__44c7_s_p7_0,
  133495. NULL,
  133496. &_vq_auxt__44c7_s_p7_0,
  133497. NULL,
  133498. 0
  133499. };
  133500. static long _vq_quantlist__44c7_s_p7_1[] = {
  133501. 5,
  133502. 4,
  133503. 6,
  133504. 3,
  133505. 7,
  133506. 2,
  133507. 8,
  133508. 1,
  133509. 9,
  133510. 0,
  133511. 10,
  133512. };
  133513. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133514. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133515. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133516. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133517. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133518. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133519. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133520. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133521. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133522. };
  133523. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133524. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133525. 3.5, 4.5,
  133526. };
  133527. static long _vq_quantmap__44c7_s_p7_1[] = {
  133528. 9, 7, 5, 3, 1, 0, 2, 4,
  133529. 6, 8, 10,
  133530. };
  133531. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133532. _vq_quantthresh__44c7_s_p7_1,
  133533. _vq_quantmap__44c7_s_p7_1,
  133534. 11,
  133535. 11
  133536. };
  133537. static static_codebook _44c7_s_p7_1 = {
  133538. 2, 121,
  133539. _vq_lengthlist__44c7_s_p7_1,
  133540. 1, -531365888, 1611661312, 4, 0,
  133541. _vq_quantlist__44c7_s_p7_1,
  133542. NULL,
  133543. &_vq_auxt__44c7_s_p7_1,
  133544. NULL,
  133545. 0
  133546. };
  133547. static long _vq_quantlist__44c7_s_p8_0[] = {
  133548. 7,
  133549. 6,
  133550. 8,
  133551. 5,
  133552. 9,
  133553. 4,
  133554. 10,
  133555. 3,
  133556. 11,
  133557. 2,
  133558. 12,
  133559. 1,
  133560. 13,
  133561. 0,
  133562. 14,
  133563. };
  133564. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133565. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133566. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133567. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133568. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133569. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133570. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133571. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133572. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133573. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133574. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133575. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133576. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133577. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133578. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133579. 14,
  133580. };
  133581. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133582. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133583. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133584. };
  133585. static long _vq_quantmap__44c7_s_p8_0[] = {
  133586. 13, 11, 9, 7, 5, 3, 1, 0,
  133587. 2, 4, 6, 8, 10, 12, 14,
  133588. };
  133589. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133590. _vq_quantthresh__44c7_s_p8_0,
  133591. _vq_quantmap__44c7_s_p8_0,
  133592. 15,
  133593. 15
  133594. };
  133595. static static_codebook _44c7_s_p8_0 = {
  133596. 2, 225,
  133597. _vq_lengthlist__44c7_s_p8_0,
  133598. 1, -520986624, 1620377600, 4, 0,
  133599. _vq_quantlist__44c7_s_p8_0,
  133600. NULL,
  133601. &_vq_auxt__44c7_s_p8_0,
  133602. NULL,
  133603. 0
  133604. };
  133605. static long _vq_quantlist__44c7_s_p8_1[] = {
  133606. 10,
  133607. 9,
  133608. 11,
  133609. 8,
  133610. 12,
  133611. 7,
  133612. 13,
  133613. 6,
  133614. 14,
  133615. 5,
  133616. 15,
  133617. 4,
  133618. 16,
  133619. 3,
  133620. 17,
  133621. 2,
  133622. 18,
  133623. 1,
  133624. 19,
  133625. 0,
  133626. 20,
  133627. };
  133628. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133629. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133630. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133631. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133632. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133633. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133634. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133635. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133636. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133637. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133638. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133639. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133640. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133641. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133642. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133643. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133644. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133645. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133646. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133647. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133648. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133649. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133650. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133651. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133652. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133653. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133654. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133655. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133656. 10,10,10,10,10,10,10,10,10,
  133657. };
  133658. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133659. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133660. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133661. 6.5, 7.5, 8.5, 9.5,
  133662. };
  133663. static long _vq_quantmap__44c7_s_p8_1[] = {
  133664. 19, 17, 15, 13, 11, 9, 7, 5,
  133665. 3, 1, 0, 2, 4, 6, 8, 10,
  133666. 12, 14, 16, 18, 20,
  133667. };
  133668. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133669. _vq_quantthresh__44c7_s_p8_1,
  133670. _vq_quantmap__44c7_s_p8_1,
  133671. 21,
  133672. 21
  133673. };
  133674. static static_codebook _44c7_s_p8_1 = {
  133675. 2, 441,
  133676. _vq_lengthlist__44c7_s_p8_1,
  133677. 1, -529268736, 1611661312, 5, 0,
  133678. _vq_quantlist__44c7_s_p8_1,
  133679. NULL,
  133680. &_vq_auxt__44c7_s_p8_1,
  133681. NULL,
  133682. 0
  133683. };
  133684. static long _vq_quantlist__44c7_s_p9_0[] = {
  133685. 6,
  133686. 5,
  133687. 7,
  133688. 4,
  133689. 8,
  133690. 3,
  133691. 9,
  133692. 2,
  133693. 10,
  133694. 1,
  133695. 11,
  133696. 0,
  133697. 12,
  133698. };
  133699. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133700. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133701. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133710. 11,11,11,11,11,11,11,11,11,
  133711. };
  133712. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133713. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133714. 1592.5, 2229.5, 2866.5, 3503.5,
  133715. };
  133716. static long _vq_quantmap__44c7_s_p9_0[] = {
  133717. 11, 9, 7, 5, 3, 1, 0, 2,
  133718. 4, 6, 8, 10, 12,
  133719. };
  133720. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133721. _vq_quantthresh__44c7_s_p9_0,
  133722. _vq_quantmap__44c7_s_p9_0,
  133723. 13,
  133724. 13
  133725. };
  133726. static static_codebook _44c7_s_p9_0 = {
  133727. 2, 169,
  133728. _vq_lengthlist__44c7_s_p9_0,
  133729. 1, -511845376, 1630791680, 4, 0,
  133730. _vq_quantlist__44c7_s_p9_0,
  133731. NULL,
  133732. &_vq_auxt__44c7_s_p9_0,
  133733. NULL,
  133734. 0
  133735. };
  133736. static long _vq_quantlist__44c7_s_p9_1[] = {
  133737. 6,
  133738. 5,
  133739. 7,
  133740. 4,
  133741. 8,
  133742. 3,
  133743. 9,
  133744. 2,
  133745. 10,
  133746. 1,
  133747. 11,
  133748. 0,
  133749. 12,
  133750. };
  133751. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133752. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133753. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133754. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133755. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133756. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133757. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133758. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133759. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133760. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133761. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133762. 15,11,11,10,10,12,12,12,12,
  133763. };
  133764. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133765. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133766. 122.5, 171.5, 220.5, 269.5,
  133767. };
  133768. static long _vq_quantmap__44c7_s_p9_1[] = {
  133769. 11, 9, 7, 5, 3, 1, 0, 2,
  133770. 4, 6, 8, 10, 12,
  133771. };
  133772. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133773. _vq_quantthresh__44c7_s_p9_1,
  133774. _vq_quantmap__44c7_s_p9_1,
  133775. 13,
  133776. 13
  133777. };
  133778. static static_codebook _44c7_s_p9_1 = {
  133779. 2, 169,
  133780. _vq_lengthlist__44c7_s_p9_1,
  133781. 1, -518889472, 1622704128, 4, 0,
  133782. _vq_quantlist__44c7_s_p9_1,
  133783. NULL,
  133784. &_vq_auxt__44c7_s_p9_1,
  133785. NULL,
  133786. 0
  133787. };
  133788. static long _vq_quantlist__44c7_s_p9_2[] = {
  133789. 24,
  133790. 23,
  133791. 25,
  133792. 22,
  133793. 26,
  133794. 21,
  133795. 27,
  133796. 20,
  133797. 28,
  133798. 19,
  133799. 29,
  133800. 18,
  133801. 30,
  133802. 17,
  133803. 31,
  133804. 16,
  133805. 32,
  133806. 15,
  133807. 33,
  133808. 14,
  133809. 34,
  133810. 13,
  133811. 35,
  133812. 12,
  133813. 36,
  133814. 11,
  133815. 37,
  133816. 10,
  133817. 38,
  133818. 9,
  133819. 39,
  133820. 8,
  133821. 40,
  133822. 7,
  133823. 41,
  133824. 6,
  133825. 42,
  133826. 5,
  133827. 43,
  133828. 4,
  133829. 44,
  133830. 3,
  133831. 45,
  133832. 2,
  133833. 46,
  133834. 1,
  133835. 47,
  133836. 0,
  133837. 48,
  133838. };
  133839. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133840. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133841. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133842. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133843. 7,
  133844. };
  133845. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133846. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133847. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133848. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133849. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133850. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133851. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133852. };
  133853. static long _vq_quantmap__44c7_s_p9_2[] = {
  133854. 47, 45, 43, 41, 39, 37, 35, 33,
  133855. 31, 29, 27, 25, 23, 21, 19, 17,
  133856. 15, 13, 11, 9, 7, 5, 3, 1,
  133857. 0, 2, 4, 6, 8, 10, 12, 14,
  133858. 16, 18, 20, 22, 24, 26, 28, 30,
  133859. 32, 34, 36, 38, 40, 42, 44, 46,
  133860. 48,
  133861. };
  133862. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133863. _vq_quantthresh__44c7_s_p9_2,
  133864. _vq_quantmap__44c7_s_p9_2,
  133865. 49,
  133866. 49
  133867. };
  133868. static static_codebook _44c7_s_p9_2 = {
  133869. 1, 49,
  133870. _vq_lengthlist__44c7_s_p9_2,
  133871. 1, -526909440, 1611661312, 6, 0,
  133872. _vq_quantlist__44c7_s_p9_2,
  133873. NULL,
  133874. &_vq_auxt__44c7_s_p9_2,
  133875. NULL,
  133876. 0
  133877. };
  133878. static long _huff_lengthlist__44c7_s_short[] = {
  133879. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133880. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133881. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133882. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133883. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133884. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133885. 10, 9,11,14,
  133886. };
  133887. static static_codebook _huff_book__44c7_s_short = {
  133888. 2, 100,
  133889. _huff_lengthlist__44c7_s_short,
  133890. 0, 0, 0, 0, 0,
  133891. NULL,
  133892. NULL,
  133893. NULL,
  133894. NULL,
  133895. 0
  133896. };
  133897. static long _huff_lengthlist__44c8_s_long[] = {
  133898. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133899. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133900. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133901. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133902. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133903. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133904. 11, 9, 9,10,
  133905. };
  133906. static static_codebook _huff_book__44c8_s_long = {
  133907. 2, 100,
  133908. _huff_lengthlist__44c8_s_long,
  133909. 0, 0, 0, 0, 0,
  133910. NULL,
  133911. NULL,
  133912. NULL,
  133913. NULL,
  133914. 0
  133915. };
  133916. static long _vq_quantlist__44c8_s_p1_0[] = {
  133917. 1,
  133918. 0,
  133919. 2,
  133920. };
  133921. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133922. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133923. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133924. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133925. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133926. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133927. 8,
  133928. };
  133929. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133930. -0.5, 0.5,
  133931. };
  133932. static long _vq_quantmap__44c8_s_p1_0[] = {
  133933. 1, 0, 2,
  133934. };
  133935. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133936. _vq_quantthresh__44c8_s_p1_0,
  133937. _vq_quantmap__44c8_s_p1_0,
  133938. 3,
  133939. 3
  133940. };
  133941. static static_codebook _44c8_s_p1_0 = {
  133942. 4, 81,
  133943. _vq_lengthlist__44c8_s_p1_0,
  133944. 1, -535822336, 1611661312, 2, 0,
  133945. _vq_quantlist__44c8_s_p1_0,
  133946. NULL,
  133947. &_vq_auxt__44c8_s_p1_0,
  133948. NULL,
  133949. 0
  133950. };
  133951. static long _vq_quantlist__44c8_s_p2_0[] = {
  133952. 2,
  133953. 1,
  133954. 3,
  133955. 0,
  133956. 4,
  133957. };
  133958. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133959. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133960. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133961. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133962. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133963. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133964. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133965. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133966. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133968. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133969. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133970. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133971. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133972. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133973. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133974. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133976. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133977. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133978. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133979. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133980. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133981. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133982. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133984. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133985. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133986. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133987. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133988. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133989. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133990. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133995. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133996. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133997. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133998. 13,
  133999. };
  134000. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134001. -1.5, -0.5, 0.5, 1.5,
  134002. };
  134003. static long _vq_quantmap__44c8_s_p2_0[] = {
  134004. 3, 1, 0, 2, 4,
  134005. };
  134006. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134007. _vq_quantthresh__44c8_s_p2_0,
  134008. _vq_quantmap__44c8_s_p2_0,
  134009. 5,
  134010. 5
  134011. };
  134012. static static_codebook _44c8_s_p2_0 = {
  134013. 4, 625,
  134014. _vq_lengthlist__44c8_s_p2_0,
  134015. 1, -533725184, 1611661312, 3, 0,
  134016. _vq_quantlist__44c8_s_p2_0,
  134017. NULL,
  134018. &_vq_auxt__44c8_s_p2_0,
  134019. NULL,
  134020. 0
  134021. };
  134022. static long _vq_quantlist__44c8_s_p3_0[] = {
  134023. 4,
  134024. 3,
  134025. 5,
  134026. 2,
  134027. 6,
  134028. 1,
  134029. 7,
  134030. 0,
  134031. 8,
  134032. };
  134033. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134034. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134035. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134036. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134037. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134039. 0,
  134040. };
  134041. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134042. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134043. };
  134044. static long _vq_quantmap__44c8_s_p3_0[] = {
  134045. 7, 5, 3, 1, 0, 2, 4, 6,
  134046. 8,
  134047. };
  134048. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134049. _vq_quantthresh__44c8_s_p3_0,
  134050. _vq_quantmap__44c8_s_p3_0,
  134051. 9,
  134052. 9
  134053. };
  134054. static static_codebook _44c8_s_p3_0 = {
  134055. 2, 81,
  134056. _vq_lengthlist__44c8_s_p3_0,
  134057. 1, -531628032, 1611661312, 4, 0,
  134058. _vq_quantlist__44c8_s_p3_0,
  134059. NULL,
  134060. &_vq_auxt__44c8_s_p3_0,
  134061. NULL,
  134062. 0
  134063. };
  134064. static long _vq_quantlist__44c8_s_p4_0[] = {
  134065. 8,
  134066. 7,
  134067. 9,
  134068. 6,
  134069. 10,
  134070. 5,
  134071. 11,
  134072. 4,
  134073. 12,
  134074. 3,
  134075. 13,
  134076. 2,
  134077. 14,
  134078. 1,
  134079. 15,
  134080. 0,
  134081. 16,
  134082. };
  134083. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134084. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134085. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134086. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134087. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134088. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134089. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134090. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134091. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134092. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134093. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134102. 0,
  134103. };
  134104. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134105. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134106. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134107. };
  134108. static long _vq_quantmap__44c8_s_p4_0[] = {
  134109. 15, 13, 11, 9, 7, 5, 3, 1,
  134110. 0, 2, 4, 6, 8, 10, 12, 14,
  134111. 16,
  134112. };
  134113. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134114. _vq_quantthresh__44c8_s_p4_0,
  134115. _vq_quantmap__44c8_s_p4_0,
  134116. 17,
  134117. 17
  134118. };
  134119. static static_codebook _44c8_s_p4_0 = {
  134120. 2, 289,
  134121. _vq_lengthlist__44c8_s_p4_0,
  134122. 1, -529530880, 1611661312, 5, 0,
  134123. _vq_quantlist__44c8_s_p4_0,
  134124. NULL,
  134125. &_vq_auxt__44c8_s_p4_0,
  134126. NULL,
  134127. 0
  134128. };
  134129. static long _vq_quantlist__44c8_s_p5_0[] = {
  134130. 1,
  134131. 0,
  134132. 2,
  134133. };
  134134. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134135. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134136. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134137. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134138. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134139. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134140. 12,
  134141. };
  134142. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134143. -5.5, 5.5,
  134144. };
  134145. static long _vq_quantmap__44c8_s_p5_0[] = {
  134146. 1, 0, 2,
  134147. };
  134148. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134149. _vq_quantthresh__44c8_s_p5_0,
  134150. _vq_quantmap__44c8_s_p5_0,
  134151. 3,
  134152. 3
  134153. };
  134154. static static_codebook _44c8_s_p5_0 = {
  134155. 4, 81,
  134156. _vq_lengthlist__44c8_s_p5_0,
  134157. 1, -529137664, 1618345984, 2, 0,
  134158. _vq_quantlist__44c8_s_p5_0,
  134159. NULL,
  134160. &_vq_auxt__44c8_s_p5_0,
  134161. NULL,
  134162. 0
  134163. };
  134164. static long _vq_quantlist__44c8_s_p5_1[] = {
  134165. 5,
  134166. 4,
  134167. 6,
  134168. 3,
  134169. 7,
  134170. 2,
  134171. 8,
  134172. 1,
  134173. 9,
  134174. 0,
  134175. 10,
  134176. };
  134177. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134178. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134179. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134180. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134181. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134182. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134183. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134184. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134185. 11,11,11, 7, 7, 7, 7, 8, 8,
  134186. };
  134187. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134188. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134189. 3.5, 4.5,
  134190. };
  134191. static long _vq_quantmap__44c8_s_p5_1[] = {
  134192. 9, 7, 5, 3, 1, 0, 2, 4,
  134193. 6, 8, 10,
  134194. };
  134195. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134196. _vq_quantthresh__44c8_s_p5_1,
  134197. _vq_quantmap__44c8_s_p5_1,
  134198. 11,
  134199. 11
  134200. };
  134201. static static_codebook _44c8_s_p5_1 = {
  134202. 2, 121,
  134203. _vq_lengthlist__44c8_s_p5_1,
  134204. 1, -531365888, 1611661312, 4, 0,
  134205. _vq_quantlist__44c8_s_p5_1,
  134206. NULL,
  134207. &_vq_auxt__44c8_s_p5_1,
  134208. NULL,
  134209. 0
  134210. };
  134211. static long _vq_quantlist__44c8_s_p6_0[] = {
  134212. 6,
  134213. 5,
  134214. 7,
  134215. 4,
  134216. 8,
  134217. 3,
  134218. 9,
  134219. 2,
  134220. 10,
  134221. 1,
  134222. 11,
  134223. 0,
  134224. 12,
  134225. };
  134226. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134227. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134228. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134229. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134230. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134231. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134232. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134237. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134238. };
  134239. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134240. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134241. 12.5, 17.5, 22.5, 27.5,
  134242. };
  134243. static long _vq_quantmap__44c8_s_p6_0[] = {
  134244. 11, 9, 7, 5, 3, 1, 0, 2,
  134245. 4, 6, 8, 10, 12,
  134246. };
  134247. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134248. _vq_quantthresh__44c8_s_p6_0,
  134249. _vq_quantmap__44c8_s_p6_0,
  134250. 13,
  134251. 13
  134252. };
  134253. static static_codebook _44c8_s_p6_0 = {
  134254. 2, 169,
  134255. _vq_lengthlist__44c8_s_p6_0,
  134256. 1, -526516224, 1616117760, 4, 0,
  134257. _vq_quantlist__44c8_s_p6_0,
  134258. NULL,
  134259. &_vq_auxt__44c8_s_p6_0,
  134260. NULL,
  134261. 0
  134262. };
  134263. static long _vq_quantlist__44c8_s_p6_1[] = {
  134264. 2,
  134265. 1,
  134266. 3,
  134267. 0,
  134268. 4,
  134269. };
  134270. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134271. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134272. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134273. };
  134274. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134275. -1.5, -0.5, 0.5, 1.5,
  134276. };
  134277. static long _vq_quantmap__44c8_s_p6_1[] = {
  134278. 3, 1, 0, 2, 4,
  134279. };
  134280. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134281. _vq_quantthresh__44c8_s_p6_1,
  134282. _vq_quantmap__44c8_s_p6_1,
  134283. 5,
  134284. 5
  134285. };
  134286. static static_codebook _44c8_s_p6_1 = {
  134287. 2, 25,
  134288. _vq_lengthlist__44c8_s_p6_1,
  134289. 1, -533725184, 1611661312, 3, 0,
  134290. _vq_quantlist__44c8_s_p6_1,
  134291. NULL,
  134292. &_vq_auxt__44c8_s_p6_1,
  134293. NULL,
  134294. 0
  134295. };
  134296. static long _vq_quantlist__44c8_s_p7_0[] = {
  134297. 6,
  134298. 5,
  134299. 7,
  134300. 4,
  134301. 8,
  134302. 3,
  134303. 9,
  134304. 2,
  134305. 10,
  134306. 1,
  134307. 11,
  134308. 0,
  134309. 12,
  134310. };
  134311. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134312. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134313. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134314. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134315. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134316. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134317. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134318. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134319. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134320. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134321. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134322. 20,13,13,13,13,14,13,15,15,
  134323. };
  134324. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134325. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134326. 27.5, 38.5, 49.5, 60.5,
  134327. };
  134328. static long _vq_quantmap__44c8_s_p7_0[] = {
  134329. 11, 9, 7, 5, 3, 1, 0, 2,
  134330. 4, 6, 8, 10, 12,
  134331. };
  134332. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134333. _vq_quantthresh__44c8_s_p7_0,
  134334. _vq_quantmap__44c8_s_p7_0,
  134335. 13,
  134336. 13
  134337. };
  134338. static static_codebook _44c8_s_p7_0 = {
  134339. 2, 169,
  134340. _vq_lengthlist__44c8_s_p7_0,
  134341. 1, -523206656, 1618345984, 4, 0,
  134342. _vq_quantlist__44c8_s_p7_0,
  134343. NULL,
  134344. &_vq_auxt__44c8_s_p7_0,
  134345. NULL,
  134346. 0
  134347. };
  134348. static long _vq_quantlist__44c8_s_p7_1[] = {
  134349. 5,
  134350. 4,
  134351. 6,
  134352. 3,
  134353. 7,
  134354. 2,
  134355. 8,
  134356. 1,
  134357. 9,
  134358. 0,
  134359. 10,
  134360. };
  134361. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134362. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134363. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134364. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134365. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134366. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134367. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134368. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134369. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134370. };
  134371. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134372. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134373. 3.5, 4.5,
  134374. };
  134375. static long _vq_quantmap__44c8_s_p7_1[] = {
  134376. 9, 7, 5, 3, 1, 0, 2, 4,
  134377. 6, 8, 10,
  134378. };
  134379. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134380. _vq_quantthresh__44c8_s_p7_1,
  134381. _vq_quantmap__44c8_s_p7_1,
  134382. 11,
  134383. 11
  134384. };
  134385. static static_codebook _44c8_s_p7_1 = {
  134386. 2, 121,
  134387. _vq_lengthlist__44c8_s_p7_1,
  134388. 1, -531365888, 1611661312, 4, 0,
  134389. _vq_quantlist__44c8_s_p7_1,
  134390. NULL,
  134391. &_vq_auxt__44c8_s_p7_1,
  134392. NULL,
  134393. 0
  134394. };
  134395. static long _vq_quantlist__44c8_s_p8_0[] = {
  134396. 7,
  134397. 6,
  134398. 8,
  134399. 5,
  134400. 9,
  134401. 4,
  134402. 10,
  134403. 3,
  134404. 11,
  134405. 2,
  134406. 12,
  134407. 1,
  134408. 13,
  134409. 0,
  134410. 14,
  134411. };
  134412. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134413. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134414. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134415. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134416. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134417. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134418. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134419. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134420. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134421. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134422. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134423. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134424. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134425. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134426. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134427. 15,
  134428. };
  134429. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134430. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134431. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134432. };
  134433. static long _vq_quantmap__44c8_s_p8_0[] = {
  134434. 13, 11, 9, 7, 5, 3, 1, 0,
  134435. 2, 4, 6, 8, 10, 12, 14,
  134436. };
  134437. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134438. _vq_quantthresh__44c8_s_p8_0,
  134439. _vq_quantmap__44c8_s_p8_0,
  134440. 15,
  134441. 15
  134442. };
  134443. static static_codebook _44c8_s_p8_0 = {
  134444. 2, 225,
  134445. _vq_lengthlist__44c8_s_p8_0,
  134446. 1, -520986624, 1620377600, 4, 0,
  134447. _vq_quantlist__44c8_s_p8_0,
  134448. NULL,
  134449. &_vq_auxt__44c8_s_p8_0,
  134450. NULL,
  134451. 0
  134452. };
  134453. static long _vq_quantlist__44c8_s_p8_1[] = {
  134454. 10,
  134455. 9,
  134456. 11,
  134457. 8,
  134458. 12,
  134459. 7,
  134460. 13,
  134461. 6,
  134462. 14,
  134463. 5,
  134464. 15,
  134465. 4,
  134466. 16,
  134467. 3,
  134468. 17,
  134469. 2,
  134470. 18,
  134471. 1,
  134472. 19,
  134473. 0,
  134474. 20,
  134475. };
  134476. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134477. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134478. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134479. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134480. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134481. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134482. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134483. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134484. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134485. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134486. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134487. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134488. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134489. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134490. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134491. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134492. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134493. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134494. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134495. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134496. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134497. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134498. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134499. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134500. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134501. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134502. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134503. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134504. 10, 9, 9,10,10, 9,10, 9, 9,
  134505. };
  134506. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134507. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134508. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134509. 6.5, 7.5, 8.5, 9.5,
  134510. };
  134511. static long _vq_quantmap__44c8_s_p8_1[] = {
  134512. 19, 17, 15, 13, 11, 9, 7, 5,
  134513. 3, 1, 0, 2, 4, 6, 8, 10,
  134514. 12, 14, 16, 18, 20,
  134515. };
  134516. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134517. _vq_quantthresh__44c8_s_p8_1,
  134518. _vq_quantmap__44c8_s_p8_1,
  134519. 21,
  134520. 21
  134521. };
  134522. static static_codebook _44c8_s_p8_1 = {
  134523. 2, 441,
  134524. _vq_lengthlist__44c8_s_p8_1,
  134525. 1, -529268736, 1611661312, 5, 0,
  134526. _vq_quantlist__44c8_s_p8_1,
  134527. NULL,
  134528. &_vq_auxt__44c8_s_p8_1,
  134529. NULL,
  134530. 0
  134531. };
  134532. static long _vq_quantlist__44c8_s_p9_0[] = {
  134533. 8,
  134534. 7,
  134535. 9,
  134536. 6,
  134537. 10,
  134538. 5,
  134539. 11,
  134540. 4,
  134541. 12,
  134542. 3,
  134543. 13,
  134544. 2,
  134545. 14,
  134546. 1,
  134547. 15,
  134548. 0,
  134549. 16,
  134550. };
  134551. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134552. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134553. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134554. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134555. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134556. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134557. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134558. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134559. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134560. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134561. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134562. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134563. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134564. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134565. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134566. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134567. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134568. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134569. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134570. 10,
  134571. };
  134572. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134573. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134574. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134575. };
  134576. static long _vq_quantmap__44c8_s_p9_0[] = {
  134577. 15, 13, 11, 9, 7, 5, 3, 1,
  134578. 0, 2, 4, 6, 8, 10, 12, 14,
  134579. 16,
  134580. };
  134581. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134582. _vq_quantthresh__44c8_s_p9_0,
  134583. _vq_quantmap__44c8_s_p9_0,
  134584. 17,
  134585. 17
  134586. };
  134587. static static_codebook _44c8_s_p9_0 = {
  134588. 2, 289,
  134589. _vq_lengthlist__44c8_s_p9_0,
  134590. 1, -509798400, 1631393792, 5, 0,
  134591. _vq_quantlist__44c8_s_p9_0,
  134592. NULL,
  134593. &_vq_auxt__44c8_s_p9_0,
  134594. NULL,
  134595. 0
  134596. };
  134597. static long _vq_quantlist__44c8_s_p9_1[] = {
  134598. 9,
  134599. 8,
  134600. 10,
  134601. 7,
  134602. 11,
  134603. 6,
  134604. 12,
  134605. 5,
  134606. 13,
  134607. 4,
  134608. 14,
  134609. 3,
  134610. 15,
  134611. 2,
  134612. 16,
  134613. 1,
  134614. 17,
  134615. 0,
  134616. 18,
  134617. };
  134618. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134619. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134620. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134621. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134622. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134623. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134624. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134625. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134626. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134627. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134628. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134629. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134630. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134631. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134632. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134633. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134634. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134635. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134636. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134637. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134638. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134639. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134640. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134641. 14,13,13,14,14,15,14,15,14,
  134642. };
  134643. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134644. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134645. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134646. 367.5, 416.5,
  134647. };
  134648. static long _vq_quantmap__44c8_s_p9_1[] = {
  134649. 17, 15, 13, 11, 9, 7, 5, 3,
  134650. 1, 0, 2, 4, 6, 8, 10, 12,
  134651. 14, 16, 18,
  134652. };
  134653. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134654. _vq_quantthresh__44c8_s_p9_1,
  134655. _vq_quantmap__44c8_s_p9_1,
  134656. 19,
  134657. 19
  134658. };
  134659. static static_codebook _44c8_s_p9_1 = {
  134660. 2, 361,
  134661. _vq_lengthlist__44c8_s_p9_1,
  134662. 1, -518287360, 1622704128, 5, 0,
  134663. _vq_quantlist__44c8_s_p9_1,
  134664. NULL,
  134665. &_vq_auxt__44c8_s_p9_1,
  134666. NULL,
  134667. 0
  134668. };
  134669. static long _vq_quantlist__44c8_s_p9_2[] = {
  134670. 24,
  134671. 23,
  134672. 25,
  134673. 22,
  134674. 26,
  134675. 21,
  134676. 27,
  134677. 20,
  134678. 28,
  134679. 19,
  134680. 29,
  134681. 18,
  134682. 30,
  134683. 17,
  134684. 31,
  134685. 16,
  134686. 32,
  134687. 15,
  134688. 33,
  134689. 14,
  134690. 34,
  134691. 13,
  134692. 35,
  134693. 12,
  134694. 36,
  134695. 11,
  134696. 37,
  134697. 10,
  134698. 38,
  134699. 9,
  134700. 39,
  134701. 8,
  134702. 40,
  134703. 7,
  134704. 41,
  134705. 6,
  134706. 42,
  134707. 5,
  134708. 43,
  134709. 4,
  134710. 44,
  134711. 3,
  134712. 45,
  134713. 2,
  134714. 46,
  134715. 1,
  134716. 47,
  134717. 0,
  134718. 48,
  134719. };
  134720. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134721. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134722. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134723. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134724. 7,
  134725. };
  134726. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134727. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134728. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134729. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134730. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134731. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134732. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134733. };
  134734. static long _vq_quantmap__44c8_s_p9_2[] = {
  134735. 47, 45, 43, 41, 39, 37, 35, 33,
  134736. 31, 29, 27, 25, 23, 21, 19, 17,
  134737. 15, 13, 11, 9, 7, 5, 3, 1,
  134738. 0, 2, 4, 6, 8, 10, 12, 14,
  134739. 16, 18, 20, 22, 24, 26, 28, 30,
  134740. 32, 34, 36, 38, 40, 42, 44, 46,
  134741. 48,
  134742. };
  134743. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134744. _vq_quantthresh__44c8_s_p9_2,
  134745. _vq_quantmap__44c8_s_p9_2,
  134746. 49,
  134747. 49
  134748. };
  134749. static static_codebook _44c8_s_p9_2 = {
  134750. 1, 49,
  134751. _vq_lengthlist__44c8_s_p9_2,
  134752. 1, -526909440, 1611661312, 6, 0,
  134753. _vq_quantlist__44c8_s_p9_2,
  134754. NULL,
  134755. &_vq_auxt__44c8_s_p9_2,
  134756. NULL,
  134757. 0
  134758. };
  134759. static long _huff_lengthlist__44c8_s_short[] = {
  134760. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134761. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134762. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134763. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134764. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134765. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134766. 10, 9,11,14,
  134767. };
  134768. static static_codebook _huff_book__44c8_s_short = {
  134769. 2, 100,
  134770. _huff_lengthlist__44c8_s_short,
  134771. 0, 0, 0, 0, 0,
  134772. NULL,
  134773. NULL,
  134774. NULL,
  134775. NULL,
  134776. 0
  134777. };
  134778. static long _huff_lengthlist__44c9_s_long[] = {
  134779. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134780. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134781. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134782. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134783. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134784. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134785. 10, 9, 8, 9,
  134786. };
  134787. static static_codebook _huff_book__44c9_s_long = {
  134788. 2, 100,
  134789. _huff_lengthlist__44c9_s_long,
  134790. 0, 0, 0, 0, 0,
  134791. NULL,
  134792. NULL,
  134793. NULL,
  134794. NULL,
  134795. 0
  134796. };
  134797. static long _vq_quantlist__44c9_s_p1_0[] = {
  134798. 1,
  134799. 0,
  134800. 2,
  134801. };
  134802. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134803. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134804. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134805. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134806. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134807. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134808. 7,
  134809. };
  134810. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134811. -0.5, 0.5,
  134812. };
  134813. static long _vq_quantmap__44c9_s_p1_0[] = {
  134814. 1, 0, 2,
  134815. };
  134816. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134817. _vq_quantthresh__44c9_s_p1_0,
  134818. _vq_quantmap__44c9_s_p1_0,
  134819. 3,
  134820. 3
  134821. };
  134822. static static_codebook _44c9_s_p1_0 = {
  134823. 4, 81,
  134824. _vq_lengthlist__44c9_s_p1_0,
  134825. 1, -535822336, 1611661312, 2, 0,
  134826. _vq_quantlist__44c9_s_p1_0,
  134827. NULL,
  134828. &_vq_auxt__44c9_s_p1_0,
  134829. NULL,
  134830. 0
  134831. };
  134832. static long _vq_quantlist__44c9_s_p2_0[] = {
  134833. 2,
  134834. 1,
  134835. 3,
  134836. 0,
  134837. 4,
  134838. };
  134839. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134840. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134841. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134842. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134843. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134844. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134845. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134846. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134847. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134849. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134850. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134851. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134852. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134853. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134854. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134855. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134857. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134858. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134859. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134860. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134861. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134862. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134863. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134865. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134866. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134867. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134868. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134869. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134870. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134871. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134876. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134877. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134878. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134879. 12,
  134880. };
  134881. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134882. -1.5, -0.5, 0.5, 1.5,
  134883. };
  134884. static long _vq_quantmap__44c9_s_p2_0[] = {
  134885. 3, 1, 0, 2, 4,
  134886. };
  134887. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134888. _vq_quantthresh__44c9_s_p2_0,
  134889. _vq_quantmap__44c9_s_p2_0,
  134890. 5,
  134891. 5
  134892. };
  134893. static static_codebook _44c9_s_p2_0 = {
  134894. 4, 625,
  134895. _vq_lengthlist__44c9_s_p2_0,
  134896. 1, -533725184, 1611661312, 3, 0,
  134897. _vq_quantlist__44c9_s_p2_0,
  134898. NULL,
  134899. &_vq_auxt__44c9_s_p2_0,
  134900. NULL,
  134901. 0
  134902. };
  134903. static long _vq_quantlist__44c9_s_p3_0[] = {
  134904. 4,
  134905. 3,
  134906. 5,
  134907. 2,
  134908. 6,
  134909. 1,
  134910. 7,
  134911. 0,
  134912. 8,
  134913. };
  134914. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134915. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134916. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134917. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134918. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134920. 0,
  134921. };
  134922. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134923. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134924. };
  134925. static long _vq_quantmap__44c9_s_p3_0[] = {
  134926. 7, 5, 3, 1, 0, 2, 4, 6,
  134927. 8,
  134928. };
  134929. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134930. _vq_quantthresh__44c9_s_p3_0,
  134931. _vq_quantmap__44c9_s_p3_0,
  134932. 9,
  134933. 9
  134934. };
  134935. static static_codebook _44c9_s_p3_0 = {
  134936. 2, 81,
  134937. _vq_lengthlist__44c9_s_p3_0,
  134938. 1, -531628032, 1611661312, 4, 0,
  134939. _vq_quantlist__44c9_s_p3_0,
  134940. NULL,
  134941. &_vq_auxt__44c9_s_p3_0,
  134942. NULL,
  134943. 0
  134944. };
  134945. static long _vq_quantlist__44c9_s_p4_0[] = {
  134946. 8,
  134947. 7,
  134948. 9,
  134949. 6,
  134950. 10,
  134951. 5,
  134952. 11,
  134953. 4,
  134954. 12,
  134955. 3,
  134956. 13,
  134957. 2,
  134958. 14,
  134959. 1,
  134960. 15,
  134961. 0,
  134962. 16,
  134963. };
  134964. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134965. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134966. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134967. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134968. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134969. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134970. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134971. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134972. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134973. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134974. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134983. 0,
  134984. };
  134985. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134986. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134987. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134988. };
  134989. static long _vq_quantmap__44c9_s_p4_0[] = {
  134990. 15, 13, 11, 9, 7, 5, 3, 1,
  134991. 0, 2, 4, 6, 8, 10, 12, 14,
  134992. 16,
  134993. };
  134994. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134995. _vq_quantthresh__44c9_s_p4_0,
  134996. _vq_quantmap__44c9_s_p4_0,
  134997. 17,
  134998. 17
  134999. };
  135000. static static_codebook _44c9_s_p4_0 = {
  135001. 2, 289,
  135002. _vq_lengthlist__44c9_s_p4_0,
  135003. 1, -529530880, 1611661312, 5, 0,
  135004. _vq_quantlist__44c9_s_p4_0,
  135005. NULL,
  135006. &_vq_auxt__44c9_s_p4_0,
  135007. NULL,
  135008. 0
  135009. };
  135010. static long _vq_quantlist__44c9_s_p5_0[] = {
  135011. 1,
  135012. 0,
  135013. 2,
  135014. };
  135015. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135016. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135017. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135018. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135019. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135020. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135021. 12,
  135022. };
  135023. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135024. -5.5, 5.5,
  135025. };
  135026. static long _vq_quantmap__44c9_s_p5_0[] = {
  135027. 1, 0, 2,
  135028. };
  135029. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135030. _vq_quantthresh__44c9_s_p5_0,
  135031. _vq_quantmap__44c9_s_p5_0,
  135032. 3,
  135033. 3
  135034. };
  135035. static static_codebook _44c9_s_p5_0 = {
  135036. 4, 81,
  135037. _vq_lengthlist__44c9_s_p5_0,
  135038. 1, -529137664, 1618345984, 2, 0,
  135039. _vq_quantlist__44c9_s_p5_0,
  135040. NULL,
  135041. &_vq_auxt__44c9_s_p5_0,
  135042. NULL,
  135043. 0
  135044. };
  135045. static long _vq_quantlist__44c9_s_p5_1[] = {
  135046. 5,
  135047. 4,
  135048. 6,
  135049. 3,
  135050. 7,
  135051. 2,
  135052. 8,
  135053. 1,
  135054. 9,
  135055. 0,
  135056. 10,
  135057. };
  135058. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135059. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135060. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135061. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135062. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135063. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135064. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135065. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135066. 11,11,11, 7, 7, 7, 7, 7, 7,
  135067. };
  135068. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135069. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135070. 3.5, 4.5,
  135071. };
  135072. static long _vq_quantmap__44c9_s_p5_1[] = {
  135073. 9, 7, 5, 3, 1, 0, 2, 4,
  135074. 6, 8, 10,
  135075. };
  135076. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135077. _vq_quantthresh__44c9_s_p5_1,
  135078. _vq_quantmap__44c9_s_p5_1,
  135079. 11,
  135080. 11
  135081. };
  135082. static static_codebook _44c9_s_p5_1 = {
  135083. 2, 121,
  135084. _vq_lengthlist__44c9_s_p5_1,
  135085. 1, -531365888, 1611661312, 4, 0,
  135086. _vq_quantlist__44c9_s_p5_1,
  135087. NULL,
  135088. &_vq_auxt__44c9_s_p5_1,
  135089. NULL,
  135090. 0
  135091. };
  135092. static long _vq_quantlist__44c9_s_p6_0[] = {
  135093. 6,
  135094. 5,
  135095. 7,
  135096. 4,
  135097. 8,
  135098. 3,
  135099. 9,
  135100. 2,
  135101. 10,
  135102. 1,
  135103. 11,
  135104. 0,
  135105. 12,
  135106. };
  135107. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135108. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135109. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135110. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135111. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135112. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135113. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135118. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135119. };
  135120. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135121. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135122. 12.5, 17.5, 22.5, 27.5,
  135123. };
  135124. static long _vq_quantmap__44c9_s_p6_0[] = {
  135125. 11, 9, 7, 5, 3, 1, 0, 2,
  135126. 4, 6, 8, 10, 12,
  135127. };
  135128. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135129. _vq_quantthresh__44c9_s_p6_0,
  135130. _vq_quantmap__44c9_s_p6_0,
  135131. 13,
  135132. 13
  135133. };
  135134. static static_codebook _44c9_s_p6_0 = {
  135135. 2, 169,
  135136. _vq_lengthlist__44c9_s_p6_0,
  135137. 1, -526516224, 1616117760, 4, 0,
  135138. _vq_quantlist__44c9_s_p6_0,
  135139. NULL,
  135140. &_vq_auxt__44c9_s_p6_0,
  135141. NULL,
  135142. 0
  135143. };
  135144. static long _vq_quantlist__44c9_s_p6_1[] = {
  135145. 2,
  135146. 1,
  135147. 3,
  135148. 0,
  135149. 4,
  135150. };
  135151. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135152. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135153. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135154. };
  135155. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135156. -1.5, -0.5, 0.5, 1.5,
  135157. };
  135158. static long _vq_quantmap__44c9_s_p6_1[] = {
  135159. 3, 1, 0, 2, 4,
  135160. };
  135161. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135162. _vq_quantthresh__44c9_s_p6_1,
  135163. _vq_quantmap__44c9_s_p6_1,
  135164. 5,
  135165. 5
  135166. };
  135167. static static_codebook _44c9_s_p6_1 = {
  135168. 2, 25,
  135169. _vq_lengthlist__44c9_s_p6_1,
  135170. 1, -533725184, 1611661312, 3, 0,
  135171. _vq_quantlist__44c9_s_p6_1,
  135172. NULL,
  135173. &_vq_auxt__44c9_s_p6_1,
  135174. NULL,
  135175. 0
  135176. };
  135177. static long _vq_quantlist__44c9_s_p7_0[] = {
  135178. 6,
  135179. 5,
  135180. 7,
  135181. 4,
  135182. 8,
  135183. 3,
  135184. 9,
  135185. 2,
  135186. 10,
  135187. 1,
  135188. 11,
  135189. 0,
  135190. 12,
  135191. };
  135192. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135193. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135194. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135195. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135196. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135197. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135198. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135199. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135200. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135201. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135202. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135203. 19,12,12,12,12,13,13,14,14,
  135204. };
  135205. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135206. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135207. 27.5, 38.5, 49.5, 60.5,
  135208. };
  135209. static long _vq_quantmap__44c9_s_p7_0[] = {
  135210. 11, 9, 7, 5, 3, 1, 0, 2,
  135211. 4, 6, 8, 10, 12,
  135212. };
  135213. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135214. _vq_quantthresh__44c9_s_p7_0,
  135215. _vq_quantmap__44c9_s_p7_0,
  135216. 13,
  135217. 13
  135218. };
  135219. static static_codebook _44c9_s_p7_0 = {
  135220. 2, 169,
  135221. _vq_lengthlist__44c9_s_p7_0,
  135222. 1, -523206656, 1618345984, 4, 0,
  135223. _vq_quantlist__44c9_s_p7_0,
  135224. NULL,
  135225. &_vq_auxt__44c9_s_p7_0,
  135226. NULL,
  135227. 0
  135228. };
  135229. static long _vq_quantlist__44c9_s_p7_1[] = {
  135230. 5,
  135231. 4,
  135232. 6,
  135233. 3,
  135234. 7,
  135235. 2,
  135236. 8,
  135237. 1,
  135238. 9,
  135239. 0,
  135240. 10,
  135241. };
  135242. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135243. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135244. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135245. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135246. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135247. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135248. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135249. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135250. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135251. };
  135252. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135253. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135254. 3.5, 4.5,
  135255. };
  135256. static long _vq_quantmap__44c9_s_p7_1[] = {
  135257. 9, 7, 5, 3, 1, 0, 2, 4,
  135258. 6, 8, 10,
  135259. };
  135260. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135261. _vq_quantthresh__44c9_s_p7_1,
  135262. _vq_quantmap__44c9_s_p7_1,
  135263. 11,
  135264. 11
  135265. };
  135266. static static_codebook _44c9_s_p7_1 = {
  135267. 2, 121,
  135268. _vq_lengthlist__44c9_s_p7_1,
  135269. 1, -531365888, 1611661312, 4, 0,
  135270. _vq_quantlist__44c9_s_p7_1,
  135271. NULL,
  135272. &_vq_auxt__44c9_s_p7_1,
  135273. NULL,
  135274. 0
  135275. };
  135276. static long _vq_quantlist__44c9_s_p8_0[] = {
  135277. 7,
  135278. 6,
  135279. 8,
  135280. 5,
  135281. 9,
  135282. 4,
  135283. 10,
  135284. 3,
  135285. 11,
  135286. 2,
  135287. 12,
  135288. 1,
  135289. 13,
  135290. 0,
  135291. 14,
  135292. };
  135293. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135294. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135295. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135296. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135297. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135298. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135299. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135300. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135301. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135302. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135303. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135304. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135305. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135306. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135307. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135308. 14,
  135309. };
  135310. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135311. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135312. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135313. };
  135314. static long _vq_quantmap__44c9_s_p8_0[] = {
  135315. 13, 11, 9, 7, 5, 3, 1, 0,
  135316. 2, 4, 6, 8, 10, 12, 14,
  135317. };
  135318. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135319. _vq_quantthresh__44c9_s_p8_0,
  135320. _vq_quantmap__44c9_s_p8_0,
  135321. 15,
  135322. 15
  135323. };
  135324. static static_codebook _44c9_s_p8_0 = {
  135325. 2, 225,
  135326. _vq_lengthlist__44c9_s_p8_0,
  135327. 1, -520986624, 1620377600, 4, 0,
  135328. _vq_quantlist__44c9_s_p8_0,
  135329. NULL,
  135330. &_vq_auxt__44c9_s_p8_0,
  135331. NULL,
  135332. 0
  135333. };
  135334. static long _vq_quantlist__44c9_s_p8_1[] = {
  135335. 10,
  135336. 9,
  135337. 11,
  135338. 8,
  135339. 12,
  135340. 7,
  135341. 13,
  135342. 6,
  135343. 14,
  135344. 5,
  135345. 15,
  135346. 4,
  135347. 16,
  135348. 3,
  135349. 17,
  135350. 2,
  135351. 18,
  135352. 1,
  135353. 19,
  135354. 0,
  135355. 20,
  135356. };
  135357. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135358. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135359. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135360. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135361. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135362. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135363. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135364. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135365. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135366. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135367. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135368. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135369. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135370. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135371. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135372. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135373. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135374. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135375. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135376. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135377. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135378. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135379. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135380. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135381. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135382. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135383. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135384. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135385. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135386. };
  135387. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135388. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135389. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135390. 6.5, 7.5, 8.5, 9.5,
  135391. };
  135392. static long _vq_quantmap__44c9_s_p8_1[] = {
  135393. 19, 17, 15, 13, 11, 9, 7, 5,
  135394. 3, 1, 0, 2, 4, 6, 8, 10,
  135395. 12, 14, 16, 18, 20,
  135396. };
  135397. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135398. _vq_quantthresh__44c9_s_p8_1,
  135399. _vq_quantmap__44c9_s_p8_1,
  135400. 21,
  135401. 21
  135402. };
  135403. static static_codebook _44c9_s_p8_1 = {
  135404. 2, 441,
  135405. _vq_lengthlist__44c9_s_p8_1,
  135406. 1, -529268736, 1611661312, 5, 0,
  135407. _vq_quantlist__44c9_s_p8_1,
  135408. NULL,
  135409. &_vq_auxt__44c9_s_p8_1,
  135410. NULL,
  135411. 0
  135412. };
  135413. static long _vq_quantlist__44c9_s_p9_0[] = {
  135414. 9,
  135415. 8,
  135416. 10,
  135417. 7,
  135418. 11,
  135419. 6,
  135420. 12,
  135421. 5,
  135422. 13,
  135423. 4,
  135424. 14,
  135425. 3,
  135426. 15,
  135427. 2,
  135428. 16,
  135429. 1,
  135430. 17,
  135431. 0,
  135432. 18,
  135433. };
  135434. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135435. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135436. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135437. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135438. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135439. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135440. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135441. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135442. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135443. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135444. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135445. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135446. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135447. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135448. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135449. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135450. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135451. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135452. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135453. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135454. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135455. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135456. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135457. 11,11,11,11,11,11,11,11,11,
  135458. };
  135459. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135460. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135461. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135462. 6982.5, 7913.5,
  135463. };
  135464. static long _vq_quantmap__44c9_s_p9_0[] = {
  135465. 17, 15, 13, 11, 9, 7, 5, 3,
  135466. 1, 0, 2, 4, 6, 8, 10, 12,
  135467. 14, 16, 18,
  135468. };
  135469. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135470. _vq_quantthresh__44c9_s_p9_0,
  135471. _vq_quantmap__44c9_s_p9_0,
  135472. 19,
  135473. 19
  135474. };
  135475. static static_codebook _44c9_s_p9_0 = {
  135476. 2, 361,
  135477. _vq_lengthlist__44c9_s_p9_0,
  135478. 1, -508535424, 1631393792, 5, 0,
  135479. _vq_quantlist__44c9_s_p9_0,
  135480. NULL,
  135481. &_vq_auxt__44c9_s_p9_0,
  135482. NULL,
  135483. 0
  135484. };
  135485. static long _vq_quantlist__44c9_s_p9_1[] = {
  135486. 9,
  135487. 8,
  135488. 10,
  135489. 7,
  135490. 11,
  135491. 6,
  135492. 12,
  135493. 5,
  135494. 13,
  135495. 4,
  135496. 14,
  135497. 3,
  135498. 15,
  135499. 2,
  135500. 16,
  135501. 1,
  135502. 17,
  135503. 0,
  135504. 18,
  135505. };
  135506. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135507. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135508. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135509. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135510. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135511. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135512. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135513. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135514. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135515. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135516. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135517. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135518. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135519. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135520. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135521. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135522. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135523. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135524. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135525. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135526. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135527. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135528. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135529. 13,13,13,14,13,14,15,15,15,
  135530. };
  135531. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135532. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135533. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135534. 367.5, 416.5,
  135535. };
  135536. static long _vq_quantmap__44c9_s_p9_1[] = {
  135537. 17, 15, 13, 11, 9, 7, 5, 3,
  135538. 1, 0, 2, 4, 6, 8, 10, 12,
  135539. 14, 16, 18,
  135540. };
  135541. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135542. _vq_quantthresh__44c9_s_p9_1,
  135543. _vq_quantmap__44c9_s_p9_1,
  135544. 19,
  135545. 19
  135546. };
  135547. static static_codebook _44c9_s_p9_1 = {
  135548. 2, 361,
  135549. _vq_lengthlist__44c9_s_p9_1,
  135550. 1, -518287360, 1622704128, 5, 0,
  135551. _vq_quantlist__44c9_s_p9_1,
  135552. NULL,
  135553. &_vq_auxt__44c9_s_p9_1,
  135554. NULL,
  135555. 0
  135556. };
  135557. static long _vq_quantlist__44c9_s_p9_2[] = {
  135558. 24,
  135559. 23,
  135560. 25,
  135561. 22,
  135562. 26,
  135563. 21,
  135564. 27,
  135565. 20,
  135566. 28,
  135567. 19,
  135568. 29,
  135569. 18,
  135570. 30,
  135571. 17,
  135572. 31,
  135573. 16,
  135574. 32,
  135575. 15,
  135576. 33,
  135577. 14,
  135578. 34,
  135579. 13,
  135580. 35,
  135581. 12,
  135582. 36,
  135583. 11,
  135584. 37,
  135585. 10,
  135586. 38,
  135587. 9,
  135588. 39,
  135589. 8,
  135590. 40,
  135591. 7,
  135592. 41,
  135593. 6,
  135594. 42,
  135595. 5,
  135596. 43,
  135597. 4,
  135598. 44,
  135599. 3,
  135600. 45,
  135601. 2,
  135602. 46,
  135603. 1,
  135604. 47,
  135605. 0,
  135606. 48,
  135607. };
  135608. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135609. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135610. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135611. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135612. 7,
  135613. };
  135614. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135615. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135616. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135617. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135618. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135619. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135620. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135621. };
  135622. static long _vq_quantmap__44c9_s_p9_2[] = {
  135623. 47, 45, 43, 41, 39, 37, 35, 33,
  135624. 31, 29, 27, 25, 23, 21, 19, 17,
  135625. 15, 13, 11, 9, 7, 5, 3, 1,
  135626. 0, 2, 4, 6, 8, 10, 12, 14,
  135627. 16, 18, 20, 22, 24, 26, 28, 30,
  135628. 32, 34, 36, 38, 40, 42, 44, 46,
  135629. 48,
  135630. };
  135631. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135632. _vq_quantthresh__44c9_s_p9_2,
  135633. _vq_quantmap__44c9_s_p9_2,
  135634. 49,
  135635. 49
  135636. };
  135637. static static_codebook _44c9_s_p9_2 = {
  135638. 1, 49,
  135639. _vq_lengthlist__44c9_s_p9_2,
  135640. 1, -526909440, 1611661312, 6, 0,
  135641. _vq_quantlist__44c9_s_p9_2,
  135642. NULL,
  135643. &_vq_auxt__44c9_s_p9_2,
  135644. NULL,
  135645. 0
  135646. };
  135647. static long _huff_lengthlist__44c9_s_short[] = {
  135648. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135649. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135650. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135651. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135652. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135653. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135654. 9, 8,10,13,
  135655. };
  135656. static static_codebook _huff_book__44c9_s_short = {
  135657. 2, 100,
  135658. _huff_lengthlist__44c9_s_short,
  135659. 0, 0, 0, 0, 0,
  135660. NULL,
  135661. NULL,
  135662. NULL,
  135663. NULL,
  135664. 0
  135665. };
  135666. static long _huff_lengthlist__44c0_s_long[] = {
  135667. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135668. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135669. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135670. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135671. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135672. 12,
  135673. };
  135674. static static_codebook _huff_book__44c0_s_long = {
  135675. 2, 81,
  135676. _huff_lengthlist__44c0_s_long,
  135677. 0, 0, 0, 0, 0,
  135678. NULL,
  135679. NULL,
  135680. NULL,
  135681. NULL,
  135682. 0
  135683. };
  135684. static long _vq_quantlist__44c0_s_p1_0[] = {
  135685. 1,
  135686. 0,
  135687. 2,
  135688. };
  135689. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135690. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135691. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135696. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135701. 0, 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0,
  135736. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  135741. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  135746. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135782. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135787. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135792. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0,
  136101. };
  136102. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136103. -0.5, 0.5,
  136104. };
  136105. static long _vq_quantmap__44c0_s_p1_0[] = {
  136106. 1, 0, 2,
  136107. };
  136108. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136109. _vq_quantthresh__44c0_s_p1_0,
  136110. _vq_quantmap__44c0_s_p1_0,
  136111. 3,
  136112. 3
  136113. };
  136114. static static_codebook _44c0_s_p1_0 = {
  136115. 8, 6561,
  136116. _vq_lengthlist__44c0_s_p1_0,
  136117. 1, -535822336, 1611661312, 2, 0,
  136118. _vq_quantlist__44c0_s_p1_0,
  136119. NULL,
  136120. &_vq_auxt__44c0_s_p1_0,
  136121. NULL,
  136122. 0
  136123. };
  136124. static long _vq_quantlist__44c0_s_p2_0[] = {
  136125. 2,
  136126. 1,
  136127. 3,
  136128. 0,
  136129. 4,
  136130. };
  136131. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136132. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0,
  136172. };
  136173. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136174. -1.5, -0.5, 0.5, 1.5,
  136175. };
  136176. static long _vq_quantmap__44c0_s_p2_0[] = {
  136177. 3, 1, 0, 2, 4,
  136178. };
  136179. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136180. _vq_quantthresh__44c0_s_p2_0,
  136181. _vq_quantmap__44c0_s_p2_0,
  136182. 5,
  136183. 5
  136184. };
  136185. static static_codebook _44c0_s_p2_0 = {
  136186. 4, 625,
  136187. _vq_lengthlist__44c0_s_p2_0,
  136188. 1, -533725184, 1611661312, 3, 0,
  136189. _vq_quantlist__44c0_s_p2_0,
  136190. NULL,
  136191. &_vq_auxt__44c0_s_p2_0,
  136192. NULL,
  136193. 0
  136194. };
  136195. static long _vq_quantlist__44c0_s_p3_0[] = {
  136196. 4,
  136197. 3,
  136198. 5,
  136199. 2,
  136200. 6,
  136201. 1,
  136202. 7,
  136203. 0,
  136204. 8,
  136205. };
  136206. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136207. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136208. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136209. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136210. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136211. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0,
  136213. };
  136214. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136215. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136216. };
  136217. static long _vq_quantmap__44c0_s_p3_0[] = {
  136218. 7, 5, 3, 1, 0, 2, 4, 6,
  136219. 8,
  136220. };
  136221. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136222. _vq_quantthresh__44c0_s_p3_0,
  136223. _vq_quantmap__44c0_s_p3_0,
  136224. 9,
  136225. 9
  136226. };
  136227. static static_codebook _44c0_s_p3_0 = {
  136228. 2, 81,
  136229. _vq_lengthlist__44c0_s_p3_0,
  136230. 1, -531628032, 1611661312, 4, 0,
  136231. _vq_quantlist__44c0_s_p3_0,
  136232. NULL,
  136233. &_vq_auxt__44c0_s_p3_0,
  136234. NULL,
  136235. 0
  136236. };
  136237. static long _vq_quantlist__44c0_s_p4_0[] = {
  136238. 4,
  136239. 3,
  136240. 5,
  136241. 2,
  136242. 6,
  136243. 1,
  136244. 7,
  136245. 0,
  136246. 8,
  136247. };
  136248. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136249. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136250. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136251. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136252. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136253. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136254. 10,
  136255. };
  136256. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136257. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136258. };
  136259. static long _vq_quantmap__44c0_s_p4_0[] = {
  136260. 7, 5, 3, 1, 0, 2, 4, 6,
  136261. 8,
  136262. };
  136263. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136264. _vq_quantthresh__44c0_s_p4_0,
  136265. _vq_quantmap__44c0_s_p4_0,
  136266. 9,
  136267. 9
  136268. };
  136269. static static_codebook _44c0_s_p4_0 = {
  136270. 2, 81,
  136271. _vq_lengthlist__44c0_s_p4_0,
  136272. 1, -531628032, 1611661312, 4, 0,
  136273. _vq_quantlist__44c0_s_p4_0,
  136274. NULL,
  136275. &_vq_auxt__44c0_s_p4_0,
  136276. NULL,
  136277. 0
  136278. };
  136279. static long _vq_quantlist__44c0_s_p5_0[] = {
  136280. 8,
  136281. 7,
  136282. 9,
  136283. 6,
  136284. 10,
  136285. 5,
  136286. 11,
  136287. 4,
  136288. 12,
  136289. 3,
  136290. 13,
  136291. 2,
  136292. 14,
  136293. 1,
  136294. 15,
  136295. 0,
  136296. 16,
  136297. };
  136298. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136299. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136300. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136301. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136302. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136303. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136304. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136305. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136306. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136307. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136308. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136309. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136310. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136311. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136312. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136313. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136314. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136315. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136316. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136317. 14,
  136318. };
  136319. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136320. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136321. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136322. };
  136323. static long _vq_quantmap__44c0_s_p5_0[] = {
  136324. 15, 13, 11, 9, 7, 5, 3, 1,
  136325. 0, 2, 4, 6, 8, 10, 12, 14,
  136326. 16,
  136327. };
  136328. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136329. _vq_quantthresh__44c0_s_p5_0,
  136330. _vq_quantmap__44c0_s_p5_0,
  136331. 17,
  136332. 17
  136333. };
  136334. static static_codebook _44c0_s_p5_0 = {
  136335. 2, 289,
  136336. _vq_lengthlist__44c0_s_p5_0,
  136337. 1, -529530880, 1611661312, 5, 0,
  136338. _vq_quantlist__44c0_s_p5_0,
  136339. NULL,
  136340. &_vq_auxt__44c0_s_p5_0,
  136341. NULL,
  136342. 0
  136343. };
  136344. static long _vq_quantlist__44c0_s_p6_0[] = {
  136345. 1,
  136346. 0,
  136347. 2,
  136348. };
  136349. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136350. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136351. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136352. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136353. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136354. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136355. 10,
  136356. };
  136357. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136358. -5.5, 5.5,
  136359. };
  136360. static long _vq_quantmap__44c0_s_p6_0[] = {
  136361. 1, 0, 2,
  136362. };
  136363. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136364. _vq_quantthresh__44c0_s_p6_0,
  136365. _vq_quantmap__44c0_s_p6_0,
  136366. 3,
  136367. 3
  136368. };
  136369. static static_codebook _44c0_s_p6_0 = {
  136370. 4, 81,
  136371. _vq_lengthlist__44c0_s_p6_0,
  136372. 1, -529137664, 1618345984, 2, 0,
  136373. _vq_quantlist__44c0_s_p6_0,
  136374. NULL,
  136375. &_vq_auxt__44c0_s_p6_0,
  136376. NULL,
  136377. 0
  136378. };
  136379. static long _vq_quantlist__44c0_s_p6_1[] = {
  136380. 5,
  136381. 4,
  136382. 6,
  136383. 3,
  136384. 7,
  136385. 2,
  136386. 8,
  136387. 1,
  136388. 9,
  136389. 0,
  136390. 10,
  136391. };
  136392. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136393. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136394. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136395. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136396. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136397. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136398. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136399. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136400. 10,10,10, 8, 8, 8, 8, 8, 8,
  136401. };
  136402. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136403. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136404. 3.5, 4.5,
  136405. };
  136406. static long _vq_quantmap__44c0_s_p6_1[] = {
  136407. 9, 7, 5, 3, 1, 0, 2, 4,
  136408. 6, 8, 10,
  136409. };
  136410. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136411. _vq_quantthresh__44c0_s_p6_1,
  136412. _vq_quantmap__44c0_s_p6_1,
  136413. 11,
  136414. 11
  136415. };
  136416. static static_codebook _44c0_s_p6_1 = {
  136417. 2, 121,
  136418. _vq_lengthlist__44c0_s_p6_1,
  136419. 1, -531365888, 1611661312, 4, 0,
  136420. _vq_quantlist__44c0_s_p6_1,
  136421. NULL,
  136422. &_vq_auxt__44c0_s_p6_1,
  136423. NULL,
  136424. 0
  136425. };
  136426. static long _vq_quantlist__44c0_s_p7_0[] = {
  136427. 6,
  136428. 5,
  136429. 7,
  136430. 4,
  136431. 8,
  136432. 3,
  136433. 9,
  136434. 2,
  136435. 10,
  136436. 1,
  136437. 11,
  136438. 0,
  136439. 12,
  136440. };
  136441. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136442. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136443. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136444. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136445. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136446. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136447. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136448. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136449. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136450. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136451. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136452. 0,12,12,11,11,12,12,13,13,
  136453. };
  136454. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136455. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136456. 12.5, 17.5, 22.5, 27.5,
  136457. };
  136458. static long _vq_quantmap__44c0_s_p7_0[] = {
  136459. 11, 9, 7, 5, 3, 1, 0, 2,
  136460. 4, 6, 8, 10, 12,
  136461. };
  136462. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136463. _vq_quantthresh__44c0_s_p7_0,
  136464. _vq_quantmap__44c0_s_p7_0,
  136465. 13,
  136466. 13
  136467. };
  136468. static static_codebook _44c0_s_p7_0 = {
  136469. 2, 169,
  136470. _vq_lengthlist__44c0_s_p7_0,
  136471. 1, -526516224, 1616117760, 4, 0,
  136472. _vq_quantlist__44c0_s_p7_0,
  136473. NULL,
  136474. &_vq_auxt__44c0_s_p7_0,
  136475. NULL,
  136476. 0
  136477. };
  136478. static long _vq_quantlist__44c0_s_p7_1[] = {
  136479. 2,
  136480. 1,
  136481. 3,
  136482. 0,
  136483. 4,
  136484. };
  136485. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136486. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136487. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136488. };
  136489. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136490. -1.5, -0.5, 0.5, 1.5,
  136491. };
  136492. static long _vq_quantmap__44c0_s_p7_1[] = {
  136493. 3, 1, 0, 2, 4,
  136494. };
  136495. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136496. _vq_quantthresh__44c0_s_p7_1,
  136497. _vq_quantmap__44c0_s_p7_1,
  136498. 5,
  136499. 5
  136500. };
  136501. static static_codebook _44c0_s_p7_1 = {
  136502. 2, 25,
  136503. _vq_lengthlist__44c0_s_p7_1,
  136504. 1, -533725184, 1611661312, 3, 0,
  136505. _vq_quantlist__44c0_s_p7_1,
  136506. NULL,
  136507. &_vq_auxt__44c0_s_p7_1,
  136508. NULL,
  136509. 0
  136510. };
  136511. static long _vq_quantlist__44c0_s_p8_0[] = {
  136512. 2,
  136513. 1,
  136514. 3,
  136515. 0,
  136516. 4,
  136517. };
  136518. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136519. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136520. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136521. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136522. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136523. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136524. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136526. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136527. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136528. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136529. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136530. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136531. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136532. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136534. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136535. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136536. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136537. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136538. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136539. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136540. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136541. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136542. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136543. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136544. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136545. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136546. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136547. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136548. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136549. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136550. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136551. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136552. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136553. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136554. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136555. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136556. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136557. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136558. 11,
  136559. };
  136560. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136561. -331.5, -110.5, 110.5, 331.5,
  136562. };
  136563. static long _vq_quantmap__44c0_s_p8_0[] = {
  136564. 3, 1, 0, 2, 4,
  136565. };
  136566. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136567. _vq_quantthresh__44c0_s_p8_0,
  136568. _vq_quantmap__44c0_s_p8_0,
  136569. 5,
  136570. 5
  136571. };
  136572. static static_codebook _44c0_s_p8_0 = {
  136573. 4, 625,
  136574. _vq_lengthlist__44c0_s_p8_0,
  136575. 1, -518283264, 1627103232, 3, 0,
  136576. _vq_quantlist__44c0_s_p8_0,
  136577. NULL,
  136578. &_vq_auxt__44c0_s_p8_0,
  136579. NULL,
  136580. 0
  136581. };
  136582. static long _vq_quantlist__44c0_s_p8_1[] = {
  136583. 6,
  136584. 5,
  136585. 7,
  136586. 4,
  136587. 8,
  136588. 3,
  136589. 9,
  136590. 2,
  136591. 10,
  136592. 1,
  136593. 11,
  136594. 0,
  136595. 12,
  136596. };
  136597. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136598. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136599. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136600. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136601. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136602. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136603. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136604. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136605. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136606. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136607. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136608. 16,13,13,12,12,14,14,15,13,
  136609. };
  136610. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136611. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136612. 42.5, 59.5, 76.5, 93.5,
  136613. };
  136614. static long _vq_quantmap__44c0_s_p8_1[] = {
  136615. 11, 9, 7, 5, 3, 1, 0, 2,
  136616. 4, 6, 8, 10, 12,
  136617. };
  136618. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136619. _vq_quantthresh__44c0_s_p8_1,
  136620. _vq_quantmap__44c0_s_p8_1,
  136621. 13,
  136622. 13
  136623. };
  136624. static static_codebook _44c0_s_p8_1 = {
  136625. 2, 169,
  136626. _vq_lengthlist__44c0_s_p8_1,
  136627. 1, -522616832, 1620115456, 4, 0,
  136628. _vq_quantlist__44c0_s_p8_1,
  136629. NULL,
  136630. &_vq_auxt__44c0_s_p8_1,
  136631. NULL,
  136632. 0
  136633. };
  136634. static long _vq_quantlist__44c0_s_p8_2[] = {
  136635. 8,
  136636. 7,
  136637. 9,
  136638. 6,
  136639. 10,
  136640. 5,
  136641. 11,
  136642. 4,
  136643. 12,
  136644. 3,
  136645. 13,
  136646. 2,
  136647. 14,
  136648. 1,
  136649. 15,
  136650. 0,
  136651. 16,
  136652. };
  136653. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136654. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136655. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136656. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136657. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136658. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136659. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136660. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136661. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136662. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136663. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136664. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136665. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136666. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136667. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136668. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136669. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136670. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136671. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136672. 10,
  136673. };
  136674. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136675. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136676. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136677. };
  136678. static long _vq_quantmap__44c0_s_p8_2[] = {
  136679. 15, 13, 11, 9, 7, 5, 3, 1,
  136680. 0, 2, 4, 6, 8, 10, 12, 14,
  136681. 16,
  136682. };
  136683. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136684. _vq_quantthresh__44c0_s_p8_2,
  136685. _vq_quantmap__44c0_s_p8_2,
  136686. 17,
  136687. 17
  136688. };
  136689. static static_codebook _44c0_s_p8_2 = {
  136690. 2, 289,
  136691. _vq_lengthlist__44c0_s_p8_2,
  136692. 1, -529530880, 1611661312, 5, 0,
  136693. _vq_quantlist__44c0_s_p8_2,
  136694. NULL,
  136695. &_vq_auxt__44c0_s_p8_2,
  136696. NULL,
  136697. 0
  136698. };
  136699. static long _huff_lengthlist__44c0_s_short[] = {
  136700. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136701. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136702. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136703. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136704. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136705. 12,
  136706. };
  136707. static static_codebook _huff_book__44c0_s_short = {
  136708. 2, 81,
  136709. _huff_lengthlist__44c0_s_short,
  136710. 0, 0, 0, 0, 0,
  136711. NULL,
  136712. NULL,
  136713. NULL,
  136714. NULL,
  136715. 0
  136716. };
  136717. static long _huff_lengthlist__44c0_sm_long[] = {
  136718. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136719. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136720. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136721. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136722. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136723. 13,
  136724. };
  136725. static static_codebook _huff_book__44c0_sm_long = {
  136726. 2, 81,
  136727. _huff_lengthlist__44c0_sm_long,
  136728. 0, 0, 0, 0, 0,
  136729. NULL,
  136730. NULL,
  136731. NULL,
  136732. NULL,
  136733. 0
  136734. };
  136735. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136736. 1,
  136737. 0,
  136738. 2,
  136739. };
  136740. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136741. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136742. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136747. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136752. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  136787. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136792. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  136797. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136833. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136838. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136843. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0,
  137152. };
  137153. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137154. -0.5, 0.5,
  137155. };
  137156. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137157. 1, 0, 2,
  137158. };
  137159. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137160. _vq_quantthresh__44c0_sm_p1_0,
  137161. _vq_quantmap__44c0_sm_p1_0,
  137162. 3,
  137163. 3
  137164. };
  137165. static static_codebook _44c0_sm_p1_0 = {
  137166. 8, 6561,
  137167. _vq_lengthlist__44c0_sm_p1_0,
  137168. 1, -535822336, 1611661312, 2, 0,
  137169. _vq_quantlist__44c0_sm_p1_0,
  137170. NULL,
  137171. &_vq_auxt__44c0_sm_p1_0,
  137172. NULL,
  137173. 0
  137174. };
  137175. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137176. 2,
  137177. 1,
  137178. 3,
  137179. 0,
  137180. 4,
  137181. };
  137182. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137183. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0,
  137223. };
  137224. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137225. -1.5, -0.5, 0.5, 1.5,
  137226. };
  137227. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137228. 3, 1, 0, 2, 4,
  137229. };
  137230. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137231. _vq_quantthresh__44c0_sm_p2_0,
  137232. _vq_quantmap__44c0_sm_p2_0,
  137233. 5,
  137234. 5
  137235. };
  137236. static static_codebook _44c0_sm_p2_0 = {
  137237. 4, 625,
  137238. _vq_lengthlist__44c0_sm_p2_0,
  137239. 1, -533725184, 1611661312, 3, 0,
  137240. _vq_quantlist__44c0_sm_p2_0,
  137241. NULL,
  137242. &_vq_auxt__44c0_sm_p2_0,
  137243. NULL,
  137244. 0
  137245. };
  137246. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137247. 4,
  137248. 3,
  137249. 5,
  137250. 2,
  137251. 6,
  137252. 1,
  137253. 7,
  137254. 0,
  137255. 8,
  137256. };
  137257. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137258. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137259. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137260. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137261. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137262. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0,
  137264. };
  137265. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137266. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137267. };
  137268. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137269. 7, 5, 3, 1, 0, 2, 4, 6,
  137270. 8,
  137271. };
  137272. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137273. _vq_quantthresh__44c0_sm_p3_0,
  137274. _vq_quantmap__44c0_sm_p3_0,
  137275. 9,
  137276. 9
  137277. };
  137278. static static_codebook _44c0_sm_p3_0 = {
  137279. 2, 81,
  137280. _vq_lengthlist__44c0_sm_p3_0,
  137281. 1, -531628032, 1611661312, 4, 0,
  137282. _vq_quantlist__44c0_sm_p3_0,
  137283. NULL,
  137284. &_vq_auxt__44c0_sm_p3_0,
  137285. NULL,
  137286. 0
  137287. };
  137288. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137289. 4,
  137290. 3,
  137291. 5,
  137292. 2,
  137293. 6,
  137294. 1,
  137295. 7,
  137296. 0,
  137297. 8,
  137298. };
  137299. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137300. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137301. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137302. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137303. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137304. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137305. 11,
  137306. };
  137307. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137308. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137309. };
  137310. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137311. 7, 5, 3, 1, 0, 2, 4, 6,
  137312. 8,
  137313. };
  137314. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137315. _vq_quantthresh__44c0_sm_p4_0,
  137316. _vq_quantmap__44c0_sm_p4_0,
  137317. 9,
  137318. 9
  137319. };
  137320. static static_codebook _44c0_sm_p4_0 = {
  137321. 2, 81,
  137322. _vq_lengthlist__44c0_sm_p4_0,
  137323. 1, -531628032, 1611661312, 4, 0,
  137324. _vq_quantlist__44c0_sm_p4_0,
  137325. NULL,
  137326. &_vq_auxt__44c0_sm_p4_0,
  137327. NULL,
  137328. 0
  137329. };
  137330. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137331. 8,
  137332. 7,
  137333. 9,
  137334. 6,
  137335. 10,
  137336. 5,
  137337. 11,
  137338. 4,
  137339. 12,
  137340. 3,
  137341. 13,
  137342. 2,
  137343. 14,
  137344. 1,
  137345. 15,
  137346. 0,
  137347. 16,
  137348. };
  137349. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137350. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137351. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137352. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137353. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137354. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137355. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137356. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137357. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137358. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137359. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137360. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137361. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137362. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137363. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137364. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137365. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137366. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137367. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137368. 14,
  137369. };
  137370. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137371. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137372. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137373. };
  137374. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137375. 15, 13, 11, 9, 7, 5, 3, 1,
  137376. 0, 2, 4, 6, 8, 10, 12, 14,
  137377. 16,
  137378. };
  137379. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137380. _vq_quantthresh__44c0_sm_p5_0,
  137381. _vq_quantmap__44c0_sm_p5_0,
  137382. 17,
  137383. 17
  137384. };
  137385. static static_codebook _44c0_sm_p5_0 = {
  137386. 2, 289,
  137387. _vq_lengthlist__44c0_sm_p5_0,
  137388. 1, -529530880, 1611661312, 5, 0,
  137389. _vq_quantlist__44c0_sm_p5_0,
  137390. NULL,
  137391. &_vq_auxt__44c0_sm_p5_0,
  137392. NULL,
  137393. 0
  137394. };
  137395. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137396. 1,
  137397. 0,
  137398. 2,
  137399. };
  137400. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137401. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137402. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137403. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137404. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137405. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137406. 11,
  137407. };
  137408. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137409. -5.5, 5.5,
  137410. };
  137411. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137412. 1, 0, 2,
  137413. };
  137414. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137415. _vq_quantthresh__44c0_sm_p6_0,
  137416. _vq_quantmap__44c0_sm_p6_0,
  137417. 3,
  137418. 3
  137419. };
  137420. static static_codebook _44c0_sm_p6_0 = {
  137421. 4, 81,
  137422. _vq_lengthlist__44c0_sm_p6_0,
  137423. 1, -529137664, 1618345984, 2, 0,
  137424. _vq_quantlist__44c0_sm_p6_0,
  137425. NULL,
  137426. &_vq_auxt__44c0_sm_p6_0,
  137427. NULL,
  137428. 0
  137429. };
  137430. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137431. 5,
  137432. 4,
  137433. 6,
  137434. 3,
  137435. 7,
  137436. 2,
  137437. 8,
  137438. 1,
  137439. 9,
  137440. 0,
  137441. 10,
  137442. };
  137443. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137444. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137445. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137446. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137447. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137448. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137449. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137450. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137451. 10,10,10, 8, 8, 8, 8, 8, 8,
  137452. };
  137453. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137454. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137455. 3.5, 4.5,
  137456. };
  137457. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137458. 9, 7, 5, 3, 1, 0, 2, 4,
  137459. 6, 8, 10,
  137460. };
  137461. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137462. _vq_quantthresh__44c0_sm_p6_1,
  137463. _vq_quantmap__44c0_sm_p6_1,
  137464. 11,
  137465. 11
  137466. };
  137467. static static_codebook _44c0_sm_p6_1 = {
  137468. 2, 121,
  137469. _vq_lengthlist__44c0_sm_p6_1,
  137470. 1, -531365888, 1611661312, 4, 0,
  137471. _vq_quantlist__44c0_sm_p6_1,
  137472. NULL,
  137473. &_vq_auxt__44c0_sm_p6_1,
  137474. NULL,
  137475. 0
  137476. };
  137477. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137478. 6,
  137479. 5,
  137480. 7,
  137481. 4,
  137482. 8,
  137483. 3,
  137484. 9,
  137485. 2,
  137486. 10,
  137487. 1,
  137488. 11,
  137489. 0,
  137490. 12,
  137491. };
  137492. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137493. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137494. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137495. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137496. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137497. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137498. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137499. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137500. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137501. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137502. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137503. 0,12,12,11,11,13,12,14,14,
  137504. };
  137505. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137506. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137507. 12.5, 17.5, 22.5, 27.5,
  137508. };
  137509. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137510. 11, 9, 7, 5, 3, 1, 0, 2,
  137511. 4, 6, 8, 10, 12,
  137512. };
  137513. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137514. _vq_quantthresh__44c0_sm_p7_0,
  137515. _vq_quantmap__44c0_sm_p7_0,
  137516. 13,
  137517. 13
  137518. };
  137519. static static_codebook _44c0_sm_p7_0 = {
  137520. 2, 169,
  137521. _vq_lengthlist__44c0_sm_p7_0,
  137522. 1, -526516224, 1616117760, 4, 0,
  137523. _vq_quantlist__44c0_sm_p7_0,
  137524. NULL,
  137525. &_vq_auxt__44c0_sm_p7_0,
  137526. NULL,
  137527. 0
  137528. };
  137529. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137530. 2,
  137531. 1,
  137532. 3,
  137533. 0,
  137534. 4,
  137535. };
  137536. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137537. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137538. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137539. };
  137540. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137541. -1.5, -0.5, 0.5, 1.5,
  137542. };
  137543. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137544. 3, 1, 0, 2, 4,
  137545. };
  137546. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137547. _vq_quantthresh__44c0_sm_p7_1,
  137548. _vq_quantmap__44c0_sm_p7_1,
  137549. 5,
  137550. 5
  137551. };
  137552. static static_codebook _44c0_sm_p7_1 = {
  137553. 2, 25,
  137554. _vq_lengthlist__44c0_sm_p7_1,
  137555. 1, -533725184, 1611661312, 3, 0,
  137556. _vq_quantlist__44c0_sm_p7_1,
  137557. NULL,
  137558. &_vq_auxt__44c0_sm_p7_1,
  137559. NULL,
  137560. 0
  137561. };
  137562. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137563. 4,
  137564. 3,
  137565. 5,
  137566. 2,
  137567. 6,
  137568. 1,
  137569. 7,
  137570. 0,
  137571. 8,
  137572. };
  137573. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137574. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137575. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137576. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137577. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137578. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137579. 12,
  137580. };
  137581. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137582. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137583. };
  137584. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137585. 7, 5, 3, 1, 0, 2, 4, 6,
  137586. 8,
  137587. };
  137588. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137589. _vq_quantthresh__44c0_sm_p8_0,
  137590. _vq_quantmap__44c0_sm_p8_0,
  137591. 9,
  137592. 9
  137593. };
  137594. static static_codebook _44c0_sm_p8_0 = {
  137595. 2, 81,
  137596. _vq_lengthlist__44c0_sm_p8_0,
  137597. 1, -516186112, 1627103232, 4, 0,
  137598. _vq_quantlist__44c0_sm_p8_0,
  137599. NULL,
  137600. &_vq_auxt__44c0_sm_p8_0,
  137601. NULL,
  137602. 0
  137603. };
  137604. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137605. 6,
  137606. 5,
  137607. 7,
  137608. 4,
  137609. 8,
  137610. 3,
  137611. 9,
  137612. 2,
  137613. 10,
  137614. 1,
  137615. 11,
  137616. 0,
  137617. 12,
  137618. };
  137619. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137620. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137621. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137622. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137623. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137624. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137625. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137626. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137627. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137628. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137629. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137630. 20,13,13,12,12,16,13,15,13,
  137631. };
  137632. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137633. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137634. 42.5, 59.5, 76.5, 93.5,
  137635. };
  137636. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137637. 11, 9, 7, 5, 3, 1, 0, 2,
  137638. 4, 6, 8, 10, 12,
  137639. };
  137640. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137641. _vq_quantthresh__44c0_sm_p8_1,
  137642. _vq_quantmap__44c0_sm_p8_1,
  137643. 13,
  137644. 13
  137645. };
  137646. static static_codebook _44c0_sm_p8_1 = {
  137647. 2, 169,
  137648. _vq_lengthlist__44c0_sm_p8_1,
  137649. 1, -522616832, 1620115456, 4, 0,
  137650. _vq_quantlist__44c0_sm_p8_1,
  137651. NULL,
  137652. &_vq_auxt__44c0_sm_p8_1,
  137653. NULL,
  137654. 0
  137655. };
  137656. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137657. 8,
  137658. 7,
  137659. 9,
  137660. 6,
  137661. 10,
  137662. 5,
  137663. 11,
  137664. 4,
  137665. 12,
  137666. 3,
  137667. 13,
  137668. 2,
  137669. 14,
  137670. 1,
  137671. 15,
  137672. 0,
  137673. 16,
  137674. };
  137675. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137676. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137677. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137678. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137679. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137680. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137681. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137682. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137683. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137684. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137685. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137686. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137687. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137688. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137689. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137690. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137691. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137692. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137693. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137694. 9,
  137695. };
  137696. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137697. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137698. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137699. };
  137700. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137701. 15, 13, 11, 9, 7, 5, 3, 1,
  137702. 0, 2, 4, 6, 8, 10, 12, 14,
  137703. 16,
  137704. };
  137705. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137706. _vq_quantthresh__44c0_sm_p8_2,
  137707. _vq_quantmap__44c0_sm_p8_2,
  137708. 17,
  137709. 17
  137710. };
  137711. static static_codebook _44c0_sm_p8_2 = {
  137712. 2, 289,
  137713. _vq_lengthlist__44c0_sm_p8_2,
  137714. 1, -529530880, 1611661312, 5, 0,
  137715. _vq_quantlist__44c0_sm_p8_2,
  137716. NULL,
  137717. &_vq_auxt__44c0_sm_p8_2,
  137718. NULL,
  137719. 0
  137720. };
  137721. static long _huff_lengthlist__44c0_sm_short[] = {
  137722. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137723. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137724. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137725. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137726. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137727. 12,
  137728. };
  137729. static static_codebook _huff_book__44c0_sm_short = {
  137730. 2, 81,
  137731. _huff_lengthlist__44c0_sm_short,
  137732. 0, 0, 0, 0, 0,
  137733. NULL,
  137734. NULL,
  137735. NULL,
  137736. NULL,
  137737. 0
  137738. };
  137739. static long _huff_lengthlist__44c1_s_long[] = {
  137740. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137741. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137742. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137743. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137744. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137745. 11,
  137746. };
  137747. static static_codebook _huff_book__44c1_s_long = {
  137748. 2, 81,
  137749. _huff_lengthlist__44c1_s_long,
  137750. 0, 0, 0, 0, 0,
  137751. NULL,
  137752. NULL,
  137753. NULL,
  137754. NULL,
  137755. 0
  137756. };
  137757. static long _vq_quantlist__44c1_s_p1_0[] = {
  137758. 1,
  137759. 0,
  137760. 2,
  137761. };
  137762. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137763. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137764. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137769. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137774. 0, 0, 0, 0, 7, 8, 8, 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, 4, 7, 7, 0, 0, 0, 0,
  137809. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  137814. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  137819. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137855. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137860. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137865. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0,
  138174. };
  138175. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138176. -0.5, 0.5,
  138177. };
  138178. static long _vq_quantmap__44c1_s_p1_0[] = {
  138179. 1, 0, 2,
  138180. };
  138181. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138182. _vq_quantthresh__44c1_s_p1_0,
  138183. _vq_quantmap__44c1_s_p1_0,
  138184. 3,
  138185. 3
  138186. };
  138187. static static_codebook _44c1_s_p1_0 = {
  138188. 8, 6561,
  138189. _vq_lengthlist__44c1_s_p1_0,
  138190. 1, -535822336, 1611661312, 2, 0,
  138191. _vq_quantlist__44c1_s_p1_0,
  138192. NULL,
  138193. &_vq_auxt__44c1_s_p1_0,
  138194. NULL,
  138195. 0
  138196. };
  138197. static long _vq_quantlist__44c1_s_p2_0[] = {
  138198. 2,
  138199. 1,
  138200. 3,
  138201. 0,
  138202. 4,
  138203. };
  138204. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138205. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0,
  138245. };
  138246. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138247. -1.5, -0.5, 0.5, 1.5,
  138248. };
  138249. static long _vq_quantmap__44c1_s_p2_0[] = {
  138250. 3, 1, 0, 2, 4,
  138251. };
  138252. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138253. _vq_quantthresh__44c1_s_p2_0,
  138254. _vq_quantmap__44c1_s_p2_0,
  138255. 5,
  138256. 5
  138257. };
  138258. static static_codebook _44c1_s_p2_0 = {
  138259. 4, 625,
  138260. _vq_lengthlist__44c1_s_p2_0,
  138261. 1, -533725184, 1611661312, 3, 0,
  138262. _vq_quantlist__44c1_s_p2_0,
  138263. NULL,
  138264. &_vq_auxt__44c1_s_p2_0,
  138265. NULL,
  138266. 0
  138267. };
  138268. static long _vq_quantlist__44c1_s_p3_0[] = {
  138269. 4,
  138270. 3,
  138271. 5,
  138272. 2,
  138273. 6,
  138274. 1,
  138275. 7,
  138276. 0,
  138277. 8,
  138278. };
  138279. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138280. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138281. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138282. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138283. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138284. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0,
  138286. };
  138287. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138288. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138289. };
  138290. static long _vq_quantmap__44c1_s_p3_0[] = {
  138291. 7, 5, 3, 1, 0, 2, 4, 6,
  138292. 8,
  138293. };
  138294. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138295. _vq_quantthresh__44c1_s_p3_0,
  138296. _vq_quantmap__44c1_s_p3_0,
  138297. 9,
  138298. 9
  138299. };
  138300. static static_codebook _44c1_s_p3_0 = {
  138301. 2, 81,
  138302. _vq_lengthlist__44c1_s_p3_0,
  138303. 1, -531628032, 1611661312, 4, 0,
  138304. _vq_quantlist__44c1_s_p3_0,
  138305. NULL,
  138306. &_vq_auxt__44c1_s_p3_0,
  138307. NULL,
  138308. 0
  138309. };
  138310. static long _vq_quantlist__44c1_s_p4_0[] = {
  138311. 4,
  138312. 3,
  138313. 5,
  138314. 2,
  138315. 6,
  138316. 1,
  138317. 7,
  138318. 0,
  138319. 8,
  138320. };
  138321. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138322. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138323. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138324. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138325. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138326. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138327. 11,
  138328. };
  138329. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138330. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138331. };
  138332. static long _vq_quantmap__44c1_s_p4_0[] = {
  138333. 7, 5, 3, 1, 0, 2, 4, 6,
  138334. 8,
  138335. };
  138336. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138337. _vq_quantthresh__44c1_s_p4_0,
  138338. _vq_quantmap__44c1_s_p4_0,
  138339. 9,
  138340. 9
  138341. };
  138342. static static_codebook _44c1_s_p4_0 = {
  138343. 2, 81,
  138344. _vq_lengthlist__44c1_s_p4_0,
  138345. 1, -531628032, 1611661312, 4, 0,
  138346. _vq_quantlist__44c1_s_p4_0,
  138347. NULL,
  138348. &_vq_auxt__44c1_s_p4_0,
  138349. NULL,
  138350. 0
  138351. };
  138352. static long _vq_quantlist__44c1_s_p5_0[] = {
  138353. 8,
  138354. 7,
  138355. 9,
  138356. 6,
  138357. 10,
  138358. 5,
  138359. 11,
  138360. 4,
  138361. 12,
  138362. 3,
  138363. 13,
  138364. 2,
  138365. 14,
  138366. 1,
  138367. 15,
  138368. 0,
  138369. 16,
  138370. };
  138371. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138372. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138373. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138374. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138375. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138376. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138377. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138378. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138379. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138380. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138381. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138382. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138383. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138384. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138385. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138386. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138387. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138388. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138390. 14,
  138391. };
  138392. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138393. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138394. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138395. };
  138396. static long _vq_quantmap__44c1_s_p5_0[] = {
  138397. 15, 13, 11, 9, 7, 5, 3, 1,
  138398. 0, 2, 4, 6, 8, 10, 12, 14,
  138399. 16,
  138400. };
  138401. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138402. _vq_quantthresh__44c1_s_p5_0,
  138403. _vq_quantmap__44c1_s_p5_0,
  138404. 17,
  138405. 17
  138406. };
  138407. static static_codebook _44c1_s_p5_0 = {
  138408. 2, 289,
  138409. _vq_lengthlist__44c1_s_p5_0,
  138410. 1, -529530880, 1611661312, 5, 0,
  138411. _vq_quantlist__44c1_s_p5_0,
  138412. NULL,
  138413. &_vq_auxt__44c1_s_p5_0,
  138414. NULL,
  138415. 0
  138416. };
  138417. static long _vq_quantlist__44c1_s_p6_0[] = {
  138418. 1,
  138419. 0,
  138420. 2,
  138421. };
  138422. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138423. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138424. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138425. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138426. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138427. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138428. 11,
  138429. };
  138430. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138431. -5.5, 5.5,
  138432. };
  138433. static long _vq_quantmap__44c1_s_p6_0[] = {
  138434. 1, 0, 2,
  138435. };
  138436. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138437. _vq_quantthresh__44c1_s_p6_0,
  138438. _vq_quantmap__44c1_s_p6_0,
  138439. 3,
  138440. 3
  138441. };
  138442. static static_codebook _44c1_s_p6_0 = {
  138443. 4, 81,
  138444. _vq_lengthlist__44c1_s_p6_0,
  138445. 1, -529137664, 1618345984, 2, 0,
  138446. _vq_quantlist__44c1_s_p6_0,
  138447. NULL,
  138448. &_vq_auxt__44c1_s_p6_0,
  138449. NULL,
  138450. 0
  138451. };
  138452. static long _vq_quantlist__44c1_s_p6_1[] = {
  138453. 5,
  138454. 4,
  138455. 6,
  138456. 3,
  138457. 7,
  138458. 2,
  138459. 8,
  138460. 1,
  138461. 9,
  138462. 0,
  138463. 10,
  138464. };
  138465. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138466. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138467. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138468. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138469. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138470. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138471. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138472. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138473. 10,10,10, 8, 8, 8, 8, 8, 8,
  138474. };
  138475. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138476. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138477. 3.5, 4.5,
  138478. };
  138479. static long _vq_quantmap__44c1_s_p6_1[] = {
  138480. 9, 7, 5, 3, 1, 0, 2, 4,
  138481. 6, 8, 10,
  138482. };
  138483. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138484. _vq_quantthresh__44c1_s_p6_1,
  138485. _vq_quantmap__44c1_s_p6_1,
  138486. 11,
  138487. 11
  138488. };
  138489. static static_codebook _44c1_s_p6_1 = {
  138490. 2, 121,
  138491. _vq_lengthlist__44c1_s_p6_1,
  138492. 1, -531365888, 1611661312, 4, 0,
  138493. _vq_quantlist__44c1_s_p6_1,
  138494. NULL,
  138495. &_vq_auxt__44c1_s_p6_1,
  138496. NULL,
  138497. 0
  138498. };
  138499. static long _vq_quantlist__44c1_s_p7_0[] = {
  138500. 6,
  138501. 5,
  138502. 7,
  138503. 4,
  138504. 8,
  138505. 3,
  138506. 9,
  138507. 2,
  138508. 10,
  138509. 1,
  138510. 11,
  138511. 0,
  138512. 12,
  138513. };
  138514. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138515. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138516. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138517. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138518. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138519. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138520. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138521. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138522. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138523. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138524. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138525. 0,12,11,11,11,13,10,14,13,
  138526. };
  138527. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138528. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138529. 12.5, 17.5, 22.5, 27.5,
  138530. };
  138531. static long _vq_quantmap__44c1_s_p7_0[] = {
  138532. 11, 9, 7, 5, 3, 1, 0, 2,
  138533. 4, 6, 8, 10, 12,
  138534. };
  138535. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138536. _vq_quantthresh__44c1_s_p7_0,
  138537. _vq_quantmap__44c1_s_p7_0,
  138538. 13,
  138539. 13
  138540. };
  138541. static static_codebook _44c1_s_p7_0 = {
  138542. 2, 169,
  138543. _vq_lengthlist__44c1_s_p7_0,
  138544. 1, -526516224, 1616117760, 4, 0,
  138545. _vq_quantlist__44c1_s_p7_0,
  138546. NULL,
  138547. &_vq_auxt__44c1_s_p7_0,
  138548. NULL,
  138549. 0
  138550. };
  138551. static long _vq_quantlist__44c1_s_p7_1[] = {
  138552. 2,
  138553. 1,
  138554. 3,
  138555. 0,
  138556. 4,
  138557. };
  138558. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138559. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138560. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138561. };
  138562. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138563. -1.5, -0.5, 0.5, 1.5,
  138564. };
  138565. static long _vq_quantmap__44c1_s_p7_1[] = {
  138566. 3, 1, 0, 2, 4,
  138567. };
  138568. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138569. _vq_quantthresh__44c1_s_p7_1,
  138570. _vq_quantmap__44c1_s_p7_1,
  138571. 5,
  138572. 5
  138573. };
  138574. static static_codebook _44c1_s_p7_1 = {
  138575. 2, 25,
  138576. _vq_lengthlist__44c1_s_p7_1,
  138577. 1, -533725184, 1611661312, 3, 0,
  138578. _vq_quantlist__44c1_s_p7_1,
  138579. NULL,
  138580. &_vq_auxt__44c1_s_p7_1,
  138581. NULL,
  138582. 0
  138583. };
  138584. static long _vq_quantlist__44c1_s_p8_0[] = {
  138585. 6,
  138586. 5,
  138587. 7,
  138588. 4,
  138589. 8,
  138590. 3,
  138591. 9,
  138592. 2,
  138593. 10,
  138594. 1,
  138595. 11,
  138596. 0,
  138597. 12,
  138598. };
  138599. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138600. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138601. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138602. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138603. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138604. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138605. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138606. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138607. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138608. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138609. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138610. 10,10,10,10,10,10,10,10,10,
  138611. };
  138612. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138613. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138614. 552.5, 773.5, 994.5, 1215.5,
  138615. };
  138616. static long _vq_quantmap__44c1_s_p8_0[] = {
  138617. 11, 9, 7, 5, 3, 1, 0, 2,
  138618. 4, 6, 8, 10, 12,
  138619. };
  138620. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138621. _vq_quantthresh__44c1_s_p8_0,
  138622. _vq_quantmap__44c1_s_p8_0,
  138623. 13,
  138624. 13
  138625. };
  138626. static static_codebook _44c1_s_p8_0 = {
  138627. 2, 169,
  138628. _vq_lengthlist__44c1_s_p8_0,
  138629. 1, -514541568, 1627103232, 4, 0,
  138630. _vq_quantlist__44c1_s_p8_0,
  138631. NULL,
  138632. &_vq_auxt__44c1_s_p8_0,
  138633. NULL,
  138634. 0
  138635. };
  138636. static long _vq_quantlist__44c1_s_p8_1[] = {
  138637. 6,
  138638. 5,
  138639. 7,
  138640. 4,
  138641. 8,
  138642. 3,
  138643. 9,
  138644. 2,
  138645. 10,
  138646. 1,
  138647. 11,
  138648. 0,
  138649. 12,
  138650. };
  138651. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138652. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138653. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138654. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138655. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138656. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138657. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138658. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138659. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138660. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138661. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138662. 16,13,12,12,11,14,12,15,13,
  138663. };
  138664. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138665. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138666. 42.5, 59.5, 76.5, 93.5,
  138667. };
  138668. static long _vq_quantmap__44c1_s_p8_1[] = {
  138669. 11, 9, 7, 5, 3, 1, 0, 2,
  138670. 4, 6, 8, 10, 12,
  138671. };
  138672. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138673. _vq_quantthresh__44c1_s_p8_1,
  138674. _vq_quantmap__44c1_s_p8_1,
  138675. 13,
  138676. 13
  138677. };
  138678. static static_codebook _44c1_s_p8_1 = {
  138679. 2, 169,
  138680. _vq_lengthlist__44c1_s_p8_1,
  138681. 1, -522616832, 1620115456, 4, 0,
  138682. _vq_quantlist__44c1_s_p8_1,
  138683. NULL,
  138684. &_vq_auxt__44c1_s_p8_1,
  138685. NULL,
  138686. 0
  138687. };
  138688. static long _vq_quantlist__44c1_s_p8_2[] = {
  138689. 8,
  138690. 7,
  138691. 9,
  138692. 6,
  138693. 10,
  138694. 5,
  138695. 11,
  138696. 4,
  138697. 12,
  138698. 3,
  138699. 13,
  138700. 2,
  138701. 14,
  138702. 1,
  138703. 15,
  138704. 0,
  138705. 16,
  138706. };
  138707. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138708. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138709. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138710. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138711. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138712. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138713. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138714. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138715. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138716. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138717. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138718. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138719. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138720. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138721. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138722. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138723. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138724. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138725. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138726. 9,
  138727. };
  138728. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138729. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138730. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138731. };
  138732. static long _vq_quantmap__44c1_s_p8_2[] = {
  138733. 15, 13, 11, 9, 7, 5, 3, 1,
  138734. 0, 2, 4, 6, 8, 10, 12, 14,
  138735. 16,
  138736. };
  138737. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138738. _vq_quantthresh__44c1_s_p8_2,
  138739. _vq_quantmap__44c1_s_p8_2,
  138740. 17,
  138741. 17
  138742. };
  138743. static static_codebook _44c1_s_p8_2 = {
  138744. 2, 289,
  138745. _vq_lengthlist__44c1_s_p8_2,
  138746. 1, -529530880, 1611661312, 5, 0,
  138747. _vq_quantlist__44c1_s_p8_2,
  138748. NULL,
  138749. &_vq_auxt__44c1_s_p8_2,
  138750. NULL,
  138751. 0
  138752. };
  138753. static long _huff_lengthlist__44c1_s_short[] = {
  138754. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138755. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138756. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138757. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138758. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138759. 11,
  138760. };
  138761. static static_codebook _huff_book__44c1_s_short = {
  138762. 2, 81,
  138763. _huff_lengthlist__44c1_s_short,
  138764. 0, 0, 0, 0, 0,
  138765. NULL,
  138766. NULL,
  138767. NULL,
  138768. NULL,
  138769. 0
  138770. };
  138771. static long _huff_lengthlist__44c1_sm_long[] = {
  138772. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138773. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138774. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138775. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138776. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138777. 11,
  138778. };
  138779. static static_codebook _huff_book__44c1_sm_long = {
  138780. 2, 81,
  138781. _huff_lengthlist__44c1_sm_long,
  138782. 0, 0, 0, 0, 0,
  138783. NULL,
  138784. NULL,
  138785. NULL,
  138786. NULL,
  138787. 0
  138788. };
  138789. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138790. 1,
  138791. 0,
  138792. 2,
  138793. };
  138794. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138795. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138796. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138801. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138806. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  138841. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  138846. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  138851. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138887. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138892. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138897. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0,
  139206. };
  139207. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139208. -0.5, 0.5,
  139209. };
  139210. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139211. 1, 0, 2,
  139212. };
  139213. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139214. _vq_quantthresh__44c1_sm_p1_0,
  139215. _vq_quantmap__44c1_sm_p1_0,
  139216. 3,
  139217. 3
  139218. };
  139219. static static_codebook _44c1_sm_p1_0 = {
  139220. 8, 6561,
  139221. _vq_lengthlist__44c1_sm_p1_0,
  139222. 1, -535822336, 1611661312, 2, 0,
  139223. _vq_quantlist__44c1_sm_p1_0,
  139224. NULL,
  139225. &_vq_auxt__44c1_sm_p1_0,
  139226. NULL,
  139227. 0
  139228. };
  139229. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139230. 2,
  139231. 1,
  139232. 3,
  139233. 0,
  139234. 4,
  139235. };
  139236. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139237. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0,
  139277. };
  139278. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139279. -1.5, -0.5, 0.5, 1.5,
  139280. };
  139281. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139282. 3, 1, 0, 2, 4,
  139283. };
  139284. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139285. _vq_quantthresh__44c1_sm_p2_0,
  139286. _vq_quantmap__44c1_sm_p2_0,
  139287. 5,
  139288. 5
  139289. };
  139290. static static_codebook _44c1_sm_p2_0 = {
  139291. 4, 625,
  139292. _vq_lengthlist__44c1_sm_p2_0,
  139293. 1, -533725184, 1611661312, 3, 0,
  139294. _vq_quantlist__44c1_sm_p2_0,
  139295. NULL,
  139296. &_vq_auxt__44c1_sm_p2_0,
  139297. NULL,
  139298. 0
  139299. };
  139300. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139301. 4,
  139302. 3,
  139303. 5,
  139304. 2,
  139305. 6,
  139306. 1,
  139307. 7,
  139308. 0,
  139309. 8,
  139310. };
  139311. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139312. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139313. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139314. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139315. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139316. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0,
  139318. };
  139319. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139320. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139321. };
  139322. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139323. 7, 5, 3, 1, 0, 2, 4, 6,
  139324. 8,
  139325. };
  139326. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139327. _vq_quantthresh__44c1_sm_p3_0,
  139328. _vq_quantmap__44c1_sm_p3_0,
  139329. 9,
  139330. 9
  139331. };
  139332. static static_codebook _44c1_sm_p3_0 = {
  139333. 2, 81,
  139334. _vq_lengthlist__44c1_sm_p3_0,
  139335. 1, -531628032, 1611661312, 4, 0,
  139336. _vq_quantlist__44c1_sm_p3_0,
  139337. NULL,
  139338. &_vq_auxt__44c1_sm_p3_0,
  139339. NULL,
  139340. 0
  139341. };
  139342. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139343. 4,
  139344. 3,
  139345. 5,
  139346. 2,
  139347. 6,
  139348. 1,
  139349. 7,
  139350. 0,
  139351. 8,
  139352. };
  139353. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139354. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139355. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139356. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139357. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139358. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139359. 11,
  139360. };
  139361. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139362. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139363. };
  139364. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139365. 7, 5, 3, 1, 0, 2, 4, 6,
  139366. 8,
  139367. };
  139368. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139369. _vq_quantthresh__44c1_sm_p4_0,
  139370. _vq_quantmap__44c1_sm_p4_0,
  139371. 9,
  139372. 9
  139373. };
  139374. static static_codebook _44c1_sm_p4_0 = {
  139375. 2, 81,
  139376. _vq_lengthlist__44c1_sm_p4_0,
  139377. 1, -531628032, 1611661312, 4, 0,
  139378. _vq_quantlist__44c1_sm_p4_0,
  139379. NULL,
  139380. &_vq_auxt__44c1_sm_p4_0,
  139381. NULL,
  139382. 0
  139383. };
  139384. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139385. 8,
  139386. 7,
  139387. 9,
  139388. 6,
  139389. 10,
  139390. 5,
  139391. 11,
  139392. 4,
  139393. 12,
  139394. 3,
  139395. 13,
  139396. 2,
  139397. 14,
  139398. 1,
  139399. 15,
  139400. 0,
  139401. 16,
  139402. };
  139403. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139404. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139405. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139406. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139407. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139408. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139409. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139410. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139411. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139412. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139413. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139414. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139415. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139416. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139417. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139418. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139419. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139420. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139421. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139422. 14,
  139423. };
  139424. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139425. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139426. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139427. };
  139428. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139429. 15, 13, 11, 9, 7, 5, 3, 1,
  139430. 0, 2, 4, 6, 8, 10, 12, 14,
  139431. 16,
  139432. };
  139433. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139434. _vq_quantthresh__44c1_sm_p5_0,
  139435. _vq_quantmap__44c1_sm_p5_0,
  139436. 17,
  139437. 17
  139438. };
  139439. static static_codebook _44c1_sm_p5_0 = {
  139440. 2, 289,
  139441. _vq_lengthlist__44c1_sm_p5_0,
  139442. 1, -529530880, 1611661312, 5, 0,
  139443. _vq_quantlist__44c1_sm_p5_0,
  139444. NULL,
  139445. &_vq_auxt__44c1_sm_p5_0,
  139446. NULL,
  139447. 0
  139448. };
  139449. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139450. 1,
  139451. 0,
  139452. 2,
  139453. };
  139454. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139455. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139456. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139457. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139458. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139459. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139460. 11,
  139461. };
  139462. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139463. -5.5, 5.5,
  139464. };
  139465. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139466. 1, 0, 2,
  139467. };
  139468. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139469. _vq_quantthresh__44c1_sm_p6_0,
  139470. _vq_quantmap__44c1_sm_p6_0,
  139471. 3,
  139472. 3
  139473. };
  139474. static static_codebook _44c1_sm_p6_0 = {
  139475. 4, 81,
  139476. _vq_lengthlist__44c1_sm_p6_0,
  139477. 1, -529137664, 1618345984, 2, 0,
  139478. _vq_quantlist__44c1_sm_p6_0,
  139479. NULL,
  139480. &_vq_auxt__44c1_sm_p6_0,
  139481. NULL,
  139482. 0
  139483. };
  139484. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139485. 5,
  139486. 4,
  139487. 6,
  139488. 3,
  139489. 7,
  139490. 2,
  139491. 8,
  139492. 1,
  139493. 9,
  139494. 0,
  139495. 10,
  139496. };
  139497. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139498. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139499. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139500. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139501. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139502. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139503. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139504. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139505. 10,10,10, 8, 8, 8, 8, 8, 8,
  139506. };
  139507. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139508. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139509. 3.5, 4.5,
  139510. };
  139511. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139512. 9, 7, 5, 3, 1, 0, 2, 4,
  139513. 6, 8, 10,
  139514. };
  139515. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139516. _vq_quantthresh__44c1_sm_p6_1,
  139517. _vq_quantmap__44c1_sm_p6_1,
  139518. 11,
  139519. 11
  139520. };
  139521. static static_codebook _44c1_sm_p6_1 = {
  139522. 2, 121,
  139523. _vq_lengthlist__44c1_sm_p6_1,
  139524. 1, -531365888, 1611661312, 4, 0,
  139525. _vq_quantlist__44c1_sm_p6_1,
  139526. NULL,
  139527. &_vq_auxt__44c1_sm_p6_1,
  139528. NULL,
  139529. 0
  139530. };
  139531. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139532. 6,
  139533. 5,
  139534. 7,
  139535. 4,
  139536. 8,
  139537. 3,
  139538. 9,
  139539. 2,
  139540. 10,
  139541. 1,
  139542. 11,
  139543. 0,
  139544. 12,
  139545. };
  139546. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139547. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139548. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139549. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139550. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139551. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139552. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139553. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139554. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139555. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139556. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139557. 0,12,12,11,11,13,12,14,13,
  139558. };
  139559. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139560. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139561. 12.5, 17.5, 22.5, 27.5,
  139562. };
  139563. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139564. 11, 9, 7, 5, 3, 1, 0, 2,
  139565. 4, 6, 8, 10, 12,
  139566. };
  139567. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139568. _vq_quantthresh__44c1_sm_p7_0,
  139569. _vq_quantmap__44c1_sm_p7_0,
  139570. 13,
  139571. 13
  139572. };
  139573. static static_codebook _44c1_sm_p7_0 = {
  139574. 2, 169,
  139575. _vq_lengthlist__44c1_sm_p7_0,
  139576. 1, -526516224, 1616117760, 4, 0,
  139577. _vq_quantlist__44c1_sm_p7_0,
  139578. NULL,
  139579. &_vq_auxt__44c1_sm_p7_0,
  139580. NULL,
  139581. 0
  139582. };
  139583. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139584. 2,
  139585. 1,
  139586. 3,
  139587. 0,
  139588. 4,
  139589. };
  139590. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139591. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139592. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139593. };
  139594. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139595. -1.5, -0.5, 0.5, 1.5,
  139596. };
  139597. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139598. 3, 1, 0, 2, 4,
  139599. };
  139600. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139601. _vq_quantthresh__44c1_sm_p7_1,
  139602. _vq_quantmap__44c1_sm_p7_1,
  139603. 5,
  139604. 5
  139605. };
  139606. static static_codebook _44c1_sm_p7_1 = {
  139607. 2, 25,
  139608. _vq_lengthlist__44c1_sm_p7_1,
  139609. 1, -533725184, 1611661312, 3, 0,
  139610. _vq_quantlist__44c1_sm_p7_1,
  139611. NULL,
  139612. &_vq_auxt__44c1_sm_p7_1,
  139613. NULL,
  139614. 0
  139615. };
  139616. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139617. 6,
  139618. 5,
  139619. 7,
  139620. 4,
  139621. 8,
  139622. 3,
  139623. 9,
  139624. 2,
  139625. 10,
  139626. 1,
  139627. 11,
  139628. 0,
  139629. 12,
  139630. };
  139631. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139632. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139633. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139634. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139635. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139636. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139637. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139638. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139639. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139640. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139641. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139642. 13,13,13,13,13,13,13,13,13,
  139643. };
  139644. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139645. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139646. 552.5, 773.5, 994.5, 1215.5,
  139647. };
  139648. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139649. 11, 9, 7, 5, 3, 1, 0, 2,
  139650. 4, 6, 8, 10, 12,
  139651. };
  139652. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139653. _vq_quantthresh__44c1_sm_p8_0,
  139654. _vq_quantmap__44c1_sm_p8_0,
  139655. 13,
  139656. 13
  139657. };
  139658. static static_codebook _44c1_sm_p8_0 = {
  139659. 2, 169,
  139660. _vq_lengthlist__44c1_sm_p8_0,
  139661. 1, -514541568, 1627103232, 4, 0,
  139662. _vq_quantlist__44c1_sm_p8_0,
  139663. NULL,
  139664. &_vq_auxt__44c1_sm_p8_0,
  139665. NULL,
  139666. 0
  139667. };
  139668. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139669. 6,
  139670. 5,
  139671. 7,
  139672. 4,
  139673. 8,
  139674. 3,
  139675. 9,
  139676. 2,
  139677. 10,
  139678. 1,
  139679. 11,
  139680. 0,
  139681. 12,
  139682. };
  139683. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139684. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139685. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139686. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139687. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139688. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139689. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139690. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139691. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139692. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139693. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139694. 20,13,12,12,12,14,12,14,13,
  139695. };
  139696. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139697. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139698. 42.5, 59.5, 76.5, 93.5,
  139699. };
  139700. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139701. 11, 9, 7, 5, 3, 1, 0, 2,
  139702. 4, 6, 8, 10, 12,
  139703. };
  139704. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139705. _vq_quantthresh__44c1_sm_p8_1,
  139706. _vq_quantmap__44c1_sm_p8_1,
  139707. 13,
  139708. 13
  139709. };
  139710. static static_codebook _44c1_sm_p8_1 = {
  139711. 2, 169,
  139712. _vq_lengthlist__44c1_sm_p8_1,
  139713. 1, -522616832, 1620115456, 4, 0,
  139714. _vq_quantlist__44c1_sm_p8_1,
  139715. NULL,
  139716. &_vq_auxt__44c1_sm_p8_1,
  139717. NULL,
  139718. 0
  139719. };
  139720. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139721. 8,
  139722. 7,
  139723. 9,
  139724. 6,
  139725. 10,
  139726. 5,
  139727. 11,
  139728. 4,
  139729. 12,
  139730. 3,
  139731. 13,
  139732. 2,
  139733. 14,
  139734. 1,
  139735. 15,
  139736. 0,
  139737. 16,
  139738. };
  139739. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139740. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139741. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139742. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139743. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139744. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139745. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139746. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139747. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139748. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139749. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139750. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139751. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139752. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139753. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139754. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139755. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139756. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139757. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139758. 9,
  139759. };
  139760. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139761. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139762. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139763. };
  139764. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139765. 15, 13, 11, 9, 7, 5, 3, 1,
  139766. 0, 2, 4, 6, 8, 10, 12, 14,
  139767. 16,
  139768. };
  139769. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139770. _vq_quantthresh__44c1_sm_p8_2,
  139771. _vq_quantmap__44c1_sm_p8_2,
  139772. 17,
  139773. 17
  139774. };
  139775. static static_codebook _44c1_sm_p8_2 = {
  139776. 2, 289,
  139777. _vq_lengthlist__44c1_sm_p8_2,
  139778. 1, -529530880, 1611661312, 5, 0,
  139779. _vq_quantlist__44c1_sm_p8_2,
  139780. NULL,
  139781. &_vq_auxt__44c1_sm_p8_2,
  139782. NULL,
  139783. 0
  139784. };
  139785. static long _huff_lengthlist__44c1_sm_short[] = {
  139786. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139787. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139788. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139789. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139790. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139791. 11,
  139792. };
  139793. static static_codebook _huff_book__44c1_sm_short = {
  139794. 2, 81,
  139795. _huff_lengthlist__44c1_sm_short,
  139796. 0, 0, 0, 0, 0,
  139797. NULL,
  139798. NULL,
  139799. NULL,
  139800. NULL,
  139801. 0
  139802. };
  139803. static long _huff_lengthlist__44cn1_s_long[] = {
  139804. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139805. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139806. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139807. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139808. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139809. 20,
  139810. };
  139811. static static_codebook _huff_book__44cn1_s_long = {
  139812. 2, 81,
  139813. _huff_lengthlist__44cn1_s_long,
  139814. 0, 0, 0, 0, 0,
  139815. NULL,
  139816. NULL,
  139817. NULL,
  139818. NULL,
  139819. 0
  139820. };
  139821. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139822. 1,
  139823. 0,
  139824. 2,
  139825. };
  139826. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139827. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139828. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139833. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139838. 0, 0, 0, 0, 8,10, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  139873. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  139878. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  139883. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139919. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139924. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139929. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0,
  140238. };
  140239. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140240. -0.5, 0.5,
  140241. };
  140242. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140243. 1, 0, 2,
  140244. };
  140245. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140246. _vq_quantthresh__44cn1_s_p1_0,
  140247. _vq_quantmap__44cn1_s_p1_0,
  140248. 3,
  140249. 3
  140250. };
  140251. static static_codebook _44cn1_s_p1_0 = {
  140252. 8, 6561,
  140253. _vq_lengthlist__44cn1_s_p1_0,
  140254. 1, -535822336, 1611661312, 2, 0,
  140255. _vq_quantlist__44cn1_s_p1_0,
  140256. NULL,
  140257. &_vq_auxt__44cn1_s_p1_0,
  140258. NULL,
  140259. 0
  140260. };
  140261. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140262. 2,
  140263. 1,
  140264. 3,
  140265. 0,
  140266. 4,
  140267. };
  140268. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140269. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0,
  140309. };
  140310. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140311. -1.5, -0.5, 0.5, 1.5,
  140312. };
  140313. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140314. 3, 1, 0, 2, 4,
  140315. };
  140316. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140317. _vq_quantthresh__44cn1_s_p2_0,
  140318. _vq_quantmap__44cn1_s_p2_0,
  140319. 5,
  140320. 5
  140321. };
  140322. static static_codebook _44cn1_s_p2_0 = {
  140323. 4, 625,
  140324. _vq_lengthlist__44cn1_s_p2_0,
  140325. 1, -533725184, 1611661312, 3, 0,
  140326. _vq_quantlist__44cn1_s_p2_0,
  140327. NULL,
  140328. &_vq_auxt__44cn1_s_p2_0,
  140329. NULL,
  140330. 0
  140331. };
  140332. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140333. 4,
  140334. 3,
  140335. 5,
  140336. 2,
  140337. 6,
  140338. 1,
  140339. 7,
  140340. 0,
  140341. 8,
  140342. };
  140343. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140344. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140345. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140346. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140347. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140348. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0,
  140350. };
  140351. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140352. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140353. };
  140354. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140355. 7, 5, 3, 1, 0, 2, 4, 6,
  140356. 8,
  140357. };
  140358. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140359. _vq_quantthresh__44cn1_s_p3_0,
  140360. _vq_quantmap__44cn1_s_p3_0,
  140361. 9,
  140362. 9
  140363. };
  140364. static static_codebook _44cn1_s_p3_0 = {
  140365. 2, 81,
  140366. _vq_lengthlist__44cn1_s_p3_0,
  140367. 1, -531628032, 1611661312, 4, 0,
  140368. _vq_quantlist__44cn1_s_p3_0,
  140369. NULL,
  140370. &_vq_auxt__44cn1_s_p3_0,
  140371. NULL,
  140372. 0
  140373. };
  140374. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140375. 4,
  140376. 3,
  140377. 5,
  140378. 2,
  140379. 6,
  140380. 1,
  140381. 7,
  140382. 0,
  140383. 8,
  140384. };
  140385. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140386. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140387. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140388. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140389. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140390. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140391. 11,
  140392. };
  140393. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140394. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140395. };
  140396. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140397. 7, 5, 3, 1, 0, 2, 4, 6,
  140398. 8,
  140399. };
  140400. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140401. _vq_quantthresh__44cn1_s_p4_0,
  140402. _vq_quantmap__44cn1_s_p4_0,
  140403. 9,
  140404. 9
  140405. };
  140406. static static_codebook _44cn1_s_p4_0 = {
  140407. 2, 81,
  140408. _vq_lengthlist__44cn1_s_p4_0,
  140409. 1, -531628032, 1611661312, 4, 0,
  140410. _vq_quantlist__44cn1_s_p4_0,
  140411. NULL,
  140412. &_vq_auxt__44cn1_s_p4_0,
  140413. NULL,
  140414. 0
  140415. };
  140416. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140417. 8,
  140418. 7,
  140419. 9,
  140420. 6,
  140421. 10,
  140422. 5,
  140423. 11,
  140424. 4,
  140425. 12,
  140426. 3,
  140427. 13,
  140428. 2,
  140429. 14,
  140430. 1,
  140431. 15,
  140432. 0,
  140433. 16,
  140434. };
  140435. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140436. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140437. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140438. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140439. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140440. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140441. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140442. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140443. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140444. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140445. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140446. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140447. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140448. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140449. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140450. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140451. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140452. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140453. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140454. 14,
  140455. };
  140456. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140457. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140458. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140459. };
  140460. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140461. 15, 13, 11, 9, 7, 5, 3, 1,
  140462. 0, 2, 4, 6, 8, 10, 12, 14,
  140463. 16,
  140464. };
  140465. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140466. _vq_quantthresh__44cn1_s_p5_0,
  140467. _vq_quantmap__44cn1_s_p5_0,
  140468. 17,
  140469. 17
  140470. };
  140471. static static_codebook _44cn1_s_p5_0 = {
  140472. 2, 289,
  140473. _vq_lengthlist__44cn1_s_p5_0,
  140474. 1, -529530880, 1611661312, 5, 0,
  140475. _vq_quantlist__44cn1_s_p5_0,
  140476. NULL,
  140477. &_vq_auxt__44cn1_s_p5_0,
  140478. NULL,
  140479. 0
  140480. };
  140481. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140482. 1,
  140483. 0,
  140484. 2,
  140485. };
  140486. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140487. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140488. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140489. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140490. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140491. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140492. 10,
  140493. };
  140494. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140495. -5.5, 5.5,
  140496. };
  140497. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140498. 1, 0, 2,
  140499. };
  140500. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140501. _vq_quantthresh__44cn1_s_p6_0,
  140502. _vq_quantmap__44cn1_s_p6_0,
  140503. 3,
  140504. 3
  140505. };
  140506. static static_codebook _44cn1_s_p6_0 = {
  140507. 4, 81,
  140508. _vq_lengthlist__44cn1_s_p6_0,
  140509. 1, -529137664, 1618345984, 2, 0,
  140510. _vq_quantlist__44cn1_s_p6_0,
  140511. NULL,
  140512. &_vq_auxt__44cn1_s_p6_0,
  140513. NULL,
  140514. 0
  140515. };
  140516. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140517. 5,
  140518. 4,
  140519. 6,
  140520. 3,
  140521. 7,
  140522. 2,
  140523. 8,
  140524. 1,
  140525. 9,
  140526. 0,
  140527. 10,
  140528. };
  140529. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140530. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140531. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140532. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140533. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140534. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140535. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140536. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140537. 10,10,10, 9, 9, 9, 9, 9, 9,
  140538. };
  140539. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140540. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140541. 3.5, 4.5,
  140542. };
  140543. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140544. 9, 7, 5, 3, 1, 0, 2, 4,
  140545. 6, 8, 10,
  140546. };
  140547. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140548. _vq_quantthresh__44cn1_s_p6_1,
  140549. _vq_quantmap__44cn1_s_p6_1,
  140550. 11,
  140551. 11
  140552. };
  140553. static static_codebook _44cn1_s_p6_1 = {
  140554. 2, 121,
  140555. _vq_lengthlist__44cn1_s_p6_1,
  140556. 1, -531365888, 1611661312, 4, 0,
  140557. _vq_quantlist__44cn1_s_p6_1,
  140558. NULL,
  140559. &_vq_auxt__44cn1_s_p6_1,
  140560. NULL,
  140561. 0
  140562. };
  140563. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140564. 6,
  140565. 5,
  140566. 7,
  140567. 4,
  140568. 8,
  140569. 3,
  140570. 9,
  140571. 2,
  140572. 10,
  140573. 1,
  140574. 11,
  140575. 0,
  140576. 12,
  140577. };
  140578. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140579. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140580. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140581. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140582. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140583. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140584. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140585. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140586. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140587. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140588. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140589. 0,13,13,12,12,13,13,13,14,
  140590. };
  140591. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140592. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140593. 12.5, 17.5, 22.5, 27.5,
  140594. };
  140595. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140596. 11, 9, 7, 5, 3, 1, 0, 2,
  140597. 4, 6, 8, 10, 12,
  140598. };
  140599. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140600. _vq_quantthresh__44cn1_s_p7_0,
  140601. _vq_quantmap__44cn1_s_p7_0,
  140602. 13,
  140603. 13
  140604. };
  140605. static static_codebook _44cn1_s_p7_0 = {
  140606. 2, 169,
  140607. _vq_lengthlist__44cn1_s_p7_0,
  140608. 1, -526516224, 1616117760, 4, 0,
  140609. _vq_quantlist__44cn1_s_p7_0,
  140610. NULL,
  140611. &_vq_auxt__44cn1_s_p7_0,
  140612. NULL,
  140613. 0
  140614. };
  140615. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140616. 2,
  140617. 1,
  140618. 3,
  140619. 0,
  140620. 4,
  140621. };
  140622. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140623. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140624. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140625. };
  140626. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140627. -1.5, -0.5, 0.5, 1.5,
  140628. };
  140629. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140630. 3, 1, 0, 2, 4,
  140631. };
  140632. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140633. _vq_quantthresh__44cn1_s_p7_1,
  140634. _vq_quantmap__44cn1_s_p7_1,
  140635. 5,
  140636. 5
  140637. };
  140638. static static_codebook _44cn1_s_p7_1 = {
  140639. 2, 25,
  140640. _vq_lengthlist__44cn1_s_p7_1,
  140641. 1, -533725184, 1611661312, 3, 0,
  140642. _vq_quantlist__44cn1_s_p7_1,
  140643. NULL,
  140644. &_vq_auxt__44cn1_s_p7_1,
  140645. NULL,
  140646. 0
  140647. };
  140648. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140649. 2,
  140650. 1,
  140651. 3,
  140652. 0,
  140653. 4,
  140654. };
  140655. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140656. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140657. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140658. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140659. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140660. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140661. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140662. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140663. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140664. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140665. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140666. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140667. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140668. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140669. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140670. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140671. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140672. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140673. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140674. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140675. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140676. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140679. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140680. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140681. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140682. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140683. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140684. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140685. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140686. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140687. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140688. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140689. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140690. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140691. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140692. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140693. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140694. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140695. 12,
  140696. };
  140697. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140698. -331.5, -110.5, 110.5, 331.5,
  140699. };
  140700. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140701. 3, 1, 0, 2, 4,
  140702. };
  140703. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140704. _vq_quantthresh__44cn1_s_p8_0,
  140705. _vq_quantmap__44cn1_s_p8_0,
  140706. 5,
  140707. 5
  140708. };
  140709. static static_codebook _44cn1_s_p8_0 = {
  140710. 4, 625,
  140711. _vq_lengthlist__44cn1_s_p8_0,
  140712. 1, -518283264, 1627103232, 3, 0,
  140713. _vq_quantlist__44cn1_s_p8_0,
  140714. NULL,
  140715. &_vq_auxt__44cn1_s_p8_0,
  140716. NULL,
  140717. 0
  140718. };
  140719. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140720. 6,
  140721. 5,
  140722. 7,
  140723. 4,
  140724. 8,
  140725. 3,
  140726. 9,
  140727. 2,
  140728. 10,
  140729. 1,
  140730. 11,
  140731. 0,
  140732. 12,
  140733. };
  140734. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140735. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140736. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140737. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140738. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140739. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140740. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140741. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140742. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140743. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140744. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140745. 15,12,12,11,11,14,12,13,14,
  140746. };
  140747. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140748. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140749. 42.5, 59.5, 76.5, 93.5,
  140750. };
  140751. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140752. 11, 9, 7, 5, 3, 1, 0, 2,
  140753. 4, 6, 8, 10, 12,
  140754. };
  140755. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140756. _vq_quantthresh__44cn1_s_p8_1,
  140757. _vq_quantmap__44cn1_s_p8_1,
  140758. 13,
  140759. 13
  140760. };
  140761. static static_codebook _44cn1_s_p8_1 = {
  140762. 2, 169,
  140763. _vq_lengthlist__44cn1_s_p8_1,
  140764. 1, -522616832, 1620115456, 4, 0,
  140765. _vq_quantlist__44cn1_s_p8_1,
  140766. NULL,
  140767. &_vq_auxt__44cn1_s_p8_1,
  140768. NULL,
  140769. 0
  140770. };
  140771. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140772. 8,
  140773. 7,
  140774. 9,
  140775. 6,
  140776. 10,
  140777. 5,
  140778. 11,
  140779. 4,
  140780. 12,
  140781. 3,
  140782. 13,
  140783. 2,
  140784. 14,
  140785. 1,
  140786. 15,
  140787. 0,
  140788. 16,
  140789. };
  140790. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140791. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140792. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140793. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140794. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140795. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140796. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140797. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140798. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140799. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140800. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140801. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140802. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140803. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140804. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140805. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140806. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140807. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140808. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140809. 9,
  140810. };
  140811. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140812. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140813. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140814. };
  140815. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140816. 15, 13, 11, 9, 7, 5, 3, 1,
  140817. 0, 2, 4, 6, 8, 10, 12, 14,
  140818. 16,
  140819. };
  140820. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140821. _vq_quantthresh__44cn1_s_p8_2,
  140822. _vq_quantmap__44cn1_s_p8_2,
  140823. 17,
  140824. 17
  140825. };
  140826. static static_codebook _44cn1_s_p8_2 = {
  140827. 2, 289,
  140828. _vq_lengthlist__44cn1_s_p8_2,
  140829. 1, -529530880, 1611661312, 5, 0,
  140830. _vq_quantlist__44cn1_s_p8_2,
  140831. NULL,
  140832. &_vq_auxt__44cn1_s_p8_2,
  140833. NULL,
  140834. 0
  140835. };
  140836. static long _huff_lengthlist__44cn1_s_short[] = {
  140837. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140838. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140839. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140840. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140841. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140842. 10,
  140843. };
  140844. static static_codebook _huff_book__44cn1_s_short = {
  140845. 2, 81,
  140846. _huff_lengthlist__44cn1_s_short,
  140847. 0, 0, 0, 0, 0,
  140848. NULL,
  140849. NULL,
  140850. NULL,
  140851. NULL,
  140852. 0
  140853. };
  140854. static long _huff_lengthlist__44cn1_sm_long[] = {
  140855. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140856. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140857. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140858. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140859. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140860. 17,
  140861. };
  140862. static static_codebook _huff_book__44cn1_sm_long = {
  140863. 2, 81,
  140864. _huff_lengthlist__44cn1_sm_long,
  140865. 0, 0, 0, 0, 0,
  140866. NULL,
  140867. NULL,
  140868. NULL,
  140869. NULL,
  140870. 0
  140871. };
  140872. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140873. 1,
  140874. 0,
  140875. 2,
  140876. };
  140877. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140878. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140879. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140884. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140889. 0, 0, 0, 0, 8, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  140924. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  140929. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  140934. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140970. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140975. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140980. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0,
  141289. };
  141290. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141291. -0.5, 0.5,
  141292. };
  141293. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141294. 1, 0, 2,
  141295. };
  141296. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141297. _vq_quantthresh__44cn1_sm_p1_0,
  141298. _vq_quantmap__44cn1_sm_p1_0,
  141299. 3,
  141300. 3
  141301. };
  141302. static static_codebook _44cn1_sm_p1_0 = {
  141303. 8, 6561,
  141304. _vq_lengthlist__44cn1_sm_p1_0,
  141305. 1, -535822336, 1611661312, 2, 0,
  141306. _vq_quantlist__44cn1_sm_p1_0,
  141307. NULL,
  141308. &_vq_auxt__44cn1_sm_p1_0,
  141309. NULL,
  141310. 0
  141311. };
  141312. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141313. 2,
  141314. 1,
  141315. 3,
  141316. 0,
  141317. 4,
  141318. };
  141319. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141320. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141359. 0,
  141360. };
  141361. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141362. -1.5, -0.5, 0.5, 1.5,
  141363. };
  141364. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141365. 3, 1, 0, 2, 4,
  141366. };
  141367. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141368. _vq_quantthresh__44cn1_sm_p2_0,
  141369. _vq_quantmap__44cn1_sm_p2_0,
  141370. 5,
  141371. 5
  141372. };
  141373. static static_codebook _44cn1_sm_p2_0 = {
  141374. 4, 625,
  141375. _vq_lengthlist__44cn1_sm_p2_0,
  141376. 1, -533725184, 1611661312, 3, 0,
  141377. _vq_quantlist__44cn1_sm_p2_0,
  141378. NULL,
  141379. &_vq_auxt__44cn1_sm_p2_0,
  141380. NULL,
  141381. 0
  141382. };
  141383. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141384. 4,
  141385. 3,
  141386. 5,
  141387. 2,
  141388. 6,
  141389. 1,
  141390. 7,
  141391. 0,
  141392. 8,
  141393. };
  141394. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141395. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141396. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141397. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141398. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141399. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141400. 0,
  141401. };
  141402. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141403. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141404. };
  141405. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141406. 7, 5, 3, 1, 0, 2, 4, 6,
  141407. 8,
  141408. };
  141409. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141410. _vq_quantthresh__44cn1_sm_p3_0,
  141411. _vq_quantmap__44cn1_sm_p3_0,
  141412. 9,
  141413. 9
  141414. };
  141415. static static_codebook _44cn1_sm_p3_0 = {
  141416. 2, 81,
  141417. _vq_lengthlist__44cn1_sm_p3_0,
  141418. 1, -531628032, 1611661312, 4, 0,
  141419. _vq_quantlist__44cn1_sm_p3_0,
  141420. NULL,
  141421. &_vq_auxt__44cn1_sm_p3_0,
  141422. NULL,
  141423. 0
  141424. };
  141425. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141426. 4,
  141427. 3,
  141428. 5,
  141429. 2,
  141430. 6,
  141431. 1,
  141432. 7,
  141433. 0,
  141434. 8,
  141435. };
  141436. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141437. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141438. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141439. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141440. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141441. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141442. 11,
  141443. };
  141444. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141445. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141446. };
  141447. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141448. 7, 5, 3, 1, 0, 2, 4, 6,
  141449. 8,
  141450. };
  141451. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141452. _vq_quantthresh__44cn1_sm_p4_0,
  141453. _vq_quantmap__44cn1_sm_p4_0,
  141454. 9,
  141455. 9
  141456. };
  141457. static static_codebook _44cn1_sm_p4_0 = {
  141458. 2, 81,
  141459. _vq_lengthlist__44cn1_sm_p4_0,
  141460. 1, -531628032, 1611661312, 4, 0,
  141461. _vq_quantlist__44cn1_sm_p4_0,
  141462. NULL,
  141463. &_vq_auxt__44cn1_sm_p4_0,
  141464. NULL,
  141465. 0
  141466. };
  141467. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141468. 8,
  141469. 7,
  141470. 9,
  141471. 6,
  141472. 10,
  141473. 5,
  141474. 11,
  141475. 4,
  141476. 12,
  141477. 3,
  141478. 13,
  141479. 2,
  141480. 14,
  141481. 1,
  141482. 15,
  141483. 0,
  141484. 16,
  141485. };
  141486. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141487. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141488. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141489. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141490. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141491. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141492. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141493. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141494. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141495. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141496. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141497. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141498. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141499. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141500. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141501. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141502. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141503. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141504. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141505. 14,
  141506. };
  141507. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141508. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141509. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141510. };
  141511. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141512. 15, 13, 11, 9, 7, 5, 3, 1,
  141513. 0, 2, 4, 6, 8, 10, 12, 14,
  141514. 16,
  141515. };
  141516. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141517. _vq_quantthresh__44cn1_sm_p5_0,
  141518. _vq_quantmap__44cn1_sm_p5_0,
  141519. 17,
  141520. 17
  141521. };
  141522. static static_codebook _44cn1_sm_p5_0 = {
  141523. 2, 289,
  141524. _vq_lengthlist__44cn1_sm_p5_0,
  141525. 1, -529530880, 1611661312, 5, 0,
  141526. _vq_quantlist__44cn1_sm_p5_0,
  141527. NULL,
  141528. &_vq_auxt__44cn1_sm_p5_0,
  141529. NULL,
  141530. 0
  141531. };
  141532. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141533. 1,
  141534. 0,
  141535. 2,
  141536. };
  141537. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141538. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141539. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141540. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141541. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141542. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141543. 10,
  141544. };
  141545. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141546. -5.5, 5.5,
  141547. };
  141548. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141549. 1, 0, 2,
  141550. };
  141551. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141552. _vq_quantthresh__44cn1_sm_p6_0,
  141553. _vq_quantmap__44cn1_sm_p6_0,
  141554. 3,
  141555. 3
  141556. };
  141557. static static_codebook _44cn1_sm_p6_0 = {
  141558. 4, 81,
  141559. _vq_lengthlist__44cn1_sm_p6_0,
  141560. 1, -529137664, 1618345984, 2, 0,
  141561. _vq_quantlist__44cn1_sm_p6_0,
  141562. NULL,
  141563. &_vq_auxt__44cn1_sm_p6_0,
  141564. NULL,
  141565. 0
  141566. };
  141567. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141568. 5,
  141569. 4,
  141570. 6,
  141571. 3,
  141572. 7,
  141573. 2,
  141574. 8,
  141575. 1,
  141576. 9,
  141577. 0,
  141578. 10,
  141579. };
  141580. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141581. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141582. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141583. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141584. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141585. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141586. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141587. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141588. 10,10,10, 8, 9, 8, 8, 9, 8,
  141589. };
  141590. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141591. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141592. 3.5, 4.5,
  141593. };
  141594. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141595. 9, 7, 5, 3, 1, 0, 2, 4,
  141596. 6, 8, 10,
  141597. };
  141598. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141599. _vq_quantthresh__44cn1_sm_p6_1,
  141600. _vq_quantmap__44cn1_sm_p6_1,
  141601. 11,
  141602. 11
  141603. };
  141604. static static_codebook _44cn1_sm_p6_1 = {
  141605. 2, 121,
  141606. _vq_lengthlist__44cn1_sm_p6_1,
  141607. 1, -531365888, 1611661312, 4, 0,
  141608. _vq_quantlist__44cn1_sm_p6_1,
  141609. NULL,
  141610. &_vq_auxt__44cn1_sm_p6_1,
  141611. NULL,
  141612. 0
  141613. };
  141614. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141615. 6,
  141616. 5,
  141617. 7,
  141618. 4,
  141619. 8,
  141620. 3,
  141621. 9,
  141622. 2,
  141623. 10,
  141624. 1,
  141625. 11,
  141626. 0,
  141627. 12,
  141628. };
  141629. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141630. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141631. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141632. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141633. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141634. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141635. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141636. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141637. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141638. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141639. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141640. 0,13,12,12,12,13,13,13,14,
  141641. };
  141642. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141643. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141644. 12.5, 17.5, 22.5, 27.5,
  141645. };
  141646. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141647. 11, 9, 7, 5, 3, 1, 0, 2,
  141648. 4, 6, 8, 10, 12,
  141649. };
  141650. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141651. _vq_quantthresh__44cn1_sm_p7_0,
  141652. _vq_quantmap__44cn1_sm_p7_0,
  141653. 13,
  141654. 13
  141655. };
  141656. static static_codebook _44cn1_sm_p7_0 = {
  141657. 2, 169,
  141658. _vq_lengthlist__44cn1_sm_p7_0,
  141659. 1, -526516224, 1616117760, 4, 0,
  141660. _vq_quantlist__44cn1_sm_p7_0,
  141661. NULL,
  141662. &_vq_auxt__44cn1_sm_p7_0,
  141663. NULL,
  141664. 0
  141665. };
  141666. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141667. 2,
  141668. 1,
  141669. 3,
  141670. 0,
  141671. 4,
  141672. };
  141673. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141674. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141675. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141676. };
  141677. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141678. -1.5, -0.5, 0.5, 1.5,
  141679. };
  141680. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141681. 3, 1, 0, 2, 4,
  141682. };
  141683. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141684. _vq_quantthresh__44cn1_sm_p7_1,
  141685. _vq_quantmap__44cn1_sm_p7_1,
  141686. 5,
  141687. 5
  141688. };
  141689. static static_codebook _44cn1_sm_p7_1 = {
  141690. 2, 25,
  141691. _vq_lengthlist__44cn1_sm_p7_1,
  141692. 1, -533725184, 1611661312, 3, 0,
  141693. _vq_quantlist__44cn1_sm_p7_1,
  141694. NULL,
  141695. &_vq_auxt__44cn1_sm_p7_1,
  141696. NULL,
  141697. 0
  141698. };
  141699. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141700. 4,
  141701. 3,
  141702. 5,
  141703. 2,
  141704. 6,
  141705. 1,
  141706. 7,
  141707. 0,
  141708. 8,
  141709. };
  141710. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141711. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141712. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141713. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141714. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141715. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141716. 14,
  141717. };
  141718. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141719. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141720. };
  141721. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141722. 7, 5, 3, 1, 0, 2, 4, 6,
  141723. 8,
  141724. };
  141725. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141726. _vq_quantthresh__44cn1_sm_p8_0,
  141727. _vq_quantmap__44cn1_sm_p8_0,
  141728. 9,
  141729. 9
  141730. };
  141731. static static_codebook _44cn1_sm_p8_0 = {
  141732. 2, 81,
  141733. _vq_lengthlist__44cn1_sm_p8_0,
  141734. 1, -516186112, 1627103232, 4, 0,
  141735. _vq_quantlist__44cn1_sm_p8_0,
  141736. NULL,
  141737. &_vq_auxt__44cn1_sm_p8_0,
  141738. NULL,
  141739. 0
  141740. };
  141741. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141742. 6,
  141743. 5,
  141744. 7,
  141745. 4,
  141746. 8,
  141747. 3,
  141748. 9,
  141749. 2,
  141750. 10,
  141751. 1,
  141752. 11,
  141753. 0,
  141754. 12,
  141755. };
  141756. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141757. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141758. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141759. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141760. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141761. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141762. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141763. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141764. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141765. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141766. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141767. 17,12,12,11,10,13,11,13,13,
  141768. };
  141769. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141770. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141771. 42.5, 59.5, 76.5, 93.5,
  141772. };
  141773. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141774. 11, 9, 7, 5, 3, 1, 0, 2,
  141775. 4, 6, 8, 10, 12,
  141776. };
  141777. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141778. _vq_quantthresh__44cn1_sm_p8_1,
  141779. _vq_quantmap__44cn1_sm_p8_1,
  141780. 13,
  141781. 13
  141782. };
  141783. static static_codebook _44cn1_sm_p8_1 = {
  141784. 2, 169,
  141785. _vq_lengthlist__44cn1_sm_p8_1,
  141786. 1, -522616832, 1620115456, 4, 0,
  141787. _vq_quantlist__44cn1_sm_p8_1,
  141788. NULL,
  141789. &_vq_auxt__44cn1_sm_p8_1,
  141790. NULL,
  141791. 0
  141792. };
  141793. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141794. 8,
  141795. 7,
  141796. 9,
  141797. 6,
  141798. 10,
  141799. 5,
  141800. 11,
  141801. 4,
  141802. 12,
  141803. 3,
  141804. 13,
  141805. 2,
  141806. 14,
  141807. 1,
  141808. 15,
  141809. 0,
  141810. 16,
  141811. };
  141812. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141813. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141814. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141815. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141816. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141817. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141818. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141819. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141820. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141821. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141822. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141823. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141824. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141825. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141826. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141827. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141828. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141829. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141830. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141831. 9,
  141832. };
  141833. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141834. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141835. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141836. };
  141837. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141838. 15, 13, 11, 9, 7, 5, 3, 1,
  141839. 0, 2, 4, 6, 8, 10, 12, 14,
  141840. 16,
  141841. };
  141842. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141843. _vq_quantthresh__44cn1_sm_p8_2,
  141844. _vq_quantmap__44cn1_sm_p8_2,
  141845. 17,
  141846. 17
  141847. };
  141848. static static_codebook _44cn1_sm_p8_2 = {
  141849. 2, 289,
  141850. _vq_lengthlist__44cn1_sm_p8_2,
  141851. 1, -529530880, 1611661312, 5, 0,
  141852. _vq_quantlist__44cn1_sm_p8_2,
  141853. NULL,
  141854. &_vq_auxt__44cn1_sm_p8_2,
  141855. NULL,
  141856. 0
  141857. };
  141858. static long _huff_lengthlist__44cn1_sm_short[] = {
  141859. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141860. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141861. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141862. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141863. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141864. 9,
  141865. };
  141866. static static_codebook _huff_book__44cn1_sm_short = {
  141867. 2, 81,
  141868. _huff_lengthlist__44cn1_sm_short,
  141869. 0, 0, 0, 0, 0,
  141870. NULL,
  141871. NULL,
  141872. NULL,
  141873. NULL,
  141874. 0
  141875. };
  141876. /*** End of inlined file: res_books_stereo.h ***/
  141877. /***** residue backends *********************************************/
  141878. static vorbis_info_residue0 _residue_44_low={
  141879. 0,-1, -1, 9,-1,
  141880. /* 0 1 2 3 4 5 6 7 */
  141881. {0},
  141882. {-1},
  141883. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141884. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141885. };
  141886. static vorbis_info_residue0 _residue_44_mid={
  141887. 0,-1, -1, 10,-1,
  141888. /* 0 1 2 3 4 5 6 7 8 */
  141889. {0},
  141890. {-1},
  141891. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141892. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141893. };
  141894. static vorbis_info_residue0 _residue_44_high={
  141895. 0,-1, -1, 10,-1,
  141896. /* 0 1 2 3 4 5 6 7 8 */
  141897. {0},
  141898. {-1},
  141899. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141900. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141901. };
  141902. static static_bookblock _resbook_44s_n1={
  141903. {
  141904. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141905. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141906. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141907. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141908. }
  141909. };
  141910. static static_bookblock _resbook_44sm_n1={
  141911. {
  141912. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141913. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141914. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141915. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141916. }
  141917. };
  141918. static static_bookblock _resbook_44s_0={
  141919. {
  141920. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141921. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141922. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141923. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141924. }
  141925. };
  141926. static static_bookblock _resbook_44sm_0={
  141927. {
  141928. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141929. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141930. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141931. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141932. }
  141933. };
  141934. static static_bookblock _resbook_44s_1={
  141935. {
  141936. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141937. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141938. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141939. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141940. }
  141941. };
  141942. static static_bookblock _resbook_44sm_1={
  141943. {
  141944. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141945. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141946. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141947. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141948. }
  141949. };
  141950. static static_bookblock _resbook_44s_2={
  141951. {
  141952. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141953. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141954. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141955. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141956. }
  141957. };
  141958. static static_bookblock _resbook_44s_3={
  141959. {
  141960. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141961. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141962. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141963. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141964. }
  141965. };
  141966. static static_bookblock _resbook_44s_4={
  141967. {
  141968. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141969. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141970. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141971. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141972. }
  141973. };
  141974. static static_bookblock _resbook_44s_5={
  141975. {
  141976. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141977. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141978. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141979. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141980. }
  141981. };
  141982. static static_bookblock _resbook_44s_6={
  141983. {
  141984. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141985. {0,0,&_44c6_s_p4_0},
  141986. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141987. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141988. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141989. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141990. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141991. }
  141992. };
  141993. static static_bookblock _resbook_44s_7={
  141994. {
  141995. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141996. {0,0,&_44c7_s_p4_0},
  141997. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141998. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141999. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142000. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142001. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142002. }
  142003. };
  142004. static static_bookblock _resbook_44s_8={
  142005. {
  142006. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142007. {0,0,&_44c8_s_p4_0},
  142008. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142009. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142010. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142011. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142012. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142013. }
  142014. };
  142015. static static_bookblock _resbook_44s_9={
  142016. {
  142017. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142018. {0,0,&_44c9_s_p4_0},
  142019. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142020. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142021. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142022. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142023. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142024. }
  142025. };
  142026. static vorbis_residue_template _res_44s_n1[]={
  142027. {2,0, &_residue_44_low,
  142028. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142029. &_resbook_44s_n1,&_resbook_44sm_n1},
  142030. {2,0, &_residue_44_low,
  142031. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142032. &_resbook_44s_n1,&_resbook_44sm_n1}
  142033. };
  142034. static vorbis_residue_template _res_44s_0[]={
  142035. {2,0, &_residue_44_low,
  142036. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142037. &_resbook_44s_0,&_resbook_44sm_0},
  142038. {2,0, &_residue_44_low,
  142039. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142040. &_resbook_44s_0,&_resbook_44sm_0}
  142041. };
  142042. static vorbis_residue_template _res_44s_1[]={
  142043. {2,0, &_residue_44_low,
  142044. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142045. &_resbook_44s_1,&_resbook_44sm_1},
  142046. {2,0, &_residue_44_low,
  142047. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142048. &_resbook_44s_1,&_resbook_44sm_1}
  142049. };
  142050. static vorbis_residue_template _res_44s_2[]={
  142051. {2,0, &_residue_44_mid,
  142052. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142053. &_resbook_44s_2,&_resbook_44s_2},
  142054. {2,0, &_residue_44_mid,
  142055. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142056. &_resbook_44s_2,&_resbook_44s_2}
  142057. };
  142058. static vorbis_residue_template _res_44s_3[]={
  142059. {2,0, &_residue_44_mid,
  142060. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142061. &_resbook_44s_3,&_resbook_44s_3},
  142062. {2,0, &_residue_44_mid,
  142063. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142064. &_resbook_44s_3,&_resbook_44s_3}
  142065. };
  142066. static vorbis_residue_template _res_44s_4[]={
  142067. {2,0, &_residue_44_mid,
  142068. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142069. &_resbook_44s_4,&_resbook_44s_4},
  142070. {2,0, &_residue_44_mid,
  142071. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142072. &_resbook_44s_4,&_resbook_44s_4}
  142073. };
  142074. static vorbis_residue_template _res_44s_5[]={
  142075. {2,0, &_residue_44_mid,
  142076. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142077. &_resbook_44s_5,&_resbook_44s_5},
  142078. {2,0, &_residue_44_mid,
  142079. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142080. &_resbook_44s_5,&_resbook_44s_5}
  142081. };
  142082. static vorbis_residue_template _res_44s_6[]={
  142083. {2,0, &_residue_44_high,
  142084. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142085. &_resbook_44s_6,&_resbook_44s_6},
  142086. {2,0, &_residue_44_high,
  142087. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142088. &_resbook_44s_6,&_resbook_44s_6}
  142089. };
  142090. static vorbis_residue_template _res_44s_7[]={
  142091. {2,0, &_residue_44_high,
  142092. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142093. &_resbook_44s_7,&_resbook_44s_7},
  142094. {2,0, &_residue_44_high,
  142095. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142096. &_resbook_44s_7,&_resbook_44s_7}
  142097. };
  142098. static vorbis_residue_template _res_44s_8[]={
  142099. {2,0, &_residue_44_high,
  142100. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142101. &_resbook_44s_8,&_resbook_44s_8},
  142102. {2,0, &_residue_44_high,
  142103. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142104. &_resbook_44s_8,&_resbook_44s_8}
  142105. };
  142106. static vorbis_residue_template _res_44s_9[]={
  142107. {2,0, &_residue_44_high,
  142108. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142109. &_resbook_44s_9,&_resbook_44s_9},
  142110. {2,0, &_residue_44_high,
  142111. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142112. &_resbook_44s_9,&_resbook_44s_9}
  142113. };
  142114. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142115. { _map_nominal, _res_44s_n1 }, /* -1 */
  142116. { _map_nominal, _res_44s_0 }, /* 0 */
  142117. { _map_nominal, _res_44s_1 }, /* 1 */
  142118. { _map_nominal, _res_44s_2 }, /* 2 */
  142119. { _map_nominal, _res_44s_3 }, /* 3 */
  142120. { _map_nominal, _res_44s_4 }, /* 4 */
  142121. { _map_nominal, _res_44s_5 }, /* 5 */
  142122. { _map_nominal, _res_44s_6 }, /* 6 */
  142123. { _map_nominal, _res_44s_7 }, /* 7 */
  142124. { _map_nominal, _res_44s_8 }, /* 8 */
  142125. { _map_nominal, _res_44s_9 }, /* 9 */
  142126. };
  142127. /*** End of inlined file: residue_44.h ***/
  142128. /*** Start of inlined file: psych_44.h ***/
  142129. /* preecho trigger settings *****************************************/
  142130. static vorbis_info_psy_global _psy_global_44[5]={
  142131. {8, /* lines per eighth octave */
  142132. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142133. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142134. -6.f,
  142135. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142136. },
  142137. {8, /* lines per eighth octave */
  142138. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142139. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142140. -6.f,
  142141. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142142. },
  142143. {8, /* lines per eighth octave */
  142144. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142145. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142146. -6.f,
  142147. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142148. },
  142149. {8, /* lines per eighth octave */
  142150. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142151. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142152. -6.f,
  142153. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142154. },
  142155. {8, /* lines per eighth octave */
  142156. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142157. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142158. -6.f,
  142159. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142160. },
  142161. };
  142162. /* noise compander lookups * low, mid, high quality ****************/
  142163. static compandblock _psy_compand_44[6]={
  142164. /* sub-mode Z short */
  142165. {{
  142166. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142167. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142168. 16,17,18,19,20,21,22, 23, /* 23dB */
  142169. 24,25,26,27,28,29,30, 31, /* 31dB */
  142170. 32,33,34,35,36,37,38, 39, /* 39dB */
  142171. }},
  142172. /* mode_Z nominal short */
  142173. {{
  142174. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142175. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142176. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142177. 15,16,17,17,17,18,18, 19, /* 31dB */
  142178. 19,19,20,21,22,23,24, 25, /* 39dB */
  142179. }},
  142180. /* mode A short */
  142181. {{
  142182. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142183. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142184. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142185. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142186. 11,12,13,14,15,16,17, 18, /* 39dB */
  142187. }},
  142188. /* sub-mode Z long */
  142189. {{
  142190. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142191. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142192. 16,17,18,19,20,21,22, 23, /* 23dB */
  142193. 24,25,26,27,28,29,30, 31, /* 31dB */
  142194. 32,33,34,35,36,37,38, 39, /* 39dB */
  142195. }},
  142196. /* mode_Z nominal long */
  142197. {{
  142198. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142199. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142200. 13,14,14,14,15,15,15, 15, /* 23dB */
  142201. 16,16,17,17,17,18,18, 19, /* 31dB */
  142202. 19,19,20,21,22,23,24, 25, /* 39dB */
  142203. }},
  142204. /* mode A long */
  142205. {{
  142206. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142207. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142208. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142209. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142210. 11,12,13,14,15,16,17, 18, /* 39dB */
  142211. }}
  142212. };
  142213. /* tonal masking curve level adjustments *************************/
  142214. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142215. /* 63 125 250 500 1 2 4 8 16 */
  142216. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142217. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142218. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142219. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142220. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142221. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142222. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142223. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142224. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142225. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142226. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142227. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142228. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142229. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142230. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142231. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142232. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142233. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142234. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142235. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142236. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142237. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142238. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142239. };
  142240. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142241. /* 63 125 250 500 1 2 4 8 16 */
  142242. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142243. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142244. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142245. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142246. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142247. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142248. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142249. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142250. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142251. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142252. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142253. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142254. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142255. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142256. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142257. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142258. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142259. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142260. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142261. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142262. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142263. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142264. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142265. };
  142266. /* noise bias (transition block) */
  142267. static noise3 _psy_noisebias_trans[12]={
  142268. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142269. /* -1 */
  142270. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142271. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142272. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142273. /* 0
  142274. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142275. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142276. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142277. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142278. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142279. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142280. /* 1
  142281. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142282. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142283. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142284. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142285. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142286. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142287. /* 2
  142288. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142289. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142290. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142291. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142292. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142293. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142294. /* 3
  142295. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142296. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142297. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142298. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142299. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142300. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142301. /* 4
  142302. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142303. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142304. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142305. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142306. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142307. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142308. /* 5
  142309. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142310. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142311. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142312. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142313. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142314. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142315. /* 6
  142316. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142317. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142318. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142319. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142320. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142321. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142322. /* 7
  142323. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142324. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142325. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142326. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142327. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142328. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142329. /* 8
  142330. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142331. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142332. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142333. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142334. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142335. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142336. /* 9
  142337. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142338. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142339. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142340. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142341. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142342. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142343. /* 10 */
  142344. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142345. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142346. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142347. };
  142348. /* noise bias (long block) */
  142349. static noise3 _psy_noisebias_long[12]={
  142350. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142351. /* -1 */
  142352. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142353. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142354. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142355. /* 0 */
  142356. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142357. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142358. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142359. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142360. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142361. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142362. /* 1 */
  142363. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142364. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142365. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142366. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142367. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142368. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142369. /* 2 */
  142370. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142371. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142372. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142373. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142374. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142375. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142376. /* 3 */
  142377. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142378. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142379. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142380. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142381. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142382. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142383. /* 4 */
  142384. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142385. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142386. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142387. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142388. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142389. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142390. /* 5 */
  142391. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142392. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142393. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142394. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142395. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142396. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142397. /* 6 */
  142398. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142399. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142400. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142401. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142402. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142403. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142404. /* 7 */
  142405. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142406. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142407. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142408. /* 8 */
  142409. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142410. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142411. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142412. /* 9 */
  142413. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142414. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142415. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142416. /* 10 */
  142417. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142418. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142419. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142420. };
  142421. /* noise bias (impulse block) */
  142422. static noise3 _psy_noisebias_impulse[12]={
  142423. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142424. /* -1 */
  142425. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142426. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142427. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142428. /* 0 */
  142429. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142430. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142431. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142432. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142433. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142434. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142435. /* 1 */
  142436. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142437. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142438. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142439. /* 2 */
  142440. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142441. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142442. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142443. /* 3 */
  142444. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142445. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142446. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142447. /* 4 */
  142448. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142449. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142450. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142451. /* 5 */
  142452. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142453. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142454. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142455. /* 6
  142456. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142457. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142458. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142459. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142460. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142461. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142462. /* 7 */
  142463. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142464. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142465. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142466. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142467. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142468. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142469. /* 8 */
  142470. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142471. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142472. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142473. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142474. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142475. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142476. /* 9 */
  142477. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142478. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142479. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142480. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142481. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142482. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142483. /* 10 */
  142484. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142485. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142486. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142487. };
  142488. /* noise bias (padding block) */
  142489. static noise3 _psy_noisebias_padding[12]={
  142490. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142491. /* -1 */
  142492. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142493. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142494. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142495. /* 0 */
  142496. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142497. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142498. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142499. /* 1 */
  142500. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142501. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142502. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142503. /* 2 */
  142504. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142505. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142506. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142507. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142508. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142509. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142510. /* 3 */
  142511. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142512. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142513. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142514. /* 4 */
  142515. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142516. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142517. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142518. /* 5 */
  142519. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142520. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142521. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142522. /* 6 */
  142523. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142524. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142525. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142526. /* 7 */
  142527. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142528. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142529. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142530. /* 8 */
  142531. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142532. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142533. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142534. /* 9 */
  142535. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142536. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142537. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142538. /* 10 */
  142539. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142540. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142541. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142542. };
  142543. static noiseguard _psy_noiseguards_44[4]={
  142544. {3,3,15},
  142545. {3,3,15},
  142546. {10,10,100},
  142547. {10,10,100},
  142548. };
  142549. static int _psy_tone_suppress[12]={
  142550. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142551. };
  142552. static int _psy_tone_0dB[12]={
  142553. 90,90,95,95,95,95,105,105,105,105,105,105,
  142554. };
  142555. static int _psy_noise_suppress[12]={
  142556. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142557. };
  142558. static vorbis_info_psy _psy_info_template={
  142559. /* blockflag */
  142560. -1,
  142561. /* ath_adjatt, ath_maxatt */
  142562. -140.,-140.,
  142563. /* tonemask att boost/decay,suppr,curves */
  142564. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142565. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142566. 1, -0.f, .5f, .5f, 0,0,0,
  142567. /* noiseoffset*3, noisecompand, max_curve_dB */
  142568. {{-1},{-1},{-1}},{-1},105.f,
  142569. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142570. 0,0,-1,-1,0.,
  142571. };
  142572. /* ath ****************/
  142573. static int _psy_ath_floater[12]={
  142574. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142575. };
  142576. static int _psy_ath_abs[12]={
  142577. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142578. };
  142579. /* stereo setup. These don't map directly to quality level, there's
  142580. an additional indirection as several of the below may be used in a
  142581. single bitmanaged stream
  142582. ****************/
  142583. /* various stereo possibilities */
  142584. /* stereo mode by base quality level */
  142585. static adj_stereo _psy_stereo_modes_44[12]={
  142586. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142587. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142588. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142589. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142590. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142591. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142592. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142593. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142594. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142595. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142596. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142597. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142598. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142599. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142600. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142601. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142602. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142603. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142604. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142605. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142606. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142607. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142608. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142609. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142610. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142611. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142612. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142613. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142614. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142615. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142616. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142617. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142618. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142619. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142620. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142621. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142622. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142623. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142624. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142625. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142626. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142627. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142628. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142629. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142630. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142631. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142632. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142633. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142634. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142635. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142636. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142637. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142638. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142639. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142640. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142641. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142642. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142643. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142644. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142645. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142646. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142647. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142648. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142649. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142650. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142651. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142652. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142653. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142654. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142655. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142656. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142657. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142658. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142659. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142660. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142661. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142662. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142663. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142664. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142665. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142666. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142667. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142668. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142669. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142670. };
  142671. /* tone master attenuation by base quality mode and bitrate tweak */
  142672. static att3 _psy_tone_masteratt_44[12]={
  142673. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142674. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142675. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142676. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142677. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142678. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142679. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142680. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142681. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142682. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142683. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142684. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142685. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142686. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142687. };
  142688. /* lowpass by mode **************/
  142689. static double _psy_lowpass_44[12]={
  142690. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142691. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142692. };
  142693. /* noise normalization **********/
  142694. static int _noise_start_short_44[11]={
  142695. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142696. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142697. };
  142698. static int _noise_start_long_44[11]={
  142699. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142700. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142701. };
  142702. static int _noise_part_short_44[11]={
  142703. 8,8,8,8,8,8,8,8,8,8,8
  142704. };
  142705. static int _noise_part_long_44[11]={
  142706. 32,32,32,32,32,32,32,32,32,32,32
  142707. };
  142708. static double _noise_thresh_44[11]={
  142709. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142710. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142711. };
  142712. static double _noise_thresh_5only[2]={
  142713. .5,.5,
  142714. };
  142715. /*** End of inlined file: psych_44.h ***/
  142716. static double rate_mapping_44_stereo[12]={
  142717. 22500.,32000.,40000.,48000.,56000.,64000.,
  142718. 80000.,96000.,112000.,128000.,160000.,250001.
  142719. };
  142720. static double quality_mapping_44[12]={
  142721. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142722. };
  142723. static int blocksize_short_44[11]={
  142724. 512,256,256,256,256,256,256,256,256,256,256
  142725. };
  142726. static int blocksize_long_44[11]={
  142727. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142728. };
  142729. static double _psy_compand_short_mapping[12]={
  142730. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142731. };
  142732. static double _psy_compand_long_mapping[12]={
  142733. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142734. };
  142735. static double _global_mapping_44[12]={
  142736. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142737. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142738. };
  142739. static int _floor_short_mapping_44[11]={
  142740. 1,0,0,2,2,4,5,5,5,5,5
  142741. };
  142742. static int _floor_long_mapping_44[11]={
  142743. 8,7,7,7,7,7,7,7,7,7,7
  142744. };
  142745. ve_setup_data_template ve_setup_44_stereo={
  142746. 11,
  142747. rate_mapping_44_stereo,
  142748. quality_mapping_44,
  142749. 2,
  142750. 40000,
  142751. 50000,
  142752. blocksize_short_44,
  142753. blocksize_long_44,
  142754. _psy_tone_masteratt_44,
  142755. _psy_tone_0dB,
  142756. _psy_tone_suppress,
  142757. _vp_tonemask_adj_otherblock,
  142758. _vp_tonemask_adj_longblock,
  142759. _vp_tonemask_adj_otherblock,
  142760. _psy_noiseguards_44,
  142761. _psy_noisebias_impulse,
  142762. _psy_noisebias_padding,
  142763. _psy_noisebias_trans,
  142764. _psy_noisebias_long,
  142765. _psy_noise_suppress,
  142766. _psy_compand_44,
  142767. _psy_compand_short_mapping,
  142768. _psy_compand_long_mapping,
  142769. {_noise_start_short_44,_noise_start_long_44},
  142770. {_noise_part_short_44,_noise_part_long_44},
  142771. _noise_thresh_44,
  142772. _psy_ath_floater,
  142773. _psy_ath_abs,
  142774. _psy_lowpass_44,
  142775. _psy_global_44,
  142776. _global_mapping_44,
  142777. _psy_stereo_modes_44,
  142778. _floor_books,
  142779. _floor,
  142780. _floor_short_mapping_44,
  142781. _floor_long_mapping_44,
  142782. _mapres_template_44_stereo
  142783. };
  142784. /*** End of inlined file: setup_44.h ***/
  142785. /*** Start of inlined file: setup_44u.h ***/
  142786. /*** Start of inlined file: residue_44u.h ***/
  142787. /*** Start of inlined file: res_books_uncoupled.h ***/
  142788. static long _vq_quantlist__16u0__p1_0[] = {
  142789. 1,
  142790. 0,
  142791. 2,
  142792. };
  142793. static long _vq_lengthlist__16u0__p1_0[] = {
  142794. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142795. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142796. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142797. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142798. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142799. 12,
  142800. };
  142801. static float _vq_quantthresh__16u0__p1_0[] = {
  142802. -0.5, 0.5,
  142803. };
  142804. static long _vq_quantmap__16u0__p1_0[] = {
  142805. 1, 0, 2,
  142806. };
  142807. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142808. _vq_quantthresh__16u0__p1_0,
  142809. _vq_quantmap__16u0__p1_0,
  142810. 3,
  142811. 3
  142812. };
  142813. static static_codebook _16u0__p1_0 = {
  142814. 4, 81,
  142815. _vq_lengthlist__16u0__p1_0,
  142816. 1, -535822336, 1611661312, 2, 0,
  142817. _vq_quantlist__16u0__p1_0,
  142818. NULL,
  142819. &_vq_auxt__16u0__p1_0,
  142820. NULL,
  142821. 0
  142822. };
  142823. static long _vq_quantlist__16u0__p2_0[] = {
  142824. 1,
  142825. 0,
  142826. 2,
  142827. };
  142828. static long _vq_lengthlist__16u0__p2_0[] = {
  142829. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142830. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142831. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142832. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142833. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142834. 8,
  142835. };
  142836. static float _vq_quantthresh__16u0__p2_0[] = {
  142837. -0.5, 0.5,
  142838. };
  142839. static long _vq_quantmap__16u0__p2_0[] = {
  142840. 1, 0, 2,
  142841. };
  142842. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142843. _vq_quantthresh__16u0__p2_0,
  142844. _vq_quantmap__16u0__p2_0,
  142845. 3,
  142846. 3
  142847. };
  142848. static static_codebook _16u0__p2_0 = {
  142849. 4, 81,
  142850. _vq_lengthlist__16u0__p2_0,
  142851. 1, -535822336, 1611661312, 2, 0,
  142852. _vq_quantlist__16u0__p2_0,
  142853. NULL,
  142854. &_vq_auxt__16u0__p2_0,
  142855. NULL,
  142856. 0
  142857. };
  142858. static long _vq_quantlist__16u0__p3_0[] = {
  142859. 2,
  142860. 1,
  142861. 3,
  142862. 0,
  142863. 4,
  142864. };
  142865. static long _vq_lengthlist__16u0__p3_0[] = {
  142866. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142867. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142868. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142869. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142870. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142871. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142872. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142873. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142874. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142875. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142876. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142877. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142878. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142879. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142880. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142881. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142882. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142883. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142884. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142885. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142886. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142887. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142888. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142889. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142890. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142891. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142892. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142893. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142894. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142895. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142896. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142897. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142898. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142899. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142900. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142901. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142902. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142903. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142904. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142905. 18,
  142906. };
  142907. static float _vq_quantthresh__16u0__p3_0[] = {
  142908. -1.5, -0.5, 0.5, 1.5,
  142909. };
  142910. static long _vq_quantmap__16u0__p3_0[] = {
  142911. 3, 1, 0, 2, 4,
  142912. };
  142913. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142914. _vq_quantthresh__16u0__p3_0,
  142915. _vq_quantmap__16u0__p3_0,
  142916. 5,
  142917. 5
  142918. };
  142919. static static_codebook _16u0__p3_0 = {
  142920. 4, 625,
  142921. _vq_lengthlist__16u0__p3_0,
  142922. 1, -533725184, 1611661312, 3, 0,
  142923. _vq_quantlist__16u0__p3_0,
  142924. NULL,
  142925. &_vq_auxt__16u0__p3_0,
  142926. NULL,
  142927. 0
  142928. };
  142929. static long _vq_quantlist__16u0__p4_0[] = {
  142930. 2,
  142931. 1,
  142932. 3,
  142933. 0,
  142934. 4,
  142935. };
  142936. static long _vq_lengthlist__16u0__p4_0[] = {
  142937. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142938. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142939. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142940. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142941. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142942. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142943. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142944. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142945. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142946. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142947. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142948. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142949. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142950. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142951. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142952. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142953. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142954. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142955. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142956. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142957. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142958. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142959. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142960. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142961. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142962. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142963. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142964. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142965. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142966. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142967. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142968. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142969. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142970. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142971. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142972. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142973. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142974. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142975. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142976. 11,
  142977. };
  142978. static float _vq_quantthresh__16u0__p4_0[] = {
  142979. -1.5, -0.5, 0.5, 1.5,
  142980. };
  142981. static long _vq_quantmap__16u0__p4_0[] = {
  142982. 3, 1, 0, 2, 4,
  142983. };
  142984. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142985. _vq_quantthresh__16u0__p4_0,
  142986. _vq_quantmap__16u0__p4_0,
  142987. 5,
  142988. 5
  142989. };
  142990. static static_codebook _16u0__p4_0 = {
  142991. 4, 625,
  142992. _vq_lengthlist__16u0__p4_0,
  142993. 1, -533725184, 1611661312, 3, 0,
  142994. _vq_quantlist__16u0__p4_0,
  142995. NULL,
  142996. &_vq_auxt__16u0__p4_0,
  142997. NULL,
  142998. 0
  142999. };
  143000. static long _vq_quantlist__16u0__p5_0[] = {
  143001. 4,
  143002. 3,
  143003. 5,
  143004. 2,
  143005. 6,
  143006. 1,
  143007. 7,
  143008. 0,
  143009. 8,
  143010. };
  143011. static long _vq_lengthlist__16u0__p5_0[] = {
  143012. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143013. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143014. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143015. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143016. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143017. 12,
  143018. };
  143019. static float _vq_quantthresh__16u0__p5_0[] = {
  143020. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143021. };
  143022. static long _vq_quantmap__16u0__p5_0[] = {
  143023. 7, 5, 3, 1, 0, 2, 4, 6,
  143024. 8,
  143025. };
  143026. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143027. _vq_quantthresh__16u0__p5_0,
  143028. _vq_quantmap__16u0__p5_0,
  143029. 9,
  143030. 9
  143031. };
  143032. static static_codebook _16u0__p5_0 = {
  143033. 2, 81,
  143034. _vq_lengthlist__16u0__p5_0,
  143035. 1, -531628032, 1611661312, 4, 0,
  143036. _vq_quantlist__16u0__p5_0,
  143037. NULL,
  143038. &_vq_auxt__16u0__p5_0,
  143039. NULL,
  143040. 0
  143041. };
  143042. static long _vq_quantlist__16u0__p6_0[] = {
  143043. 6,
  143044. 5,
  143045. 7,
  143046. 4,
  143047. 8,
  143048. 3,
  143049. 9,
  143050. 2,
  143051. 10,
  143052. 1,
  143053. 11,
  143054. 0,
  143055. 12,
  143056. };
  143057. static long _vq_lengthlist__16u0__p6_0[] = {
  143058. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143059. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143060. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143061. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143062. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143063. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143064. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143065. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143066. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143067. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143068. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143069. };
  143070. static float _vq_quantthresh__16u0__p6_0[] = {
  143071. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143072. 12.5, 17.5, 22.5, 27.5,
  143073. };
  143074. static long _vq_quantmap__16u0__p6_0[] = {
  143075. 11, 9, 7, 5, 3, 1, 0, 2,
  143076. 4, 6, 8, 10, 12,
  143077. };
  143078. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143079. _vq_quantthresh__16u0__p6_0,
  143080. _vq_quantmap__16u0__p6_0,
  143081. 13,
  143082. 13
  143083. };
  143084. static static_codebook _16u0__p6_0 = {
  143085. 2, 169,
  143086. _vq_lengthlist__16u0__p6_0,
  143087. 1, -526516224, 1616117760, 4, 0,
  143088. _vq_quantlist__16u0__p6_0,
  143089. NULL,
  143090. &_vq_auxt__16u0__p6_0,
  143091. NULL,
  143092. 0
  143093. };
  143094. static long _vq_quantlist__16u0__p6_1[] = {
  143095. 2,
  143096. 1,
  143097. 3,
  143098. 0,
  143099. 4,
  143100. };
  143101. static long _vq_lengthlist__16u0__p6_1[] = {
  143102. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143103. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143104. };
  143105. static float _vq_quantthresh__16u0__p6_1[] = {
  143106. -1.5, -0.5, 0.5, 1.5,
  143107. };
  143108. static long _vq_quantmap__16u0__p6_1[] = {
  143109. 3, 1, 0, 2, 4,
  143110. };
  143111. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143112. _vq_quantthresh__16u0__p6_1,
  143113. _vq_quantmap__16u0__p6_1,
  143114. 5,
  143115. 5
  143116. };
  143117. static static_codebook _16u0__p6_1 = {
  143118. 2, 25,
  143119. _vq_lengthlist__16u0__p6_1,
  143120. 1, -533725184, 1611661312, 3, 0,
  143121. _vq_quantlist__16u0__p6_1,
  143122. NULL,
  143123. &_vq_auxt__16u0__p6_1,
  143124. NULL,
  143125. 0
  143126. };
  143127. static long _vq_quantlist__16u0__p7_0[] = {
  143128. 1,
  143129. 0,
  143130. 2,
  143131. };
  143132. static long _vq_lengthlist__16u0__p7_0[] = {
  143133. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143134. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143135. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143136. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143137. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143138. 7,
  143139. };
  143140. static float _vq_quantthresh__16u0__p7_0[] = {
  143141. -157.5, 157.5,
  143142. };
  143143. static long _vq_quantmap__16u0__p7_0[] = {
  143144. 1, 0, 2,
  143145. };
  143146. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143147. _vq_quantthresh__16u0__p7_0,
  143148. _vq_quantmap__16u0__p7_0,
  143149. 3,
  143150. 3
  143151. };
  143152. static static_codebook _16u0__p7_0 = {
  143153. 4, 81,
  143154. _vq_lengthlist__16u0__p7_0,
  143155. 1, -518803456, 1628680192, 2, 0,
  143156. _vq_quantlist__16u0__p7_0,
  143157. NULL,
  143158. &_vq_auxt__16u0__p7_0,
  143159. NULL,
  143160. 0
  143161. };
  143162. static long _vq_quantlist__16u0__p7_1[] = {
  143163. 7,
  143164. 6,
  143165. 8,
  143166. 5,
  143167. 9,
  143168. 4,
  143169. 10,
  143170. 3,
  143171. 11,
  143172. 2,
  143173. 12,
  143174. 1,
  143175. 13,
  143176. 0,
  143177. 14,
  143178. };
  143179. static long _vq_lengthlist__16u0__p7_1[] = {
  143180. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143181. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143182. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143183. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143184. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143185. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143186. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143187. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143188. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143189. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143190. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143191. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143192. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143193. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143194. 10,
  143195. };
  143196. static float _vq_quantthresh__16u0__p7_1[] = {
  143197. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143198. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143199. };
  143200. static long _vq_quantmap__16u0__p7_1[] = {
  143201. 13, 11, 9, 7, 5, 3, 1, 0,
  143202. 2, 4, 6, 8, 10, 12, 14,
  143203. };
  143204. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143205. _vq_quantthresh__16u0__p7_1,
  143206. _vq_quantmap__16u0__p7_1,
  143207. 15,
  143208. 15
  143209. };
  143210. static static_codebook _16u0__p7_1 = {
  143211. 2, 225,
  143212. _vq_lengthlist__16u0__p7_1,
  143213. 1, -520986624, 1620377600, 4, 0,
  143214. _vq_quantlist__16u0__p7_1,
  143215. NULL,
  143216. &_vq_auxt__16u0__p7_1,
  143217. NULL,
  143218. 0
  143219. };
  143220. static long _vq_quantlist__16u0__p7_2[] = {
  143221. 10,
  143222. 9,
  143223. 11,
  143224. 8,
  143225. 12,
  143226. 7,
  143227. 13,
  143228. 6,
  143229. 14,
  143230. 5,
  143231. 15,
  143232. 4,
  143233. 16,
  143234. 3,
  143235. 17,
  143236. 2,
  143237. 18,
  143238. 1,
  143239. 19,
  143240. 0,
  143241. 20,
  143242. };
  143243. static long _vq_lengthlist__16u0__p7_2[] = {
  143244. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143245. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143246. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143247. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143248. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143249. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143250. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143251. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143252. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143253. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143254. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143255. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143256. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143257. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143258. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143259. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143260. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143261. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143262. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143263. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143264. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143265. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143266. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143267. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143268. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143269. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143270. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143271. 10,10,12,11,10,11,11,11,10,
  143272. };
  143273. static float _vq_quantthresh__16u0__p7_2[] = {
  143274. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143275. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143276. 6.5, 7.5, 8.5, 9.5,
  143277. };
  143278. static long _vq_quantmap__16u0__p7_2[] = {
  143279. 19, 17, 15, 13, 11, 9, 7, 5,
  143280. 3, 1, 0, 2, 4, 6, 8, 10,
  143281. 12, 14, 16, 18, 20,
  143282. };
  143283. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143284. _vq_quantthresh__16u0__p7_2,
  143285. _vq_quantmap__16u0__p7_2,
  143286. 21,
  143287. 21
  143288. };
  143289. static static_codebook _16u0__p7_2 = {
  143290. 2, 441,
  143291. _vq_lengthlist__16u0__p7_2,
  143292. 1, -529268736, 1611661312, 5, 0,
  143293. _vq_quantlist__16u0__p7_2,
  143294. NULL,
  143295. &_vq_auxt__16u0__p7_2,
  143296. NULL,
  143297. 0
  143298. };
  143299. static long _huff_lengthlist__16u0__single[] = {
  143300. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143301. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143302. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143303. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143304. };
  143305. static static_codebook _huff_book__16u0__single = {
  143306. 2, 64,
  143307. _huff_lengthlist__16u0__single,
  143308. 0, 0, 0, 0, 0,
  143309. NULL,
  143310. NULL,
  143311. NULL,
  143312. NULL,
  143313. 0
  143314. };
  143315. static long _huff_lengthlist__16u1__long[] = {
  143316. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143317. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143318. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143319. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143320. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143321. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143322. 16,13,16,18,
  143323. };
  143324. static static_codebook _huff_book__16u1__long = {
  143325. 2, 100,
  143326. _huff_lengthlist__16u1__long,
  143327. 0, 0, 0, 0, 0,
  143328. NULL,
  143329. NULL,
  143330. NULL,
  143331. NULL,
  143332. 0
  143333. };
  143334. static long _vq_quantlist__16u1__p1_0[] = {
  143335. 1,
  143336. 0,
  143337. 2,
  143338. };
  143339. static long _vq_lengthlist__16u1__p1_0[] = {
  143340. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143341. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143342. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143343. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143344. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143345. 11,
  143346. };
  143347. static float _vq_quantthresh__16u1__p1_0[] = {
  143348. -0.5, 0.5,
  143349. };
  143350. static long _vq_quantmap__16u1__p1_0[] = {
  143351. 1, 0, 2,
  143352. };
  143353. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143354. _vq_quantthresh__16u1__p1_0,
  143355. _vq_quantmap__16u1__p1_0,
  143356. 3,
  143357. 3
  143358. };
  143359. static static_codebook _16u1__p1_0 = {
  143360. 4, 81,
  143361. _vq_lengthlist__16u1__p1_0,
  143362. 1, -535822336, 1611661312, 2, 0,
  143363. _vq_quantlist__16u1__p1_0,
  143364. NULL,
  143365. &_vq_auxt__16u1__p1_0,
  143366. NULL,
  143367. 0
  143368. };
  143369. static long _vq_quantlist__16u1__p2_0[] = {
  143370. 1,
  143371. 0,
  143372. 2,
  143373. };
  143374. static long _vq_lengthlist__16u1__p2_0[] = {
  143375. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143376. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143377. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143378. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143379. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143380. 8,
  143381. };
  143382. static float _vq_quantthresh__16u1__p2_0[] = {
  143383. -0.5, 0.5,
  143384. };
  143385. static long _vq_quantmap__16u1__p2_0[] = {
  143386. 1, 0, 2,
  143387. };
  143388. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143389. _vq_quantthresh__16u1__p2_0,
  143390. _vq_quantmap__16u1__p2_0,
  143391. 3,
  143392. 3
  143393. };
  143394. static static_codebook _16u1__p2_0 = {
  143395. 4, 81,
  143396. _vq_lengthlist__16u1__p2_0,
  143397. 1, -535822336, 1611661312, 2, 0,
  143398. _vq_quantlist__16u1__p2_0,
  143399. NULL,
  143400. &_vq_auxt__16u1__p2_0,
  143401. NULL,
  143402. 0
  143403. };
  143404. static long _vq_quantlist__16u1__p3_0[] = {
  143405. 2,
  143406. 1,
  143407. 3,
  143408. 0,
  143409. 4,
  143410. };
  143411. static long _vq_lengthlist__16u1__p3_0[] = {
  143412. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143413. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143414. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143415. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143416. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143417. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143418. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143419. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143420. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143421. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143422. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143423. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143424. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143425. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143426. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143427. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143428. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143429. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143430. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143431. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143432. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143433. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143434. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143435. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143436. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143437. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143438. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143439. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143440. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143441. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143442. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143443. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143444. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143445. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143446. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143447. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143448. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143449. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143450. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143451. 16,
  143452. };
  143453. static float _vq_quantthresh__16u1__p3_0[] = {
  143454. -1.5, -0.5, 0.5, 1.5,
  143455. };
  143456. static long _vq_quantmap__16u1__p3_0[] = {
  143457. 3, 1, 0, 2, 4,
  143458. };
  143459. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143460. _vq_quantthresh__16u1__p3_0,
  143461. _vq_quantmap__16u1__p3_0,
  143462. 5,
  143463. 5
  143464. };
  143465. static static_codebook _16u1__p3_0 = {
  143466. 4, 625,
  143467. _vq_lengthlist__16u1__p3_0,
  143468. 1, -533725184, 1611661312, 3, 0,
  143469. _vq_quantlist__16u1__p3_0,
  143470. NULL,
  143471. &_vq_auxt__16u1__p3_0,
  143472. NULL,
  143473. 0
  143474. };
  143475. static long _vq_quantlist__16u1__p4_0[] = {
  143476. 2,
  143477. 1,
  143478. 3,
  143479. 0,
  143480. 4,
  143481. };
  143482. static long _vq_lengthlist__16u1__p4_0[] = {
  143483. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143484. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143485. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143486. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143487. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143488. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143489. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143490. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143491. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143492. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143493. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143494. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143495. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143496. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143497. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143498. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143499. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143500. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143501. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143502. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143503. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143504. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143505. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143506. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143507. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143508. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143509. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143510. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143511. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143512. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143513. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143514. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143515. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143516. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143517. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143518. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143519. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143520. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143521. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143522. 11,
  143523. };
  143524. static float _vq_quantthresh__16u1__p4_0[] = {
  143525. -1.5, -0.5, 0.5, 1.5,
  143526. };
  143527. static long _vq_quantmap__16u1__p4_0[] = {
  143528. 3, 1, 0, 2, 4,
  143529. };
  143530. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143531. _vq_quantthresh__16u1__p4_0,
  143532. _vq_quantmap__16u1__p4_0,
  143533. 5,
  143534. 5
  143535. };
  143536. static static_codebook _16u1__p4_0 = {
  143537. 4, 625,
  143538. _vq_lengthlist__16u1__p4_0,
  143539. 1, -533725184, 1611661312, 3, 0,
  143540. _vq_quantlist__16u1__p4_0,
  143541. NULL,
  143542. &_vq_auxt__16u1__p4_0,
  143543. NULL,
  143544. 0
  143545. };
  143546. static long _vq_quantlist__16u1__p5_0[] = {
  143547. 4,
  143548. 3,
  143549. 5,
  143550. 2,
  143551. 6,
  143552. 1,
  143553. 7,
  143554. 0,
  143555. 8,
  143556. };
  143557. static long _vq_lengthlist__16u1__p5_0[] = {
  143558. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143559. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143560. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143561. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143562. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143563. 13,
  143564. };
  143565. static float _vq_quantthresh__16u1__p5_0[] = {
  143566. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143567. };
  143568. static long _vq_quantmap__16u1__p5_0[] = {
  143569. 7, 5, 3, 1, 0, 2, 4, 6,
  143570. 8,
  143571. };
  143572. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143573. _vq_quantthresh__16u1__p5_0,
  143574. _vq_quantmap__16u1__p5_0,
  143575. 9,
  143576. 9
  143577. };
  143578. static static_codebook _16u1__p5_0 = {
  143579. 2, 81,
  143580. _vq_lengthlist__16u1__p5_0,
  143581. 1, -531628032, 1611661312, 4, 0,
  143582. _vq_quantlist__16u1__p5_0,
  143583. NULL,
  143584. &_vq_auxt__16u1__p5_0,
  143585. NULL,
  143586. 0
  143587. };
  143588. static long _vq_quantlist__16u1__p6_0[] = {
  143589. 4,
  143590. 3,
  143591. 5,
  143592. 2,
  143593. 6,
  143594. 1,
  143595. 7,
  143596. 0,
  143597. 8,
  143598. };
  143599. static long _vq_lengthlist__16u1__p6_0[] = {
  143600. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143601. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143602. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143603. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143604. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143605. 11,
  143606. };
  143607. static float _vq_quantthresh__16u1__p6_0[] = {
  143608. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143609. };
  143610. static long _vq_quantmap__16u1__p6_0[] = {
  143611. 7, 5, 3, 1, 0, 2, 4, 6,
  143612. 8,
  143613. };
  143614. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143615. _vq_quantthresh__16u1__p6_0,
  143616. _vq_quantmap__16u1__p6_0,
  143617. 9,
  143618. 9
  143619. };
  143620. static static_codebook _16u1__p6_0 = {
  143621. 2, 81,
  143622. _vq_lengthlist__16u1__p6_0,
  143623. 1, -531628032, 1611661312, 4, 0,
  143624. _vq_quantlist__16u1__p6_0,
  143625. NULL,
  143626. &_vq_auxt__16u1__p6_0,
  143627. NULL,
  143628. 0
  143629. };
  143630. static long _vq_quantlist__16u1__p7_0[] = {
  143631. 1,
  143632. 0,
  143633. 2,
  143634. };
  143635. static long _vq_lengthlist__16u1__p7_0[] = {
  143636. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143637. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143638. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143639. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143640. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143641. 13,
  143642. };
  143643. static float _vq_quantthresh__16u1__p7_0[] = {
  143644. -5.5, 5.5,
  143645. };
  143646. static long _vq_quantmap__16u1__p7_0[] = {
  143647. 1, 0, 2,
  143648. };
  143649. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143650. _vq_quantthresh__16u1__p7_0,
  143651. _vq_quantmap__16u1__p7_0,
  143652. 3,
  143653. 3
  143654. };
  143655. static static_codebook _16u1__p7_0 = {
  143656. 4, 81,
  143657. _vq_lengthlist__16u1__p7_0,
  143658. 1, -529137664, 1618345984, 2, 0,
  143659. _vq_quantlist__16u1__p7_0,
  143660. NULL,
  143661. &_vq_auxt__16u1__p7_0,
  143662. NULL,
  143663. 0
  143664. };
  143665. static long _vq_quantlist__16u1__p7_1[] = {
  143666. 5,
  143667. 4,
  143668. 6,
  143669. 3,
  143670. 7,
  143671. 2,
  143672. 8,
  143673. 1,
  143674. 9,
  143675. 0,
  143676. 10,
  143677. };
  143678. static long _vq_lengthlist__16u1__p7_1[] = {
  143679. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143680. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143681. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143682. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143683. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143684. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143685. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143686. 8, 9, 9,10,10,10,10,10,10,
  143687. };
  143688. static float _vq_quantthresh__16u1__p7_1[] = {
  143689. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143690. 3.5, 4.5,
  143691. };
  143692. static long _vq_quantmap__16u1__p7_1[] = {
  143693. 9, 7, 5, 3, 1, 0, 2, 4,
  143694. 6, 8, 10,
  143695. };
  143696. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143697. _vq_quantthresh__16u1__p7_1,
  143698. _vq_quantmap__16u1__p7_1,
  143699. 11,
  143700. 11
  143701. };
  143702. static static_codebook _16u1__p7_1 = {
  143703. 2, 121,
  143704. _vq_lengthlist__16u1__p7_1,
  143705. 1, -531365888, 1611661312, 4, 0,
  143706. _vq_quantlist__16u1__p7_1,
  143707. NULL,
  143708. &_vq_auxt__16u1__p7_1,
  143709. NULL,
  143710. 0
  143711. };
  143712. static long _vq_quantlist__16u1__p8_0[] = {
  143713. 5,
  143714. 4,
  143715. 6,
  143716. 3,
  143717. 7,
  143718. 2,
  143719. 8,
  143720. 1,
  143721. 9,
  143722. 0,
  143723. 10,
  143724. };
  143725. static long _vq_lengthlist__16u1__p8_0[] = {
  143726. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143727. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143728. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143729. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143730. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143731. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143732. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143733. 13,14,14,15,15,16,16,15,16,
  143734. };
  143735. static float _vq_quantthresh__16u1__p8_0[] = {
  143736. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143737. 38.5, 49.5,
  143738. };
  143739. static long _vq_quantmap__16u1__p8_0[] = {
  143740. 9, 7, 5, 3, 1, 0, 2, 4,
  143741. 6, 8, 10,
  143742. };
  143743. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143744. _vq_quantthresh__16u1__p8_0,
  143745. _vq_quantmap__16u1__p8_0,
  143746. 11,
  143747. 11
  143748. };
  143749. static static_codebook _16u1__p8_0 = {
  143750. 2, 121,
  143751. _vq_lengthlist__16u1__p8_0,
  143752. 1, -524582912, 1618345984, 4, 0,
  143753. _vq_quantlist__16u1__p8_0,
  143754. NULL,
  143755. &_vq_auxt__16u1__p8_0,
  143756. NULL,
  143757. 0
  143758. };
  143759. static long _vq_quantlist__16u1__p8_1[] = {
  143760. 5,
  143761. 4,
  143762. 6,
  143763. 3,
  143764. 7,
  143765. 2,
  143766. 8,
  143767. 1,
  143768. 9,
  143769. 0,
  143770. 10,
  143771. };
  143772. static long _vq_lengthlist__16u1__p8_1[] = {
  143773. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143774. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143775. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143776. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143777. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143778. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143779. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143780. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143781. };
  143782. static float _vq_quantthresh__16u1__p8_1[] = {
  143783. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143784. 3.5, 4.5,
  143785. };
  143786. static long _vq_quantmap__16u1__p8_1[] = {
  143787. 9, 7, 5, 3, 1, 0, 2, 4,
  143788. 6, 8, 10,
  143789. };
  143790. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143791. _vq_quantthresh__16u1__p8_1,
  143792. _vq_quantmap__16u1__p8_1,
  143793. 11,
  143794. 11
  143795. };
  143796. static static_codebook _16u1__p8_1 = {
  143797. 2, 121,
  143798. _vq_lengthlist__16u1__p8_1,
  143799. 1, -531365888, 1611661312, 4, 0,
  143800. _vq_quantlist__16u1__p8_1,
  143801. NULL,
  143802. &_vq_auxt__16u1__p8_1,
  143803. NULL,
  143804. 0
  143805. };
  143806. static long _vq_quantlist__16u1__p9_0[] = {
  143807. 7,
  143808. 6,
  143809. 8,
  143810. 5,
  143811. 9,
  143812. 4,
  143813. 10,
  143814. 3,
  143815. 11,
  143816. 2,
  143817. 12,
  143818. 1,
  143819. 13,
  143820. 0,
  143821. 14,
  143822. };
  143823. static long _vq_lengthlist__16u1__p9_0[] = {
  143824. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143825. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143826. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143827. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143828. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143829. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143830. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143831. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143832. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143833. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143834. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143835. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143836. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143837. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143838. 8,
  143839. };
  143840. static float _vq_quantthresh__16u1__p9_0[] = {
  143841. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143842. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143843. };
  143844. static long _vq_quantmap__16u1__p9_0[] = {
  143845. 13, 11, 9, 7, 5, 3, 1, 0,
  143846. 2, 4, 6, 8, 10, 12, 14,
  143847. };
  143848. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143849. _vq_quantthresh__16u1__p9_0,
  143850. _vq_quantmap__16u1__p9_0,
  143851. 15,
  143852. 15
  143853. };
  143854. static static_codebook _16u1__p9_0 = {
  143855. 2, 225,
  143856. _vq_lengthlist__16u1__p9_0,
  143857. 1, -514071552, 1627381760, 4, 0,
  143858. _vq_quantlist__16u1__p9_0,
  143859. NULL,
  143860. &_vq_auxt__16u1__p9_0,
  143861. NULL,
  143862. 0
  143863. };
  143864. static long _vq_quantlist__16u1__p9_1[] = {
  143865. 7,
  143866. 6,
  143867. 8,
  143868. 5,
  143869. 9,
  143870. 4,
  143871. 10,
  143872. 3,
  143873. 11,
  143874. 2,
  143875. 12,
  143876. 1,
  143877. 13,
  143878. 0,
  143879. 14,
  143880. };
  143881. static long _vq_lengthlist__16u1__p9_1[] = {
  143882. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143883. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143884. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143885. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143886. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143887. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143888. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143889. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143890. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143891. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143892. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143893. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143894. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143895. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143896. 9,
  143897. };
  143898. static float _vq_quantthresh__16u1__p9_1[] = {
  143899. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143900. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143901. };
  143902. static long _vq_quantmap__16u1__p9_1[] = {
  143903. 13, 11, 9, 7, 5, 3, 1, 0,
  143904. 2, 4, 6, 8, 10, 12, 14,
  143905. };
  143906. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143907. _vq_quantthresh__16u1__p9_1,
  143908. _vq_quantmap__16u1__p9_1,
  143909. 15,
  143910. 15
  143911. };
  143912. static static_codebook _16u1__p9_1 = {
  143913. 2, 225,
  143914. _vq_lengthlist__16u1__p9_1,
  143915. 1, -522338304, 1620115456, 4, 0,
  143916. _vq_quantlist__16u1__p9_1,
  143917. NULL,
  143918. &_vq_auxt__16u1__p9_1,
  143919. NULL,
  143920. 0
  143921. };
  143922. static long _vq_quantlist__16u1__p9_2[] = {
  143923. 8,
  143924. 7,
  143925. 9,
  143926. 6,
  143927. 10,
  143928. 5,
  143929. 11,
  143930. 4,
  143931. 12,
  143932. 3,
  143933. 13,
  143934. 2,
  143935. 14,
  143936. 1,
  143937. 15,
  143938. 0,
  143939. 16,
  143940. };
  143941. static long _vq_lengthlist__16u1__p9_2[] = {
  143942. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143943. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143944. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143945. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143946. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143947. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143948. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143949. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143950. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143951. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143952. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143953. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143954. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143955. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143956. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143957. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143958. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143959. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143960. 10,
  143961. };
  143962. static float _vq_quantthresh__16u1__p9_2[] = {
  143963. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143964. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143965. };
  143966. static long _vq_quantmap__16u1__p9_2[] = {
  143967. 15, 13, 11, 9, 7, 5, 3, 1,
  143968. 0, 2, 4, 6, 8, 10, 12, 14,
  143969. 16,
  143970. };
  143971. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143972. _vq_quantthresh__16u1__p9_2,
  143973. _vq_quantmap__16u1__p9_2,
  143974. 17,
  143975. 17
  143976. };
  143977. static static_codebook _16u1__p9_2 = {
  143978. 2, 289,
  143979. _vq_lengthlist__16u1__p9_2,
  143980. 1, -529530880, 1611661312, 5, 0,
  143981. _vq_quantlist__16u1__p9_2,
  143982. NULL,
  143983. &_vq_auxt__16u1__p9_2,
  143984. NULL,
  143985. 0
  143986. };
  143987. static long _huff_lengthlist__16u1__short[] = {
  143988. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143989. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143990. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143991. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143992. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143993. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143994. 16,16,16,16,
  143995. };
  143996. static static_codebook _huff_book__16u1__short = {
  143997. 2, 100,
  143998. _huff_lengthlist__16u1__short,
  143999. 0, 0, 0, 0, 0,
  144000. NULL,
  144001. NULL,
  144002. NULL,
  144003. NULL,
  144004. 0
  144005. };
  144006. static long _huff_lengthlist__16u2__long[] = {
  144007. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144008. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144009. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144010. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144011. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144012. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144013. 13,14,18,18,
  144014. };
  144015. static static_codebook _huff_book__16u2__long = {
  144016. 2, 100,
  144017. _huff_lengthlist__16u2__long,
  144018. 0, 0, 0, 0, 0,
  144019. NULL,
  144020. NULL,
  144021. NULL,
  144022. NULL,
  144023. 0
  144024. };
  144025. static long _huff_lengthlist__16u2__short[] = {
  144026. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144027. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144028. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144029. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144030. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144031. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144032. 16,16,16,16,
  144033. };
  144034. static static_codebook _huff_book__16u2__short = {
  144035. 2, 100,
  144036. _huff_lengthlist__16u2__short,
  144037. 0, 0, 0, 0, 0,
  144038. NULL,
  144039. NULL,
  144040. NULL,
  144041. NULL,
  144042. 0
  144043. };
  144044. static long _vq_quantlist__16u2_p1_0[] = {
  144045. 1,
  144046. 0,
  144047. 2,
  144048. };
  144049. static long _vq_lengthlist__16u2_p1_0[] = {
  144050. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144051. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144052. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144053. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144054. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144055. 10,
  144056. };
  144057. static float _vq_quantthresh__16u2_p1_0[] = {
  144058. -0.5, 0.5,
  144059. };
  144060. static long _vq_quantmap__16u2_p1_0[] = {
  144061. 1, 0, 2,
  144062. };
  144063. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144064. _vq_quantthresh__16u2_p1_0,
  144065. _vq_quantmap__16u2_p1_0,
  144066. 3,
  144067. 3
  144068. };
  144069. static static_codebook _16u2_p1_0 = {
  144070. 4, 81,
  144071. _vq_lengthlist__16u2_p1_0,
  144072. 1, -535822336, 1611661312, 2, 0,
  144073. _vq_quantlist__16u2_p1_0,
  144074. NULL,
  144075. &_vq_auxt__16u2_p1_0,
  144076. NULL,
  144077. 0
  144078. };
  144079. static long _vq_quantlist__16u2_p2_0[] = {
  144080. 2,
  144081. 1,
  144082. 3,
  144083. 0,
  144084. 4,
  144085. };
  144086. static long _vq_lengthlist__16u2_p2_0[] = {
  144087. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144088. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144089. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144090. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144091. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144092. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144093. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144094. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144095. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144096. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144097. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144098. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144099. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144100. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144101. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144102. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144103. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144104. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144105. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144106. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144107. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144108. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144109. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144110. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144111. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144112. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144113. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144114. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144115. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144116. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144117. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144118. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144119. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144120. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144121. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144122. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144123. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144124. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144125. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144126. 13,
  144127. };
  144128. static float _vq_quantthresh__16u2_p2_0[] = {
  144129. -1.5, -0.5, 0.5, 1.5,
  144130. };
  144131. static long _vq_quantmap__16u2_p2_0[] = {
  144132. 3, 1, 0, 2, 4,
  144133. };
  144134. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144135. _vq_quantthresh__16u2_p2_0,
  144136. _vq_quantmap__16u2_p2_0,
  144137. 5,
  144138. 5
  144139. };
  144140. static static_codebook _16u2_p2_0 = {
  144141. 4, 625,
  144142. _vq_lengthlist__16u2_p2_0,
  144143. 1, -533725184, 1611661312, 3, 0,
  144144. _vq_quantlist__16u2_p2_0,
  144145. NULL,
  144146. &_vq_auxt__16u2_p2_0,
  144147. NULL,
  144148. 0
  144149. };
  144150. static long _vq_quantlist__16u2_p3_0[] = {
  144151. 4,
  144152. 3,
  144153. 5,
  144154. 2,
  144155. 6,
  144156. 1,
  144157. 7,
  144158. 0,
  144159. 8,
  144160. };
  144161. static long _vq_lengthlist__16u2_p3_0[] = {
  144162. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144163. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144164. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144165. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144166. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144167. 11,
  144168. };
  144169. static float _vq_quantthresh__16u2_p3_0[] = {
  144170. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144171. };
  144172. static long _vq_quantmap__16u2_p3_0[] = {
  144173. 7, 5, 3, 1, 0, 2, 4, 6,
  144174. 8,
  144175. };
  144176. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144177. _vq_quantthresh__16u2_p3_0,
  144178. _vq_quantmap__16u2_p3_0,
  144179. 9,
  144180. 9
  144181. };
  144182. static static_codebook _16u2_p3_0 = {
  144183. 2, 81,
  144184. _vq_lengthlist__16u2_p3_0,
  144185. 1, -531628032, 1611661312, 4, 0,
  144186. _vq_quantlist__16u2_p3_0,
  144187. NULL,
  144188. &_vq_auxt__16u2_p3_0,
  144189. NULL,
  144190. 0
  144191. };
  144192. static long _vq_quantlist__16u2_p4_0[] = {
  144193. 8,
  144194. 7,
  144195. 9,
  144196. 6,
  144197. 10,
  144198. 5,
  144199. 11,
  144200. 4,
  144201. 12,
  144202. 3,
  144203. 13,
  144204. 2,
  144205. 14,
  144206. 1,
  144207. 15,
  144208. 0,
  144209. 16,
  144210. };
  144211. static long _vq_lengthlist__16u2_p4_0[] = {
  144212. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144213. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144214. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144215. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144216. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144217. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144218. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144219. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144220. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144221. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144222. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144223. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144224. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144225. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144226. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144227. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144228. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144229. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144230. 14,
  144231. };
  144232. static float _vq_quantthresh__16u2_p4_0[] = {
  144233. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144234. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144235. };
  144236. static long _vq_quantmap__16u2_p4_0[] = {
  144237. 15, 13, 11, 9, 7, 5, 3, 1,
  144238. 0, 2, 4, 6, 8, 10, 12, 14,
  144239. 16,
  144240. };
  144241. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144242. _vq_quantthresh__16u2_p4_0,
  144243. _vq_quantmap__16u2_p4_0,
  144244. 17,
  144245. 17
  144246. };
  144247. static static_codebook _16u2_p4_0 = {
  144248. 2, 289,
  144249. _vq_lengthlist__16u2_p4_0,
  144250. 1, -529530880, 1611661312, 5, 0,
  144251. _vq_quantlist__16u2_p4_0,
  144252. NULL,
  144253. &_vq_auxt__16u2_p4_0,
  144254. NULL,
  144255. 0
  144256. };
  144257. static long _vq_quantlist__16u2_p5_0[] = {
  144258. 1,
  144259. 0,
  144260. 2,
  144261. };
  144262. static long _vq_lengthlist__16u2_p5_0[] = {
  144263. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144264. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144265. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144266. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144267. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144268. 10,
  144269. };
  144270. static float _vq_quantthresh__16u2_p5_0[] = {
  144271. -5.5, 5.5,
  144272. };
  144273. static long _vq_quantmap__16u2_p5_0[] = {
  144274. 1, 0, 2,
  144275. };
  144276. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144277. _vq_quantthresh__16u2_p5_0,
  144278. _vq_quantmap__16u2_p5_0,
  144279. 3,
  144280. 3
  144281. };
  144282. static static_codebook _16u2_p5_0 = {
  144283. 4, 81,
  144284. _vq_lengthlist__16u2_p5_0,
  144285. 1, -529137664, 1618345984, 2, 0,
  144286. _vq_quantlist__16u2_p5_0,
  144287. NULL,
  144288. &_vq_auxt__16u2_p5_0,
  144289. NULL,
  144290. 0
  144291. };
  144292. static long _vq_quantlist__16u2_p5_1[] = {
  144293. 5,
  144294. 4,
  144295. 6,
  144296. 3,
  144297. 7,
  144298. 2,
  144299. 8,
  144300. 1,
  144301. 9,
  144302. 0,
  144303. 10,
  144304. };
  144305. static long _vq_lengthlist__16u2_p5_1[] = {
  144306. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144307. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144308. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144309. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144310. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144311. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144312. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144313. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144314. };
  144315. static float _vq_quantthresh__16u2_p5_1[] = {
  144316. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144317. 3.5, 4.5,
  144318. };
  144319. static long _vq_quantmap__16u2_p5_1[] = {
  144320. 9, 7, 5, 3, 1, 0, 2, 4,
  144321. 6, 8, 10,
  144322. };
  144323. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144324. _vq_quantthresh__16u2_p5_1,
  144325. _vq_quantmap__16u2_p5_1,
  144326. 11,
  144327. 11
  144328. };
  144329. static static_codebook _16u2_p5_1 = {
  144330. 2, 121,
  144331. _vq_lengthlist__16u2_p5_1,
  144332. 1, -531365888, 1611661312, 4, 0,
  144333. _vq_quantlist__16u2_p5_1,
  144334. NULL,
  144335. &_vq_auxt__16u2_p5_1,
  144336. NULL,
  144337. 0
  144338. };
  144339. static long _vq_quantlist__16u2_p6_0[] = {
  144340. 6,
  144341. 5,
  144342. 7,
  144343. 4,
  144344. 8,
  144345. 3,
  144346. 9,
  144347. 2,
  144348. 10,
  144349. 1,
  144350. 11,
  144351. 0,
  144352. 12,
  144353. };
  144354. static long _vq_lengthlist__16u2_p6_0[] = {
  144355. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144356. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144357. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144358. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144359. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144360. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144361. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144362. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144363. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144364. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144365. 12,13,13,14,14,14,14,15,15,
  144366. };
  144367. static float _vq_quantthresh__16u2_p6_0[] = {
  144368. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144369. 12.5, 17.5, 22.5, 27.5,
  144370. };
  144371. static long _vq_quantmap__16u2_p6_0[] = {
  144372. 11, 9, 7, 5, 3, 1, 0, 2,
  144373. 4, 6, 8, 10, 12,
  144374. };
  144375. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144376. _vq_quantthresh__16u2_p6_0,
  144377. _vq_quantmap__16u2_p6_0,
  144378. 13,
  144379. 13
  144380. };
  144381. static static_codebook _16u2_p6_0 = {
  144382. 2, 169,
  144383. _vq_lengthlist__16u2_p6_0,
  144384. 1, -526516224, 1616117760, 4, 0,
  144385. _vq_quantlist__16u2_p6_0,
  144386. NULL,
  144387. &_vq_auxt__16u2_p6_0,
  144388. NULL,
  144389. 0
  144390. };
  144391. static long _vq_quantlist__16u2_p6_1[] = {
  144392. 2,
  144393. 1,
  144394. 3,
  144395. 0,
  144396. 4,
  144397. };
  144398. static long _vq_lengthlist__16u2_p6_1[] = {
  144399. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144400. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144401. };
  144402. static float _vq_quantthresh__16u2_p6_1[] = {
  144403. -1.5, -0.5, 0.5, 1.5,
  144404. };
  144405. static long _vq_quantmap__16u2_p6_1[] = {
  144406. 3, 1, 0, 2, 4,
  144407. };
  144408. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144409. _vq_quantthresh__16u2_p6_1,
  144410. _vq_quantmap__16u2_p6_1,
  144411. 5,
  144412. 5
  144413. };
  144414. static static_codebook _16u2_p6_1 = {
  144415. 2, 25,
  144416. _vq_lengthlist__16u2_p6_1,
  144417. 1, -533725184, 1611661312, 3, 0,
  144418. _vq_quantlist__16u2_p6_1,
  144419. NULL,
  144420. &_vq_auxt__16u2_p6_1,
  144421. NULL,
  144422. 0
  144423. };
  144424. static long _vq_quantlist__16u2_p7_0[] = {
  144425. 6,
  144426. 5,
  144427. 7,
  144428. 4,
  144429. 8,
  144430. 3,
  144431. 9,
  144432. 2,
  144433. 10,
  144434. 1,
  144435. 11,
  144436. 0,
  144437. 12,
  144438. };
  144439. static long _vq_lengthlist__16u2_p7_0[] = {
  144440. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144441. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144442. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144443. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144444. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144445. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144446. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144447. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144448. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144449. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144450. 12,13,13,13,14,14,14,15,14,
  144451. };
  144452. static float _vq_quantthresh__16u2_p7_0[] = {
  144453. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144454. 27.5, 38.5, 49.5, 60.5,
  144455. };
  144456. static long _vq_quantmap__16u2_p7_0[] = {
  144457. 11, 9, 7, 5, 3, 1, 0, 2,
  144458. 4, 6, 8, 10, 12,
  144459. };
  144460. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144461. _vq_quantthresh__16u2_p7_0,
  144462. _vq_quantmap__16u2_p7_0,
  144463. 13,
  144464. 13
  144465. };
  144466. static static_codebook _16u2_p7_0 = {
  144467. 2, 169,
  144468. _vq_lengthlist__16u2_p7_0,
  144469. 1, -523206656, 1618345984, 4, 0,
  144470. _vq_quantlist__16u2_p7_0,
  144471. NULL,
  144472. &_vq_auxt__16u2_p7_0,
  144473. NULL,
  144474. 0
  144475. };
  144476. static long _vq_quantlist__16u2_p7_1[] = {
  144477. 5,
  144478. 4,
  144479. 6,
  144480. 3,
  144481. 7,
  144482. 2,
  144483. 8,
  144484. 1,
  144485. 9,
  144486. 0,
  144487. 10,
  144488. };
  144489. static long _vq_lengthlist__16u2_p7_1[] = {
  144490. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144491. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144492. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144493. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144494. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144495. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144496. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144497. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144498. };
  144499. static float _vq_quantthresh__16u2_p7_1[] = {
  144500. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144501. 3.5, 4.5,
  144502. };
  144503. static long _vq_quantmap__16u2_p7_1[] = {
  144504. 9, 7, 5, 3, 1, 0, 2, 4,
  144505. 6, 8, 10,
  144506. };
  144507. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144508. _vq_quantthresh__16u2_p7_1,
  144509. _vq_quantmap__16u2_p7_1,
  144510. 11,
  144511. 11
  144512. };
  144513. static static_codebook _16u2_p7_1 = {
  144514. 2, 121,
  144515. _vq_lengthlist__16u2_p7_1,
  144516. 1, -531365888, 1611661312, 4, 0,
  144517. _vq_quantlist__16u2_p7_1,
  144518. NULL,
  144519. &_vq_auxt__16u2_p7_1,
  144520. NULL,
  144521. 0
  144522. };
  144523. static long _vq_quantlist__16u2_p8_0[] = {
  144524. 7,
  144525. 6,
  144526. 8,
  144527. 5,
  144528. 9,
  144529. 4,
  144530. 10,
  144531. 3,
  144532. 11,
  144533. 2,
  144534. 12,
  144535. 1,
  144536. 13,
  144537. 0,
  144538. 14,
  144539. };
  144540. static long _vq_lengthlist__16u2_p8_0[] = {
  144541. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144542. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144543. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144544. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144545. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144546. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144547. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144548. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144549. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144550. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144551. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144552. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144553. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144554. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144555. 14,
  144556. };
  144557. static float _vq_quantthresh__16u2_p8_0[] = {
  144558. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144559. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144560. };
  144561. static long _vq_quantmap__16u2_p8_0[] = {
  144562. 13, 11, 9, 7, 5, 3, 1, 0,
  144563. 2, 4, 6, 8, 10, 12, 14,
  144564. };
  144565. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144566. _vq_quantthresh__16u2_p8_0,
  144567. _vq_quantmap__16u2_p8_0,
  144568. 15,
  144569. 15
  144570. };
  144571. static static_codebook _16u2_p8_0 = {
  144572. 2, 225,
  144573. _vq_lengthlist__16u2_p8_0,
  144574. 1, -520986624, 1620377600, 4, 0,
  144575. _vq_quantlist__16u2_p8_0,
  144576. NULL,
  144577. &_vq_auxt__16u2_p8_0,
  144578. NULL,
  144579. 0
  144580. };
  144581. static long _vq_quantlist__16u2_p8_1[] = {
  144582. 10,
  144583. 9,
  144584. 11,
  144585. 8,
  144586. 12,
  144587. 7,
  144588. 13,
  144589. 6,
  144590. 14,
  144591. 5,
  144592. 15,
  144593. 4,
  144594. 16,
  144595. 3,
  144596. 17,
  144597. 2,
  144598. 18,
  144599. 1,
  144600. 19,
  144601. 0,
  144602. 20,
  144603. };
  144604. static long _vq_lengthlist__16u2_p8_1[] = {
  144605. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144606. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144607. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144608. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144609. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144610. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144611. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144612. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144613. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144614. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144615. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144616. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144617. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144618. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144619. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144620. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144621. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144622. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144623. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144624. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144625. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144626. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144627. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144628. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144630. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144631. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144632. 11,11,10,11,11,11,10,11,11,
  144633. };
  144634. static float _vq_quantthresh__16u2_p8_1[] = {
  144635. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144636. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144637. 6.5, 7.5, 8.5, 9.5,
  144638. };
  144639. static long _vq_quantmap__16u2_p8_1[] = {
  144640. 19, 17, 15, 13, 11, 9, 7, 5,
  144641. 3, 1, 0, 2, 4, 6, 8, 10,
  144642. 12, 14, 16, 18, 20,
  144643. };
  144644. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144645. _vq_quantthresh__16u2_p8_1,
  144646. _vq_quantmap__16u2_p8_1,
  144647. 21,
  144648. 21
  144649. };
  144650. static static_codebook _16u2_p8_1 = {
  144651. 2, 441,
  144652. _vq_lengthlist__16u2_p8_1,
  144653. 1, -529268736, 1611661312, 5, 0,
  144654. _vq_quantlist__16u2_p8_1,
  144655. NULL,
  144656. &_vq_auxt__16u2_p8_1,
  144657. NULL,
  144658. 0
  144659. };
  144660. static long _vq_quantlist__16u2_p9_0[] = {
  144661. 5586,
  144662. 4655,
  144663. 6517,
  144664. 3724,
  144665. 7448,
  144666. 2793,
  144667. 8379,
  144668. 1862,
  144669. 9310,
  144670. 931,
  144671. 10241,
  144672. 0,
  144673. 11172,
  144674. 5521,
  144675. 5651,
  144676. };
  144677. static long _vq_lengthlist__16u2_p9_0[] = {
  144678. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144679. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144680. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144681. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144682. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144683. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144684. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144685. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144686. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144687. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144688. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144689. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144690. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144691. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144692. 5,
  144693. };
  144694. static float _vq_quantthresh__16u2_p9_0[] = {
  144695. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144696. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144697. };
  144698. static long _vq_quantmap__16u2_p9_0[] = {
  144699. 11, 9, 7, 5, 3, 1, 13, 0,
  144700. 14, 2, 4, 6, 8, 10, 12,
  144701. };
  144702. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144703. _vq_quantthresh__16u2_p9_0,
  144704. _vq_quantmap__16u2_p9_0,
  144705. 15,
  144706. 15
  144707. };
  144708. static static_codebook _16u2_p9_0 = {
  144709. 2, 225,
  144710. _vq_lengthlist__16u2_p9_0,
  144711. 1, -510275072, 1611661312, 14, 0,
  144712. _vq_quantlist__16u2_p9_0,
  144713. NULL,
  144714. &_vq_auxt__16u2_p9_0,
  144715. NULL,
  144716. 0
  144717. };
  144718. static long _vq_quantlist__16u2_p9_1[] = {
  144719. 392,
  144720. 343,
  144721. 441,
  144722. 294,
  144723. 490,
  144724. 245,
  144725. 539,
  144726. 196,
  144727. 588,
  144728. 147,
  144729. 637,
  144730. 98,
  144731. 686,
  144732. 49,
  144733. 735,
  144734. 0,
  144735. 784,
  144736. 388,
  144737. 396,
  144738. };
  144739. static long _vq_lengthlist__16u2_p9_1[] = {
  144740. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144741. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144742. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144743. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144744. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144745. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144746. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144747. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144748. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144749. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144750. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144751. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144752. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144753. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144754. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144759. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144760. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144761. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144762. 11,11,11,11,11,11,11, 5, 4,
  144763. };
  144764. static float _vq_quantthresh__16u2_p9_1[] = {
  144765. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144766. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144767. 318.5, 367.5,
  144768. };
  144769. static long _vq_quantmap__16u2_p9_1[] = {
  144770. 15, 13, 11, 9, 7, 5, 3, 1,
  144771. 17, 0, 18, 2, 4, 6, 8, 10,
  144772. 12, 14, 16,
  144773. };
  144774. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144775. _vq_quantthresh__16u2_p9_1,
  144776. _vq_quantmap__16u2_p9_1,
  144777. 19,
  144778. 19
  144779. };
  144780. static static_codebook _16u2_p9_1 = {
  144781. 2, 361,
  144782. _vq_lengthlist__16u2_p9_1,
  144783. 1, -518488064, 1611661312, 10, 0,
  144784. _vq_quantlist__16u2_p9_1,
  144785. NULL,
  144786. &_vq_auxt__16u2_p9_1,
  144787. NULL,
  144788. 0
  144789. };
  144790. static long _vq_quantlist__16u2_p9_2[] = {
  144791. 24,
  144792. 23,
  144793. 25,
  144794. 22,
  144795. 26,
  144796. 21,
  144797. 27,
  144798. 20,
  144799. 28,
  144800. 19,
  144801. 29,
  144802. 18,
  144803. 30,
  144804. 17,
  144805. 31,
  144806. 16,
  144807. 32,
  144808. 15,
  144809. 33,
  144810. 14,
  144811. 34,
  144812. 13,
  144813. 35,
  144814. 12,
  144815. 36,
  144816. 11,
  144817. 37,
  144818. 10,
  144819. 38,
  144820. 9,
  144821. 39,
  144822. 8,
  144823. 40,
  144824. 7,
  144825. 41,
  144826. 6,
  144827. 42,
  144828. 5,
  144829. 43,
  144830. 4,
  144831. 44,
  144832. 3,
  144833. 45,
  144834. 2,
  144835. 46,
  144836. 1,
  144837. 47,
  144838. 0,
  144839. 48,
  144840. };
  144841. static long _vq_lengthlist__16u2_p9_2[] = {
  144842. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144843. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144844. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144845. 11,
  144846. };
  144847. static float _vq_quantthresh__16u2_p9_2[] = {
  144848. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144849. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144850. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144851. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144852. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144853. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144854. };
  144855. static long _vq_quantmap__16u2_p9_2[] = {
  144856. 47, 45, 43, 41, 39, 37, 35, 33,
  144857. 31, 29, 27, 25, 23, 21, 19, 17,
  144858. 15, 13, 11, 9, 7, 5, 3, 1,
  144859. 0, 2, 4, 6, 8, 10, 12, 14,
  144860. 16, 18, 20, 22, 24, 26, 28, 30,
  144861. 32, 34, 36, 38, 40, 42, 44, 46,
  144862. 48,
  144863. };
  144864. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144865. _vq_quantthresh__16u2_p9_2,
  144866. _vq_quantmap__16u2_p9_2,
  144867. 49,
  144868. 49
  144869. };
  144870. static static_codebook _16u2_p9_2 = {
  144871. 1, 49,
  144872. _vq_lengthlist__16u2_p9_2,
  144873. 1, -526909440, 1611661312, 6, 0,
  144874. _vq_quantlist__16u2_p9_2,
  144875. NULL,
  144876. &_vq_auxt__16u2_p9_2,
  144877. NULL,
  144878. 0
  144879. };
  144880. static long _vq_quantlist__8u0__p1_0[] = {
  144881. 1,
  144882. 0,
  144883. 2,
  144884. };
  144885. static long _vq_lengthlist__8u0__p1_0[] = {
  144886. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144887. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144888. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144889. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144890. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144891. 11,
  144892. };
  144893. static float _vq_quantthresh__8u0__p1_0[] = {
  144894. -0.5, 0.5,
  144895. };
  144896. static long _vq_quantmap__8u0__p1_0[] = {
  144897. 1, 0, 2,
  144898. };
  144899. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144900. _vq_quantthresh__8u0__p1_0,
  144901. _vq_quantmap__8u0__p1_0,
  144902. 3,
  144903. 3
  144904. };
  144905. static static_codebook _8u0__p1_0 = {
  144906. 4, 81,
  144907. _vq_lengthlist__8u0__p1_0,
  144908. 1, -535822336, 1611661312, 2, 0,
  144909. _vq_quantlist__8u0__p1_0,
  144910. NULL,
  144911. &_vq_auxt__8u0__p1_0,
  144912. NULL,
  144913. 0
  144914. };
  144915. static long _vq_quantlist__8u0__p2_0[] = {
  144916. 1,
  144917. 0,
  144918. 2,
  144919. };
  144920. static long _vq_lengthlist__8u0__p2_0[] = {
  144921. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144922. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144923. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144924. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144925. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144926. 8,
  144927. };
  144928. static float _vq_quantthresh__8u0__p2_0[] = {
  144929. -0.5, 0.5,
  144930. };
  144931. static long _vq_quantmap__8u0__p2_0[] = {
  144932. 1, 0, 2,
  144933. };
  144934. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144935. _vq_quantthresh__8u0__p2_0,
  144936. _vq_quantmap__8u0__p2_0,
  144937. 3,
  144938. 3
  144939. };
  144940. static static_codebook _8u0__p2_0 = {
  144941. 4, 81,
  144942. _vq_lengthlist__8u0__p2_0,
  144943. 1, -535822336, 1611661312, 2, 0,
  144944. _vq_quantlist__8u0__p2_0,
  144945. NULL,
  144946. &_vq_auxt__8u0__p2_0,
  144947. NULL,
  144948. 0
  144949. };
  144950. static long _vq_quantlist__8u0__p3_0[] = {
  144951. 2,
  144952. 1,
  144953. 3,
  144954. 0,
  144955. 4,
  144956. };
  144957. static long _vq_lengthlist__8u0__p3_0[] = {
  144958. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144959. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144960. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144961. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144962. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144963. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144964. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144965. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144966. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144967. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144968. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144969. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144970. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144971. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144972. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144973. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144974. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144975. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144976. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144977. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144978. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144979. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144980. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144981. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144982. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144983. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144984. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144985. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144986. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144987. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144988. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144989. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144990. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144991. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144992. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144993. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144994. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144995. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144996. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144997. 16,
  144998. };
  144999. static float _vq_quantthresh__8u0__p3_0[] = {
  145000. -1.5, -0.5, 0.5, 1.5,
  145001. };
  145002. static long _vq_quantmap__8u0__p3_0[] = {
  145003. 3, 1, 0, 2, 4,
  145004. };
  145005. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145006. _vq_quantthresh__8u0__p3_0,
  145007. _vq_quantmap__8u0__p3_0,
  145008. 5,
  145009. 5
  145010. };
  145011. static static_codebook _8u0__p3_0 = {
  145012. 4, 625,
  145013. _vq_lengthlist__8u0__p3_0,
  145014. 1, -533725184, 1611661312, 3, 0,
  145015. _vq_quantlist__8u0__p3_0,
  145016. NULL,
  145017. &_vq_auxt__8u0__p3_0,
  145018. NULL,
  145019. 0
  145020. };
  145021. static long _vq_quantlist__8u0__p4_0[] = {
  145022. 2,
  145023. 1,
  145024. 3,
  145025. 0,
  145026. 4,
  145027. };
  145028. static long _vq_lengthlist__8u0__p4_0[] = {
  145029. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145030. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145031. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145032. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145033. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145034. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145035. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145036. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145037. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145038. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145039. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145040. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145041. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145042. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145043. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145044. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145045. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145046. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145047. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145048. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145049. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145050. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145051. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145052. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145053. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145054. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145055. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145056. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145057. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145058. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145059. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145060. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145061. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145062. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145063. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145064. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145065. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145066. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145067. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145068. 12,
  145069. };
  145070. static float _vq_quantthresh__8u0__p4_0[] = {
  145071. -1.5, -0.5, 0.5, 1.5,
  145072. };
  145073. static long _vq_quantmap__8u0__p4_0[] = {
  145074. 3, 1, 0, 2, 4,
  145075. };
  145076. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145077. _vq_quantthresh__8u0__p4_0,
  145078. _vq_quantmap__8u0__p4_0,
  145079. 5,
  145080. 5
  145081. };
  145082. static static_codebook _8u0__p4_0 = {
  145083. 4, 625,
  145084. _vq_lengthlist__8u0__p4_0,
  145085. 1, -533725184, 1611661312, 3, 0,
  145086. _vq_quantlist__8u0__p4_0,
  145087. NULL,
  145088. &_vq_auxt__8u0__p4_0,
  145089. NULL,
  145090. 0
  145091. };
  145092. static long _vq_quantlist__8u0__p5_0[] = {
  145093. 4,
  145094. 3,
  145095. 5,
  145096. 2,
  145097. 6,
  145098. 1,
  145099. 7,
  145100. 0,
  145101. 8,
  145102. };
  145103. static long _vq_lengthlist__8u0__p5_0[] = {
  145104. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145105. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145106. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145107. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145108. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145109. 12,
  145110. };
  145111. static float _vq_quantthresh__8u0__p5_0[] = {
  145112. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145113. };
  145114. static long _vq_quantmap__8u0__p5_0[] = {
  145115. 7, 5, 3, 1, 0, 2, 4, 6,
  145116. 8,
  145117. };
  145118. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145119. _vq_quantthresh__8u0__p5_0,
  145120. _vq_quantmap__8u0__p5_0,
  145121. 9,
  145122. 9
  145123. };
  145124. static static_codebook _8u0__p5_0 = {
  145125. 2, 81,
  145126. _vq_lengthlist__8u0__p5_0,
  145127. 1, -531628032, 1611661312, 4, 0,
  145128. _vq_quantlist__8u0__p5_0,
  145129. NULL,
  145130. &_vq_auxt__8u0__p5_0,
  145131. NULL,
  145132. 0
  145133. };
  145134. static long _vq_quantlist__8u0__p6_0[] = {
  145135. 6,
  145136. 5,
  145137. 7,
  145138. 4,
  145139. 8,
  145140. 3,
  145141. 9,
  145142. 2,
  145143. 10,
  145144. 1,
  145145. 11,
  145146. 0,
  145147. 12,
  145148. };
  145149. static long _vq_lengthlist__8u0__p6_0[] = {
  145150. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145151. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145152. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145153. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145154. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145155. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145156. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145157. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145158. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145159. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145160. 16, 0,15, 0,17, 0, 0, 0, 0,
  145161. };
  145162. static float _vq_quantthresh__8u0__p6_0[] = {
  145163. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145164. 12.5, 17.5, 22.5, 27.5,
  145165. };
  145166. static long _vq_quantmap__8u0__p6_0[] = {
  145167. 11, 9, 7, 5, 3, 1, 0, 2,
  145168. 4, 6, 8, 10, 12,
  145169. };
  145170. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145171. _vq_quantthresh__8u0__p6_0,
  145172. _vq_quantmap__8u0__p6_0,
  145173. 13,
  145174. 13
  145175. };
  145176. static static_codebook _8u0__p6_0 = {
  145177. 2, 169,
  145178. _vq_lengthlist__8u0__p6_0,
  145179. 1, -526516224, 1616117760, 4, 0,
  145180. _vq_quantlist__8u0__p6_0,
  145181. NULL,
  145182. &_vq_auxt__8u0__p6_0,
  145183. NULL,
  145184. 0
  145185. };
  145186. static long _vq_quantlist__8u0__p6_1[] = {
  145187. 2,
  145188. 1,
  145189. 3,
  145190. 0,
  145191. 4,
  145192. };
  145193. static long _vq_lengthlist__8u0__p6_1[] = {
  145194. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145195. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145196. };
  145197. static float _vq_quantthresh__8u0__p6_1[] = {
  145198. -1.5, -0.5, 0.5, 1.5,
  145199. };
  145200. static long _vq_quantmap__8u0__p6_1[] = {
  145201. 3, 1, 0, 2, 4,
  145202. };
  145203. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145204. _vq_quantthresh__8u0__p6_1,
  145205. _vq_quantmap__8u0__p6_1,
  145206. 5,
  145207. 5
  145208. };
  145209. static static_codebook _8u0__p6_1 = {
  145210. 2, 25,
  145211. _vq_lengthlist__8u0__p6_1,
  145212. 1, -533725184, 1611661312, 3, 0,
  145213. _vq_quantlist__8u0__p6_1,
  145214. NULL,
  145215. &_vq_auxt__8u0__p6_1,
  145216. NULL,
  145217. 0
  145218. };
  145219. static long _vq_quantlist__8u0__p7_0[] = {
  145220. 1,
  145221. 0,
  145222. 2,
  145223. };
  145224. static long _vq_lengthlist__8u0__p7_0[] = {
  145225. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145226. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145227. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145228. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145229. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145230. 7,
  145231. };
  145232. static float _vq_quantthresh__8u0__p7_0[] = {
  145233. -157.5, 157.5,
  145234. };
  145235. static long _vq_quantmap__8u0__p7_0[] = {
  145236. 1, 0, 2,
  145237. };
  145238. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145239. _vq_quantthresh__8u0__p7_0,
  145240. _vq_quantmap__8u0__p7_0,
  145241. 3,
  145242. 3
  145243. };
  145244. static static_codebook _8u0__p7_0 = {
  145245. 4, 81,
  145246. _vq_lengthlist__8u0__p7_0,
  145247. 1, -518803456, 1628680192, 2, 0,
  145248. _vq_quantlist__8u0__p7_0,
  145249. NULL,
  145250. &_vq_auxt__8u0__p7_0,
  145251. NULL,
  145252. 0
  145253. };
  145254. static long _vq_quantlist__8u0__p7_1[] = {
  145255. 7,
  145256. 6,
  145257. 8,
  145258. 5,
  145259. 9,
  145260. 4,
  145261. 10,
  145262. 3,
  145263. 11,
  145264. 2,
  145265. 12,
  145266. 1,
  145267. 13,
  145268. 0,
  145269. 14,
  145270. };
  145271. static long _vq_lengthlist__8u0__p7_1[] = {
  145272. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145273. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145274. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145275. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145276. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145277. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145278. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145280. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145281. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145282. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145283. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145284. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145285. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145286. 10,
  145287. };
  145288. static float _vq_quantthresh__8u0__p7_1[] = {
  145289. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145290. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145291. };
  145292. static long _vq_quantmap__8u0__p7_1[] = {
  145293. 13, 11, 9, 7, 5, 3, 1, 0,
  145294. 2, 4, 6, 8, 10, 12, 14,
  145295. };
  145296. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145297. _vq_quantthresh__8u0__p7_1,
  145298. _vq_quantmap__8u0__p7_1,
  145299. 15,
  145300. 15
  145301. };
  145302. static static_codebook _8u0__p7_1 = {
  145303. 2, 225,
  145304. _vq_lengthlist__8u0__p7_1,
  145305. 1, -520986624, 1620377600, 4, 0,
  145306. _vq_quantlist__8u0__p7_1,
  145307. NULL,
  145308. &_vq_auxt__8u0__p7_1,
  145309. NULL,
  145310. 0
  145311. };
  145312. static long _vq_quantlist__8u0__p7_2[] = {
  145313. 10,
  145314. 9,
  145315. 11,
  145316. 8,
  145317. 12,
  145318. 7,
  145319. 13,
  145320. 6,
  145321. 14,
  145322. 5,
  145323. 15,
  145324. 4,
  145325. 16,
  145326. 3,
  145327. 17,
  145328. 2,
  145329. 18,
  145330. 1,
  145331. 19,
  145332. 0,
  145333. 20,
  145334. };
  145335. static long _vq_lengthlist__8u0__p7_2[] = {
  145336. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145337. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145338. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145339. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145340. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145341. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145342. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145343. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145344. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145345. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145346. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145347. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145348. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145349. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145350. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145351. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145352. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145353. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145354. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145355. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145356. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145357. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145358. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145359. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145360. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145361. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145362. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145363. 11,12,11,11,11,10,10,11,11,
  145364. };
  145365. static float _vq_quantthresh__8u0__p7_2[] = {
  145366. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145367. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145368. 6.5, 7.5, 8.5, 9.5,
  145369. };
  145370. static long _vq_quantmap__8u0__p7_2[] = {
  145371. 19, 17, 15, 13, 11, 9, 7, 5,
  145372. 3, 1, 0, 2, 4, 6, 8, 10,
  145373. 12, 14, 16, 18, 20,
  145374. };
  145375. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145376. _vq_quantthresh__8u0__p7_2,
  145377. _vq_quantmap__8u0__p7_2,
  145378. 21,
  145379. 21
  145380. };
  145381. static static_codebook _8u0__p7_2 = {
  145382. 2, 441,
  145383. _vq_lengthlist__8u0__p7_2,
  145384. 1, -529268736, 1611661312, 5, 0,
  145385. _vq_quantlist__8u0__p7_2,
  145386. NULL,
  145387. &_vq_auxt__8u0__p7_2,
  145388. NULL,
  145389. 0
  145390. };
  145391. static long _huff_lengthlist__8u0__single[] = {
  145392. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145393. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145394. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145395. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145396. };
  145397. static static_codebook _huff_book__8u0__single = {
  145398. 2, 64,
  145399. _huff_lengthlist__8u0__single,
  145400. 0, 0, 0, 0, 0,
  145401. NULL,
  145402. NULL,
  145403. NULL,
  145404. NULL,
  145405. 0
  145406. };
  145407. static long _vq_quantlist__8u1__p1_0[] = {
  145408. 1,
  145409. 0,
  145410. 2,
  145411. };
  145412. static long _vq_lengthlist__8u1__p1_0[] = {
  145413. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145414. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145415. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145416. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145417. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145418. 10,
  145419. };
  145420. static float _vq_quantthresh__8u1__p1_0[] = {
  145421. -0.5, 0.5,
  145422. };
  145423. static long _vq_quantmap__8u1__p1_0[] = {
  145424. 1, 0, 2,
  145425. };
  145426. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145427. _vq_quantthresh__8u1__p1_0,
  145428. _vq_quantmap__8u1__p1_0,
  145429. 3,
  145430. 3
  145431. };
  145432. static static_codebook _8u1__p1_0 = {
  145433. 4, 81,
  145434. _vq_lengthlist__8u1__p1_0,
  145435. 1, -535822336, 1611661312, 2, 0,
  145436. _vq_quantlist__8u1__p1_0,
  145437. NULL,
  145438. &_vq_auxt__8u1__p1_0,
  145439. NULL,
  145440. 0
  145441. };
  145442. static long _vq_quantlist__8u1__p2_0[] = {
  145443. 1,
  145444. 0,
  145445. 2,
  145446. };
  145447. static long _vq_lengthlist__8u1__p2_0[] = {
  145448. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145449. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145450. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145451. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145452. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145453. 7,
  145454. };
  145455. static float _vq_quantthresh__8u1__p2_0[] = {
  145456. -0.5, 0.5,
  145457. };
  145458. static long _vq_quantmap__8u1__p2_0[] = {
  145459. 1, 0, 2,
  145460. };
  145461. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145462. _vq_quantthresh__8u1__p2_0,
  145463. _vq_quantmap__8u1__p2_0,
  145464. 3,
  145465. 3
  145466. };
  145467. static static_codebook _8u1__p2_0 = {
  145468. 4, 81,
  145469. _vq_lengthlist__8u1__p2_0,
  145470. 1, -535822336, 1611661312, 2, 0,
  145471. _vq_quantlist__8u1__p2_0,
  145472. NULL,
  145473. &_vq_auxt__8u1__p2_0,
  145474. NULL,
  145475. 0
  145476. };
  145477. static long _vq_quantlist__8u1__p3_0[] = {
  145478. 2,
  145479. 1,
  145480. 3,
  145481. 0,
  145482. 4,
  145483. };
  145484. static long _vq_lengthlist__8u1__p3_0[] = {
  145485. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145486. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145487. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145488. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145489. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145490. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145491. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145492. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145493. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145494. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145495. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145496. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145497. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145498. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145499. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145500. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145501. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145502. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145503. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145504. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145505. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145506. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145507. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145508. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145509. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145510. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145511. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145512. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145513. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145514. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145515. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145516. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145517. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145518. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145519. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145520. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145521. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145522. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145523. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145524. 16,
  145525. };
  145526. static float _vq_quantthresh__8u1__p3_0[] = {
  145527. -1.5, -0.5, 0.5, 1.5,
  145528. };
  145529. static long _vq_quantmap__8u1__p3_0[] = {
  145530. 3, 1, 0, 2, 4,
  145531. };
  145532. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145533. _vq_quantthresh__8u1__p3_0,
  145534. _vq_quantmap__8u1__p3_0,
  145535. 5,
  145536. 5
  145537. };
  145538. static static_codebook _8u1__p3_0 = {
  145539. 4, 625,
  145540. _vq_lengthlist__8u1__p3_0,
  145541. 1, -533725184, 1611661312, 3, 0,
  145542. _vq_quantlist__8u1__p3_0,
  145543. NULL,
  145544. &_vq_auxt__8u1__p3_0,
  145545. NULL,
  145546. 0
  145547. };
  145548. static long _vq_quantlist__8u1__p4_0[] = {
  145549. 2,
  145550. 1,
  145551. 3,
  145552. 0,
  145553. 4,
  145554. };
  145555. static long _vq_lengthlist__8u1__p4_0[] = {
  145556. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145557. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145558. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145559. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145560. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145561. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145562. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145563. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145564. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145565. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145566. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145567. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145568. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145569. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145570. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145571. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145572. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145573. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145574. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145575. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145576. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145577. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145578. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145579. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145580. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145581. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145582. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145583. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145584. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145585. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145586. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145587. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145588. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145589. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145590. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145591. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145592. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145593. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145594. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145595. 10,
  145596. };
  145597. static float _vq_quantthresh__8u1__p4_0[] = {
  145598. -1.5, -0.5, 0.5, 1.5,
  145599. };
  145600. static long _vq_quantmap__8u1__p4_0[] = {
  145601. 3, 1, 0, 2, 4,
  145602. };
  145603. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145604. _vq_quantthresh__8u1__p4_0,
  145605. _vq_quantmap__8u1__p4_0,
  145606. 5,
  145607. 5
  145608. };
  145609. static static_codebook _8u1__p4_0 = {
  145610. 4, 625,
  145611. _vq_lengthlist__8u1__p4_0,
  145612. 1, -533725184, 1611661312, 3, 0,
  145613. _vq_quantlist__8u1__p4_0,
  145614. NULL,
  145615. &_vq_auxt__8u1__p4_0,
  145616. NULL,
  145617. 0
  145618. };
  145619. static long _vq_quantlist__8u1__p5_0[] = {
  145620. 4,
  145621. 3,
  145622. 5,
  145623. 2,
  145624. 6,
  145625. 1,
  145626. 7,
  145627. 0,
  145628. 8,
  145629. };
  145630. static long _vq_lengthlist__8u1__p5_0[] = {
  145631. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145632. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145633. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145634. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145635. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145636. 13,
  145637. };
  145638. static float _vq_quantthresh__8u1__p5_0[] = {
  145639. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145640. };
  145641. static long _vq_quantmap__8u1__p5_0[] = {
  145642. 7, 5, 3, 1, 0, 2, 4, 6,
  145643. 8,
  145644. };
  145645. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145646. _vq_quantthresh__8u1__p5_0,
  145647. _vq_quantmap__8u1__p5_0,
  145648. 9,
  145649. 9
  145650. };
  145651. static static_codebook _8u1__p5_0 = {
  145652. 2, 81,
  145653. _vq_lengthlist__8u1__p5_0,
  145654. 1, -531628032, 1611661312, 4, 0,
  145655. _vq_quantlist__8u1__p5_0,
  145656. NULL,
  145657. &_vq_auxt__8u1__p5_0,
  145658. NULL,
  145659. 0
  145660. };
  145661. static long _vq_quantlist__8u1__p6_0[] = {
  145662. 4,
  145663. 3,
  145664. 5,
  145665. 2,
  145666. 6,
  145667. 1,
  145668. 7,
  145669. 0,
  145670. 8,
  145671. };
  145672. static long _vq_lengthlist__8u1__p6_0[] = {
  145673. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145674. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145675. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145676. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145677. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145678. 10,
  145679. };
  145680. static float _vq_quantthresh__8u1__p6_0[] = {
  145681. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145682. };
  145683. static long _vq_quantmap__8u1__p6_0[] = {
  145684. 7, 5, 3, 1, 0, 2, 4, 6,
  145685. 8,
  145686. };
  145687. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145688. _vq_quantthresh__8u1__p6_0,
  145689. _vq_quantmap__8u1__p6_0,
  145690. 9,
  145691. 9
  145692. };
  145693. static static_codebook _8u1__p6_0 = {
  145694. 2, 81,
  145695. _vq_lengthlist__8u1__p6_0,
  145696. 1, -531628032, 1611661312, 4, 0,
  145697. _vq_quantlist__8u1__p6_0,
  145698. NULL,
  145699. &_vq_auxt__8u1__p6_0,
  145700. NULL,
  145701. 0
  145702. };
  145703. static long _vq_quantlist__8u1__p7_0[] = {
  145704. 1,
  145705. 0,
  145706. 2,
  145707. };
  145708. static long _vq_lengthlist__8u1__p7_0[] = {
  145709. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145710. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145711. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145712. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145713. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145714. 11,
  145715. };
  145716. static float _vq_quantthresh__8u1__p7_0[] = {
  145717. -5.5, 5.5,
  145718. };
  145719. static long _vq_quantmap__8u1__p7_0[] = {
  145720. 1, 0, 2,
  145721. };
  145722. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145723. _vq_quantthresh__8u1__p7_0,
  145724. _vq_quantmap__8u1__p7_0,
  145725. 3,
  145726. 3
  145727. };
  145728. static static_codebook _8u1__p7_0 = {
  145729. 4, 81,
  145730. _vq_lengthlist__8u1__p7_0,
  145731. 1, -529137664, 1618345984, 2, 0,
  145732. _vq_quantlist__8u1__p7_0,
  145733. NULL,
  145734. &_vq_auxt__8u1__p7_0,
  145735. NULL,
  145736. 0
  145737. };
  145738. static long _vq_quantlist__8u1__p7_1[] = {
  145739. 5,
  145740. 4,
  145741. 6,
  145742. 3,
  145743. 7,
  145744. 2,
  145745. 8,
  145746. 1,
  145747. 9,
  145748. 0,
  145749. 10,
  145750. };
  145751. static long _vq_lengthlist__8u1__p7_1[] = {
  145752. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145753. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145754. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145755. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145756. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145757. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145758. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145759. 9, 9, 9, 9, 9,10,10,10,10,
  145760. };
  145761. static float _vq_quantthresh__8u1__p7_1[] = {
  145762. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145763. 3.5, 4.5,
  145764. };
  145765. static long _vq_quantmap__8u1__p7_1[] = {
  145766. 9, 7, 5, 3, 1, 0, 2, 4,
  145767. 6, 8, 10,
  145768. };
  145769. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145770. _vq_quantthresh__8u1__p7_1,
  145771. _vq_quantmap__8u1__p7_1,
  145772. 11,
  145773. 11
  145774. };
  145775. static static_codebook _8u1__p7_1 = {
  145776. 2, 121,
  145777. _vq_lengthlist__8u1__p7_1,
  145778. 1, -531365888, 1611661312, 4, 0,
  145779. _vq_quantlist__8u1__p7_1,
  145780. NULL,
  145781. &_vq_auxt__8u1__p7_1,
  145782. NULL,
  145783. 0
  145784. };
  145785. static long _vq_quantlist__8u1__p8_0[] = {
  145786. 5,
  145787. 4,
  145788. 6,
  145789. 3,
  145790. 7,
  145791. 2,
  145792. 8,
  145793. 1,
  145794. 9,
  145795. 0,
  145796. 10,
  145797. };
  145798. static long _vq_lengthlist__8u1__p8_0[] = {
  145799. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145800. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145801. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145802. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145803. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145804. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145805. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145806. 12,13,13,14,14,15,15,15,15,
  145807. };
  145808. static float _vq_quantthresh__8u1__p8_0[] = {
  145809. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145810. 38.5, 49.5,
  145811. };
  145812. static long _vq_quantmap__8u1__p8_0[] = {
  145813. 9, 7, 5, 3, 1, 0, 2, 4,
  145814. 6, 8, 10,
  145815. };
  145816. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145817. _vq_quantthresh__8u1__p8_0,
  145818. _vq_quantmap__8u1__p8_0,
  145819. 11,
  145820. 11
  145821. };
  145822. static static_codebook _8u1__p8_0 = {
  145823. 2, 121,
  145824. _vq_lengthlist__8u1__p8_0,
  145825. 1, -524582912, 1618345984, 4, 0,
  145826. _vq_quantlist__8u1__p8_0,
  145827. NULL,
  145828. &_vq_auxt__8u1__p8_0,
  145829. NULL,
  145830. 0
  145831. };
  145832. static long _vq_quantlist__8u1__p8_1[] = {
  145833. 5,
  145834. 4,
  145835. 6,
  145836. 3,
  145837. 7,
  145838. 2,
  145839. 8,
  145840. 1,
  145841. 9,
  145842. 0,
  145843. 10,
  145844. };
  145845. static long _vq_lengthlist__8u1__p8_1[] = {
  145846. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145847. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145848. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145849. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145850. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145851. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145852. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145853. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145854. };
  145855. static float _vq_quantthresh__8u1__p8_1[] = {
  145856. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145857. 3.5, 4.5,
  145858. };
  145859. static long _vq_quantmap__8u1__p8_1[] = {
  145860. 9, 7, 5, 3, 1, 0, 2, 4,
  145861. 6, 8, 10,
  145862. };
  145863. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145864. _vq_quantthresh__8u1__p8_1,
  145865. _vq_quantmap__8u1__p8_1,
  145866. 11,
  145867. 11
  145868. };
  145869. static static_codebook _8u1__p8_1 = {
  145870. 2, 121,
  145871. _vq_lengthlist__8u1__p8_1,
  145872. 1, -531365888, 1611661312, 4, 0,
  145873. _vq_quantlist__8u1__p8_1,
  145874. NULL,
  145875. &_vq_auxt__8u1__p8_1,
  145876. NULL,
  145877. 0
  145878. };
  145879. static long _vq_quantlist__8u1__p9_0[] = {
  145880. 7,
  145881. 6,
  145882. 8,
  145883. 5,
  145884. 9,
  145885. 4,
  145886. 10,
  145887. 3,
  145888. 11,
  145889. 2,
  145890. 12,
  145891. 1,
  145892. 13,
  145893. 0,
  145894. 14,
  145895. };
  145896. static long _vq_lengthlist__8u1__p9_0[] = {
  145897. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145898. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145899. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145900. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145901. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145902. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145903. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145904. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145905. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145906. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145907. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145909. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145910. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145911. 10,
  145912. };
  145913. static float _vq_quantthresh__8u1__p9_0[] = {
  145914. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145915. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145916. };
  145917. static long _vq_quantmap__8u1__p9_0[] = {
  145918. 13, 11, 9, 7, 5, 3, 1, 0,
  145919. 2, 4, 6, 8, 10, 12, 14,
  145920. };
  145921. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145922. _vq_quantthresh__8u1__p9_0,
  145923. _vq_quantmap__8u1__p9_0,
  145924. 15,
  145925. 15
  145926. };
  145927. static static_codebook _8u1__p9_0 = {
  145928. 2, 225,
  145929. _vq_lengthlist__8u1__p9_0,
  145930. 1, -514071552, 1627381760, 4, 0,
  145931. _vq_quantlist__8u1__p9_0,
  145932. NULL,
  145933. &_vq_auxt__8u1__p9_0,
  145934. NULL,
  145935. 0
  145936. };
  145937. static long _vq_quantlist__8u1__p9_1[] = {
  145938. 7,
  145939. 6,
  145940. 8,
  145941. 5,
  145942. 9,
  145943. 4,
  145944. 10,
  145945. 3,
  145946. 11,
  145947. 2,
  145948. 12,
  145949. 1,
  145950. 13,
  145951. 0,
  145952. 14,
  145953. };
  145954. static long _vq_lengthlist__8u1__p9_1[] = {
  145955. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145956. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145957. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145958. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145959. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145960. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145961. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145962. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145963. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145964. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145965. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145966. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145967. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145968. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145969. 13,
  145970. };
  145971. static float _vq_quantthresh__8u1__p9_1[] = {
  145972. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145973. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145974. };
  145975. static long _vq_quantmap__8u1__p9_1[] = {
  145976. 13, 11, 9, 7, 5, 3, 1, 0,
  145977. 2, 4, 6, 8, 10, 12, 14,
  145978. };
  145979. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145980. _vq_quantthresh__8u1__p9_1,
  145981. _vq_quantmap__8u1__p9_1,
  145982. 15,
  145983. 15
  145984. };
  145985. static static_codebook _8u1__p9_1 = {
  145986. 2, 225,
  145987. _vq_lengthlist__8u1__p9_1,
  145988. 1, -522338304, 1620115456, 4, 0,
  145989. _vq_quantlist__8u1__p9_1,
  145990. NULL,
  145991. &_vq_auxt__8u1__p9_1,
  145992. NULL,
  145993. 0
  145994. };
  145995. static long _vq_quantlist__8u1__p9_2[] = {
  145996. 8,
  145997. 7,
  145998. 9,
  145999. 6,
  146000. 10,
  146001. 5,
  146002. 11,
  146003. 4,
  146004. 12,
  146005. 3,
  146006. 13,
  146007. 2,
  146008. 14,
  146009. 1,
  146010. 15,
  146011. 0,
  146012. 16,
  146013. };
  146014. static long _vq_lengthlist__8u1__p9_2[] = {
  146015. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146016. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146017. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146018. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146019. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146020. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146021. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146022. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146023. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146024. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146025. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146026. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146027. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146028. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146029. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146030. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146031. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146032. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146033. 10,
  146034. };
  146035. static float _vq_quantthresh__8u1__p9_2[] = {
  146036. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146037. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146038. };
  146039. static long _vq_quantmap__8u1__p9_2[] = {
  146040. 15, 13, 11, 9, 7, 5, 3, 1,
  146041. 0, 2, 4, 6, 8, 10, 12, 14,
  146042. 16,
  146043. };
  146044. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146045. _vq_quantthresh__8u1__p9_2,
  146046. _vq_quantmap__8u1__p9_2,
  146047. 17,
  146048. 17
  146049. };
  146050. static static_codebook _8u1__p9_2 = {
  146051. 2, 289,
  146052. _vq_lengthlist__8u1__p9_2,
  146053. 1, -529530880, 1611661312, 5, 0,
  146054. _vq_quantlist__8u1__p9_2,
  146055. NULL,
  146056. &_vq_auxt__8u1__p9_2,
  146057. NULL,
  146058. 0
  146059. };
  146060. static long _huff_lengthlist__8u1__single[] = {
  146061. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146062. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146063. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146064. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146065. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146066. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146067. 13, 8, 8,15,
  146068. };
  146069. static static_codebook _huff_book__8u1__single = {
  146070. 2, 100,
  146071. _huff_lengthlist__8u1__single,
  146072. 0, 0, 0, 0, 0,
  146073. NULL,
  146074. NULL,
  146075. NULL,
  146076. NULL,
  146077. 0
  146078. };
  146079. static long _huff_lengthlist__44u0__long[] = {
  146080. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146081. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146082. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146083. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146084. };
  146085. static static_codebook _huff_book__44u0__long = {
  146086. 2, 64,
  146087. _huff_lengthlist__44u0__long,
  146088. 0, 0, 0, 0, 0,
  146089. NULL,
  146090. NULL,
  146091. NULL,
  146092. NULL,
  146093. 0
  146094. };
  146095. static long _vq_quantlist__44u0__p1_0[] = {
  146096. 1,
  146097. 0,
  146098. 2,
  146099. };
  146100. static long _vq_lengthlist__44u0__p1_0[] = {
  146101. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146102. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146103. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146104. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146105. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146106. 13,
  146107. };
  146108. static float _vq_quantthresh__44u0__p1_0[] = {
  146109. -0.5, 0.5,
  146110. };
  146111. static long _vq_quantmap__44u0__p1_0[] = {
  146112. 1, 0, 2,
  146113. };
  146114. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146115. _vq_quantthresh__44u0__p1_0,
  146116. _vq_quantmap__44u0__p1_0,
  146117. 3,
  146118. 3
  146119. };
  146120. static static_codebook _44u0__p1_0 = {
  146121. 4, 81,
  146122. _vq_lengthlist__44u0__p1_0,
  146123. 1, -535822336, 1611661312, 2, 0,
  146124. _vq_quantlist__44u0__p1_0,
  146125. NULL,
  146126. &_vq_auxt__44u0__p1_0,
  146127. NULL,
  146128. 0
  146129. };
  146130. static long _vq_quantlist__44u0__p2_0[] = {
  146131. 1,
  146132. 0,
  146133. 2,
  146134. };
  146135. static long _vq_lengthlist__44u0__p2_0[] = {
  146136. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146137. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146138. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146139. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146140. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146141. 9,
  146142. };
  146143. static float _vq_quantthresh__44u0__p2_0[] = {
  146144. -0.5, 0.5,
  146145. };
  146146. static long _vq_quantmap__44u0__p2_0[] = {
  146147. 1, 0, 2,
  146148. };
  146149. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146150. _vq_quantthresh__44u0__p2_0,
  146151. _vq_quantmap__44u0__p2_0,
  146152. 3,
  146153. 3
  146154. };
  146155. static static_codebook _44u0__p2_0 = {
  146156. 4, 81,
  146157. _vq_lengthlist__44u0__p2_0,
  146158. 1, -535822336, 1611661312, 2, 0,
  146159. _vq_quantlist__44u0__p2_0,
  146160. NULL,
  146161. &_vq_auxt__44u0__p2_0,
  146162. NULL,
  146163. 0
  146164. };
  146165. static long _vq_quantlist__44u0__p3_0[] = {
  146166. 2,
  146167. 1,
  146168. 3,
  146169. 0,
  146170. 4,
  146171. };
  146172. static long _vq_lengthlist__44u0__p3_0[] = {
  146173. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146174. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146175. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146176. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146177. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146178. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146179. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146180. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146181. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146182. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146183. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146184. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146185. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146186. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146187. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146188. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146189. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146190. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146191. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146192. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146193. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146194. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146195. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146196. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146197. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146198. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146199. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146200. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146201. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146202. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146203. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146204. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146205. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146206. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146207. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146208. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146209. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146210. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146211. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146212. 19,
  146213. };
  146214. static float _vq_quantthresh__44u0__p3_0[] = {
  146215. -1.5, -0.5, 0.5, 1.5,
  146216. };
  146217. static long _vq_quantmap__44u0__p3_0[] = {
  146218. 3, 1, 0, 2, 4,
  146219. };
  146220. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146221. _vq_quantthresh__44u0__p3_0,
  146222. _vq_quantmap__44u0__p3_0,
  146223. 5,
  146224. 5
  146225. };
  146226. static static_codebook _44u0__p3_0 = {
  146227. 4, 625,
  146228. _vq_lengthlist__44u0__p3_0,
  146229. 1, -533725184, 1611661312, 3, 0,
  146230. _vq_quantlist__44u0__p3_0,
  146231. NULL,
  146232. &_vq_auxt__44u0__p3_0,
  146233. NULL,
  146234. 0
  146235. };
  146236. static long _vq_quantlist__44u0__p4_0[] = {
  146237. 2,
  146238. 1,
  146239. 3,
  146240. 0,
  146241. 4,
  146242. };
  146243. static long _vq_lengthlist__44u0__p4_0[] = {
  146244. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146245. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146246. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146247. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146248. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146249. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146250. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146251. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146252. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146253. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146254. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146255. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146256. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146257. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146258. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146259. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146260. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146261. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146262. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146263. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146264. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146265. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146266. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146267. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146268. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146269. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146270. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146271. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146272. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146273. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146274. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146275. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146276. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146277. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146278. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146279. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146280. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146281. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146282. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146283. 12,
  146284. };
  146285. static float _vq_quantthresh__44u0__p4_0[] = {
  146286. -1.5, -0.5, 0.5, 1.5,
  146287. };
  146288. static long _vq_quantmap__44u0__p4_0[] = {
  146289. 3, 1, 0, 2, 4,
  146290. };
  146291. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146292. _vq_quantthresh__44u0__p4_0,
  146293. _vq_quantmap__44u0__p4_0,
  146294. 5,
  146295. 5
  146296. };
  146297. static static_codebook _44u0__p4_0 = {
  146298. 4, 625,
  146299. _vq_lengthlist__44u0__p4_0,
  146300. 1, -533725184, 1611661312, 3, 0,
  146301. _vq_quantlist__44u0__p4_0,
  146302. NULL,
  146303. &_vq_auxt__44u0__p4_0,
  146304. NULL,
  146305. 0
  146306. };
  146307. static long _vq_quantlist__44u0__p5_0[] = {
  146308. 4,
  146309. 3,
  146310. 5,
  146311. 2,
  146312. 6,
  146313. 1,
  146314. 7,
  146315. 0,
  146316. 8,
  146317. };
  146318. static long _vq_lengthlist__44u0__p5_0[] = {
  146319. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146320. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146321. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146322. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146323. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146324. 12,
  146325. };
  146326. static float _vq_quantthresh__44u0__p5_0[] = {
  146327. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146328. };
  146329. static long _vq_quantmap__44u0__p5_0[] = {
  146330. 7, 5, 3, 1, 0, 2, 4, 6,
  146331. 8,
  146332. };
  146333. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146334. _vq_quantthresh__44u0__p5_0,
  146335. _vq_quantmap__44u0__p5_0,
  146336. 9,
  146337. 9
  146338. };
  146339. static static_codebook _44u0__p5_0 = {
  146340. 2, 81,
  146341. _vq_lengthlist__44u0__p5_0,
  146342. 1, -531628032, 1611661312, 4, 0,
  146343. _vq_quantlist__44u0__p5_0,
  146344. NULL,
  146345. &_vq_auxt__44u0__p5_0,
  146346. NULL,
  146347. 0
  146348. };
  146349. static long _vq_quantlist__44u0__p6_0[] = {
  146350. 6,
  146351. 5,
  146352. 7,
  146353. 4,
  146354. 8,
  146355. 3,
  146356. 9,
  146357. 2,
  146358. 10,
  146359. 1,
  146360. 11,
  146361. 0,
  146362. 12,
  146363. };
  146364. static long _vq_lengthlist__44u0__p6_0[] = {
  146365. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146366. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146367. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146368. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146369. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146370. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146371. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146372. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146373. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146374. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146375. 15,17,16,17,18,17,17,18, 0,
  146376. };
  146377. static float _vq_quantthresh__44u0__p6_0[] = {
  146378. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146379. 12.5, 17.5, 22.5, 27.5,
  146380. };
  146381. static long _vq_quantmap__44u0__p6_0[] = {
  146382. 11, 9, 7, 5, 3, 1, 0, 2,
  146383. 4, 6, 8, 10, 12,
  146384. };
  146385. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146386. _vq_quantthresh__44u0__p6_0,
  146387. _vq_quantmap__44u0__p6_0,
  146388. 13,
  146389. 13
  146390. };
  146391. static static_codebook _44u0__p6_0 = {
  146392. 2, 169,
  146393. _vq_lengthlist__44u0__p6_0,
  146394. 1, -526516224, 1616117760, 4, 0,
  146395. _vq_quantlist__44u0__p6_0,
  146396. NULL,
  146397. &_vq_auxt__44u0__p6_0,
  146398. NULL,
  146399. 0
  146400. };
  146401. static long _vq_quantlist__44u0__p6_1[] = {
  146402. 2,
  146403. 1,
  146404. 3,
  146405. 0,
  146406. 4,
  146407. };
  146408. static long _vq_lengthlist__44u0__p6_1[] = {
  146409. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146410. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146411. };
  146412. static float _vq_quantthresh__44u0__p6_1[] = {
  146413. -1.5, -0.5, 0.5, 1.5,
  146414. };
  146415. static long _vq_quantmap__44u0__p6_1[] = {
  146416. 3, 1, 0, 2, 4,
  146417. };
  146418. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146419. _vq_quantthresh__44u0__p6_1,
  146420. _vq_quantmap__44u0__p6_1,
  146421. 5,
  146422. 5
  146423. };
  146424. static static_codebook _44u0__p6_1 = {
  146425. 2, 25,
  146426. _vq_lengthlist__44u0__p6_1,
  146427. 1, -533725184, 1611661312, 3, 0,
  146428. _vq_quantlist__44u0__p6_1,
  146429. NULL,
  146430. &_vq_auxt__44u0__p6_1,
  146431. NULL,
  146432. 0
  146433. };
  146434. static long _vq_quantlist__44u0__p7_0[] = {
  146435. 2,
  146436. 1,
  146437. 3,
  146438. 0,
  146439. 4,
  146440. };
  146441. static long _vq_lengthlist__44u0__p7_0[] = {
  146442. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146443. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146444. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146445. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146446. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146447. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146448. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146449. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146450. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146451. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146452. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146453. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146454. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146455. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146456. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146457. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146458. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146459. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146460. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146461. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146462. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146463. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146464. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146465. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146467. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146468. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146469. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146470. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146471. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146472. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146473. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146474. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146475. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146476. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146477. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146478. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146479. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146480. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146481. 10,
  146482. };
  146483. static float _vq_quantthresh__44u0__p7_0[] = {
  146484. -253.5, -84.5, 84.5, 253.5,
  146485. };
  146486. static long _vq_quantmap__44u0__p7_0[] = {
  146487. 3, 1, 0, 2, 4,
  146488. };
  146489. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146490. _vq_quantthresh__44u0__p7_0,
  146491. _vq_quantmap__44u0__p7_0,
  146492. 5,
  146493. 5
  146494. };
  146495. static static_codebook _44u0__p7_0 = {
  146496. 4, 625,
  146497. _vq_lengthlist__44u0__p7_0,
  146498. 1, -518709248, 1626677248, 3, 0,
  146499. _vq_quantlist__44u0__p7_0,
  146500. NULL,
  146501. &_vq_auxt__44u0__p7_0,
  146502. NULL,
  146503. 0
  146504. };
  146505. static long _vq_quantlist__44u0__p7_1[] = {
  146506. 6,
  146507. 5,
  146508. 7,
  146509. 4,
  146510. 8,
  146511. 3,
  146512. 9,
  146513. 2,
  146514. 10,
  146515. 1,
  146516. 11,
  146517. 0,
  146518. 12,
  146519. };
  146520. static long _vq_lengthlist__44u0__p7_1[] = {
  146521. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146522. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146523. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146524. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146525. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146526. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146527. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146528. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146529. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146530. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146531. 15,15,15,15,15,15,15,15,15,
  146532. };
  146533. static float _vq_quantthresh__44u0__p7_1[] = {
  146534. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146535. 32.5, 45.5, 58.5, 71.5,
  146536. };
  146537. static long _vq_quantmap__44u0__p7_1[] = {
  146538. 11, 9, 7, 5, 3, 1, 0, 2,
  146539. 4, 6, 8, 10, 12,
  146540. };
  146541. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146542. _vq_quantthresh__44u0__p7_1,
  146543. _vq_quantmap__44u0__p7_1,
  146544. 13,
  146545. 13
  146546. };
  146547. static static_codebook _44u0__p7_1 = {
  146548. 2, 169,
  146549. _vq_lengthlist__44u0__p7_1,
  146550. 1, -523010048, 1618608128, 4, 0,
  146551. _vq_quantlist__44u0__p7_1,
  146552. NULL,
  146553. &_vq_auxt__44u0__p7_1,
  146554. NULL,
  146555. 0
  146556. };
  146557. static long _vq_quantlist__44u0__p7_2[] = {
  146558. 6,
  146559. 5,
  146560. 7,
  146561. 4,
  146562. 8,
  146563. 3,
  146564. 9,
  146565. 2,
  146566. 10,
  146567. 1,
  146568. 11,
  146569. 0,
  146570. 12,
  146571. };
  146572. static long _vq_lengthlist__44u0__p7_2[] = {
  146573. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146574. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146575. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146576. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146577. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146578. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146579. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146580. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146581. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146582. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146583. 9, 9, 9,10, 9, 9,10,10, 9,
  146584. };
  146585. static float _vq_quantthresh__44u0__p7_2[] = {
  146586. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146587. 2.5, 3.5, 4.5, 5.5,
  146588. };
  146589. static long _vq_quantmap__44u0__p7_2[] = {
  146590. 11, 9, 7, 5, 3, 1, 0, 2,
  146591. 4, 6, 8, 10, 12,
  146592. };
  146593. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146594. _vq_quantthresh__44u0__p7_2,
  146595. _vq_quantmap__44u0__p7_2,
  146596. 13,
  146597. 13
  146598. };
  146599. static static_codebook _44u0__p7_2 = {
  146600. 2, 169,
  146601. _vq_lengthlist__44u0__p7_2,
  146602. 1, -531103744, 1611661312, 4, 0,
  146603. _vq_quantlist__44u0__p7_2,
  146604. NULL,
  146605. &_vq_auxt__44u0__p7_2,
  146606. NULL,
  146607. 0
  146608. };
  146609. static long _huff_lengthlist__44u0__short[] = {
  146610. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146611. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146612. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146613. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146614. };
  146615. static static_codebook _huff_book__44u0__short = {
  146616. 2, 64,
  146617. _huff_lengthlist__44u0__short,
  146618. 0, 0, 0, 0, 0,
  146619. NULL,
  146620. NULL,
  146621. NULL,
  146622. NULL,
  146623. 0
  146624. };
  146625. static long _huff_lengthlist__44u1__long[] = {
  146626. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146627. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146628. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146629. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146630. };
  146631. static static_codebook _huff_book__44u1__long = {
  146632. 2, 64,
  146633. _huff_lengthlist__44u1__long,
  146634. 0, 0, 0, 0, 0,
  146635. NULL,
  146636. NULL,
  146637. NULL,
  146638. NULL,
  146639. 0
  146640. };
  146641. static long _vq_quantlist__44u1__p1_0[] = {
  146642. 1,
  146643. 0,
  146644. 2,
  146645. };
  146646. static long _vq_lengthlist__44u1__p1_0[] = {
  146647. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146648. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146649. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146650. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146651. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146652. 13,
  146653. };
  146654. static float _vq_quantthresh__44u1__p1_0[] = {
  146655. -0.5, 0.5,
  146656. };
  146657. static long _vq_quantmap__44u1__p1_0[] = {
  146658. 1, 0, 2,
  146659. };
  146660. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146661. _vq_quantthresh__44u1__p1_0,
  146662. _vq_quantmap__44u1__p1_0,
  146663. 3,
  146664. 3
  146665. };
  146666. static static_codebook _44u1__p1_0 = {
  146667. 4, 81,
  146668. _vq_lengthlist__44u1__p1_0,
  146669. 1, -535822336, 1611661312, 2, 0,
  146670. _vq_quantlist__44u1__p1_0,
  146671. NULL,
  146672. &_vq_auxt__44u1__p1_0,
  146673. NULL,
  146674. 0
  146675. };
  146676. static long _vq_quantlist__44u1__p2_0[] = {
  146677. 1,
  146678. 0,
  146679. 2,
  146680. };
  146681. static long _vq_lengthlist__44u1__p2_0[] = {
  146682. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146683. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146684. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146685. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146686. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146687. 9,
  146688. };
  146689. static float _vq_quantthresh__44u1__p2_0[] = {
  146690. -0.5, 0.5,
  146691. };
  146692. static long _vq_quantmap__44u1__p2_0[] = {
  146693. 1, 0, 2,
  146694. };
  146695. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146696. _vq_quantthresh__44u1__p2_0,
  146697. _vq_quantmap__44u1__p2_0,
  146698. 3,
  146699. 3
  146700. };
  146701. static static_codebook _44u1__p2_0 = {
  146702. 4, 81,
  146703. _vq_lengthlist__44u1__p2_0,
  146704. 1, -535822336, 1611661312, 2, 0,
  146705. _vq_quantlist__44u1__p2_0,
  146706. NULL,
  146707. &_vq_auxt__44u1__p2_0,
  146708. NULL,
  146709. 0
  146710. };
  146711. static long _vq_quantlist__44u1__p3_0[] = {
  146712. 2,
  146713. 1,
  146714. 3,
  146715. 0,
  146716. 4,
  146717. };
  146718. static long _vq_lengthlist__44u1__p3_0[] = {
  146719. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146720. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146721. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146722. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146723. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146724. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146725. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146726. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146727. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146728. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146729. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146730. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146731. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146732. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146733. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146734. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146735. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146736. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146737. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146738. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146739. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146740. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146741. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146742. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146743. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146744. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146745. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146746. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146747. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146748. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146749. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146750. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146751. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146752. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146753. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146754. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146755. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146756. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146757. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146758. 19,
  146759. };
  146760. static float _vq_quantthresh__44u1__p3_0[] = {
  146761. -1.5, -0.5, 0.5, 1.5,
  146762. };
  146763. static long _vq_quantmap__44u1__p3_0[] = {
  146764. 3, 1, 0, 2, 4,
  146765. };
  146766. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146767. _vq_quantthresh__44u1__p3_0,
  146768. _vq_quantmap__44u1__p3_0,
  146769. 5,
  146770. 5
  146771. };
  146772. static static_codebook _44u1__p3_0 = {
  146773. 4, 625,
  146774. _vq_lengthlist__44u1__p3_0,
  146775. 1, -533725184, 1611661312, 3, 0,
  146776. _vq_quantlist__44u1__p3_0,
  146777. NULL,
  146778. &_vq_auxt__44u1__p3_0,
  146779. NULL,
  146780. 0
  146781. };
  146782. static long _vq_quantlist__44u1__p4_0[] = {
  146783. 2,
  146784. 1,
  146785. 3,
  146786. 0,
  146787. 4,
  146788. };
  146789. static long _vq_lengthlist__44u1__p4_0[] = {
  146790. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146791. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146792. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146793. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146794. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146795. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146796. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146797. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146798. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146799. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146800. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146801. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146802. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146803. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146804. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146805. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146806. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146807. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146808. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146809. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146810. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146811. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146812. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146813. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146814. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146815. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146816. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146817. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146818. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146819. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146820. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146821. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146822. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146823. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146824. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146825. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146826. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146827. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146828. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146829. 12,
  146830. };
  146831. static float _vq_quantthresh__44u1__p4_0[] = {
  146832. -1.5, -0.5, 0.5, 1.5,
  146833. };
  146834. static long _vq_quantmap__44u1__p4_0[] = {
  146835. 3, 1, 0, 2, 4,
  146836. };
  146837. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146838. _vq_quantthresh__44u1__p4_0,
  146839. _vq_quantmap__44u1__p4_0,
  146840. 5,
  146841. 5
  146842. };
  146843. static static_codebook _44u1__p4_0 = {
  146844. 4, 625,
  146845. _vq_lengthlist__44u1__p4_0,
  146846. 1, -533725184, 1611661312, 3, 0,
  146847. _vq_quantlist__44u1__p4_0,
  146848. NULL,
  146849. &_vq_auxt__44u1__p4_0,
  146850. NULL,
  146851. 0
  146852. };
  146853. static long _vq_quantlist__44u1__p5_0[] = {
  146854. 4,
  146855. 3,
  146856. 5,
  146857. 2,
  146858. 6,
  146859. 1,
  146860. 7,
  146861. 0,
  146862. 8,
  146863. };
  146864. static long _vq_lengthlist__44u1__p5_0[] = {
  146865. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146866. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146867. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146868. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146869. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146870. 12,
  146871. };
  146872. static float _vq_quantthresh__44u1__p5_0[] = {
  146873. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146874. };
  146875. static long _vq_quantmap__44u1__p5_0[] = {
  146876. 7, 5, 3, 1, 0, 2, 4, 6,
  146877. 8,
  146878. };
  146879. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146880. _vq_quantthresh__44u1__p5_0,
  146881. _vq_quantmap__44u1__p5_0,
  146882. 9,
  146883. 9
  146884. };
  146885. static static_codebook _44u1__p5_0 = {
  146886. 2, 81,
  146887. _vq_lengthlist__44u1__p5_0,
  146888. 1, -531628032, 1611661312, 4, 0,
  146889. _vq_quantlist__44u1__p5_0,
  146890. NULL,
  146891. &_vq_auxt__44u1__p5_0,
  146892. NULL,
  146893. 0
  146894. };
  146895. static long _vq_quantlist__44u1__p6_0[] = {
  146896. 6,
  146897. 5,
  146898. 7,
  146899. 4,
  146900. 8,
  146901. 3,
  146902. 9,
  146903. 2,
  146904. 10,
  146905. 1,
  146906. 11,
  146907. 0,
  146908. 12,
  146909. };
  146910. static long _vq_lengthlist__44u1__p6_0[] = {
  146911. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146912. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146913. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146914. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146915. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146916. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146917. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146918. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146919. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146920. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146921. 15,17,16,17,18,17,17,18, 0,
  146922. };
  146923. static float _vq_quantthresh__44u1__p6_0[] = {
  146924. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146925. 12.5, 17.5, 22.5, 27.5,
  146926. };
  146927. static long _vq_quantmap__44u1__p6_0[] = {
  146928. 11, 9, 7, 5, 3, 1, 0, 2,
  146929. 4, 6, 8, 10, 12,
  146930. };
  146931. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146932. _vq_quantthresh__44u1__p6_0,
  146933. _vq_quantmap__44u1__p6_0,
  146934. 13,
  146935. 13
  146936. };
  146937. static static_codebook _44u1__p6_0 = {
  146938. 2, 169,
  146939. _vq_lengthlist__44u1__p6_0,
  146940. 1, -526516224, 1616117760, 4, 0,
  146941. _vq_quantlist__44u1__p6_0,
  146942. NULL,
  146943. &_vq_auxt__44u1__p6_0,
  146944. NULL,
  146945. 0
  146946. };
  146947. static long _vq_quantlist__44u1__p6_1[] = {
  146948. 2,
  146949. 1,
  146950. 3,
  146951. 0,
  146952. 4,
  146953. };
  146954. static long _vq_lengthlist__44u1__p6_1[] = {
  146955. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146956. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146957. };
  146958. static float _vq_quantthresh__44u1__p6_1[] = {
  146959. -1.5, -0.5, 0.5, 1.5,
  146960. };
  146961. static long _vq_quantmap__44u1__p6_1[] = {
  146962. 3, 1, 0, 2, 4,
  146963. };
  146964. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146965. _vq_quantthresh__44u1__p6_1,
  146966. _vq_quantmap__44u1__p6_1,
  146967. 5,
  146968. 5
  146969. };
  146970. static static_codebook _44u1__p6_1 = {
  146971. 2, 25,
  146972. _vq_lengthlist__44u1__p6_1,
  146973. 1, -533725184, 1611661312, 3, 0,
  146974. _vq_quantlist__44u1__p6_1,
  146975. NULL,
  146976. &_vq_auxt__44u1__p6_1,
  146977. NULL,
  146978. 0
  146979. };
  146980. static long _vq_quantlist__44u1__p7_0[] = {
  146981. 3,
  146982. 2,
  146983. 4,
  146984. 1,
  146985. 5,
  146986. 0,
  146987. 6,
  146988. };
  146989. static long _vq_lengthlist__44u1__p7_0[] = {
  146990. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146991. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146992. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146993. 8,
  146994. };
  146995. static float _vq_quantthresh__44u1__p7_0[] = {
  146996. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146997. };
  146998. static long _vq_quantmap__44u1__p7_0[] = {
  146999. 5, 3, 1, 0, 2, 4, 6,
  147000. };
  147001. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147002. _vq_quantthresh__44u1__p7_0,
  147003. _vq_quantmap__44u1__p7_0,
  147004. 7,
  147005. 7
  147006. };
  147007. static static_codebook _44u1__p7_0 = {
  147008. 2, 49,
  147009. _vq_lengthlist__44u1__p7_0,
  147010. 1, -518017024, 1626677248, 3, 0,
  147011. _vq_quantlist__44u1__p7_0,
  147012. NULL,
  147013. &_vq_auxt__44u1__p7_0,
  147014. NULL,
  147015. 0
  147016. };
  147017. static long _vq_quantlist__44u1__p7_1[] = {
  147018. 6,
  147019. 5,
  147020. 7,
  147021. 4,
  147022. 8,
  147023. 3,
  147024. 9,
  147025. 2,
  147026. 10,
  147027. 1,
  147028. 11,
  147029. 0,
  147030. 12,
  147031. };
  147032. static long _vq_lengthlist__44u1__p7_1[] = {
  147033. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147034. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147035. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147036. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147037. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147038. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147039. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147040. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147041. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147042. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147043. 15,15,15,15,15,15,15,15,15,
  147044. };
  147045. static float _vq_quantthresh__44u1__p7_1[] = {
  147046. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147047. 32.5, 45.5, 58.5, 71.5,
  147048. };
  147049. static long _vq_quantmap__44u1__p7_1[] = {
  147050. 11, 9, 7, 5, 3, 1, 0, 2,
  147051. 4, 6, 8, 10, 12,
  147052. };
  147053. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147054. _vq_quantthresh__44u1__p7_1,
  147055. _vq_quantmap__44u1__p7_1,
  147056. 13,
  147057. 13
  147058. };
  147059. static static_codebook _44u1__p7_1 = {
  147060. 2, 169,
  147061. _vq_lengthlist__44u1__p7_1,
  147062. 1, -523010048, 1618608128, 4, 0,
  147063. _vq_quantlist__44u1__p7_1,
  147064. NULL,
  147065. &_vq_auxt__44u1__p7_1,
  147066. NULL,
  147067. 0
  147068. };
  147069. static long _vq_quantlist__44u1__p7_2[] = {
  147070. 6,
  147071. 5,
  147072. 7,
  147073. 4,
  147074. 8,
  147075. 3,
  147076. 9,
  147077. 2,
  147078. 10,
  147079. 1,
  147080. 11,
  147081. 0,
  147082. 12,
  147083. };
  147084. static long _vq_lengthlist__44u1__p7_2[] = {
  147085. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147086. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147087. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147088. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147089. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147090. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147091. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147092. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147093. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147094. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147095. 9, 9, 9,10, 9, 9,10,10, 9,
  147096. };
  147097. static float _vq_quantthresh__44u1__p7_2[] = {
  147098. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147099. 2.5, 3.5, 4.5, 5.5,
  147100. };
  147101. static long _vq_quantmap__44u1__p7_2[] = {
  147102. 11, 9, 7, 5, 3, 1, 0, 2,
  147103. 4, 6, 8, 10, 12,
  147104. };
  147105. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147106. _vq_quantthresh__44u1__p7_2,
  147107. _vq_quantmap__44u1__p7_2,
  147108. 13,
  147109. 13
  147110. };
  147111. static static_codebook _44u1__p7_2 = {
  147112. 2, 169,
  147113. _vq_lengthlist__44u1__p7_2,
  147114. 1, -531103744, 1611661312, 4, 0,
  147115. _vq_quantlist__44u1__p7_2,
  147116. NULL,
  147117. &_vq_auxt__44u1__p7_2,
  147118. NULL,
  147119. 0
  147120. };
  147121. static long _huff_lengthlist__44u1__short[] = {
  147122. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147123. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147124. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147125. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147126. };
  147127. static static_codebook _huff_book__44u1__short = {
  147128. 2, 64,
  147129. _huff_lengthlist__44u1__short,
  147130. 0, 0, 0, 0, 0,
  147131. NULL,
  147132. NULL,
  147133. NULL,
  147134. NULL,
  147135. 0
  147136. };
  147137. static long _huff_lengthlist__44u2__long[] = {
  147138. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147139. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147140. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147141. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147142. };
  147143. static static_codebook _huff_book__44u2__long = {
  147144. 2, 64,
  147145. _huff_lengthlist__44u2__long,
  147146. 0, 0, 0, 0, 0,
  147147. NULL,
  147148. NULL,
  147149. NULL,
  147150. NULL,
  147151. 0
  147152. };
  147153. static long _vq_quantlist__44u2__p1_0[] = {
  147154. 1,
  147155. 0,
  147156. 2,
  147157. };
  147158. static long _vq_lengthlist__44u2__p1_0[] = {
  147159. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147160. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147161. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147162. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147163. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147164. 13,
  147165. };
  147166. static float _vq_quantthresh__44u2__p1_0[] = {
  147167. -0.5, 0.5,
  147168. };
  147169. static long _vq_quantmap__44u2__p1_0[] = {
  147170. 1, 0, 2,
  147171. };
  147172. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147173. _vq_quantthresh__44u2__p1_0,
  147174. _vq_quantmap__44u2__p1_0,
  147175. 3,
  147176. 3
  147177. };
  147178. static static_codebook _44u2__p1_0 = {
  147179. 4, 81,
  147180. _vq_lengthlist__44u2__p1_0,
  147181. 1, -535822336, 1611661312, 2, 0,
  147182. _vq_quantlist__44u2__p1_0,
  147183. NULL,
  147184. &_vq_auxt__44u2__p1_0,
  147185. NULL,
  147186. 0
  147187. };
  147188. static long _vq_quantlist__44u2__p2_0[] = {
  147189. 1,
  147190. 0,
  147191. 2,
  147192. };
  147193. static long _vq_lengthlist__44u2__p2_0[] = {
  147194. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147195. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147196. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147197. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147198. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147199. 9,
  147200. };
  147201. static float _vq_quantthresh__44u2__p2_0[] = {
  147202. -0.5, 0.5,
  147203. };
  147204. static long _vq_quantmap__44u2__p2_0[] = {
  147205. 1, 0, 2,
  147206. };
  147207. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147208. _vq_quantthresh__44u2__p2_0,
  147209. _vq_quantmap__44u2__p2_0,
  147210. 3,
  147211. 3
  147212. };
  147213. static static_codebook _44u2__p2_0 = {
  147214. 4, 81,
  147215. _vq_lengthlist__44u2__p2_0,
  147216. 1, -535822336, 1611661312, 2, 0,
  147217. _vq_quantlist__44u2__p2_0,
  147218. NULL,
  147219. &_vq_auxt__44u2__p2_0,
  147220. NULL,
  147221. 0
  147222. };
  147223. static long _vq_quantlist__44u2__p3_0[] = {
  147224. 2,
  147225. 1,
  147226. 3,
  147227. 0,
  147228. 4,
  147229. };
  147230. static long _vq_lengthlist__44u2__p3_0[] = {
  147231. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147232. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147233. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147234. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147235. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147236. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147237. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147238. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147239. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147240. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147241. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147242. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147243. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147244. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147245. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147246. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147247. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147248. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147249. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147250. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147251. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147252. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147253. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147254. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147255. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147256. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147257. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147258. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147259. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147260. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147261. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147262. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147263. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147264. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147265. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147266. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147267. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147268. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147269. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147270. 0,
  147271. };
  147272. static float _vq_quantthresh__44u2__p3_0[] = {
  147273. -1.5, -0.5, 0.5, 1.5,
  147274. };
  147275. static long _vq_quantmap__44u2__p3_0[] = {
  147276. 3, 1, 0, 2, 4,
  147277. };
  147278. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147279. _vq_quantthresh__44u2__p3_0,
  147280. _vq_quantmap__44u2__p3_0,
  147281. 5,
  147282. 5
  147283. };
  147284. static static_codebook _44u2__p3_0 = {
  147285. 4, 625,
  147286. _vq_lengthlist__44u2__p3_0,
  147287. 1, -533725184, 1611661312, 3, 0,
  147288. _vq_quantlist__44u2__p3_0,
  147289. NULL,
  147290. &_vq_auxt__44u2__p3_0,
  147291. NULL,
  147292. 0
  147293. };
  147294. static long _vq_quantlist__44u2__p4_0[] = {
  147295. 2,
  147296. 1,
  147297. 3,
  147298. 0,
  147299. 4,
  147300. };
  147301. static long _vq_lengthlist__44u2__p4_0[] = {
  147302. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147303. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147304. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147305. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147306. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147307. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147308. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147309. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147310. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147311. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147312. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147313. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147314. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147315. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147316. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147317. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147318. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147319. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147320. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147321. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147322. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147323. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147324. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147325. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147326. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147327. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147328. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147329. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147330. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147331. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147332. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147333. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147334. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147335. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147336. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147337. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147338. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147339. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147340. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147341. 13,
  147342. };
  147343. static float _vq_quantthresh__44u2__p4_0[] = {
  147344. -1.5, -0.5, 0.5, 1.5,
  147345. };
  147346. static long _vq_quantmap__44u2__p4_0[] = {
  147347. 3, 1, 0, 2, 4,
  147348. };
  147349. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147350. _vq_quantthresh__44u2__p4_0,
  147351. _vq_quantmap__44u2__p4_0,
  147352. 5,
  147353. 5
  147354. };
  147355. static static_codebook _44u2__p4_0 = {
  147356. 4, 625,
  147357. _vq_lengthlist__44u2__p4_0,
  147358. 1, -533725184, 1611661312, 3, 0,
  147359. _vq_quantlist__44u2__p4_0,
  147360. NULL,
  147361. &_vq_auxt__44u2__p4_0,
  147362. NULL,
  147363. 0
  147364. };
  147365. static long _vq_quantlist__44u2__p5_0[] = {
  147366. 4,
  147367. 3,
  147368. 5,
  147369. 2,
  147370. 6,
  147371. 1,
  147372. 7,
  147373. 0,
  147374. 8,
  147375. };
  147376. static long _vq_lengthlist__44u2__p5_0[] = {
  147377. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147378. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147379. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147380. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147381. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147382. 13,
  147383. };
  147384. static float _vq_quantthresh__44u2__p5_0[] = {
  147385. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147386. };
  147387. static long _vq_quantmap__44u2__p5_0[] = {
  147388. 7, 5, 3, 1, 0, 2, 4, 6,
  147389. 8,
  147390. };
  147391. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147392. _vq_quantthresh__44u2__p5_0,
  147393. _vq_quantmap__44u2__p5_0,
  147394. 9,
  147395. 9
  147396. };
  147397. static static_codebook _44u2__p5_0 = {
  147398. 2, 81,
  147399. _vq_lengthlist__44u2__p5_0,
  147400. 1, -531628032, 1611661312, 4, 0,
  147401. _vq_quantlist__44u2__p5_0,
  147402. NULL,
  147403. &_vq_auxt__44u2__p5_0,
  147404. NULL,
  147405. 0
  147406. };
  147407. static long _vq_quantlist__44u2__p6_0[] = {
  147408. 6,
  147409. 5,
  147410. 7,
  147411. 4,
  147412. 8,
  147413. 3,
  147414. 9,
  147415. 2,
  147416. 10,
  147417. 1,
  147418. 11,
  147419. 0,
  147420. 12,
  147421. };
  147422. static long _vq_lengthlist__44u2__p6_0[] = {
  147423. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147424. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147425. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147426. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147427. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147428. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147429. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147430. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147431. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147432. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147433. 15,17,17,16,18,17,18, 0, 0,
  147434. };
  147435. static float _vq_quantthresh__44u2__p6_0[] = {
  147436. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147437. 12.5, 17.5, 22.5, 27.5,
  147438. };
  147439. static long _vq_quantmap__44u2__p6_0[] = {
  147440. 11, 9, 7, 5, 3, 1, 0, 2,
  147441. 4, 6, 8, 10, 12,
  147442. };
  147443. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147444. _vq_quantthresh__44u2__p6_0,
  147445. _vq_quantmap__44u2__p6_0,
  147446. 13,
  147447. 13
  147448. };
  147449. static static_codebook _44u2__p6_0 = {
  147450. 2, 169,
  147451. _vq_lengthlist__44u2__p6_0,
  147452. 1, -526516224, 1616117760, 4, 0,
  147453. _vq_quantlist__44u2__p6_0,
  147454. NULL,
  147455. &_vq_auxt__44u2__p6_0,
  147456. NULL,
  147457. 0
  147458. };
  147459. static long _vq_quantlist__44u2__p6_1[] = {
  147460. 2,
  147461. 1,
  147462. 3,
  147463. 0,
  147464. 4,
  147465. };
  147466. static long _vq_lengthlist__44u2__p6_1[] = {
  147467. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147468. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147469. };
  147470. static float _vq_quantthresh__44u2__p6_1[] = {
  147471. -1.5, -0.5, 0.5, 1.5,
  147472. };
  147473. static long _vq_quantmap__44u2__p6_1[] = {
  147474. 3, 1, 0, 2, 4,
  147475. };
  147476. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147477. _vq_quantthresh__44u2__p6_1,
  147478. _vq_quantmap__44u2__p6_1,
  147479. 5,
  147480. 5
  147481. };
  147482. static static_codebook _44u2__p6_1 = {
  147483. 2, 25,
  147484. _vq_lengthlist__44u2__p6_1,
  147485. 1, -533725184, 1611661312, 3, 0,
  147486. _vq_quantlist__44u2__p6_1,
  147487. NULL,
  147488. &_vq_auxt__44u2__p6_1,
  147489. NULL,
  147490. 0
  147491. };
  147492. static long _vq_quantlist__44u2__p7_0[] = {
  147493. 4,
  147494. 3,
  147495. 5,
  147496. 2,
  147497. 6,
  147498. 1,
  147499. 7,
  147500. 0,
  147501. 8,
  147502. };
  147503. static long _vq_lengthlist__44u2__p7_0[] = {
  147504. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147505. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147506. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147509. 11,
  147510. };
  147511. static float _vq_quantthresh__44u2__p7_0[] = {
  147512. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147513. };
  147514. static long _vq_quantmap__44u2__p7_0[] = {
  147515. 7, 5, 3, 1, 0, 2, 4, 6,
  147516. 8,
  147517. };
  147518. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147519. _vq_quantthresh__44u2__p7_0,
  147520. _vq_quantmap__44u2__p7_0,
  147521. 9,
  147522. 9
  147523. };
  147524. static static_codebook _44u2__p7_0 = {
  147525. 2, 81,
  147526. _vq_lengthlist__44u2__p7_0,
  147527. 1, -516612096, 1626677248, 4, 0,
  147528. _vq_quantlist__44u2__p7_0,
  147529. NULL,
  147530. &_vq_auxt__44u2__p7_0,
  147531. NULL,
  147532. 0
  147533. };
  147534. static long _vq_quantlist__44u2__p7_1[] = {
  147535. 6,
  147536. 5,
  147537. 7,
  147538. 4,
  147539. 8,
  147540. 3,
  147541. 9,
  147542. 2,
  147543. 10,
  147544. 1,
  147545. 11,
  147546. 0,
  147547. 12,
  147548. };
  147549. static long _vq_lengthlist__44u2__p7_1[] = {
  147550. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147551. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147552. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147553. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147554. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147555. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147556. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147557. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147558. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147559. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147560. 14,14,14,17,15,17,17,17,17,
  147561. };
  147562. static float _vq_quantthresh__44u2__p7_1[] = {
  147563. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147564. 32.5, 45.5, 58.5, 71.5,
  147565. };
  147566. static long _vq_quantmap__44u2__p7_1[] = {
  147567. 11, 9, 7, 5, 3, 1, 0, 2,
  147568. 4, 6, 8, 10, 12,
  147569. };
  147570. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147571. _vq_quantthresh__44u2__p7_1,
  147572. _vq_quantmap__44u2__p7_1,
  147573. 13,
  147574. 13
  147575. };
  147576. static static_codebook _44u2__p7_1 = {
  147577. 2, 169,
  147578. _vq_lengthlist__44u2__p7_1,
  147579. 1, -523010048, 1618608128, 4, 0,
  147580. _vq_quantlist__44u2__p7_1,
  147581. NULL,
  147582. &_vq_auxt__44u2__p7_1,
  147583. NULL,
  147584. 0
  147585. };
  147586. static long _vq_quantlist__44u2__p7_2[] = {
  147587. 6,
  147588. 5,
  147589. 7,
  147590. 4,
  147591. 8,
  147592. 3,
  147593. 9,
  147594. 2,
  147595. 10,
  147596. 1,
  147597. 11,
  147598. 0,
  147599. 12,
  147600. };
  147601. static long _vq_lengthlist__44u2__p7_2[] = {
  147602. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147603. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147604. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147605. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147606. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147607. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147608. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147609. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147610. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147611. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147612. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147613. };
  147614. static float _vq_quantthresh__44u2__p7_2[] = {
  147615. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147616. 2.5, 3.5, 4.5, 5.5,
  147617. };
  147618. static long _vq_quantmap__44u2__p7_2[] = {
  147619. 11, 9, 7, 5, 3, 1, 0, 2,
  147620. 4, 6, 8, 10, 12,
  147621. };
  147622. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147623. _vq_quantthresh__44u2__p7_2,
  147624. _vq_quantmap__44u2__p7_2,
  147625. 13,
  147626. 13
  147627. };
  147628. static static_codebook _44u2__p7_2 = {
  147629. 2, 169,
  147630. _vq_lengthlist__44u2__p7_2,
  147631. 1, -531103744, 1611661312, 4, 0,
  147632. _vq_quantlist__44u2__p7_2,
  147633. NULL,
  147634. &_vq_auxt__44u2__p7_2,
  147635. NULL,
  147636. 0
  147637. };
  147638. static long _huff_lengthlist__44u2__short[] = {
  147639. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147640. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147641. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147642. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147643. };
  147644. static static_codebook _huff_book__44u2__short = {
  147645. 2, 64,
  147646. _huff_lengthlist__44u2__short,
  147647. 0, 0, 0, 0, 0,
  147648. NULL,
  147649. NULL,
  147650. NULL,
  147651. NULL,
  147652. 0
  147653. };
  147654. static long _huff_lengthlist__44u3__long[] = {
  147655. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147656. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147657. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147658. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147659. };
  147660. static static_codebook _huff_book__44u3__long = {
  147661. 2, 64,
  147662. _huff_lengthlist__44u3__long,
  147663. 0, 0, 0, 0, 0,
  147664. NULL,
  147665. NULL,
  147666. NULL,
  147667. NULL,
  147668. 0
  147669. };
  147670. static long _vq_quantlist__44u3__p1_0[] = {
  147671. 1,
  147672. 0,
  147673. 2,
  147674. };
  147675. static long _vq_lengthlist__44u3__p1_0[] = {
  147676. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147677. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147678. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147679. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147680. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147681. 13,
  147682. };
  147683. static float _vq_quantthresh__44u3__p1_0[] = {
  147684. -0.5, 0.5,
  147685. };
  147686. static long _vq_quantmap__44u3__p1_0[] = {
  147687. 1, 0, 2,
  147688. };
  147689. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147690. _vq_quantthresh__44u3__p1_0,
  147691. _vq_quantmap__44u3__p1_0,
  147692. 3,
  147693. 3
  147694. };
  147695. static static_codebook _44u3__p1_0 = {
  147696. 4, 81,
  147697. _vq_lengthlist__44u3__p1_0,
  147698. 1, -535822336, 1611661312, 2, 0,
  147699. _vq_quantlist__44u3__p1_0,
  147700. NULL,
  147701. &_vq_auxt__44u3__p1_0,
  147702. NULL,
  147703. 0
  147704. };
  147705. static long _vq_quantlist__44u3__p2_0[] = {
  147706. 1,
  147707. 0,
  147708. 2,
  147709. };
  147710. static long _vq_lengthlist__44u3__p2_0[] = {
  147711. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147712. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147713. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147714. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147715. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147716. 9,
  147717. };
  147718. static float _vq_quantthresh__44u3__p2_0[] = {
  147719. -0.5, 0.5,
  147720. };
  147721. static long _vq_quantmap__44u3__p2_0[] = {
  147722. 1, 0, 2,
  147723. };
  147724. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147725. _vq_quantthresh__44u3__p2_0,
  147726. _vq_quantmap__44u3__p2_0,
  147727. 3,
  147728. 3
  147729. };
  147730. static static_codebook _44u3__p2_0 = {
  147731. 4, 81,
  147732. _vq_lengthlist__44u3__p2_0,
  147733. 1, -535822336, 1611661312, 2, 0,
  147734. _vq_quantlist__44u3__p2_0,
  147735. NULL,
  147736. &_vq_auxt__44u3__p2_0,
  147737. NULL,
  147738. 0
  147739. };
  147740. static long _vq_quantlist__44u3__p3_0[] = {
  147741. 2,
  147742. 1,
  147743. 3,
  147744. 0,
  147745. 4,
  147746. };
  147747. static long _vq_lengthlist__44u3__p3_0[] = {
  147748. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147749. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147750. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147751. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147752. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147753. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147754. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147755. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147756. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147757. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147758. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147759. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147760. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147761. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147762. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147763. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147764. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147765. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147766. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147767. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147768. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147769. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147770. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147771. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147772. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147773. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147774. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147775. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147776. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147777. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147778. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147779. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147780. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147781. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147782. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147783. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147784. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147785. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147786. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147787. 0,
  147788. };
  147789. static float _vq_quantthresh__44u3__p3_0[] = {
  147790. -1.5, -0.5, 0.5, 1.5,
  147791. };
  147792. static long _vq_quantmap__44u3__p3_0[] = {
  147793. 3, 1, 0, 2, 4,
  147794. };
  147795. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147796. _vq_quantthresh__44u3__p3_0,
  147797. _vq_quantmap__44u3__p3_0,
  147798. 5,
  147799. 5
  147800. };
  147801. static static_codebook _44u3__p3_0 = {
  147802. 4, 625,
  147803. _vq_lengthlist__44u3__p3_0,
  147804. 1, -533725184, 1611661312, 3, 0,
  147805. _vq_quantlist__44u3__p3_0,
  147806. NULL,
  147807. &_vq_auxt__44u3__p3_0,
  147808. NULL,
  147809. 0
  147810. };
  147811. static long _vq_quantlist__44u3__p4_0[] = {
  147812. 2,
  147813. 1,
  147814. 3,
  147815. 0,
  147816. 4,
  147817. };
  147818. static long _vq_lengthlist__44u3__p4_0[] = {
  147819. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147820. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147821. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147822. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147823. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147824. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147825. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147826. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147827. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147828. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147829. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147830. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147831. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147832. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147833. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147834. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147835. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147836. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147837. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147838. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147839. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147840. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147841. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147842. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147843. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147844. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147845. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147846. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147847. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147848. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147849. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147850. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147851. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147852. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147853. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147854. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147855. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147856. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147857. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147858. 13,
  147859. };
  147860. static float _vq_quantthresh__44u3__p4_0[] = {
  147861. -1.5, -0.5, 0.5, 1.5,
  147862. };
  147863. static long _vq_quantmap__44u3__p4_0[] = {
  147864. 3, 1, 0, 2, 4,
  147865. };
  147866. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147867. _vq_quantthresh__44u3__p4_0,
  147868. _vq_quantmap__44u3__p4_0,
  147869. 5,
  147870. 5
  147871. };
  147872. static static_codebook _44u3__p4_0 = {
  147873. 4, 625,
  147874. _vq_lengthlist__44u3__p4_0,
  147875. 1, -533725184, 1611661312, 3, 0,
  147876. _vq_quantlist__44u3__p4_0,
  147877. NULL,
  147878. &_vq_auxt__44u3__p4_0,
  147879. NULL,
  147880. 0
  147881. };
  147882. static long _vq_quantlist__44u3__p5_0[] = {
  147883. 4,
  147884. 3,
  147885. 5,
  147886. 2,
  147887. 6,
  147888. 1,
  147889. 7,
  147890. 0,
  147891. 8,
  147892. };
  147893. static long _vq_lengthlist__44u3__p5_0[] = {
  147894. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147895. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147896. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147897. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147898. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147899. 12,
  147900. };
  147901. static float _vq_quantthresh__44u3__p5_0[] = {
  147902. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147903. };
  147904. static long _vq_quantmap__44u3__p5_0[] = {
  147905. 7, 5, 3, 1, 0, 2, 4, 6,
  147906. 8,
  147907. };
  147908. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147909. _vq_quantthresh__44u3__p5_0,
  147910. _vq_quantmap__44u3__p5_0,
  147911. 9,
  147912. 9
  147913. };
  147914. static static_codebook _44u3__p5_0 = {
  147915. 2, 81,
  147916. _vq_lengthlist__44u3__p5_0,
  147917. 1, -531628032, 1611661312, 4, 0,
  147918. _vq_quantlist__44u3__p5_0,
  147919. NULL,
  147920. &_vq_auxt__44u3__p5_0,
  147921. NULL,
  147922. 0
  147923. };
  147924. static long _vq_quantlist__44u3__p6_0[] = {
  147925. 6,
  147926. 5,
  147927. 7,
  147928. 4,
  147929. 8,
  147930. 3,
  147931. 9,
  147932. 2,
  147933. 10,
  147934. 1,
  147935. 11,
  147936. 0,
  147937. 12,
  147938. };
  147939. static long _vq_lengthlist__44u3__p6_0[] = {
  147940. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147941. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147942. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147943. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147944. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147945. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147946. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147947. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147948. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147949. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147950. 15,16,16,16,17,18,16,20,18,
  147951. };
  147952. static float _vq_quantthresh__44u3__p6_0[] = {
  147953. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147954. 12.5, 17.5, 22.5, 27.5,
  147955. };
  147956. static long _vq_quantmap__44u3__p6_0[] = {
  147957. 11, 9, 7, 5, 3, 1, 0, 2,
  147958. 4, 6, 8, 10, 12,
  147959. };
  147960. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147961. _vq_quantthresh__44u3__p6_0,
  147962. _vq_quantmap__44u3__p6_0,
  147963. 13,
  147964. 13
  147965. };
  147966. static static_codebook _44u3__p6_0 = {
  147967. 2, 169,
  147968. _vq_lengthlist__44u3__p6_0,
  147969. 1, -526516224, 1616117760, 4, 0,
  147970. _vq_quantlist__44u3__p6_0,
  147971. NULL,
  147972. &_vq_auxt__44u3__p6_0,
  147973. NULL,
  147974. 0
  147975. };
  147976. static long _vq_quantlist__44u3__p6_1[] = {
  147977. 2,
  147978. 1,
  147979. 3,
  147980. 0,
  147981. 4,
  147982. };
  147983. static long _vq_lengthlist__44u3__p6_1[] = {
  147984. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147985. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147986. };
  147987. static float _vq_quantthresh__44u3__p6_1[] = {
  147988. -1.5, -0.5, 0.5, 1.5,
  147989. };
  147990. static long _vq_quantmap__44u3__p6_1[] = {
  147991. 3, 1, 0, 2, 4,
  147992. };
  147993. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147994. _vq_quantthresh__44u3__p6_1,
  147995. _vq_quantmap__44u3__p6_1,
  147996. 5,
  147997. 5
  147998. };
  147999. static static_codebook _44u3__p6_1 = {
  148000. 2, 25,
  148001. _vq_lengthlist__44u3__p6_1,
  148002. 1, -533725184, 1611661312, 3, 0,
  148003. _vq_quantlist__44u3__p6_1,
  148004. NULL,
  148005. &_vq_auxt__44u3__p6_1,
  148006. NULL,
  148007. 0
  148008. };
  148009. static long _vq_quantlist__44u3__p7_0[] = {
  148010. 4,
  148011. 3,
  148012. 5,
  148013. 2,
  148014. 6,
  148015. 1,
  148016. 7,
  148017. 0,
  148018. 8,
  148019. };
  148020. static long _vq_lengthlist__44u3__p7_0[] = {
  148021. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148022. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148023. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148024. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148025. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148026. 9,
  148027. };
  148028. static float _vq_quantthresh__44u3__p7_0[] = {
  148029. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148030. };
  148031. static long _vq_quantmap__44u3__p7_0[] = {
  148032. 7, 5, 3, 1, 0, 2, 4, 6,
  148033. 8,
  148034. };
  148035. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148036. _vq_quantthresh__44u3__p7_0,
  148037. _vq_quantmap__44u3__p7_0,
  148038. 9,
  148039. 9
  148040. };
  148041. static static_codebook _44u3__p7_0 = {
  148042. 2, 81,
  148043. _vq_lengthlist__44u3__p7_0,
  148044. 1, -515907584, 1627381760, 4, 0,
  148045. _vq_quantlist__44u3__p7_0,
  148046. NULL,
  148047. &_vq_auxt__44u3__p7_0,
  148048. NULL,
  148049. 0
  148050. };
  148051. static long _vq_quantlist__44u3__p7_1[] = {
  148052. 7,
  148053. 6,
  148054. 8,
  148055. 5,
  148056. 9,
  148057. 4,
  148058. 10,
  148059. 3,
  148060. 11,
  148061. 2,
  148062. 12,
  148063. 1,
  148064. 13,
  148065. 0,
  148066. 14,
  148067. };
  148068. static long _vq_lengthlist__44u3__p7_1[] = {
  148069. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148070. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148071. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148072. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148073. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148074. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148075. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148076. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148077. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148078. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148079. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148080. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148081. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148082. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148083. 17,
  148084. };
  148085. static float _vq_quantthresh__44u3__p7_1[] = {
  148086. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148087. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148088. };
  148089. static long _vq_quantmap__44u3__p7_1[] = {
  148090. 13, 11, 9, 7, 5, 3, 1, 0,
  148091. 2, 4, 6, 8, 10, 12, 14,
  148092. };
  148093. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148094. _vq_quantthresh__44u3__p7_1,
  148095. _vq_quantmap__44u3__p7_1,
  148096. 15,
  148097. 15
  148098. };
  148099. static static_codebook _44u3__p7_1 = {
  148100. 2, 225,
  148101. _vq_lengthlist__44u3__p7_1,
  148102. 1, -522338304, 1620115456, 4, 0,
  148103. _vq_quantlist__44u3__p7_1,
  148104. NULL,
  148105. &_vq_auxt__44u3__p7_1,
  148106. NULL,
  148107. 0
  148108. };
  148109. static long _vq_quantlist__44u3__p7_2[] = {
  148110. 8,
  148111. 7,
  148112. 9,
  148113. 6,
  148114. 10,
  148115. 5,
  148116. 11,
  148117. 4,
  148118. 12,
  148119. 3,
  148120. 13,
  148121. 2,
  148122. 14,
  148123. 1,
  148124. 15,
  148125. 0,
  148126. 16,
  148127. };
  148128. static long _vq_lengthlist__44u3__p7_2[] = {
  148129. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148130. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148131. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148132. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148133. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148134. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148135. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148136. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148137. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148138. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148139. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148140. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148141. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148142. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148143. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148144. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148145. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148146. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148147. 11,
  148148. };
  148149. static float _vq_quantthresh__44u3__p7_2[] = {
  148150. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148151. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148152. };
  148153. static long _vq_quantmap__44u3__p7_2[] = {
  148154. 15, 13, 11, 9, 7, 5, 3, 1,
  148155. 0, 2, 4, 6, 8, 10, 12, 14,
  148156. 16,
  148157. };
  148158. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148159. _vq_quantthresh__44u3__p7_2,
  148160. _vq_quantmap__44u3__p7_2,
  148161. 17,
  148162. 17
  148163. };
  148164. static static_codebook _44u3__p7_2 = {
  148165. 2, 289,
  148166. _vq_lengthlist__44u3__p7_2,
  148167. 1, -529530880, 1611661312, 5, 0,
  148168. _vq_quantlist__44u3__p7_2,
  148169. NULL,
  148170. &_vq_auxt__44u3__p7_2,
  148171. NULL,
  148172. 0
  148173. };
  148174. static long _huff_lengthlist__44u3__short[] = {
  148175. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148176. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148177. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148178. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148179. };
  148180. static static_codebook _huff_book__44u3__short = {
  148181. 2, 64,
  148182. _huff_lengthlist__44u3__short,
  148183. 0, 0, 0, 0, 0,
  148184. NULL,
  148185. NULL,
  148186. NULL,
  148187. NULL,
  148188. 0
  148189. };
  148190. static long _huff_lengthlist__44u4__long[] = {
  148191. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148192. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148193. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148194. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148195. };
  148196. static static_codebook _huff_book__44u4__long = {
  148197. 2, 64,
  148198. _huff_lengthlist__44u4__long,
  148199. 0, 0, 0, 0, 0,
  148200. NULL,
  148201. NULL,
  148202. NULL,
  148203. NULL,
  148204. 0
  148205. };
  148206. static long _vq_quantlist__44u4__p1_0[] = {
  148207. 1,
  148208. 0,
  148209. 2,
  148210. };
  148211. static long _vq_lengthlist__44u4__p1_0[] = {
  148212. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148213. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148214. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148215. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148216. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148217. 13,
  148218. };
  148219. static float _vq_quantthresh__44u4__p1_0[] = {
  148220. -0.5, 0.5,
  148221. };
  148222. static long _vq_quantmap__44u4__p1_0[] = {
  148223. 1, 0, 2,
  148224. };
  148225. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148226. _vq_quantthresh__44u4__p1_0,
  148227. _vq_quantmap__44u4__p1_0,
  148228. 3,
  148229. 3
  148230. };
  148231. static static_codebook _44u4__p1_0 = {
  148232. 4, 81,
  148233. _vq_lengthlist__44u4__p1_0,
  148234. 1, -535822336, 1611661312, 2, 0,
  148235. _vq_quantlist__44u4__p1_0,
  148236. NULL,
  148237. &_vq_auxt__44u4__p1_0,
  148238. NULL,
  148239. 0
  148240. };
  148241. static long _vq_quantlist__44u4__p2_0[] = {
  148242. 1,
  148243. 0,
  148244. 2,
  148245. };
  148246. static long _vq_lengthlist__44u4__p2_0[] = {
  148247. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148248. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148249. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148250. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148251. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148252. 9,
  148253. };
  148254. static float _vq_quantthresh__44u4__p2_0[] = {
  148255. -0.5, 0.5,
  148256. };
  148257. static long _vq_quantmap__44u4__p2_0[] = {
  148258. 1, 0, 2,
  148259. };
  148260. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148261. _vq_quantthresh__44u4__p2_0,
  148262. _vq_quantmap__44u4__p2_0,
  148263. 3,
  148264. 3
  148265. };
  148266. static static_codebook _44u4__p2_0 = {
  148267. 4, 81,
  148268. _vq_lengthlist__44u4__p2_0,
  148269. 1, -535822336, 1611661312, 2, 0,
  148270. _vq_quantlist__44u4__p2_0,
  148271. NULL,
  148272. &_vq_auxt__44u4__p2_0,
  148273. NULL,
  148274. 0
  148275. };
  148276. static long _vq_quantlist__44u4__p3_0[] = {
  148277. 2,
  148278. 1,
  148279. 3,
  148280. 0,
  148281. 4,
  148282. };
  148283. static long _vq_lengthlist__44u4__p3_0[] = {
  148284. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148285. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148286. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148287. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148288. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148289. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148290. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148291. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148292. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148293. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148294. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148295. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148296. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148297. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148298. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148299. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148300. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148301. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148302. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148303. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148304. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148305. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148306. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148307. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148308. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148309. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148310. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148311. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148312. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148313. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148314. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148315. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148316. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148317. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148318. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148319. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148320. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148321. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148322. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148323. 0,
  148324. };
  148325. static float _vq_quantthresh__44u4__p3_0[] = {
  148326. -1.5, -0.5, 0.5, 1.5,
  148327. };
  148328. static long _vq_quantmap__44u4__p3_0[] = {
  148329. 3, 1, 0, 2, 4,
  148330. };
  148331. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148332. _vq_quantthresh__44u4__p3_0,
  148333. _vq_quantmap__44u4__p3_0,
  148334. 5,
  148335. 5
  148336. };
  148337. static static_codebook _44u4__p3_0 = {
  148338. 4, 625,
  148339. _vq_lengthlist__44u4__p3_0,
  148340. 1, -533725184, 1611661312, 3, 0,
  148341. _vq_quantlist__44u4__p3_0,
  148342. NULL,
  148343. &_vq_auxt__44u4__p3_0,
  148344. NULL,
  148345. 0
  148346. };
  148347. static long _vq_quantlist__44u4__p4_0[] = {
  148348. 2,
  148349. 1,
  148350. 3,
  148351. 0,
  148352. 4,
  148353. };
  148354. static long _vq_lengthlist__44u4__p4_0[] = {
  148355. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148356. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148357. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148358. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148359. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148360. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148361. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148362. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148363. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148364. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148365. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148366. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148367. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148368. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148369. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148370. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148371. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148372. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148373. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148374. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148375. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148376. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148377. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148378. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148379. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148380. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148381. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148382. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148383. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148384. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148385. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148386. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148387. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148388. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148389. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148390. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148391. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148392. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148393. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148394. 13,
  148395. };
  148396. static float _vq_quantthresh__44u4__p4_0[] = {
  148397. -1.5, -0.5, 0.5, 1.5,
  148398. };
  148399. static long _vq_quantmap__44u4__p4_0[] = {
  148400. 3, 1, 0, 2, 4,
  148401. };
  148402. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148403. _vq_quantthresh__44u4__p4_0,
  148404. _vq_quantmap__44u4__p4_0,
  148405. 5,
  148406. 5
  148407. };
  148408. static static_codebook _44u4__p4_0 = {
  148409. 4, 625,
  148410. _vq_lengthlist__44u4__p4_0,
  148411. 1, -533725184, 1611661312, 3, 0,
  148412. _vq_quantlist__44u4__p4_0,
  148413. NULL,
  148414. &_vq_auxt__44u4__p4_0,
  148415. NULL,
  148416. 0
  148417. };
  148418. static long _vq_quantlist__44u4__p5_0[] = {
  148419. 4,
  148420. 3,
  148421. 5,
  148422. 2,
  148423. 6,
  148424. 1,
  148425. 7,
  148426. 0,
  148427. 8,
  148428. };
  148429. static long _vq_lengthlist__44u4__p5_0[] = {
  148430. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148431. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148432. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148433. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148434. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148435. 12,
  148436. };
  148437. static float _vq_quantthresh__44u4__p5_0[] = {
  148438. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148439. };
  148440. static long _vq_quantmap__44u4__p5_0[] = {
  148441. 7, 5, 3, 1, 0, 2, 4, 6,
  148442. 8,
  148443. };
  148444. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148445. _vq_quantthresh__44u4__p5_0,
  148446. _vq_quantmap__44u4__p5_0,
  148447. 9,
  148448. 9
  148449. };
  148450. static static_codebook _44u4__p5_0 = {
  148451. 2, 81,
  148452. _vq_lengthlist__44u4__p5_0,
  148453. 1, -531628032, 1611661312, 4, 0,
  148454. _vq_quantlist__44u4__p5_0,
  148455. NULL,
  148456. &_vq_auxt__44u4__p5_0,
  148457. NULL,
  148458. 0
  148459. };
  148460. static long _vq_quantlist__44u4__p6_0[] = {
  148461. 6,
  148462. 5,
  148463. 7,
  148464. 4,
  148465. 8,
  148466. 3,
  148467. 9,
  148468. 2,
  148469. 10,
  148470. 1,
  148471. 11,
  148472. 0,
  148473. 12,
  148474. };
  148475. static long _vq_lengthlist__44u4__p6_0[] = {
  148476. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148477. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148478. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148479. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148480. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148481. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148482. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148483. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148484. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148485. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148486. 16,16,16,17,17,18,17,20,21,
  148487. };
  148488. static float _vq_quantthresh__44u4__p6_0[] = {
  148489. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148490. 12.5, 17.5, 22.5, 27.5,
  148491. };
  148492. static long _vq_quantmap__44u4__p6_0[] = {
  148493. 11, 9, 7, 5, 3, 1, 0, 2,
  148494. 4, 6, 8, 10, 12,
  148495. };
  148496. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148497. _vq_quantthresh__44u4__p6_0,
  148498. _vq_quantmap__44u4__p6_0,
  148499. 13,
  148500. 13
  148501. };
  148502. static static_codebook _44u4__p6_0 = {
  148503. 2, 169,
  148504. _vq_lengthlist__44u4__p6_0,
  148505. 1, -526516224, 1616117760, 4, 0,
  148506. _vq_quantlist__44u4__p6_0,
  148507. NULL,
  148508. &_vq_auxt__44u4__p6_0,
  148509. NULL,
  148510. 0
  148511. };
  148512. static long _vq_quantlist__44u4__p6_1[] = {
  148513. 2,
  148514. 1,
  148515. 3,
  148516. 0,
  148517. 4,
  148518. };
  148519. static long _vq_lengthlist__44u4__p6_1[] = {
  148520. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148521. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148522. };
  148523. static float _vq_quantthresh__44u4__p6_1[] = {
  148524. -1.5, -0.5, 0.5, 1.5,
  148525. };
  148526. static long _vq_quantmap__44u4__p6_1[] = {
  148527. 3, 1, 0, 2, 4,
  148528. };
  148529. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148530. _vq_quantthresh__44u4__p6_1,
  148531. _vq_quantmap__44u4__p6_1,
  148532. 5,
  148533. 5
  148534. };
  148535. static static_codebook _44u4__p6_1 = {
  148536. 2, 25,
  148537. _vq_lengthlist__44u4__p6_1,
  148538. 1, -533725184, 1611661312, 3, 0,
  148539. _vq_quantlist__44u4__p6_1,
  148540. NULL,
  148541. &_vq_auxt__44u4__p6_1,
  148542. NULL,
  148543. 0
  148544. };
  148545. static long _vq_quantlist__44u4__p7_0[] = {
  148546. 6,
  148547. 5,
  148548. 7,
  148549. 4,
  148550. 8,
  148551. 3,
  148552. 9,
  148553. 2,
  148554. 10,
  148555. 1,
  148556. 11,
  148557. 0,
  148558. 12,
  148559. };
  148560. static long _vq_lengthlist__44u4__p7_0[] = {
  148561. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148562. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148563. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148564. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148565. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148566. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148567. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148568. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148569. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148570. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148571. 11,11,11,11,11,11,11,11,11,
  148572. };
  148573. static float _vq_quantthresh__44u4__p7_0[] = {
  148574. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148575. 637.5, 892.5, 1147.5, 1402.5,
  148576. };
  148577. static long _vq_quantmap__44u4__p7_0[] = {
  148578. 11, 9, 7, 5, 3, 1, 0, 2,
  148579. 4, 6, 8, 10, 12,
  148580. };
  148581. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148582. _vq_quantthresh__44u4__p7_0,
  148583. _vq_quantmap__44u4__p7_0,
  148584. 13,
  148585. 13
  148586. };
  148587. static static_codebook _44u4__p7_0 = {
  148588. 2, 169,
  148589. _vq_lengthlist__44u4__p7_0,
  148590. 1, -514332672, 1627381760, 4, 0,
  148591. _vq_quantlist__44u4__p7_0,
  148592. NULL,
  148593. &_vq_auxt__44u4__p7_0,
  148594. NULL,
  148595. 0
  148596. };
  148597. static long _vq_quantlist__44u4__p7_1[] = {
  148598. 7,
  148599. 6,
  148600. 8,
  148601. 5,
  148602. 9,
  148603. 4,
  148604. 10,
  148605. 3,
  148606. 11,
  148607. 2,
  148608. 12,
  148609. 1,
  148610. 13,
  148611. 0,
  148612. 14,
  148613. };
  148614. static long _vq_lengthlist__44u4__p7_1[] = {
  148615. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148616. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148617. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148618. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148619. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148620. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148621. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148622. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148623. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148624. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148625. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148626. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148627. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148628. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148629. 16,
  148630. };
  148631. static float _vq_quantthresh__44u4__p7_1[] = {
  148632. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148633. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148634. };
  148635. static long _vq_quantmap__44u4__p7_1[] = {
  148636. 13, 11, 9, 7, 5, 3, 1, 0,
  148637. 2, 4, 6, 8, 10, 12, 14,
  148638. };
  148639. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148640. _vq_quantthresh__44u4__p7_1,
  148641. _vq_quantmap__44u4__p7_1,
  148642. 15,
  148643. 15
  148644. };
  148645. static static_codebook _44u4__p7_1 = {
  148646. 2, 225,
  148647. _vq_lengthlist__44u4__p7_1,
  148648. 1, -522338304, 1620115456, 4, 0,
  148649. _vq_quantlist__44u4__p7_1,
  148650. NULL,
  148651. &_vq_auxt__44u4__p7_1,
  148652. NULL,
  148653. 0
  148654. };
  148655. static long _vq_quantlist__44u4__p7_2[] = {
  148656. 8,
  148657. 7,
  148658. 9,
  148659. 6,
  148660. 10,
  148661. 5,
  148662. 11,
  148663. 4,
  148664. 12,
  148665. 3,
  148666. 13,
  148667. 2,
  148668. 14,
  148669. 1,
  148670. 15,
  148671. 0,
  148672. 16,
  148673. };
  148674. static long _vq_lengthlist__44u4__p7_2[] = {
  148675. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148676. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148677. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148678. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148679. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148680. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148681. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148682. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148683. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148684. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148685. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148686. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148687. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148688. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148689. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148690. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148691. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148692. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148693. 10,
  148694. };
  148695. static float _vq_quantthresh__44u4__p7_2[] = {
  148696. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148697. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148698. };
  148699. static long _vq_quantmap__44u4__p7_2[] = {
  148700. 15, 13, 11, 9, 7, 5, 3, 1,
  148701. 0, 2, 4, 6, 8, 10, 12, 14,
  148702. 16,
  148703. };
  148704. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148705. _vq_quantthresh__44u4__p7_2,
  148706. _vq_quantmap__44u4__p7_2,
  148707. 17,
  148708. 17
  148709. };
  148710. static static_codebook _44u4__p7_2 = {
  148711. 2, 289,
  148712. _vq_lengthlist__44u4__p7_2,
  148713. 1, -529530880, 1611661312, 5, 0,
  148714. _vq_quantlist__44u4__p7_2,
  148715. NULL,
  148716. &_vq_auxt__44u4__p7_2,
  148717. NULL,
  148718. 0
  148719. };
  148720. static long _huff_lengthlist__44u4__short[] = {
  148721. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148722. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148723. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148724. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148725. };
  148726. static static_codebook _huff_book__44u4__short = {
  148727. 2, 64,
  148728. _huff_lengthlist__44u4__short,
  148729. 0, 0, 0, 0, 0,
  148730. NULL,
  148731. NULL,
  148732. NULL,
  148733. NULL,
  148734. 0
  148735. };
  148736. static long _huff_lengthlist__44u5__long[] = {
  148737. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148738. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148739. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148740. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148741. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148742. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148743. 14, 8, 7, 8,
  148744. };
  148745. static static_codebook _huff_book__44u5__long = {
  148746. 2, 100,
  148747. _huff_lengthlist__44u5__long,
  148748. 0, 0, 0, 0, 0,
  148749. NULL,
  148750. NULL,
  148751. NULL,
  148752. NULL,
  148753. 0
  148754. };
  148755. static long _vq_quantlist__44u5__p1_0[] = {
  148756. 1,
  148757. 0,
  148758. 2,
  148759. };
  148760. static long _vq_lengthlist__44u5__p1_0[] = {
  148761. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148762. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148763. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148764. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148765. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148766. 12,
  148767. };
  148768. static float _vq_quantthresh__44u5__p1_0[] = {
  148769. -0.5, 0.5,
  148770. };
  148771. static long _vq_quantmap__44u5__p1_0[] = {
  148772. 1, 0, 2,
  148773. };
  148774. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148775. _vq_quantthresh__44u5__p1_0,
  148776. _vq_quantmap__44u5__p1_0,
  148777. 3,
  148778. 3
  148779. };
  148780. static static_codebook _44u5__p1_0 = {
  148781. 4, 81,
  148782. _vq_lengthlist__44u5__p1_0,
  148783. 1, -535822336, 1611661312, 2, 0,
  148784. _vq_quantlist__44u5__p1_0,
  148785. NULL,
  148786. &_vq_auxt__44u5__p1_0,
  148787. NULL,
  148788. 0
  148789. };
  148790. static long _vq_quantlist__44u5__p2_0[] = {
  148791. 1,
  148792. 0,
  148793. 2,
  148794. };
  148795. static long _vq_lengthlist__44u5__p2_0[] = {
  148796. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148797. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148798. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148799. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148800. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148801. 9,
  148802. };
  148803. static float _vq_quantthresh__44u5__p2_0[] = {
  148804. -0.5, 0.5,
  148805. };
  148806. static long _vq_quantmap__44u5__p2_0[] = {
  148807. 1, 0, 2,
  148808. };
  148809. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148810. _vq_quantthresh__44u5__p2_0,
  148811. _vq_quantmap__44u5__p2_0,
  148812. 3,
  148813. 3
  148814. };
  148815. static static_codebook _44u5__p2_0 = {
  148816. 4, 81,
  148817. _vq_lengthlist__44u5__p2_0,
  148818. 1, -535822336, 1611661312, 2, 0,
  148819. _vq_quantlist__44u5__p2_0,
  148820. NULL,
  148821. &_vq_auxt__44u5__p2_0,
  148822. NULL,
  148823. 0
  148824. };
  148825. static long _vq_quantlist__44u5__p3_0[] = {
  148826. 2,
  148827. 1,
  148828. 3,
  148829. 0,
  148830. 4,
  148831. };
  148832. static long _vq_lengthlist__44u5__p3_0[] = {
  148833. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148834. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148835. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148836. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148837. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148838. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148839. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148840. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148841. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148842. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148843. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148844. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148845. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148846. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148847. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148848. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148849. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148850. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148851. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148852. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148853. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148854. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148855. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148856. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148857. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148858. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148859. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148860. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148861. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148862. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148863. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148864. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148865. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148866. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148867. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148868. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148869. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148870. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148871. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148872. 0,
  148873. };
  148874. static float _vq_quantthresh__44u5__p3_0[] = {
  148875. -1.5, -0.5, 0.5, 1.5,
  148876. };
  148877. static long _vq_quantmap__44u5__p3_0[] = {
  148878. 3, 1, 0, 2, 4,
  148879. };
  148880. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148881. _vq_quantthresh__44u5__p3_0,
  148882. _vq_quantmap__44u5__p3_0,
  148883. 5,
  148884. 5
  148885. };
  148886. static static_codebook _44u5__p3_0 = {
  148887. 4, 625,
  148888. _vq_lengthlist__44u5__p3_0,
  148889. 1, -533725184, 1611661312, 3, 0,
  148890. _vq_quantlist__44u5__p3_0,
  148891. NULL,
  148892. &_vq_auxt__44u5__p3_0,
  148893. NULL,
  148894. 0
  148895. };
  148896. static long _vq_quantlist__44u5__p4_0[] = {
  148897. 2,
  148898. 1,
  148899. 3,
  148900. 0,
  148901. 4,
  148902. };
  148903. static long _vq_lengthlist__44u5__p4_0[] = {
  148904. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148905. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148906. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148907. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148908. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148909. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148910. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148911. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148912. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148913. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148914. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148915. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148916. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148917. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148918. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148919. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148920. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148921. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148922. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148923. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148924. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148925. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148926. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148927. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148928. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148929. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148930. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148931. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148932. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148933. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148934. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148935. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148936. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148937. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148938. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148939. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148940. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148941. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148942. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148943. 12,
  148944. };
  148945. static float _vq_quantthresh__44u5__p4_0[] = {
  148946. -1.5, -0.5, 0.5, 1.5,
  148947. };
  148948. static long _vq_quantmap__44u5__p4_0[] = {
  148949. 3, 1, 0, 2, 4,
  148950. };
  148951. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148952. _vq_quantthresh__44u5__p4_0,
  148953. _vq_quantmap__44u5__p4_0,
  148954. 5,
  148955. 5
  148956. };
  148957. static static_codebook _44u5__p4_0 = {
  148958. 4, 625,
  148959. _vq_lengthlist__44u5__p4_0,
  148960. 1, -533725184, 1611661312, 3, 0,
  148961. _vq_quantlist__44u5__p4_0,
  148962. NULL,
  148963. &_vq_auxt__44u5__p4_0,
  148964. NULL,
  148965. 0
  148966. };
  148967. static long _vq_quantlist__44u5__p5_0[] = {
  148968. 4,
  148969. 3,
  148970. 5,
  148971. 2,
  148972. 6,
  148973. 1,
  148974. 7,
  148975. 0,
  148976. 8,
  148977. };
  148978. static long _vq_lengthlist__44u5__p5_0[] = {
  148979. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148980. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148981. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148982. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148983. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148984. 14,
  148985. };
  148986. static float _vq_quantthresh__44u5__p5_0[] = {
  148987. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148988. };
  148989. static long _vq_quantmap__44u5__p5_0[] = {
  148990. 7, 5, 3, 1, 0, 2, 4, 6,
  148991. 8,
  148992. };
  148993. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148994. _vq_quantthresh__44u5__p5_0,
  148995. _vq_quantmap__44u5__p5_0,
  148996. 9,
  148997. 9
  148998. };
  148999. static static_codebook _44u5__p5_0 = {
  149000. 2, 81,
  149001. _vq_lengthlist__44u5__p5_0,
  149002. 1, -531628032, 1611661312, 4, 0,
  149003. _vq_quantlist__44u5__p5_0,
  149004. NULL,
  149005. &_vq_auxt__44u5__p5_0,
  149006. NULL,
  149007. 0
  149008. };
  149009. static long _vq_quantlist__44u5__p6_0[] = {
  149010. 4,
  149011. 3,
  149012. 5,
  149013. 2,
  149014. 6,
  149015. 1,
  149016. 7,
  149017. 0,
  149018. 8,
  149019. };
  149020. static long _vq_lengthlist__44u5__p6_0[] = {
  149021. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149022. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149023. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149024. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149025. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149026. 11,
  149027. };
  149028. static float _vq_quantthresh__44u5__p6_0[] = {
  149029. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149030. };
  149031. static long _vq_quantmap__44u5__p6_0[] = {
  149032. 7, 5, 3, 1, 0, 2, 4, 6,
  149033. 8,
  149034. };
  149035. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149036. _vq_quantthresh__44u5__p6_0,
  149037. _vq_quantmap__44u5__p6_0,
  149038. 9,
  149039. 9
  149040. };
  149041. static static_codebook _44u5__p6_0 = {
  149042. 2, 81,
  149043. _vq_lengthlist__44u5__p6_0,
  149044. 1, -531628032, 1611661312, 4, 0,
  149045. _vq_quantlist__44u5__p6_0,
  149046. NULL,
  149047. &_vq_auxt__44u5__p6_0,
  149048. NULL,
  149049. 0
  149050. };
  149051. static long _vq_quantlist__44u5__p7_0[] = {
  149052. 1,
  149053. 0,
  149054. 2,
  149055. };
  149056. static long _vq_lengthlist__44u5__p7_0[] = {
  149057. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149058. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149059. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149060. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149061. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149062. 12,
  149063. };
  149064. static float _vq_quantthresh__44u5__p7_0[] = {
  149065. -5.5, 5.5,
  149066. };
  149067. static long _vq_quantmap__44u5__p7_0[] = {
  149068. 1, 0, 2,
  149069. };
  149070. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149071. _vq_quantthresh__44u5__p7_0,
  149072. _vq_quantmap__44u5__p7_0,
  149073. 3,
  149074. 3
  149075. };
  149076. static static_codebook _44u5__p7_0 = {
  149077. 4, 81,
  149078. _vq_lengthlist__44u5__p7_0,
  149079. 1, -529137664, 1618345984, 2, 0,
  149080. _vq_quantlist__44u5__p7_0,
  149081. NULL,
  149082. &_vq_auxt__44u5__p7_0,
  149083. NULL,
  149084. 0
  149085. };
  149086. static long _vq_quantlist__44u5__p7_1[] = {
  149087. 5,
  149088. 4,
  149089. 6,
  149090. 3,
  149091. 7,
  149092. 2,
  149093. 8,
  149094. 1,
  149095. 9,
  149096. 0,
  149097. 10,
  149098. };
  149099. static long _vq_lengthlist__44u5__p7_1[] = {
  149100. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149101. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149102. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149103. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149104. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149105. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149106. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149107. 9, 9, 9, 9, 9,10,10,10,10,
  149108. };
  149109. static float _vq_quantthresh__44u5__p7_1[] = {
  149110. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149111. 3.5, 4.5,
  149112. };
  149113. static long _vq_quantmap__44u5__p7_1[] = {
  149114. 9, 7, 5, 3, 1, 0, 2, 4,
  149115. 6, 8, 10,
  149116. };
  149117. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149118. _vq_quantthresh__44u5__p7_1,
  149119. _vq_quantmap__44u5__p7_1,
  149120. 11,
  149121. 11
  149122. };
  149123. static static_codebook _44u5__p7_1 = {
  149124. 2, 121,
  149125. _vq_lengthlist__44u5__p7_1,
  149126. 1, -531365888, 1611661312, 4, 0,
  149127. _vq_quantlist__44u5__p7_1,
  149128. NULL,
  149129. &_vq_auxt__44u5__p7_1,
  149130. NULL,
  149131. 0
  149132. };
  149133. static long _vq_quantlist__44u5__p8_0[] = {
  149134. 5,
  149135. 4,
  149136. 6,
  149137. 3,
  149138. 7,
  149139. 2,
  149140. 8,
  149141. 1,
  149142. 9,
  149143. 0,
  149144. 10,
  149145. };
  149146. static long _vq_lengthlist__44u5__p8_0[] = {
  149147. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149148. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149149. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149150. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149151. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149152. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149153. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149154. 12,13,13,14,14,14,14,15,15,
  149155. };
  149156. static float _vq_quantthresh__44u5__p8_0[] = {
  149157. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149158. 38.5, 49.5,
  149159. };
  149160. static long _vq_quantmap__44u5__p8_0[] = {
  149161. 9, 7, 5, 3, 1, 0, 2, 4,
  149162. 6, 8, 10,
  149163. };
  149164. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149165. _vq_quantthresh__44u5__p8_0,
  149166. _vq_quantmap__44u5__p8_0,
  149167. 11,
  149168. 11
  149169. };
  149170. static static_codebook _44u5__p8_0 = {
  149171. 2, 121,
  149172. _vq_lengthlist__44u5__p8_0,
  149173. 1, -524582912, 1618345984, 4, 0,
  149174. _vq_quantlist__44u5__p8_0,
  149175. NULL,
  149176. &_vq_auxt__44u5__p8_0,
  149177. NULL,
  149178. 0
  149179. };
  149180. static long _vq_quantlist__44u5__p8_1[] = {
  149181. 5,
  149182. 4,
  149183. 6,
  149184. 3,
  149185. 7,
  149186. 2,
  149187. 8,
  149188. 1,
  149189. 9,
  149190. 0,
  149191. 10,
  149192. };
  149193. static long _vq_lengthlist__44u5__p8_1[] = {
  149194. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149195. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149196. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149197. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149198. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149199. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149200. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149201. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149202. };
  149203. static float _vq_quantthresh__44u5__p8_1[] = {
  149204. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149205. 3.5, 4.5,
  149206. };
  149207. static long _vq_quantmap__44u5__p8_1[] = {
  149208. 9, 7, 5, 3, 1, 0, 2, 4,
  149209. 6, 8, 10,
  149210. };
  149211. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149212. _vq_quantthresh__44u5__p8_1,
  149213. _vq_quantmap__44u5__p8_1,
  149214. 11,
  149215. 11
  149216. };
  149217. static static_codebook _44u5__p8_1 = {
  149218. 2, 121,
  149219. _vq_lengthlist__44u5__p8_1,
  149220. 1, -531365888, 1611661312, 4, 0,
  149221. _vq_quantlist__44u5__p8_1,
  149222. NULL,
  149223. &_vq_auxt__44u5__p8_1,
  149224. NULL,
  149225. 0
  149226. };
  149227. static long _vq_quantlist__44u5__p9_0[] = {
  149228. 6,
  149229. 5,
  149230. 7,
  149231. 4,
  149232. 8,
  149233. 3,
  149234. 9,
  149235. 2,
  149236. 10,
  149237. 1,
  149238. 11,
  149239. 0,
  149240. 12,
  149241. };
  149242. static long _vq_lengthlist__44u5__p9_0[] = {
  149243. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149244. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149245. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149246. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149247. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149248. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149249. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149250. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149251. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149252. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149253. 12,12,12,12,12,12,12,12,12,
  149254. };
  149255. static float _vq_quantthresh__44u5__p9_0[] = {
  149256. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149257. 637.5, 892.5, 1147.5, 1402.5,
  149258. };
  149259. static long _vq_quantmap__44u5__p9_0[] = {
  149260. 11, 9, 7, 5, 3, 1, 0, 2,
  149261. 4, 6, 8, 10, 12,
  149262. };
  149263. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149264. _vq_quantthresh__44u5__p9_0,
  149265. _vq_quantmap__44u5__p9_0,
  149266. 13,
  149267. 13
  149268. };
  149269. static static_codebook _44u5__p9_0 = {
  149270. 2, 169,
  149271. _vq_lengthlist__44u5__p9_0,
  149272. 1, -514332672, 1627381760, 4, 0,
  149273. _vq_quantlist__44u5__p9_0,
  149274. NULL,
  149275. &_vq_auxt__44u5__p9_0,
  149276. NULL,
  149277. 0
  149278. };
  149279. static long _vq_quantlist__44u5__p9_1[] = {
  149280. 7,
  149281. 6,
  149282. 8,
  149283. 5,
  149284. 9,
  149285. 4,
  149286. 10,
  149287. 3,
  149288. 11,
  149289. 2,
  149290. 12,
  149291. 1,
  149292. 13,
  149293. 0,
  149294. 14,
  149295. };
  149296. static long _vq_lengthlist__44u5__p9_1[] = {
  149297. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149298. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149299. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149300. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149301. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149302. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149303. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149304. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149305. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149306. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149307. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149308. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149309. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149310. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149311. 14,
  149312. };
  149313. static float _vq_quantthresh__44u5__p9_1[] = {
  149314. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149315. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149316. };
  149317. static long _vq_quantmap__44u5__p9_1[] = {
  149318. 13, 11, 9, 7, 5, 3, 1, 0,
  149319. 2, 4, 6, 8, 10, 12, 14,
  149320. };
  149321. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149322. _vq_quantthresh__44u5__p9_1,
  149323. _vq_quantmap__44u5__p9_1,
  149324. 15,
  149325. 15
  149326. };
  149327. static static_codebook _44u5__p9_1 = {
  149328. 2, 225,
  149329. _vq_lengthlist__44u5__p9_1,
  149330. 1, -522338304, 1620115456, 4, 0,
  149331. _vq_quantlist__44u5__p9_1,
  149332. NULL,
  149333. &_vq_auxt__44u5__p9_1,
  149334. NULL,
  149335. 0
  149336. };
  149337. static long _vq_quantlist__44u5__p9_2[] = {
  149338. 8,
  149339. 7,
  149340. 9,
  149341. 6,
  149342. 10,
  149343. 5,
  149344. 11,
  149345. 4,
  149346. 12,
  149347. 3,
  149348. 13,
  149349. 2,
  149350. 14,
  149351. 1,
  149352. 15,
  149353. 0,
  149354. 16,
  149355. };
  149356. static long _vq_lengthlist__44u5__p9_2[] = {
  149357. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149358. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149359. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149360. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149361. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149362. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149363. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149364. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149365. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149366. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149367. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149368. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149369. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149370. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149371. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149372. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149373. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149374. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149375. 10,
  149376. };
  149377. static float _vq_quantthresh__44u5__p9_2[] = {
  149378. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149379. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149380. };
  149381. static long _vq_quantmap__44u5__p9_2[] = {
  149382. 15, 13, 11, 9, 7, 5, 3, 1,
  149383. 0, 2, 4, 6, 8, 10, 12, 14,
  149384. 16,
  149385. };
  149386. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149387. _vq_quantthresh__44u5__p9_2,
  149388. _vq_quantmap__44u5__p9_2,
  149389. 17,
  149390. 17
  149391. };
  149392. static static_codebook _44u5__p9_2 = {
  149393. 2, 289,
  149394. _vq_lengthlist__44u5__p9_2,
  149395. 1, -529530880, 1611661312, 5, 0,
  149396. _vq_quantlist__44u5__p9_2,
  149397. NULL,
  149398. &_vq_auxt__44u5__p9_2,
  149399. NULL,
  149400. 0
  149401. };
  149402. static long _huff_lengthlist__44u5__short[] = {
  149403. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149404. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149405. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149406. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149407. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149408. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149409. 6, 8,15,17,
  149410. };
  149411. static static_codebook _huff_book__44u5__short = {
  149412. 2, 100,
  149413. _huff_lengthlist__44u5__short,
  149414. 0, 0, 0, 0, 0,
  149415. NULL,
  149416. NULL,
  149417. NULL,
  149418. NULL,
  149419. 0
  149420. };
  149421. static long _huff_lengthlist__44u6__long[] = {
  149422. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149423. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149424. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149425. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149426. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149427. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149428. 13, 8, 7, 7,
  149429. };
  149430. static static_codebook _huff_book__44u6__long = {
  149431. 2, 100,
  149432. _huff_lengthlist__44u6__long,
  149433. 0, 0, 0, 0, 0,
  149434. NULL,
  149435. NULL,
  149436. NULL,
  149437. NULL,
  149438. 0
  149439. };
  149440. static long _vq_quantlist__44u6__p1_0[] = {
  149441. 1,
  149442. 0,
  149443. 2,
  149444. };
  149445. static long _vq_lengthlist__44u6__p1_0[] = {
  149446. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149447. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149448. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149449. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149450. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149451. 12,
  149452. };
  149453. static float _vq_quantthresh__44u6__p1_0[] = {
  149454. -0.5, 0.5,
  149455. };
  149456. static long _vq_quantmap__44u6__p1_0[] = {
  149457. 1, 0, 2,
  149458. };
  149459. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149460. _vq_quantthresh__44u6__p1_0,
  149461. _vq_quantmap__44u6__p1_0,
  149462. 3,
  149463. 3
  149464. };
  149465. static static_codebook _44u6__p1_0 = {
  149466. 4, 81,
  149467. _vq_lengthlist__44u6__p1_0,
  149468. 1, -535822336, 1611661312, 2, 0,
  149469. _vq_quantlist__44u6__p1_0,
  149470. NULL,
  149471. &_vq_auxt__44u6__p1_0,
  149472. NULL,
  149473. 0
  149474. };
  149475. static long _vq_quantlist__44u6__p2_0[] = {
  149476. 1,
  149477. 0,
  149478. 2,
  149479. };
  149480. static long _vq_lengthlist__44u6__p2_0[] = {
  149481. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149482. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149483. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149484. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149485. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149486. 9,
  149487. };
  149488. static float _vq_quantthresh__44u6__p2_0[] = {
  149489. -0.5, 0.5,
  149490. };
  149491. static long _vq_quantmap__44u6__p2_0[] = {
  149492. 1, 0, 2,
  149493. };
  149494. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149495. _vq_quantthresh__44u6__p2_0,
  149496. _vq_quantmap__44u6__p2_0,
  149497. 3,
  149498. 3
  149499. };
  149500. static static_codebook _44u6__p2_0 = {
  149501. 4, 81,
  149502. _vq_lengthlist__44u6__p2_0,
  149503. 1, -535822336, 1611661312, 2, 0,
  149504. _vq_quantlist__44u6__p2_0,
  149505. NULL,
  149506. &_vq_auxt__44u6__p2_0,
  149507. NULL,
  149508. 0
  149509. };
  149510. static long _vq_quantlist__44u6__p3_0[] = {
  149511. 2,
  149512. 1,
  149513. 3,
  149514. 0,
  149515. 4,
  149516. };
  149517. static long _vq_lengthlist__44u6__p3_0[] = {
  149518. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149519. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149520. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149521. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149522. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149523. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149524. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149525. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149526. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149527. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149528. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149529. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149530. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149531. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149532. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149533. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149534. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149535. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149536. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149537. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149538. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149539. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149540. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149541. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149542. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149543. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149544. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149545. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149546. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149547. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149548. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149549. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149550. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149551. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149552. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149553. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149554. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149555. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149556. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149557. 19,
  149558. };
  149559. static float _vq_quantthresh__44u6__p3_0[] = {
  149560. -1.5, -0.5, 0.5, 1.5,
  149561. };
  149562. static long _vq_quantmap__44u6__p3_0[] = {
  149563. 3, 1, 0, 2, 4,
  149564. };
  149565. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149566. _vq_quantthresh__44u6__p3_0,
  149567. _vq_quantmap__44u6__p3_0,
  149568. 5,
  149569. 5
  149570. };
  149571. static static_codebook _44u6__p3_0 = {
  149572. 4, 625,
  149573. _vq_lengthlist__44u6__p3_0,
  149574. 1, -533725184, 1611661312, 3, 0,
  149575. _vq_quantlist__44u6__p3_0,
  149576. NULL,
  149577. &_vq_auxt__44u6__p3_0,
  149578. NULL,
  149579. 0
  149580. };
  149581. static long _vq_quantlist__44u6__p4_0[] = {
  149582. 2,
  149583. 1,
  149584. 3,
  149585. 0,
  149586. 4,
  149587. };
  149588. static long _vq_lengthlist__44u6__p4_0[] = {
  149589. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149590. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149591. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149592. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149593. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149594. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149595. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149596. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149597. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149598. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149599. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149600. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149601. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149602. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149603. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149604. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149605. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149606. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149607. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149608. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149609. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149610. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149611. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149612. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149613. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149614. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149615. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149616. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149617. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149618. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149619. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149620. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149621. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149622. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149623. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149624. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149625. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149626. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149627. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149628. 13,
  149629. };
  149630. static float _vq_quantthresh__44u6__p4_0[] = {
  149631. -1.5, -0.5, 0.5, 1.5,
  149632. };
  149633. static long _vq_quantmap__44u6__p4_0[] = {
  149634. 3, 1, 0, 2, 4,
  149635. };
  149636. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149637. _vq_quantthresh__44u6__p4_0,
  149638. _vq_quantmap__44u6__p4_0,
  149639. 5,
  149640. 5
  149641. };
  149642. static static_codebook _44u6__p4_0 = {
  149643. 4, 625,
  149644. _vq_lengthlist__44u6__p4_0,
  149645. 1, -533725184, 1611661312, 3, 0,
  149646. _vq_quantlist__44u6__p4_0,
  149647. NULL,
  149648. &_vq_auxt__44u6__p4_0,
  149649. NULL,
  149650. 0
  149651. };
  149652. static long _vq_quantlist__44u6__p5_0[] = {
  149653. 4,
  149654. 3,
  149655. 5,
  149656. 2,
  149657. 6,
  149658. 1,
  149659. 7,
  149660. 0,
  149661. 8,
  149662. };
  149663. static long _vq_lengthlist__44u6__p5_0[] = {
  149664. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149665. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149666. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149667. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149668. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149669. 14,
  149670. };
  149671. static float _vq_quantthresh__44u6__p5_0[] = {
  149672. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149673. };
  149674. static long _vq_quantmap__44u6__p5_0[] = {
  149675. 7, 5, 3, 1, 0, 2, 4, 6,
  149676. 8,
  149677. };
  149678. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149679. _vq_quantthresh__44u6__p5_0,
  149680. _vq_quantmap__44u6__p5_0,
  149681. 9,
  149682. 9
  149683. };
  149684. static static_codebook _44u6__p5_0 = {
  149685. 2, 81,
  149686. _vq_lengthlist__44u6__p5_0,
  149687. 1, -531628032, 1611661312, 4, 0,
  149688. _vq_quantlist__44u6__p5_0,
  149689. NULL,
  149690. &_vq_auxt__44u6__p5_0,
  149691. NULL,
  149692. 0
  149693. };
  149694. static long _vq_quantlist__44u6__p6_0[] = {
  149695. 4,
  149696. 3,
  149697. 5,
  149698. 2,
  149699. 6,
  149700. 1,
  149701. 7,
  149702. 0,
  149703. 8,
  149704. };
  149705. static long _vq_lengthlist__44u6__p6_0[] = {
  149706. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149707. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149708. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149709. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149710. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149711. 12,
  149712. };
  149713. static float _vq_quantthresh__44u6__p6_0[] = {
  149714. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149715. };
  149716. static long _vq_quantmap__44u6__p6_0[] = {
  149717. 7, 5, 3, 1, 0, 2, 4, 6,
  149718. 8,
  149719. };
  149720. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149721. _vq_quantthresh__44u6__p6_0,
  149722. _vq_quantmap__44u6__p6_0,
  149723. 9,
  149724. 9
  149725. };
  149726. static static_codebook _44u6__p6_0 = {
  149727. 2, 81,
  149728. _vq_lengthlist__44u6__p6_0,
  149729. 1, -531628032, 1611661312, 4, 0,
  149730. _vq_quantlist__44u6__p6_0,
  149731. NULL,
  149732. &_vq_auxt__44u6__p6_0,
  149733. NULL,
  149734. 0
  149735. };
  149736. static long _vq_quantlist__44u6__p7_0[] = {
  149737. 1,
  149738. 0,
  149739. 2,
  149740. };
  149741. static long _vq_lengthlist__44u6__p7_0[] = {
  149742. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149743. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149744. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149745. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149746. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149747. 10,
  149748. };
  149749. static float _vq_quantthresh__44u6__p7_0[] = {
  149750. -5.5, 5.5,
  149751. };
  149752. static long _vq_quantmap__44u6__p7_0[] = {
  149753. 1, 0, 2,
  149754. };
  149755. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149756. _vq_quantthresh__44u6__p7_0,
  149757. _vq_quantmap__44u6__p7_0,
  149758. 3,
  149759. 3
  149760. };
  149761. static static_codebook _44u6__p7_0 = {
  149762. 4, 81,
  149763. _vq_lengthlist__44u6__p7_0,
  149764. 1, -529137664, 1618345984, 2, 0,
  149765. _vq_quantlist__44u6__p7_0,
  149766. NULL,
  149767. &_vq_auxt__44u6__p7_0,
  149768. NULL,
  149769. 0
  149770. };
  149771. static long _vq_quantlist__44u6__p7_1[] = {
  149772. 5,
  149773. 4,
  149774. 6,
  149775. 3,
  149776. 7,
  149777. 2,
  149778. 8,
  149779. 1,
  149780. 9,
  149781. 0,
  149782. 10,
  149783. };
  149784. static long _vq_lengthlist__44u6__p7_1[] = {
  149785. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149786. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149787. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149788. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149789. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149790. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149791. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149792. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149793. };
  149794. static float _vq_quantthresh__44u6__p7_1[] = {
  149795. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149796. 3.5, 4.5,
  149797. };
  149798. static long _vq_quantmap__44u6__p7_1[] = {
  149799. 9, 7, 5, 3, 1, 0, 2, 4,
  149800. 6, 8, 10,
  149801. };
  149802. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149803. _vq_quantthresh__44u6__p7_1,
  149804. _vq_quantmap__44u6__p7_1,
  149805. 11,
  149806. 11
  149807. };
  149808. static static_codebook _44u6__p7_1 = {
  149809. 2, 121,
  149810. _vq_lengthlist__44u6__p7_1,
  149811. 1, -531365888, 1611661312, 4, 0,
  149812. _vq_quantlist__44u6__p7_1,
  149813. NULL,
  149814. &_vq_auxt__44u6__p7_1,
  149815. NULL,
  149816. 0
  149817. };
  149818. static long _vq_quantlist__44u6__p8_0[] = {
  149819. 5,
  149820. 4,
  149821. 6,
  149822. 3,
  149823. 7,
  149824. 2,
  149825. 8,
  149826. 1,
  149827. 9,
  149828. 0,
  149829. 10,
  149830. };
  149831. static long _vq_lengthlist__44u6__p8_0[] = {
  149832. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149833. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149834. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149835. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149836. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149837. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149838. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149839. 12,13,13,14,14,14,15,15,15,
  149840. };
  149841. static float _vq_quantthresh__44u6__p8_0[] = {
  149842. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149843. 38.5, 49.5,
  149844. };
  149845. static long _vq_quantmap__44u6__p8_0[] = {
  149846. 9, 7, 5, 3, 1, 0, 2, 4,
  149847. 6, 8, 10,
  149848. };
  149849. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149850. _vq_quantthresh__44u6__p8_0,
  149851. _vq_quantmap__44u6__p8_0,
  149852. 11,
  149853. 11
  149854. };
  149855. static static_codebook _44u6__p8_0 = {
  149856. 2, 121,
  149857. _vq_lengthlist__44u6__p8_0,
  149858. 1, -524582912, 1618345984, 4, 0,
  149859. _vq_quantlist__44u6__p8_0,
  149860. NULL,
  149861. &_vq_auxt__44u6__p8_0,
  149862. NULL,
  149863. 0
  149864. };
  149865. static long _vq_quantlist__44u6__p8_1[] = {
  149866. 5,
  149867. 4,
  149868. 6,
  149869. 3,
  149870. 7,
  149871. 2,
  149872. 8,
  149873. 1,
  149874. 9,
  149875. 0,
  149876. 10,
  149877. };
  149878. static long _vq_lengthlist__44u6__p8_1[] = {
  149879. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149880. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149881. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149882. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149883. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149884. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149885. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149886. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149887. };
  149888. static float _vq_quantthresh__44u6__p8_1[] = {
  149889. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149890. 3.5, 4.5,
  149891. };
  149892. static long _vq_quantmap__44u6__p8_1[] = {
  149893. 9, 7, 5, 3, 1, 0, 2, 4,
  149894. 6, 8, 10,
  149895. };
  149896. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149897. _vq_quantthresh__44u6__p8_1,
  149898. _vq_quantmap__44u6__p8_1,
  149899. 11,
  149900. 11
  149901. };
  149902. static static_codebook _44u6__p8_1 = {
  149903. 2, 121,
  149904. _vq_lengthlist__44u6__p8_1,
  149905. 1, -531365888, 1611661312, 4, 0,
  149906. _vq_quantlist__44u6__p8_1,
  149907. NULL,
  149908. &_vq_auxt__44u6__p8_1,
  149909. NULL,
  149910. 0
  149911. };
  149912. static long _vq_quantlist__44u6__p9_0[] = {
  149913. 7,
  149914. 6,
  149915. 8,
  149916. 5,
  149917. 9,
  149918. 4,
  149919. 10,
  149920. 3,
  149921. 11,
  149922. 2,
  149923. 12,
  149924. 1,
  149925. 13,
  149926. 0,
  149927. 14,
  149928. };
  149929. static long _vq_lengthlist__44u6__p9_0[] = {
  149930. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149931. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149932. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149933. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149934. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149935. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149936. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149937. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149938. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149939. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149940. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149941. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149942. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149943. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149944. 14,
  149945. };
  149946. static float _vq_quantthresh__44u6__p9_0[] = {
  149947. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149948. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149949. };
  149950. static long _vq_quantmap__44u6__p9_0[] = {
  149951. 13, 11, 9, 7, 5, 3, 1, 0,
  149952. 2, 4, 6, 8, 10, 12, 14,
  149953. };
  149954. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149955. _vq_quantthresh__44u6__p9_0,
  149956. _vq_quantmap__44u6__p9_0,
  149957. 15,
  149958. 15
  149959. };
  149960. static static_codebook _44u6__p9_0 = {
  149961. 2, 225,
  149962. _vq_lengthlist__44u6__p9_0,
  149963. 1, -514071552, 1627381760, 4, 0,
  149964. _vq_quantlist__44u6__p9_0,
  149965. NULL,
  149966. &_vq_auxt__44u6__p9_0,
  149967. NULL,
  149968. 0
  149969. };
  149970. static long _vq_quantlist__44u6__p9_1[] = {
  149971. 7,
  149972. 6,
  149973. 8,
  149974. 5,
  149975. 9,
  149976. 4,
  149977. 10,
  149978. 3,
  149979. 11,
  149980. 2,
  149981. 12,
  149982. 1,
  149983. 13,
  149984. 0,
  149985. 14,
  149986. };
  149987. static long _vq_lengthlist__44u6__p9_1[] = {
  149988. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149989. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149990. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149991. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149992. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149993. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149994. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149995. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149996. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149997. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149998. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149999. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150000. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150001. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150002. 13,
  150003. };
  150004. static float _vq_quantthresh__44u6__p9_1[] = {
  150005. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150006. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150007. };
  150008. static long _vq_quantmap__44u6__p9_1[] = {
  150009. 13, 11, 9, 7, 5, 3, 1, 0,
  150010. 2, 4, 6, 8, 10, 12, 14,
  150011. };
  150012. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150013. _vq_quantthresh__44u6__p9_1,
  150014. _vq_quantmap__44u6__p9_1,
  150015. 15,
  150016. 15
  150017. };
  150018. static static_codebook _44u6__p9_1 = {
  150019. 2, 225,
  150020. _vq_lengthlist__44u6__p9_1,
  150021. 1, -522338304, 1620115456, 4, 0,
  150022. _vq_quantlist__44u6__p9_1,
  150023. NULL,
  150024. &_vq_auxt__44u6__p9_1,
  150025. NULL,
  150026. 0
  150027. };
  150028. static long _vq_quantlist__44u6__p9_2[] = {
  150029. 8,
  150030. 7,
  150031. 9,
  150032. 6,
  150033. 10,
  150034. 5,
  150035. 11,
  150036. 4,
  150037. 12,
  150038. 3,
  150039. 13,
  150040. 2,
  150041. 14,
  150042. 1,
  150043. 15,
  150044. 0,
  150045. 16,
  150046. };
  150047. static long _vq_lengthlist__44u6__p9_2[] = {
  150048. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150049. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150050. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150051. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150052. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150053. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150054. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150055. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150056. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150057. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150058. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150059. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150060. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150061. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150062. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150063. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150064. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150065. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150066. 10,
  150067. };
  150068. static float _vq_quantthresh__44u6__p9_2[] = {
  150069. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150070. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150071. };
  150072. static long _vq_quantmap__44u6__p9_2[] = {
  150073. 15, 13, 11, 9, 7, 5, 3, 1,
  150074. 0, 2, 4, 6, 8, 10, 12, 14,
  150075. 16,
  150076. };
  150077. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150078. _vq_quantthresh__44u6__p9_2,
  150079. _vq_quantmap__44u6__p9_2,
  150080. 17,
  150081. 17
  150082. };
  150083. static static_codebook _44u6__p9_2 = {
  150084. 2, 289,
  150085. _vq_lengthlist__44u6__p9_2,
  150086. 1, -529530880, 1611661312, 5, 0,
  150087. _vq_quantlist__44u6__p9_2,
  150088. NULL,
  150089. &_vq_auxt__44u6__p9_2,
  150090. NULL,
  150091. 0
  150092. };
  150093. static long _huff_lengthlist__44u6__short[] = {
  150094. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150095. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150096. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150097. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150098. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150099. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150100. 7, 6, 9,16,
  150101. };
  150102. static static_codebook _huff_book__44u6__short = {
  150103. 2, 100,
  150104. _huff_lengthlist__44u6__short,
  150105. 0, 0, 0, 0, 0,
  150106. NULL,
  150107. NULL,
  150108. NULL,
  150109. NULL,
  150110. 0
  150111. };
  150112. static long _huff_lengthlist__44u7__long[] = {
  150113. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150114. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150115. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150116. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150117. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150118. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150119. 12, 8, 6, 7,
  150120. };
  150121. static static_codebook _huff_book__44u7__long = {
  150122. 2, 100,
  150123. _huff_lengthlist__44u7__long,
  150124. 0, 0, 0, 0, 0,
  150125. NULL,
  150126. NULL,
  150127. NULL,
  150128. NULL,
  150129. 0
  150130. };
  150131. static long _vq_quantlist__44u7__p1_0[] = {
  150132. 1,
  150133. 0,
  150134. 2,
  150135. };
  150136. static long _vq_lengthlist__44u7__p1_0[] = {
  150137. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150138. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150139. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150140. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150141. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150142. 12,
  150143. };
  150144. static float _vq_quantthresh__44u7__p1_0[] = {
  150145. -0.5, 0.5,
  150146. };
  150147. static long _vq_quantmap__44u7__p1_0[] = {
  150148. 1, 0, 2,
  150149. };
  150150. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150151. _vq_quantthresh__44u7__p1_0,
  150152. _vq_quantmap__44u7__p1_0,
  150153. 3,
  150154. 3
  150155. };
  150156. static static_codebook _44u7__p1_0 = {
  150157. 4, 81,
  150158. _vq_lengthlist__44u7__p1_0,
  150159. 1, -535822336, 1611661312, 2, 0,
  150160. _vq_quantlist__44u7__p1_0,
  150161. NULL,
  150162. &_vq_auxt__44u7__p1_0,
  150163. NULL,
  150164. 0
  150165. };
  150166. static long _vq_quantlist__44u7__p2_0[] = {
  150167. 1,
  150168. 0,
  150169. 2,
  150170. };
  150171. static long _vq_lengthlist__44u7__p2_0[] = {
  150172. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150173. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150174. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150175. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150176. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150177. 9,
  150178. };
  150179. static float _vq_quantthresh__44u7__p2_0[] = {
  150180. -0.5, 0.5,
  150181. };
  150182. static long _vq_quantmap__44u7__p2_0[] = {
  150183. 1, 0, 2,
  150184. };
  150185. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150186. _vq_quantthresh__44u7__p2_0,
  150187. _vq_quantmap__44u7__p2_0,
  150188. 3,
  150189. 3
  150190. };
  150191. static static_codebook _44u7__p2_0 = {
  150192. 4, 81,
  150193. _vq_lengthlist__44u7__p2_0,
  150194. 1, -535822336, 1611661312, 2, 0,
  150195. _vq_quantlist__44u7__p2_0,
  150196. NULL,
  150197. &_vq_auxt__44u7__p2_0,
  150198. NULL,
  150199. 0
  150200. };
  150201. static long _vq_quantlist__44u7__p3_0[] = {
  150202. 2,
  150203. 1,
  150204. 3,
  150205. 0,
  150206. 4,
  150207. };
  150208. static long _vq_lengthlist__44u7__p3_0[] = {
  150209. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150210. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150211. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150212. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150213. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150214. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150215. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150216. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150217. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150218. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150219. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150220. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150221. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150222. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150223. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150224. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150225. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150226. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150227. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150228. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150229. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150230. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150231. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150232. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150233. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150234. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150235. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150236. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150237. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150238. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150239. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150240. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150241. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150242. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150243. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150244. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150245. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150246. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150247. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150248. 0,
  150249. };
  150250. static float _vq_quantthresh__44u7__p3_0[] = {
  150251. -1.5, -0.5, 0.5, 1.5,
  150252. };
  150253. static long _vq_quantmap__44u7__p3_0[] = {
  150254. 3, 1, 0, 2, 4,
  150255. };
  150256. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150257. _vq_quantthresh__44u7__p3_0,
  150258. _vq_quantmap__44u7__p3_0,
  150259. 5,
  150260. 5
  150261. };
  150262. static static_codebook _44u7__p3_0 = {
  150263. 4, 625,
  150264. _vq_lengthlist__44u7__p3_0,
  150265. 1, -533725184, 1611661312, 3, 0,
  150266. _vq_quantlist__44u7__p3_0,
  150267. NULL,
  150268. &_vq_auxt__44u7__p3_0,
  150269. NULL,
  150270. 0
  150271. };
  150272. static long _vq_quantlist__44u7__p4_0[] = {
  150273. 2,
  150274. 1,
  150275. 3,
  150276. 0,
  150277. 4,
  150278. };
  150279. static long _vq_lengthlist__44u7__p4_0[] = {
  150280. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150281. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150282. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150283. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150284. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150285. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150286. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150287. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150288. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150289. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150290. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150291. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150292. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150293. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150294. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150295. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150296. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150297. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150298. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150299. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150300. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150301. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150302. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150303. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150304. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150305. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150306. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150307. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150308. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150309. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150310. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150311. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150312. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150313. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150314. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150315. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150316. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150317. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150318. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150319. 14,
  150320. };
  150321. static float _vq_quantthresh__44u7__p4_0[] = {
  150322. -1.5, -0.5, 0.5, 1.5,
  150323. };
  150324. static long _vq_quantmap__44u7__p4_0[] = {
  150325. 3, 1, 0, 2, 4,
  150326. };
  150327. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150328. _vq_quantthresh__44u7__p4_0,
  150329. _vq_quantmap__44u7__p4_0,
  150330. 5,
  150331. 5
  150332. };
  150333. static static_codebook _44u7__p4_0 = {
  150334. 4, 625,
  150335. _vq_lengthlist__44u7__p4_0,
  150336. 1, -533725184, 1611661312, 3, 0,
  150337. _vq_quantlist__44u7__p4_0,
  150338. NULL,
  150339. &_vq_auxt__44u7__p4_0,
  150340. NULL,
  150341. 0
  150342. };
  150343. static long _vq_quantlist__44u7__p5_0[] = {
  150344. 4,
  150345. 3,
  150346. 5,
  150347. 2,
  150348. 6,
  150349. 1,
  150350. 7,
  150351. 0,
  150352. 8,
  150353. };
  150354. static long _vq_lengthlist__44u7__p5_0[] = {
  150355. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150356. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150357. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150358. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150359. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150360. 14,
  150361. };
  150362. static float _vq_quantthresh__44u7__p5_0[] = {
  150363. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150364. };
  150365. static long _vq_quantmap__44u7__p5_0[] = {
  150366. 7, 5, 3, 1, 0, 2, 4, 6,
  150367. 8,
  150368. };
  150369. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150370. _vq_quantthresh__44u7__p5_0,
  150371. _vq_quantmap__44u7__p5_0,
  150372. 9,
  150373. 9
  150374. };
  150375. static static_codebook _44u7__p5_0 = {
  150376. 2, 81,
  150377. _vq_lengthlist__44u7__p5_0,
  150378. 1, -531628032, 1611661312, 4, 0,
  150379. _vq_quantlist__44u7__p5_0,
  150380. NULL,
  150381. &_vq_auxt__44u7__p5_0,
  150382. NULL,
  150383. 0
  150384. };
  150385. static long _vq_quantlist__44u7__p6_0[] = {
  150386. 4,
  150387. 3,
  150388. 5,
  150389. 2,
  150390. 6,
  150391. 1,
  150392. 7,
  150393. 0,
  150394. 8,
  150395. };
  150396. static long _vq_lengthlist__44u7__p6_0[] = {
  150397. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150398. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150399. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150400. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150401. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150402. 12,
  150403. };
  150404. static float _vq_quantthresh__44u7__p6_0[] = {
  150405. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150406. };
  150407. static long _vq_quantmap__44u7__p6_0[] = {
  150408. 7, 5, 3, 1, 0, 2, 4, 6,
  150409. 8,
  150410. };
  150411. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150412. _vq_quantthresh__44u7__p6_0,
  150413. _vq_quantmap__44u7__p6_0,
  150414. 9,
  150415. 9
  150416. };
  150417. static static_codebook _44u7__p6_0 = {
  150418. 2, 81,
  150419. _vq_lengthlist__44u7__p6_0,
  150420. 1, -531628032, 1611661312, 4, 0,
  150421. _vq_quantlist__44u7__p6_0,
  150422. NULL,
  150423. &_vq_auxt__44u7__p6_0,
  150424. NULL,
  150425. 0
  150426. };
  150427. static long _vq_quantlist__44u7__p7_0[] = {
  150428. 1,
  150429. 0,
  150430. 2,
  150431. };
  150432. static long _vq_lengthlist__44u7__p7_0[] = {
  150433. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150434. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150435. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150436. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150437. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150438. 10,
  150439. };
  150440. static float _vq_quantthresh__44u7__p7_0[] = {
  150441. -5.5, 5.5,
  150442. };
  150443. static long _vq_quantmap__44u7__p7_0[] = {
  150444. 1, 0, 2,
  150445. };
  150446. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150447. _vq_quantthresh__44u7__p7_0,
  150448. _vq_quantmap__44u7__p7_0,
  150449. 3,
  150450. 3
  150451. };
  150452. static static_codebook _44u7__p7_0 = {
  150453. 4, 81,
  150454. _vq_lengthlist__44u7__p7_0,
  150455. 1, -529137664, 1618345984, 2, 0,
  150456. _vq_quantlist__44u7__p7_0,
  150457. NULL,
  150458. &_vq_auxt__44u7__p7_0,
  150459. NULL,
  150460. 0
  150461. };
  150462. static long _vq_quantlist__44u7__p7_1[] = {
  150463. 5,
  150464. 4,
  150465. 6,
  150466. 3,
  150467. 7,
  150468. 2,
  150469. 8,
  150470. 1,
  150471. 9,
  150472. 0,
  150473. 10,
  150474. };
  150475. static long _vq_lengthlist__44u7__p7_1[] = {
  150476. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150477. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150478. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150479. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150480. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150481. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150482. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150483. 8, 9, 9, 9, 9, 9,10,10,10,
  150484. };
  150485. static float _vq_quantthresh__44u7__p7_1[] = {
  150486. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150487. 3.5, 4.5,
  150488. };
  150489. static long _vq_quantmap__44u7__p7_1[] = {
  150490. 9, 7, 5, 3, 1, 0, 2, 4,
  150491. 6, 8, 10,
  150492. };
  150493. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150494. _vq_quantthresh__44u7__p7_1,
  150495. _vq_quantmap__44u7__p7_1,
  150496. 11,
  150497. 11
  150498. };
  150499. static static_codebook _44u7__p7_1 = {
  150500. 2, 121,
  150501. _vq_lengthlist__44u7__p7_1,
  150502. 1, -531365888, 1611661312, 4, 0,
  150503. _vq_quantlist__44u7__p7_1,
  150504. NULL,
  150505. &_vq_auxt__44u7__p7_1,
  150506. NULL,
  150507. 0
  150508. };
  150509. static long _vq_quantlist__44u7__p8_0[] = {
  150510. 5,
  150511. 4,
  150512. 6,
  150513. 3,
  150514. 7,
  150515. 2,
  150516. 8,
  150517. 1,
  150518. 9,
  150519. 0,
  150520. 10,
  150521. };
  150522. static long _vq_lengthlist__44u7__p8_0[] = {
  150523. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150524. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150525. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150526. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150527. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150528. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150529. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150530. 12,13,13,14,14,15,15,15,16,
  150531. };
  150532. static float _vq_quantthresh__44u7__p8_0[] = {
  150533. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150534. 38.5, 49.5,
  150535. };
  150536. static long _vq_quantmap__44u7__p8_0[] = {
  150537. 9, 7, 5, 3, 1, 0, 2, 4,
  150538. 6, 8, 10,
  150539. };
  150540. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150541. _vq_quantthresh__44u7__p8_0,
  150542. _vq_quantmap__44u7__p8_0,
  150543. 11,
  150544. 11
  150545. };
  150546. static static_codebook _44u7__p8_0 = {
  150547. 2, 121,
  150548. _vq_lengthlist__44u7__p8_0,
  150549. 1, -524582912, 1618345984, 4, 0,
  150550. _vq_quantlist__44u7__p8_0,
  150551. NULL,
  150552. &_vq_auxt__44u7__p8_0,
  150553. NULL,
  150554. 0
  150555. };
  150556. static long _vq_quantlist__44u7__p8_1[] = {
  150557. 5,
  150558. 4,
  150559. 6,
  150560. 3,
  150561. 7,
  150562. 2,
  150563. 8,
  150564. 1,
  150565. 9,
  150566. 0,
  150567. 10,
  150568. };
  150569. static long _vq_lengthlist__44u7__p8_1[] = {
  150570. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150571. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150572. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150573. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150574. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150575. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150576. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150577. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150578. };
  150579. static float _vq_quantthresh__44u7__p8_1[] = {
  150580. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150581. 3.5, 4.5,
  150582. };
  150583. static long _vq_quantmap__44u7__p8_1[] = {
  150584. 9, 7, 5, 3, 1, 0, 2, 4,
  150585. 6, 8, 10,
  150586. };
  150587. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150588. _vq_quantthresh__44u7__p8_1,
  150589. _vq_quantmap__44u7__p8_1,
  150590. 11,
  150591. 11
  150592. };
  150593. static static_codebook _44u7__p8_1 = {
  150594. 2, 121,
  150595. _vq_lengthlist__44u7__p8_1,
  150596. 1, -531365888, 1611661312, 4, 0,
  150597. _vq_quantlist__44u7__p8_1,
  150598. NULL,
  150599. &_vq_auxt__44u7__p8_1,
  150600. NULL,
  150601. 0
  150602. };
  150603. static long _vq_quantlist__44u7__p9_0[] = {
  150604. 5,
  150605. 4,
  150606. 6,
  150607. 3,
  150608. 7,
  150609. 2,
  150610. 8,
  150611. 1,
  150612. 9,
  150613. 0,
  150614. 10,
  150615. };
  150616. static long _vq_lengthlist__44u7__p9_0[] = {
  150617. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150618. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150619. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150620. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150621. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150622. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150623. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150624. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150625. };
  150626. static float _vq_quantthresh__44u7__p9_0[] = {
  150627. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150628. 2229.5, 2866.5,
  150629. };
  150630. static long _vq_quantmap__44u7__p9_0[] = {
  150631. 9, 7, 5, 3, 1, 0, 2, 4,
  150632. 6, 8, 10,
  150633. };
  150634. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150635. _vq_quantthresh__44u7__p9_0,
  150636. _vq_quantmap__44u7__p9_0,
  150637. 11,
  150638. 11
  150639. };
  150640. static static_codebook _44u7__p9_0 = {
  150641. 2, 121,
  150642. _vq_lengthlist__44u7__p9_0,
  150643. 1, -512171520, 1630791680, 4, 0,
  150644. _vq_quantlist__44u7__p9_0,
  150645. NULL,
  150646. &_vq_auxt__44u7__p9_0,
  150647. NULL,
  150648. 0
  150649. };
  150650. static long _vq_quantlist__44u7__p9_1[] = {
  150651. 6,
  150652. 5,
  150653. 7,
  150654. 4,
  150655. 8,
  150656. 3,
  150657. 9,
  150658. 2,
  150659. 10,
  150660. 1,
  150661. 11,
  150662. 0,
  150663. 12,
  150664. };
  150665. static long _vq_lengthlist__44u7__p9_1[] = {
  150666. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150667. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150668. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150669. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150670. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150671. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150672. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150673. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150674. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150675. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150676. 15,15,15,15,17,17,16,17,16,
  150677. };
  150678. static float _vq_quantthresh__44u7__p9_1[] = {
  150679. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150680. 122.5, 171.5, 220.5, 269.5,
  150681. };
  150682. static long _vq_quantmap__44u7__p9_1[] = {
  150683. 11, 9, 7, 5, 3, 1, 0, 2,
  150684. 4, 6, 8, 10, 12,
  150685. };
  150686. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150687. _vq_quantthresh__44u7__p9_1,
  150688. _vq_quantmap__44u7__p9_1,
  150689. 13,
  150690. 13
  150691. };
  150692. static static_codebook _44u7__p9_1 = {
  150693. 2, 169,
  150694. _vq_lengthlist__44u7__p9_1,
  150695. 1, -518889472, 1622704128, 4, 0,
  150696. _vq_quantlist__44u7__p9_1,
  150697. NULL,
  150698. &_vq_auxt__44u7__p9_1,
  150699. NULL,
  150700. 0
  150701. };
  150702. static long _vq_quantlist__44u7__p9_2[] = {
  150703. 24,
  150704. 23,
  150705. 25,
  150706. 22,
  150707. 26,
  150708. 21,
  150709. 27,
  150710. 20,
  150711. 28,
  150712. 19,
  150713. 29,
  150714. 18,
  150715. 30,
  150716. 17,
  150717. 31,
  150718. 16,
  150719. 32,
  150720. 15,
  150721. 33,
  150722. 14,
  150723. 34,
  150724. 13,
  150725. 35,
  150726. 12,
  150727. 36,
  150728. 11,
  150729. 37,
  150730. 10,
  150731. 38,
  150732. 9,
  150733. 39,
  150734. 8,
  150735. 40,
  150736. 7,
  150737. 41,
  150738. 6,
  150739. 42,
  150740. 5,
  150741. 43,
  150742. 4,
  150743. 44,
  150744. 3,
  150745. 45,
  150746. 2,
  150747. 46,
  150748. 1,
  150749. 47,
  150750. 0,
  150751. 48,
  150752. };
  150753. static long _vq_lengthlist__44u7__p9_2[] = {
  150754. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150755. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150756. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150757. 8,
  150758. };
  150759. static float _vq_quantthresh__44u7__p9_2[] = {
  150760. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150761. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150762. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150763. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150764. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150765. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150766. };
  150767. static long _vq_quantmap__44u7__p9_2[] = {
  150768. 47, 45, 43, 41, 39, 37, 35, 33,
  150769. 31, 29, 27, 25, 23, 21, 19, 17,
  150770. 15, 13, 11, 9, 7, 5, 3, 1,
  150771. 0, 2, 4, 6, 8, 10, 12, 14,
  150772. 16, 18, 20, 22, 24, 26, 28, 30,
  150773. 32, 34, 36, 38, 40, 42, 44, 46,
  150774. 48,
  150775. };
  150776. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150777. _vq_quantthresh__44u7__p9_2,
  150778. _vq_quantmap__44u7__p9_2,
  150779. 49,
  150780. 49
  150781. };
  150782. static static_codebook _44u7__p9_2 = {
  150783. 1, 49,
  150784. _vq_lengthlist__44u7__p9_2,
  150785. 1, -526909440, 1611661312, 6, 0,
  150786. _vq_quantlist__44u7__p9_2,
  150787. NULL,
  150788. &_vq_auxt__44u7__p9_2,
  150789. NULL,
  150790. 0
  150791. };
  150792. static long _huff_lengthlist__44u7__short[] = {
  150793. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150794. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150795. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150796. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150797. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150798. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150799. 6, 8, 5, 9,
  150800. };
  150801. static static_codebook _huff_book__44u7__short = {
  150802. 2, 100,
  150803. _huff_lengthlist__44u7__short,
  150804. 0, 0, 0, 0, 0,
  150805. NULL,
  150806. NULL,
  150807. NULL,
  150808. NULL,
  150809. 0
  150810. };
  150811. static long _huff_lengthlist__44u8__long[] = {
  150812. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150813. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150814. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150815. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150816. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150817. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150818. 10, 8, 8, 9,
  150819. };
  150820. static static_codebook _huff_book__44u8__long = {
  150821. 2, 100,
  150822. _huff_lengthlist__44u8__long,
  150823. 0, 0, 0, 0, 0,
  150824. NULL,
  150825. NULL,
  150826. NULL,
  150827. NULL,
  150828. 0
  150829. };
  150830. static long _huff_lengthlist__44u8__short[] = {
  150831. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150832. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150833. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150834. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150835. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150836. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150837. 10,10,15,17,
  150838. };
  150839. static static_codebook _huff_book__44u8__short = {
  150840. 2, 100,
  150841. _huff_lengthlist__44u8__short,
  150842. 0, 0, 0, 0, 0,
  150843. NULL,
  150844. NULL,
  150845. NULL,
  150846. NULL,
  150847. 0
  150848. };
  150849. static long _vq_quantlist__44u8_p1_0[] = {
  150850. 1,
  150851. 0,
  150852. 2,
  150853. };
  150854. static long _vq_lengthlist__44u8_p1_0[] = {
  150855. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150856. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150857. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150858. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150859. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150860. 10,
  150861. };
  150862. static float _vq_quantthresh__44u8_p1_0[] = {
  150863. -0.5, 0.5,
  150864. };
  150865. static long _vq_quantmap__44u8_p1_0[] = {
  150866. 1, 0, 2,
  150867. };
  150868. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150869. _vq_quantthresh__44u8_p1_0,
  150870. _vq_quantmap__44u8_p1_0,
  150871. 3,
  150872. 3
  150873. };
  150874. static static_codebook _44u8_p1_0 = {
  150875. 4, 81,
  150876. _vq_lengthlist__44u8_p1_0,
  150877. 1, -535822336, 1611661312, 2, 0,
  150878. _vq_quantlist__44u8_p1_0,
  150879. NULL,
  150880. &_vq_auxt__44u8_p1_0,
  150881. NULL,
  150882. 0
  150883. };
  150884. static long _vq_quantlist__44u8_p2_0[] = {
  150885. 2,
  150886. 1,
  150887. 3,
  150888. 0,
  150889. 4,
  150890. };
  150891. static long _vq_lengthlist__44u8_p2_0[] = {
  150892. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150893. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150894. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150895. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150896. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150897. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150898. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150899. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150900. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150901. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150902. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150903. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150904. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150905. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150906. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150907. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150908. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150909. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150910. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150911. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150912. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150913. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150914. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150915. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150916. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150917. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150918. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150919. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150920. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150921. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150922. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150923. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150924. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150925. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150926. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150927. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150928. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150929. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150930. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150931. 14,
  150932. };
  150933. static float _vq_quantthresh__44u8_p2_0[] = {
  150934. -1.5, -0.5, 0.5, 1.5,
  150935. };
  150936. static long _vq_quantmap__44u8_p2_0[] = {
  150937. 3, 1, 0, 2, 4,
  150938. };
  150939. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150940. _vq_quantthresh__44u8_p2_0,
  150941. _vq_quantmap__44u8_p2_0,
  150942. 5,
  150943. 5
  150944. };
  150945. static static_codebook _44u8_p2_0 = {
  150946. 4, 625,
  150947. _vq_lengthlist__44u8_p2_0,
  150948. 1, -533725184, 1611661312, 3, 0,
  150949. _vq_quantlist__44u8_p2_0,
  150950. NULL,
  150951. &_vq_auxt__44u8_p2_0,
  150952. NULL,
  150953. 0
  150954. };
  150955. static long _vq_quantlist__44u8_p3_0[] = {
  150956. 4,
  150957. 3,
  150958. 5,
  150959. 2,
  150960. 6,
  150961. 1,
  150962. 7,
  150963. 0,
  150964. 8,
  150965. };
  150966. static long _vq_lengthlist__44u8_p3_0[] = {
  150967. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150968. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150969. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150970. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150971. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150972. 12,
  150973. };
  150974. static float _vq_quantthresh__44u8_p3_0[] = {
  150975. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150976. };
  150977. static long _vq_quantmap__44u8_p3_0[] = {
  150978. 7, 5, 3, 1, 0, 2, 4, 6,
  150979. 8,
  150980. };
  150981. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150982. _vq_quantthresh__44u8_p3_0,
  150983. _vq_quantmap__44u8_p3_0,
  150984. 9,
  150985. 9
  150986. };
  150987. static static_codebook _44u8_p3_0 = {
  150988. 2, 81,
  150989. _vq_lengthlist__44u8_p3_0,
  150990. 1, -531628032, 1611661312, 4, 0,
  150991. _vq_quantlist__44u8_p3_0,
  150992. NULL,
  150993. &_vq_auxt__44u8_p3_0,
  150994. NULL,
  150995. 0
  150996. };
  150997. static long _vq_quantlist__44u8_p4_0[] = {
  150998. 8,
  150999. 7,
  151000. 9,
  151001. 6,
  151002. 10,
  151003. 5,
  151004. 11,
  151005. 4,
  151006. 12,
  151007. 3,
  151008. 13,
  151009. 2,
  151010. 14,
  151011. 1,
  151012. 15,
  151013. 0,
  151014. 16,
  151015. };
  151016. static long _vq_lengthlist__44u8_p4_0[] = {
  151017. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151018. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151019. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151020. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151021. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151022. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151023. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151024. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151025. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151026. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151027. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151028. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151029. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151030. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151031. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151032. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151033. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151034. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151035. 14,
  151036. };
  151037. static float _vq_quantthresh__44u8_p4_0[] = {
  151038. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151039. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151040. };
  151041. static long _vq_quantmap__44u8_p4_0[] = {
  151042. 15, 13, 11, 9, 7, 5, 3, 1,
  151043. 0, 2, 4, 6, 8, 10, 12, 14,
  151044. 16,
  151045. };
  151046. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151047. _vq_quantthresh__44u8_p4_0,
  151048. _vq_quantmap__44u8_p4_0,
  151049. 17,
  151050. 17
  151051. };
  151052. static static_codebook _44u8_p4_0 = {
  151053. 2, 289,
  151054. _vq_lengthlist__44u8_p4_0,
  151055. 1, -529530880, 1611661312, 5, 0,
  151056. _vq_quantlist__44u8_p4_0,
  151057. NULL,
  151058. &_vq_auxt__44u8_p4_0,
  151059. NULL,
  151060. 0
  151061. };
  151062. static long _vq_quantlist__44u8_p5_0[] = {
  151063. 1,
  151064. 0,
  151065. 2,
  151066. };
  151067. static long _vq_lengthlist__44u8_p5_0[] = {
  151068. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151069. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151070. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151071. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151072. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151073. 10,
  151074. };
  151075. static float _vq_quantthresh__44u8_p5_0[] = {
  151076. -5.5, 5.5,
  151077. };
  151078. static long _vq_quantmap__44u8_p5_0[] = {
  151079. 1, 0, 2,
  151080. };
  151081. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151082. _vq_quantthresh__44u8_p5_0,
  151083. _vq_quantmap__44u8_p5_0,
  151084. 3,
  151085. 3
  151086. };
  151087. static static_codebook _44u8_p5_0 = {
  151088. 4, 81,
  151089. _vq_lengthlist__44u8_p5_0,
  151090. 1, -529137664, 1618345984, 2, 0,
  151091. _vq_quantlist__44u8_p5_0,
  151092. NULL,
  151093. &_vq_auxt__44u8_p5_0,
  151094. NULL,
  151095. 0
  151096. };
  151097. static long _vq_quantlist__44u8_p5_1[] = {
  151098. 5,
  151099. 4,
  151100. 6,
  151101. 3,
  151102. 7,
  151103. 2,
  151104. 8,
  151105. 1,
  151106. 9,
  151107. 0,
  151108. 10,
  151109. };
  151110. static long _vq_lengthlist__44u8_p5_1[] = {
  151111. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151112. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151113. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151114. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151115. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151116. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151117. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151118. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151119. };
  151120. static float _vq_quantthresh__44u8_p5_1[] = {
  151121. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151122. 3.5, 4.5,
  151123. };
  151124. static long _vq_quantmap__44u8_p5_1[] = {
  151125. 9, 7, 5, 3, 1, 0, 2, 4,
  151126. 6, 8, 10,
  151127. };
  151128. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151129. _vq_quantthresh__44u8_p5_1,
  151130. _vq_quantmap__44u8_p5_1,
  151131. 11,
  151132. 11
  151133. };
  151134. static static_codebook _44u8_p5_1 = {
  151135. 2, 121,
  151136. _vq_lengthlist__44u8_p5_1,
  151137. 1, -531365888, 1611661312, 4, 0,
  151138. _vq_quantlist__44u8_p5_1,
  151139. NULL,
  151140. &_vq_auxt__44u8_p5_1,
  151141. NULL,
  151142. 0
  151143. };
  151144. static long _vq_quantlist__44u8_p6_0[] = {
  151145. 6,
  151146. 5,
  151147. 7,
  151148. 4,
  151149. 8,
  151150. 3,
  151151. 9,
  151152. 2,
  151153. 10,
  151154. 1,
  151155. 11,
  151156. 0,
  151157. 12,
  151158. };
  151159. static long _vq_lengthlist__44u8_p6_0[] = {
  151160. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151161. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151162. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151163. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151164. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151165. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151166. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151167. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151168. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151169. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151170. 11,11,11,11,11,12,11,12,12,
  151171. };
  151172. static float _vq_quantthresh__44u8_p6_0[] = {
  151173. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151174. 12.5, 17.5, 22.5, 27.5,
  151175. };
  151176. static long _vq_quantmap__44u8_p6_0[] = {
  151177. 11, 9, 7, 5, 3, 1, 0, 2,
  151178. 4, 6, 8, 10, 12,
  151179. };
  151180. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151181. _vq_quantthresh__44u8_p6_0,
  151182. _vq_quantmap__44u8_p6_0,
  151183. 13,
  151184. 13
  151185. };
  151186. static static_codebook _44u8_p6_0 = {
  151187. 2, 169,
  151188. _vq_lengthlist__44u8_p6_0,
  151189. 1, -526516224, 1616117760, 4, 0,
  151190. _vq_quantlist__44u8_p6_0,
  151191. NULL,
  151192. &_vq_auxt__44u8_p6_0,
  151193. NULL,
  151194. 0
  151195. };
  151196. static long _vq_quantlist__44u8_p6_1[] = {
  151197. 2,
  151198. 1,
  151199. 3,
  151200. 0,
  151201. 4,
  151202. };
  151203. static long _vq_lengthlist__44u8_p6_1[] = {
  151204. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151205. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151206. };
  151207. static float _vq_quantthresh__44u8_p6_1[] = {
  151208. -1.5, -0.5, 0.5, 1.5,
  151209. };
  151210. static long _vq_quantmap__44u8_p6_1[] = {
  151211. 3, 1, 0, 2, 4,
  151212. };
  151213. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151214. _vq_quantthresh__44u8_p6_1,
  151215. _vq_quantmap__44u8_p6_1,
  151216. 5,
  151217. 5
  151218. };
  151219. static static_codebook _44u8_p6_1 = {
  151220. 2, 25,
  151221. _vq_lengthlist__44u8_p6_1,
  151222. 1, -533725184, 1611661312, 3, 0,
  151223. _vq_quantlist__44u8_p6_1,
  151224. NULL,
  151225. &_vq_auxt__44u8_p6_1,
  151226. NULL,
  151227. 0
  151228. };
  151229. static long _vq_quantlist__44u8_p7_0[] = {
  151230. 6,
  151231. 5,
  151232. 7,
  151233. 4,
  151234. 8,
  151235. 3,
  151236. 9,
  151237. 2,
  151238. 10,
  151239. 1,
  151240. 11,
  151241. 0,
  151242. 12,
  151243. };
  151244. static long _vq_lengthlist__44u8_p7_0[] = {
  151245. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151246. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151247. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151248. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151249. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151250. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151251. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151252. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151253. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151254. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151255. 13,13,14,14,14,15,15,15,16,
  151256. };
  151257. static float _vq_quantthresh__44u8_p7_0[] = {
  151258. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151259. 27.5, 38.5, 49.5, 60.5,
  151260. };
  151261. static long _vq_quantmap__44u8_p7_0[] = {
  151262. 11, 9, 7, 5, 3, 1, 0, 2,
  151263. 4, 6, 8, 10, 12,
  151264. };
  151265. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151266. _vq_quantthresh__44u8_p7_0,
  151267. _vq_quantmap__44u8_p7_0,
  151268. 13,
  151269. 13
  151270. };
  151271. static static_codebook _44u8_p7_0 = {
  151272. 2, 169,
  151273. _vq_lengthlist__44u8_p7_0,
  151274. 1, -523206656, 1618345984, 4, 0,
  151275. _vq_quantlist__44u8_p7_0,
  151276. NULL,
  151277. &_vq_auxt__44u8_p7_0,
  151278. NULL,
  151279. 0
  151280. };
  151281. static long _vq_quantlist__44u8_p7_1[] = {
  151282. 5,
  151283. 4,
  151284. 6,
  151285. 3,
  151286. 7,
  151287. 2,
  151288. 8,
  151289. 1,
  151290. 9,
  151291. 0,
  151292. 10,
  151293. };
  151294. static long _vq_lengthlist__44u8_p7_1[] = {
  151295. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151296. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151297. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151298. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151299. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151300. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151301. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151302. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151303. };
  151304. static float _vq_quantthresh__44u8_p7_1[] = {
  151305. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151306. 3.5, 4.5,
  151307. };
  151308. static long _vq_quantmap__44u8_p7_1[] = {
  151309. 9, 7, 5, 3, 1, 0, 2, 4,
  151310. 6, 8, 10,
  151311. };
  151312. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151313. _vq_quantthresh__44u8_p7_1,
  151314. _vq_quantmap__44u8_p7_1,
  151315. 11,
  151316. 11
  151317. };
  151318. static static_codebook _44u8_p7_1 = {
  151319. 2, 121,
  151320. _vq_lengthlist__44u8_p7_1,
  151321. 1, -531365888, 1611661312, 4, 0,
  151322. _vq_quantlist__44u8_p7_1,
  151323. NULL,
  151324. &_vq_auxt__44u8_p7_1,
  151325. NULL,
  151326. 0
  151327. };
  151328. static long _vq_quantlist__44u8_p8_0[] = {
  151329. 7,
  151330. 6,
  151331. 8,
  151332. 5,
  151333. 9,
  151334. 4,
  151335. 10,
  151336. 3,
  151337. 11,
  151338. 2,
  151339. 12,
  151340. 1,
  151341. 13,
  151342. 0,
  151343. 14,
  151344. };
  151345. static long _vq_lengthlist__44u8_p8_0[] = {
  151346. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151347. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151348. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151349. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151350. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151351. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151352. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151353. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151354. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151355. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151356. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151357. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151358. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151359. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151360. 17,
  151361. };
  151362. static float _vq_quantthresh__44u8_p8_0[] = {
  151363. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151364. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151365. };
  151366. static long _vq_quantmap__44u8_p8_0[] = {
  151367. 13, 11, 9, 7, 5, 3, 1, 0,
  151368. 2, 4, 6, 8, 10, 12, 14,
  151369. };
  151370. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151371. _vq_quantthresh__44u8_p8_0,
  151372. _vq_quantmap__44u8_p8_0,
  151373. 15,
  151374. 15
  151375. };
  151376. static static_codebook _44u8_p8_0 = {
  151377. 2, 225,
  151378. _vq_lengthlist__44u8_p8_0,
  151379. 1, -520986624, 1620377600, 4, 0,
  151380. _vq_quantlist__44u8_p8_0,
  151381. NULL,
  151382. &_vq_auxt__44u8_p8_0,
  151383. NULL,
  151384. 0
  151385. };
  151386. static long _vq_quantlist__44u8_p8_1[] = {
  151387. 10,
  151388. 9,
  151389. 11,
  151390. 8,
  151391. 12,
  151392. 7,
  151393. 13,
  151394. 6,
  151395. 14,
  151396. 5,
  151397. 15,
  151398. 4,
  151399. 16,
  151400. 3,
  151401. 17,
  151402. 2,
  151403. 18,
  151404. 1,
  151405. 19,
  151406. 0,
  151407. 20,
  151408. };
  151409. static long _vq_lengthlist__44u8_p8_1[] = {
  151410. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151411. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151412. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151413. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151414. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151415. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151416. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151417. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151418. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151419. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151420. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151421. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151422. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151423. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151424. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151425. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151426. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151427. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151428. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151429. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151430. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151431. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151432. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151433. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151434. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151435. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151436. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151437. 10,10,10,10,10,10,10,10,10,
  151438. };
  151439. static float _vq_quantthresh__44u8_p8_1[] = {
  151440. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151441. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151442. 6.5, 7.5, 8.5, 9.5,
  151443. };
  151444. static long _vq_quantmap__44u8_p8_1[] = {
  151445. 19, 17, 15, 13, 11, 9, 7, 5,
  151446. 3, 1, 0, 2, 4, 6, 8, 10,
  151447. 12, 14, 16, 18, 20,
  151448. };
  151449. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151450. _vq_quantthresh__44u8_p8_1,
  151451. _vq_quantmap__44u8_p8_1,
  151452. 21,
  151453. 21
  151454. };
  151455. static static_codebook _44u8_p8_1 = {
  151456. 2, 441,
  151457. _vq_lengthlist__44u8_p8_1,
  151458. 1, -529268736, 1611661312, 5, 0,
  151459. _vq_quantlist__44u8_p8_1,
  151460. NULL,
  151461. &_vq_auxt__44u8_p8_1,
  151462. NULL,
  151463. 0
  151464. };
  151465. static long _vq_quantlist__44u8_p9_0[] = {
  151466. 4,
  151467. 3,
  151468. 5,
  151469. 2,
  151470. 6,
  151471. 1,
  151472. 7,
  151473. 0,
  151474. 8,
  151475. };
  151476. static long _vq_lengthlist__44u8_p9_0[] = {
  151477. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151478. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151479. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151480. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151481. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151482. 8,
  151483. };
  151484. static float _vq_quantthresh__44u8_p9_0[] = {
  151485. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151486. };
  151487. static long _vq_quantmap__44u8_p9_0[] = {
  151488. 7, 5, 3, 1, 0, 2, 4, 6,
  151489. 8,
  151490. };
  151491. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151492. _vq_quantthresh__44u8_p9_0,
  151493. _vq_quantmap__44u8_p9_0,
  151494. 9,
  151495. 9
  151496. };
  151497. static static_codebook _44u8_p9_0 = {
  151498. 2, 81,
  151499. _vq_lengthlist__44u8_p9_0,
  151500. 1, -511895552, 1631393792, 4, 0,
  151501. _vq_quantlist__44u8_p9_0,
  151502. NULL,
  151503. &_vq_auxt__44u8_p9_0,
  151504. NULL,
  151505. 0
  151506. };
  151507. static long _vq_quantlist__44u8_p9_1[] = {
  151508. 9,
  151509. 8,
  151510. 10,
  151511. 7,
  151512. 11,
  151513. 6,
  151514. 12,
  151515. 5,
  151516. 13,
  151517. 4,
  151518. 14,
  151519. 3,
  151520. 15,
  151521. 2,
  151522. 16,
  151523. 1,
  151524. 17,
  151525. 0,
  151526. 18,
  151527. };
  151528. static long _vq_lengthlist__44u8_p9_1[] = {
  151529. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151530. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151531. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151532. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151533. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151534. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151535. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151536. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151537. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151538. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151539. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151540. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151541. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151542. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151543. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151544. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151545. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151546. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151547. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151548. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151549. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151550. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151551. 16,15,16,16,16,16,16,16,16,
  151552. };
  151553. static float _vq_quantthresh__44u8_p9_1[] = {
  151554. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151555. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151556. 367.5, 416.5,
  151557. };
  151558. static long _vq_quantmap__44u8_p9_1[] = {
  151559. 17, 15, 13, 11, 9, 7, 5, 3,
  151560. 1, 0, 2, 4, 6, 8, 10, 12,
  151561. 14, 16, 18,
  151562. };
  151563. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151564. _vq_quantthresh__44u8_p9_1,
  151565. _vq_quantmap__44u8_p9_1,
  151566. 19,
  151567. 19
  151568. };
  151569. static static_codebook _44u8_p9_1 = {
  151570. 2, 361,
  151571. _vq_lengthlist__44u8_p9_1,
  151572. 1, -518287360, 1622704128, 5, 0,
  151573. _vq_quantlist__44u8_p9_1,
  151574. NULL,
  151575. &_vq_auxt__44u8_p9_1,
  151576. NULL,
  151577. 0
  151578. };
  151579. static long _vq_quantlist__44u8_p9_2[] = {
  151580. 24,
  151581. 23,
  151582. 25,
  151583. 22,
  151584. 26,
  151585. 21,
  151586. 27,
  151587. 20,
  151588. 28,
  151589. 19,
  151590. 29,
  151591. 18,
  151592. 30,
  151593. 17,
  151594. 31,
  151595. 16,
  151596. 32,
  151597. 15,
  151598. 33,
  151599. 14,
  151600. 34,
  151601. 13,
  151602. 35,
  151603. 12,
  151604. 36,
  151605. 11,
  151606. 37,
  151607. 10,
  151608. 38,
  151609. 9,
  151610. 39,
  151611. 8,
  151612. 40,
  151613. 7,
  151614. 41,
  151615. 6,
  151616. 42,
  151617. 5,
  151618. 43,
  151619. 4,
  151620. 44,
  151621. 3,
  151622. 45,
  151623. 2,
  151624. 46,
  151625. 1,
  151626. 47,
  151627. 0,
  151628. 48,
  151629. };
  151630. static long _vq_lengthlist__44u8_p9_2[] = {
  151631. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151632. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151633. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151634. 7,
  151635. };
  151636. static float _vq_quantthresh__44u8_p9_2[] = {
  151637. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151638. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151639. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151640. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151641. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151642. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151643. };
  151644. static long _vq_quantmap__44u8_p9_2[] = {
  151645. 47, 45, 43, 41, 39, 37, 35, 33,
  151646. 31, 29, 27, 25, 23, 21, 19, 17,
  151647. 15, 13, 11, 9, 7, 5, 3, 1,
  151648. 0, 2, 4, 6, 8, 10, 12, 14,
  151649. 16, 18, 20, 22, 24, 26, 28, 30,
  151650. 32, 34, 36, 38, 40, 42, 44, 46,
  151651. 48,
  151652. };
  151653. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151654. _vq_quantthresh__44u8_p9_2,
  151655. _vq_quantmap__44u8_p9_2,
  151656. 49,
  151657. 49
  151658. };
  151659. static static_codebook _44u8_p9_2 = {
  151660. 1, 49,
  151661. _vq_lengthlist__44u8_p9_2,
  151662. 1, -526909440, 1611661312, 6, 0,
  151663. _vq_quantlist__44u8_p9_2,
  151664. NULL,
  151665. &_vq_auxt__44u8_p9_2,
  151666. NULL,
  151667. 0
  151668. };
  151669. static long _huff_lengthlist__44u9__long[] = {
  151670. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151671. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151672. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151673. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151674. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151675. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151676. 10, 8, 8, 9,
  151677. };
  151678. static static_codebook _huff_book__44u9__long = {
  151679. 2, 100,
  151680. _huff_lengthlist__44u9__long,
  151681. 0, 0, 0, 0, 0,
  151682. NULL,
  151683. NULL,
  151684. NULL,
  151685. NULL,
  151686. 0
  151687. };
  151688. static long _huff_lengthlist__44u9__short[] = {
  151689. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151690. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151691. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151692. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151693. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151694. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151695. 9, 9,12,15,
  151696. };
  151697. static static_codebook _huff_book__44u9__short = {
  151698. 2, 100,
  151699. _huff_lengthlist__44u9__short,
  151700. 0, 0, 0, 0, 0,
  151701. NULL,
  151702. NULL,
  151703. NULL,
  151704. NULL,
  151705. 0
  151706. };
  151707. static long _vq_quantlist__44u9_p1_0[] = {
  151708. 1,
  151709. 0,
  151710. 2,
  151711. };
  151712. static long _vq_lengthlist__44u9_p1_0[] = {
  151713. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151714. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151715. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151716. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151717. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151718. 10,
  151719. };
  151720. static float _vq_quantthresh__44u9_p1_0[] = {
  151721. -0.5, 0.5,
  151722. };
  151723. static long _vq_quantmap__44u9_p1_0[] = {
  151724. 1, 0, 2,
  151725. };
  151726. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151727. _vq_quantthresh__44u9_p1_0,
  151728. _vq_quantmap__44u9_p1_0,
  151729. 3,
  151730. 3
  151731. };
  151732. static static_codebook _44u9_p1_0 = {
  151733. 4, 81,
  151734. _vq_lengthlist__44u9_p1_0,
  151735. 1, -535822336, 1611661312, 2, 0,
  151736. _vq_quantlist__44u9_p1_0,
  151737. NULL,
  151738. &_vq_auxt__44u9_p1_0,
  151739. NULL,
  151740. 0
  151741. };
  151742. static long _vq_quantlist__44u9_p2_0[] = {
  151743. 2,
  151744. 1,
  151745. 3,
  151746. 0,
  151747. 4,
  151748. };
  151749. static long _vq_lengthlist__44u9_p2_0[] = {
  151750. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151751. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151752. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151753. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151754. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151755. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151756. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151757. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151758. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151759. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151760. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151761. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151762. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151763. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151764. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151765. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151766. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151767. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151768. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151769. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151770. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151771. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151772. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151773. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151774. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151775. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151776. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151777. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151778. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151779. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151780. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151781. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151782. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151783. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151784. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151785. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151786. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151787. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151788. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151789. 14,
  151790. };
  151791. static float _vq_quantthresh__44u9_p2_0[] = {
  151792. -1.5, -0.5, 0.5, 1.5,
  151793. };
  151794. static long _vq_quantmap__44u9_p2_0[] = {
  151795. 3, 1, 0, 2, 4,
  151796. };
  151797. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151798. _vq_quantthresh__44u9_p2_0,
  151799. _vq_quantmap__44u9_p2_0,
  151800. 5,
  151801. 5
  151802. };
  151803. static static_codebook _44u9_p2_0 = {
  151804. 4, 625,
  151805. _vq_lengthlist__44u9_p2_0,
  151806. 1, -533725184, 1611661312, 3, 0,
  151807. _vq_quantlist__44u9_p2_0,
  151808. NULL,
  151809. &_vq_auxt__44u9_p2_0,
  151810. NULL,
  151811. 0
  151812. };
  151813. static long _vq_quantlist__44u9_p3_0[] = {
  151814. 4,
  151815. 3,
  151816. 5,
  151817. 2,
  151818. 6,
  151819. 1,
  151820. 7,
  151821. 0,
  151822. 8,
  151823. };
  151824. static long _vq_lengthlist__44u9_p3_0[] = {
  151825. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151826. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151827. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151828. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151829. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151830. 11,
  151831. };
  151832. static float _vq_quantthresh__44u9_p3_0[] = {
  151833. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151834. };
  151835. static long _vq_quantmap__44u9_p3_0[] = {
  151836. 7, 5, 3, 1, 0, 2, 4, 6,
  151837. 8,
  151838. };
  151839. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151840. _vq_quantthresh__44u9_p3_0,
  151841. _vq_quantmap__44u9_p3_0,
  151842. 9,
  151843. 9
  151844. };
  151845. static static_codebook _44u9_p3_0 = {
  151846. 2, 81,
  151847. _vq_lengthlist__44u9_p3_0,
  151848. 1, -531628032, 1611661312, 4, 0,
  151849. _vq_quantlist__44u9_p3_0,
  151850. NULL,
  151851. &_vq_auxt__44u9_p3_0,
  151852. NULL,
  151853. 0
  151854. };
  151855. static long _vq_quantlist__44u9_p4_0[] = {
  151856. 8,
  151857. 7,
  151858. 9,
  151859. 6,
  151860. 10,
  151861. 5,
  151862. 11,
  151863. 4,
  151864. 12,
  151865. 3,
  151866. 13,
  151867. 2,
  151868. 14,
  151869. 1,
  151870. 15,
  151871. 0,
  151872. 16,
  151873. };
  151874. static long _vq_lengthlist__44u9_p4_0[] = {
  151875. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151876. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151877. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151878. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151879. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151880. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151881. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151882. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151883. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151884. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151885. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151886. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151887. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151888. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151889. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151890. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151891. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151892. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151893. 14,
  151894. };
  151895. static float _vq_quantthresh__44u9_p4_0[] = {
  151896. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151897. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151898. };
  151899. static long _vq_quantmap__44u9_p4_0[] = {
  151900. 15, 13, 11, 9, 7, 5, 3, 1,
  151901. 0, 2, 4, 6, 8, 10, 12, 14,
  151902. 16,
  151903. };
  151904. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151905. _vq_quantthresh__44u9_p4_0,
  151906. _vq_quantmap__44u9_p4_0,
  151907. 17,
  151908. 17
  151909. };
  151910. static static_codebook _44u9_p4_0 = {
  151911. 2, 289,
  151912. _vq_lengthlist__44u9_p4_0,
  151913. 1, -529530880, 1611661312, 5, 0,
  151914. _vq_quantlist__44u9_p4_0,
  151915. NULL,
  151916. &_vq_auxt__44u9_p4_0,
  151917. NULL,
  151918. 0
  151919. };
  151920. static long _vq_quantlist__44u9_p5_0[] = {
  151921. 1,
  151922. 0,
  151923. 2,
  151924. };
  151925. static long _vq_lengthlist__44u9_p5_0[] = {
  151926. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151927. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151928. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151929. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151930. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151931. 10,
  151932. };
  151933. static float _vq_quantthresh__44u9_p5_0[] = {
  151934. -5.5, 5.5,
  151935. };
  151936. static long _vq_quantmap__44u9_p5_0[] = {
  151937. 1, 0, 2,
  151938. };
  151939. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151940. _vq_quantthresh__44u9_p5_0,
  151941. _vq_quantmap__44u9_p5_0,
  151942. 3,
  151943. 3
  151944. };
  151945. static static_codebook _44u9_p5_0 = {
  151946. 4, 81,
  151947. _vq_lengthlist__44u9_p5_0,
  151948. 1, -529137664, 1618345984, 2, 0,
  151949. _vq_quantlist__44u9_p5_0,
  151950. NULL,
  151951. &_vq_auxt__44u9_p5_0,
  151952. NULL,
  151953. 0
  151954. };
  151955. static long _vq_quantlist__44u9_p5_1[] = {
  151956. 5,
  151957. 4,
  151958. 6,
  151959. 3,
  151960. 7,
  151961. 2,
  151962. 8,
  151963. 1,
  151964. 9,
  151965. 0,
  151966. 10,
  151967. };
  151968. static long _vq_lengthlist__44u9_p5_1[] = {
  151969. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151970. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151971. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151972. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151973. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151974. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151975. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151976. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151977. };
  151978. static float _vq_quantthresh__44u9_p5_1[] = {
  151979. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151980. 3.5, 4.5,
  151981. };
  151982. static long _vq_quantmap__44u9_p5_1[] = {
  151983. 9, 7, 5, 3, 1, 0, 2, 4,
  151984. 6, 8, 10,
  151985. };
  151986. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151987. _vq_quantthresh__44u9_p5_1,
  151988. _vq_quantmap__44u9_p5_1,
  151989. 11,
  151990. 11
  151991. };
  151992. static static_codebook _44u9_p5_1 = {
  151993. 2, 121,
  151994. _vq_lengthlist__44u9_p5_1,
  151995. 1, -531365888, 1611661312, 4, 0,
  151996. _vq_quantlist__44u9_p5_1,
  151997. NULL,
  151998. &_vq_auxt__44u9_p5_1,
  151999. NULL,
  152000. 0
  152001. };
  152002. static long _vq_quantlist__44u9_p6_0[] = {
  152003. 6,
  152004. 5,
  152005. 7,
  152006. 4,
  152007. 8,
  152008. 3,
  152009. 9,
  152010. 2,
  152011. 10,
  152012. 1,
  152013. 11,
  152014. 0,
  152015. 12,
  152016. };
  152017. static long _vq_lengthlist__44u9_p6_0[] = {
  152018. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152019. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152020. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152021. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152022. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152023. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152024. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152025. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152026. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152027. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152028. 10,11,11,11,11,12,11,12,12,
  152029. };
  152030. static float _vq_quantthresh__44u9_p6_0[] = {
  152031. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152032. 12.5, 17.5, 22.5, 27.5,
  152033. };
  152034. static long _vq_quantmap__44u9_p6_0[] = {
  152035. 11, 9, 7, 5, 3, 1, 0, 2,
  152036. 4, 6, 8, 10, 12,
  152037. };
  152038. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152039. _vq_quantthresh__44u9_p6_0,
  152040. _vq_quantmap__44u9_p6_0,
  152041. 13,
  152042. 13
  152043. };
  152044. static static_codebook _44u9_p6_0 = {
  152045. 2, 169,
  152046. _vq_lengthlist__44u9_p6_0,
  152047. 1, -526516224, 1616117760, 4, 0,
  152048. _vq_quantlist__44u9_p6_0,
  152049. NULL,
  152050. &_vq_auxt__44u9_p6_0,
  152051. NULL,
  152052. 0
  152053. };
  152054. static long _vq_quantlist__44u9_p6_1[] = {
  152055. 2,
  152056. 1,
  152057. 3,
  152058. 0,
  152059. 4,
  152060. };
  152061. static long _vq_lengthlist__44u9_p6_1[] = {
  152062. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152063. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152064. };
  152065. static float _vq_quantthresh__44u9_p6_1[] = {
  152066. -1.5, -0.5, 0.5, 1.5,
  152067. };
  152068. static long _vq_quantmap__44u9_p6_1[] = {
  152069. 3, 1, 0, 2, 4,
  152070. };
  152071. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152072. _vq_quantthresh__44u9_p6_1,
  152073. _vq_quantmap__44u9_p6_1,
  152074. 5,
  152075. 5
  152076. };
  152077. static static_codebook _44u9_p6_1 = {
  152078. 2, 25,
  152079. _vq_lengthlist__44u9_p6_1,
  152080. 1, -533725184, 1611661312, 3, 0,
  152081. _vq_quantlist__44u9_p6_1,
  152082. NULL,
  152083. &_vq_auxt__44u9_p6_1,
  152084. NULL,
  152085. 0
  152086. };
  152087. static long _vq_quantlist__44u9_p7_0[] = {
  152088. 6,
  152089. 5,
  152090. 7,
  152091. 4,
  152092. 8,
  152093. 3,
  152094. 9,
  152095. 2,
  152096. 10,
  152097. 1,
  152098. 11,
  152099. 0,
  152100. 12,
  152101. };
  152102. static long _vq_lengthlist__44u9_p7_0[] = {
  152103. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152104. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152105. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152106. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152107. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152108. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152109. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152110. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152111. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152112. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152113. 12,13,13,14,14,14,15,15,15,
  152114. };
  152115. static float _vq_quantthresh__44u9_p7_0[] = {
  152116. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152117. 27.5, 38.5, 49.5, 60.5,
  152118. };
  152119. static long _vq_quantmap__44u9_p7_0[] = {
  152120. 11, 9, 7, 5, 3, 1, 0, 2,
  152121. 4, 6, 8, 10, 12,
  152122. };
  152123. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152124. _vq_quantthresh__44u9_p7_0,
  152125. _vq_quantmap__44u9_p7_0,
  152126. 13,
  152127. 13
  152128. };
  152129. static static_codebook _44u9_p7_0 = {
  152130. 2, 169,
  152131. _vq_lengthlist__44u9_p7_0,
  152132. 1, -523206656, 1618345984, 4, 0,
  152133. _vq_quantlist__44u9_p7_0,
  152134. NULL,
  152135. &_vq_auxt__44u9_p7_0,
  152136. NULL,
  152137. 0
  152138. };
  152139. static long _vq_quantlist__44u9_p7_1[] = {
  152140. 5,
  152141. 4,
  152142. 6,
  152143. 3,
  152144. 7,
  152145. 2,
  152146. 8,
  152147. 1,
  152148. 9,
  152149. 0,
  152150. 10,
  152151. };
  152152. static long _vq_lengthlist__44u9_p7_1[] = {
  152153. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152154. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152155. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152156. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152157. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152158. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152159. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152160. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152161. };
  152162. static float _vq_quantthresh__44u9_p7_1[] = {
  152163. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152164. 3.5, 4.5,
  152165. };
  152166. static long _vq_quantmap__44u9_p7_1[] = {
  152167. 9, 7, 5, 3, 1, 0, 2, 4,
  152168. 6, 8, 10,
  152169. };
  152170. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152171. _vq_quantthresh__44u9_p7_1,
  152172. _vq_quantmap__44u9_p7_1,
  152173. 11,
  152174. 11
  152175. };
  152176. static static_codebook _44u9_p7_1 = {
  152177. 2, 121,
  152178. _vq_lengthlist__44u9_p7_1,
  152179. 1, -531365888, 1611661312, 4, 0,
  152180. _vq_quantlist__44u9_p7_1,
  152181. NULL,
  152182. &_vq_auxt__44u9_p7_1,
  152183. NULL,
  152184. 0
  152185. };
  152186. static long _vq_quantlist__44u9_p8_0[] = {
  152187. 7,
  152188. 6,
  152189. 8,
  152190. 5,
  152191. 9,
  152192. 4,
  152193. 10,
  152194. 3,
  152195. 11,
  152196. 2,
  152197. 12,
  152198. 1,
  152199. 13,
  152200. 0,
  152201. 14,
  152202. };
  152203. static long _vq_lengthlist__44u9_p8_0[] = {
  152204. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152205. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152206. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152207. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152208. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152209. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152210. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152211. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152212. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152213. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152214. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152215. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152216. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152217. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152218. 15,
  152219. };
  152220. static float _vq_quantthresh__44u9_p8_0[] = {
  152221. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152222. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152223. };
  152224. static long _vq_quantmap__44u9_p8_0[] = {
  152225. 13, 11, 9, 7, 5, 3, 1, 0,
  152226. 2, 4, 6, 8, 10, 12, 14,
  152227. };
  152228. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152229. _vq_quantthresh__44u9_p8_0,
  152230. _vq_quantmap__44u9_p8_0,
  152231. 15,
  152232. 15
  152233. };
  152234. static static_codebook _44u9_p8_0 = {
  152235. 2, 225,
  152236. _vq_lengthlist__44u9_p8_0,
  152237. 1, -520986624, 1620377600, 4, 0,
  152238. _vq_quantlist__44u9_p8_0,
  152239. NULL,
  152240. &_vq_auxt__44u9_p8_0,
  152241. NULL,
  152242. 0
  152243. };
  152244. static long _vq_quantlist__44u9_p8_1[] = {
  152245. 10,
  152246. 9,
  152247. 11,
  152248. 8,
  152249. 12,
  152250. 7,
  152251. 13,
  152252. 6,
  152253. 14,
  152254. 5,
  152255. 15,
  152256. 4,
  152257. 16,
  152258. 3,
  152259. 17,
  152260. 2,
  152261. 18,
  152262. 1,
  152263. 19,
  152264. 0,
  152265. 20,
  152266. };
  152267. static long _vq_lengthlist__44u9_p8_1[] = {
  152268. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152269. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152270. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152271. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152272. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152273. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152274. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152275. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152276. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152277. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152278. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152279. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152280. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152281. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152282. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152283. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152284. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152285. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152286. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152287. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152288. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152289. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152290. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152291. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152292. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152293. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152294. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152295. 10,10,10,10,10,10,10,10,10,
  152296. };
  152297. static float _vq_quantthresh__44u9_p8_1[] = {
  152298. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152299. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152300. 6.5, 7.5, 8.5, 9.5,
  152301. };
  152302. static long _vq_quantmap__44u9_p8_1[] = {
  152303. 19, 17, 15, 13, 11, 9, 7, 5,
  152304. 3, 1, 0, 2, 4, 6, 8, 10,
  152305. 12, 14, 16, 18, 20,
  152306. };
  152307. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152308. _vq_quantthresh__44u9_p8_1,
  152309. _vq_quantmap__44u9_p8_1,
  152310. 21,
  152311. 21
  152312. };
  152313. static static_codebook _44u9_p8_1 = {
  152314. 2, 441,
  152315. _vq_lengthlist__44u9_p8_1,
  152316. 1, -529268736, 1611661312, 5, 0,
  152317. _vq_quantlist__44u9_p8_1,
  152318. NULL,
  152319. &_vq_auxt__44u9_p8_1,
  152320. NULL,
  152321. 0
  152322. };
  152323. static long _vq_quantlist__44u9_p9_0[] = {
  152324. 7,
  152325. 6,
  152326. 8,
  152327. 5,
  152328. 9,
  152329. 4,
  152330. 10,
  152331. 3,
  152332. 11,
  152333. 2,
  152334. 12,
  152335. 1,
  152336. 13,
  152337. 0,
  152338. 14,
  152339. };
  152340. static long _vq_lengthlist__44u9_p9_0[] = {
  152341. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152342. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152343. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152344. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152345. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152346. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152347. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152348. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152349. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152350. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152351. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152352. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152353. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152354. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152355. 10,
  152356. };
  152357. static float _vq_quantthresh__44u9_p9_0[] = {
  152358. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152359. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152360. };
  152361. static long _vq_quantmap__44u9_p9_0[] = {
  152362. 13, 11, 9, 7, 5, 3, 1, 0,
  152363. 2, 4, 6, 8, 10, 12, 14,
  152364. };
  152365. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152366. _vq_quantthresh__44u9_p9_0,
  152367. _vq_quantmap__44u9_p9_0,
  152368. 15,
  152369. 15
  152370. };
  152371. static static_codebook _44u9_p9_0 = {
  152372. 2, 225,
  152373. _vq_lengthlist__44u9_p9_0,
  152374. 1, -510036736, 1631393792, 4, 0,
  152375. _vq_quantlist__44u9_p9_0,
  152376. NULL,
  152377. &_vq_auxt__44u9_p9_0,
  152378. NULL,
  152379. 0
  152380. };
  152381. static long _vq_quantlist__44u9_p9_1[] = {
  152382. 9,
  152383. 8,
  152384. 10,
  152385. 7,
  152386. 11,
  152387. 6,
  152388. 12,
  152389. 5,
  152390. 13,
  152391. 4,
  152392. 14,
  152393. 3,
  152394. 15,
  152395. 2,
  152396. 16,
  152397. 1,
  152398. 17,
  152399. 0,
  152400. 18,
  152401. };
  152402. static long _vq_lengthlist__44u9_p9_1[] = {
  152403. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152404. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152405. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152406. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152407. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152408. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152409. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152410. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152411. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152412. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152413. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152414. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152415. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152416. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152417. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152418. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152419. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152420. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152421. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152422. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152423. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152424. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152425. 17,17,15,17,15,17,16,16,17,
  152426. };
  152427. static float _vq_quantthresh__44u9_p9_1[] = {
  152428. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152429. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152430. 367.5, 416.5,
  152431. };
  152432. static long _vq_quantmap__44u9_p9_1[] = {
  152433. 17, 15, 13, 11, 9, 7, 5, 3,
  152434. 1, 0, 2, 4, 6, 8, 10, 12,
  152435. 14, 16, 18,
  152436. };
  152437. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152438. _vq_quantthresh__44u9_p9_1,
  152439. _vq_quantmap__44u9_p9_1,
  152440. 19,
  152441. 19
  152442. };
  152443. static static_codebook _44u9_p9_1 = {
  152444. 2, 361,
  152445. _vq_lengthlist__44u9_p9_1,
  152446. 1, -518287360, 1622704128, 5, 0,
  152447. _vq_quantlist__44u9_p9_1,
  152448. NULL,
  152449. &_vq_auxt__44u9_p9_1,
  152450. NULL,
  152451. 0
  152452. };
  152453. static long _vq_quantlist__44u9_p9_2[] = {
  152454. 24,
  152455. 23,
  152456. 25,
  152457. 22,
  152458. 26,
  152459. 21,
  152460. 27,
  152461. 20,
  152462. 28,
  152463. 19,
  152464. 29,
  152465. 18,
  152466. 30,
  152467. 17,
  152468. 31,
  152469. 16,
  152470. 32,
  152471. 15,
  152472. 33,
  152473. 14,
  152474. 34,
  152475. 13,
  152476. 35,
  152477. 12,
  152478. 36,
  152479. 11,
  152480. 37,
  152481. 10,
  152482. 38,
  152483. 9,
  152484. 39,
  152485. 8,
  152486. 40,
  152487. 7,
  152488. 41,
  152489. 6,
  152490. 42,
  152491. 5,
  152492. 43,
  152493. 4,
  152494. 44,
  152495. 3,
  152496. 45,
  152497. 2,
  152498. 46,
  152499. 1,
  152500. 47,
  152501. 0,
  152502. 48,
  152503. };
  152504. static long _vq_lengthlist__44u9_p9_2[] = {
  152505. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152506. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152507. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152508. 7,
  152509. };
  152510. static float _vq_quantthresh__44u9_p9_2[] = {
  152511. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152512. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152513. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152514. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152515. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152516. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152517. };
  152518. static long _vq_quantmap__44u9_p9_2[] = {
  152519. 47, 45, 43, 41, 39, 37, 35, 33,
  152520. 31, 29, 27, 25, 23, 21, 19, 17,
  152521. 15, 13, 11, 9, 7, 5, 3, 1,
  152522. 0, 2, 4, 6, 8, 10, 12, 14,
  152523. 16, 18, 20, 22, 24, 26, 28, 30,
  152524. 32, 34, 36, 38, 40, 42, 44, 46,
  152525. 48,
  152526. };
  152527. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152528. _vq_quantthresh__44u9_p9_2,
  152529. _vq_quantmap__44u9_p9_2,
  152530. 49,
  152531. 49
  152532. };
  152533. static static_codebook _44u9_p9_2 = {
  152534. 1, 49,
  152535. _vq_lengthlist__44u9_p9_2,
  152536. 1, -526909440, 1611661312, 6, 0,
  152537. _vq_quantlist__44u9_p9_2,
  152538. NULL,
  152539. &_vq_auxt__44u9_p9_2,
  152540. NULL,
  152541. 0
  152542. };
  152543. static long _huff_lengthlist__44un1__long[] = {
  152544. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152545. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152546. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152547. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152548. };
  152549. static static_codebook _huff_book__44un1__long = {
  152550. 2, 64,
  152551. _huff_lengthlist__44un1__long,
  152552. 0, 0, 0, 0, 0,
  152553. NULL,
  152554. NULL,
  152555. NULL,
  152556. NULL,
  152557. 0
  152558. };
  152559. static long _vq_quantlist__44un1__p1_0[] = {
  152560. 1,
  152561. 0,
  152562. 2,
  152563. };
  152564. static long _vq_lengthlist__44un1__p1_0[] = {
  152565. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152566. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152567. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152568. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152569. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152570. 12,
  152571. };
  152572. static float _vq_quantthresh__44un1__p1_0[] = {
  152573. -0.5, 0.5,
  152574. };
  152575. static long _vq_quantmap__44un1__p1_0[] = {
  152576. 1, 0, 2,
  152577. };
  152578. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152579. _vq_quantthresh__44un1__p1_0,
  152580. _vq_quantmap__44un1__p1_0,
  152581. 3,
  152582. 3
  152583. };
  152584. static static_codebook _44un1__p1_0 = {
  152585. 4, 81,
  152586. _vq_lengthlist__44un1__p1_0,
  152587. 1, -535822336, 1611661312, 2, 0,
  152588. _vq_quantlist__44un1__p1_0,
  152589. NULL,
  152590. &_vq_auxt__44un1__p1_0,
  152591. NULL,
  152592. 0
  152593. };
  152594. static long _vq_quantlist__44un1__p2_0[] = {
  152595. 1,
  152596. 0,
  152597. 2,
  152598. };
  152599. static long _vq_lengthlist__44un1__p2_0[] = {
  152600. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152601. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152602. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152603. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152604. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152605. 8,
  152606. };
  152607. static float _vq_quantthresh__44un1__p2_0[] = {
  152608. -0.5, 0.5,
  152609. };
  152610. static long _vq_quantmap__44un1__p2_0[] = {
  152611. 1, 0, 2,
  152612. };
  152613. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152614. _vq_quantthresh__44un1__p2_0,
  152615. _vq_quantmap__44un1__p2_0,
  152616. 3,
  152617. 3
  152618. };
  152619. static static_codebook _44un1__p2_0 = {
  152620. 4, 81,
  152621. _vq_lengthlist__44un1__p2_0,
  152622. 1, -535822336, 1611661312, 2, 0,
  152623. _vq_quantlist__44un1__p2_0,
  152624. NULL,
  152625. &_vq_auxt__44un1__p2_0,
  152626. NULL,
  152627. 0
  152628. };
  152629. static long _vq_quantlist__44un1__p3_0[] = {
  152630. 2,
  152631. 1,
  152632. 3,
  152633. 0,
  152634. 4,
  152635. };
  152636. static long _vq_lengthlist__44un1__p3_0[] = {
  152637. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152638. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152639. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152640. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152641. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152642. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152643. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152644. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152645. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152646. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152647. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152648. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152649. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152650. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152651. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152652. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152653. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152654. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152655. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152656. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152657. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152658. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152659. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152660. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152661. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152662. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152663. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152664. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152665. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152666. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152667. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152668. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152669. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152670. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152671. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152672. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152673. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152674. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152675. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152676. 17,
  152677. };
  152678. static float _vq_quantthresh__44un1__p3_0[] = {
  152679. -1.5, -0.5, 0.5, 1.5,
  152680. };
  152681. static long _vq_quantmap__44un1__p3_0[] = {
  152682. 3, 1, 0, 2, 4,
  152683. };
  152684. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152685. _vq_quantthresh__44un1__p3_0,
  152686. _vq_quantmap__44un1__p3_0,
  152687. 5,
  152688. 5
  152689. };
  152690. static static_codebook _44un1__p3_0 = {
  152691. 4, 625,
  152692. _vq_lengthlist__44un1__p3_0,
  152693. 1, -533725184, 1611661312, 3, 0,
  152694. _vq_quantlist__44un1__p3_0,
  152695. NULL,
  152696. &_vq_auxt__44un1__p3_0,
  152697. NULL,
  152698. 0
  152699. };
  152700. static long _vq_quantlist__44un1__p4_0[] = {
  152701. 2,
  152702. 1,
  152703. 3,
  152704. 0,
  152705. 4,
  152706. };
  152707. static long _vq_lengthlist__44un1__p4_0[] = {
  152708. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152709. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152710. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152711. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152712. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152713. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152714. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152715. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152716. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152717. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152718. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152719. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152720. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152721. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152722. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152723. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152724. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152725. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152726. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152727. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152728. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152729. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152730. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152731. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152732. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152733. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152734. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152735. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152736. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152737. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152738. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152739. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152740. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152741. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152742. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152743. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152744. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152745. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152746. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152747. 12,
  152748. };
  152749. static float _vq_quantthresh__44un1__p4_0[] = {
  152750. -1.5, -0.5, 0.5, 1.5,
  152751. };
  152752. static long _vq_quantmap__44un1__p4_0[] = {
  152753. 3, 1, 0, 2, 4,
  152754. };
  152755. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152756. _vq_quantthresh__44un1__p4_0,
  152757. _vq_quantmap__44un1__p4_0,
  152758. 5,
  152759. 5
  152760. };
  152761. static static_codebook _44un1__p4_0 = {
  152762. 4, 625,
  152763. _vq_lengthlist__44un1__p4_0,
  152764. 1, -533725184, 1611661312, 3, 0,
  152765. _vq_quantlist__44un1__p4_0,
  152766. NULL,
  152767. &_vq_auxt__44un1__p4_0,
  152768. NULL,
  152769. 0
  152770. };
  152771. static long _vq_quantlist__44un1__p5_0[] = {
  152772. 4,
  152773. 3,
  152774. 5,
  152775. 2,
  152776. 6,
  152777. 1,
  152778. 7,
  152779. 0,
  152780. 8,
  152781. };
  152782. static long _vq_lengthlist__44un1__p5_0[] = {
  152783. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152784. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152785. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152786. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152787. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152788. 12,
  152789. };
  152790. static float _vq_quantthresh__44un1__p5_0[] = {
  152791. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152792. };
  152793. static long _vq_quantmap__44un1__p5_0[] = {
  152794. 7, 5, 3, 1, 0, 2, 4, 6,
  152795. 8,
  152796. };
  152797. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152798. _vq_quantthresh__44un1__p5_0,
  152799. _vq_quantmap__44un1__p5_0,
  152800. 9,
  152801. 9
  152802. };
  152803. static static_codebook _44un1__p5_0 = {
  152804. 2, 81,
  152805. _vq_lengthlist__44un1__p5_0,
  152806. 1, -531628032, 1611661312, 4, 0,
  152807. _vq_quantlist__44un1__p5_0,
  152808. NULL,
  152809. &_vq_auxt__44un1__p5_0,
  152810. NULL,
  152811. 0
  152812. };
  152813. static long _vq_quantlist__44un1__p6_0[] = {
  152814. 6,
  152815. 5,
  152816. 7,
  152817. 4,
  152818. 8,
  152819. 3,
  152820. 9,
  152821. 2,
  152822. 10,
  152823. 1,
  152824. 11,
  152825. 0,
  152826. 12,
  152827. };
  152828. static long _vq_lengthlist__44un1__p6_0[] = {
  152829. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152830. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152831. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152832. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152833. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152834. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152835. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152836. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152837. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152838. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152839. 16, 0,15,18,18, 0,16, 0, 0,
  152840. };
  152841. static float _vq_quantthresh__44un1__p6_0[] = {
  152842. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152843. 12.5, 17.5, 22.5, 27.5,
  152844. };
  152845. static long _vq_quantmap__44un1__p6_0[] = {
  152846. 11, 9, 7, 5, 3, 1, 0, 2,
  152847. 4, 6, 8, 10, 12,
  152848. };
  152849. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152850. _vq_quantthresh__44un1__p6_0,
  152851. _vq_quantmap__44un1__p6_0,
  152852. 13,
  152853. 13
  152854. };
  152855. static static_codebook _44un1__p6_0 = {
  152856. 2, 169,
  152857. _vq_lengthlist__44un1__p6_0,
  152858. 1, -526516224, 1616117760, 4, 0,
  152859. _vq_quantlist__44un1__p6_0,
  152860. NULL,
  152861. &_vq_auxt__44un1__p6_0,
  152862. NULL,
  152863. 0
  152864. };
  152865. static long _vq_quantlist__44un1__p6_1[] = {
  152866. 2,
  152867. 1,
  152868. 3,
  152869. 0,
  152870. 4,
  152871. };
  152872. static long _vq_lengthlist__44un1__p6_1[] = {
  152873. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152874. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152875. };
  152876. static float _vq_quantthresh__44un1__p6_1[] = {
  152877. -1.5, -0.5, 0.5, 1.5,
  152878. };
  152879. static long _vq_quantmap__44un1__p6_1[] = {
  152880. 3, 1, 0, 2, 4,
  152881. };
  152882. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152883. _vq_quantthresh__44un1__p6_1,
  152884. _vq_quantmap__44un1__p6_1,
  152885. 5,
  152886. 5
  152887. };
  152888. static static_codebook _44un1__p6_1 = {
  152889. 2, 25,
  152890. _vq_lengthlist__44un1__p6_1,
  152891. 1, -533725184, 1611661312, 3, 0,
  152892. _vq_quantlist__44un1__p6_1,
  152893. NULL,
  152894. &_vq_auxt__44un1__p6_1,
  152895. NULL,
  152896. 0
  152897. };
  152898. static long _vq_quantlist__44un1__p7_0[] = {
  152899. 2,
  152900. 1,
  152901. 3,
  152902. 0,
  152903. 4,
  152904. };
  152905. static long _vq_lengthlist__44un1__p7_0[] = {
  152906. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152907. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152909. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152913. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152914. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152915. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152916. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152918. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152919. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152920. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152921. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152922. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152923. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152925. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152926. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152928. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152929. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152930. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152931. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152932. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152933. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152934. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152935. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152938. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152939. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152942. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152943. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152944. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152945. 10,
  152946. };
  152947. static float _vq_quantthresh__44un1__p7_0[] = {
  152948. -253.5, -84.5, 84.5, 253.5,
  152949. };
  152950. static long _vq_quantmap__44un1__p7_0[] = {
  152951. 3, 1, 0, 2, 4,
  152952. };
  152953. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152954. _vq_quantthresh__44un1__p7_0,
  152955. _vq_quantmap__44un1__p7_0,
  152956. 5,
  152957. 5
  152958. };
  152959. static static_codebook _44un1__p7_0 = {
  152960. 4, 625,
  152961. _vq_lengthlist__44un1__p7_0,
  152962. 1, -518709248, 1626677248, 3, 0,
  152963. _vq_quantlist__44un1__p7_0,
  152964. NULL,
  152965. &_vq_auxt__44un1__p7_0,
  152966. NULL,
  152967. 0
  152968. };
  152969. static long _vq_quantlist__44un1__p7_1[] = {
  152970. 6,
  152971. 5,
  152972. 7,
  152973. 4,
  152974. 8,
  152975. 3,
  152976. 9,
  152977. 2,
  152978. 10,
  152979. 1,
  152980. 11,
  152981. 0,
  152982. 12,
  152983. };
  152984. static long _vq_lengthlist__44un1__p7_1[] = {
  152985. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152986. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152987. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152988. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152989. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152990. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152991. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152992. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152993. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152994. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152995. 12,13,13,12,13,13,14,14,14,
  152996. };
  152997. static float _vq_quantthresh__44un1__p7_1[] = {
  152998. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152999. 32.5, 45.5, 58.5, 71.5,
  153000. };
  153001. static long _vq_quantmap__44un1__p7_1[] = {
  153002. 11, 9, 7, 5, 3, 1, 0, 2,
  153003. 4, 6, 8, 10, 12,
  153004. };
  153005. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153006. _vq_quantthresh__44un1__p7_1,
  153007. _vq_quantmap__44un1__p7_1,
  153008. 13,
  153009. 13
  153010. };
  153011. static static_codebook _44un1__p7_1 = {
  153012. 2, 169,
  153013. _vq_lengthlist__44un1__p7_1,
  153014. 1, -523010048, 1618608128, 4, 0,
  153015. _vq_quantlist__44un1__p7_1,
  153016. NULL,
  153017. &_vq_auxt__44un1__p7_1,
  153018. NULL,
  153019. 0
  153020. };
  153021. static long _vq_quantlist__44un1__p7_2[] = {
  153022. 6,
  153023. 5,
  153024. 7,
  153025. 4,
  153026. 8,
  153027. 3,
  153028. 9,
  153029. 2,
  153030. 10,
  153031. 1,
  153032. 11,
  153033. 0,
  153034. 12,
  153035. };
  153036. static long _vq_lengthlist__44un1__p7_2[] = {
  153037. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153038. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153039. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153040. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153041. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153042. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153043. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153044. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153045. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153046. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153047. 9, 9, 9,10,10,10,10,10,10,
  153048. };
  153049. static float _vq_quantthresh__44un1__p7_2[] = {
  153050. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153051. 2.5, 3.5, 4.5, 5.5,
  153052. };
  153053. static long _vq_quantmap__44un1__p7_2[] = {
  153054. 11, 9, 7, 5, 3, 1, 0, 2,
  153055. 4, 6, 8, 10, 12,
  153056. };
  153057. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153058. _vq_quantthresh__44un1__p7_2,
  153059. _vq_quantmap__44un1__p7_2,
  153060. 13,
  153061. 13
  153062. };
  153063. static static_codebook _44un1__p7_2 = {
  153064. 2, 169,
  153065. _vq_lengthlist__44un1__p7_2,
  153066. 1, -531103744, 1611661312, 4, 0,
  153067. _vq_quantlist__44un1__p7_2,
  153068. NULL,
  153069. &_vq_auxt__44un1__p7_2,
  153070. NULL,
  153071. 0
  153072. };
  153073. static long _huff_lengthlist__44un1__short[] = {
  153074. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153075. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153076. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153077. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153078. };
  153079. static static_codebook _huff_book__44un1__short = {
  153080. 2, 64,
  153081. _huff_lengthlist__44un1__short,
  153082. 0, 0, 0, 0, 0,
  153083. NULL,
  153084. NULL,
  153085. NULL,
  153086. NULL,
  153087. 0
  153088. };
  153089. /*** End of inlined file: res_books_uncoupled.h ***/
  153090. /***** residue backends *********************************************/
  153091. static vorbis_info_residue0 _residue_44_low_un={
  153092. 0,-1, -1, 8,-1,
  153093. {0},
  153094. {-1},
  153095. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153096. { -1, 25, -1, 45, -1, -1, -1}
  153097. };
  153098. static vorbis_info_residue0 _residue_44_mid_un={
  153099. 0,-1, -1, 10,-1,
  153100. /* 0 1 2 3 4 5 6 7 8 9 */
  153101. {0},
  153102. {-1},
  153103. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153104. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153105. };
  153106. static vorbis_info_residue0 _residue_44_hi_un={
  153107. 0,-1, -1, 10,-1,
  153108. /* 0 1 2 3 4 5 6 7 8 9 */
  153109. {0},
  153110. {-1},
  153111. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153112. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153113. };
  153114. /* mapping conventions:
  153115. only one submap (this would change for efficient 5.1 support for example)*/
  153116. /* Four psychoacoustic profiles are used, one for each blocktype */
  153117. static vorbis_info_mapping0 _map_nominal_u[2]={
  153118. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153119. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153120. };
  153121. static static_bookblock _resbook_44u_n1={
  153122. {
  153123. {0},
  153124. {0,0,&_44un1__p1_0},
  153125. {0,0,&_44un1__p2_0},
  153126. {0,0,&_44un1__p3_0},
  153127. {0,0,&_44un1__p4_0},
  153128. {0,0,&_44un1__p5_0},
  153129. {&_44un1__p6_0,&_44un1__p6_1},
  153130. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153131. }
  153132. };
  153133. static static_bookblock _resbook_44u_0={
  153134. {
  153135. {0},
  153136. {0,0,&_44u0__p1_0},
  153137. {0,0,&_44u0__p2_0},
  153138. {0,0,&_44u0__p3_0},
  153139. {0,0,&_44u0__p4_0},
  153140. {0,0,&_44u0__p5_0},
  153141. {&_44u0__p6_0,&_44u0__p6_1},
  153142. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153143. }
  153144. };
  153145. static static_bookblock _resbook_44u_1={
  153146. {
  153147. {0},
  153148. {0,0,&_44u1__p1_0},
  153149. {0,0,&_44u1__p2_0},
  153150. {0,0,&_44u1__p3_0},
  153151. {0,0,&_44u1__p4_0},
  153152. {0,0,&_44u1__p5_0},
  153153. {&_44u1__p6_0,&_44u1__p6_1},
  153154. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153155. }
  153156. };
  153157. static static_bookblock _resbook_44u_2={
  153158. {
  153159. {0},
  153160. {0,0,&_44u2__p1_0},
  153161. {0,0,&_44u2__p2_0},
  153162. {0,0,&_44u2__p3_0},
  153163. {0,0,&_44u2__p4_0},
  153164. {0,0,&_44u2__p5_0},
  153165. {&_44u2__p6_0,&_44u2__p6_1},
  153166. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153167. }
  153168. };
  153169. static static_bookblock _resbook_44u_3={
  153170. {
  153171. {0},
  153172. {0,0,&_44u3__p1_0},
  153173. {0,0,&_44u3__p2_0},
  153174. {0,0,&_44u3__p3_0},
  153175. {0,0,&_44u3__p4_0},
  153176. {0,0,&_44u3__p5_0},
  153177. {&_44u3__p6_0,&_44u3__p6_1},
  153178. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153179. }
  153180. };
  153181. static static_bookblock _resbook_44u_4={
  153182. {
  153183. {0},
  153184. {0,0,&_44u4__p1_0},
  153185. {0,0,&_44u4__p2_0},
  153186. {0,0,&_44u4__p3_0},
  153187. {0,0,&_44u4__p4_0},
  153188. {0,0,&_44u4__p5_0},
  153189. {&_44u4__p6_0,&_44u4__p6_1},
  153190. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153191. }
  153192. };
  153193. static static_bookblock _resbook_44u_5={
  153194. {
  153195. {0},
  153196. {0,0,&_44u5__p1_0},
  153197. {0,0,&_44u5__p2_0},
  153198. {0,0,&_44u5__p3_0},
  153199. {0,0,&_44u5__p4_0},
  153200. {0,0,&_44u5__p5_0},
  153201. {0,0,&_44u5__p6_0},
  153202. {&_44u5__p7_0,&_44u5__p7_1},
  153203. {&_44u5__p8_0,&_44u5__p8_1},
  153204. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153205. }
  153206. };
  153207. static static_bookblock _resbook_44u_6={
  153208. {
  153209. {0},
  153210. {0,0,&_44u6__p1_0},
  153211. {0,0,&_44u6__p2_0},
  153212. {0,0,&_44u6__p3_0},
  153213. {0,0,&_44u6__p4_0},
  153214. {0,0,&_44u6__p5_0},
  153215. {0,0,&_44u6__p6_0},
  153216. {&_44u6__p7_0,&_44u6__p7_1},
  153217. {&_44u6__p8_0,&_44u6__p8_1},
  153218. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153219. }
  153220. };
  153221. static static_bookblock _resbook_44u_7={
  153222. {
  153223. {0},
  153224. {0,0,&_44u7__p1_0},
  153225. {0,0,&_44u7__p2_0},
  153226. {0,0,&_44u7__p3_0},
  153227. {0,0,&_44u7__p4_0},
  153228. {0,0,&_44u7__p5_0},
  153229. {0,0,&_44u7__p6_0},
  153230. {&_44u7__p7_0,&_44u7__p7_1},
  153231. {&_44u7__p8_0,&_44u7__p8_1},
  153232. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153233. }
  153234. };
  153235. static static_bookblock _resbook_44u_8={
  153236. {
  153237. {0},
  153238. {0,0,&_44u8_p1_0},
  153239. {0,0,&_44u8_p2_0},
  153240. {0,0,&_44u8_p3_0},
  153241. {0,0,&_44u8_p4_0},
  153242. {&_44u8_p5_0,&_44u8_p5_1},
  153243. {&_44u8_p6_0,&_44u8_p6_1},
  153244. {&_44u8_p7_0,&_44u8_p7_1},
  153245. {&_44u8_p8_0,&_44u8_p8_1},
  153246. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153247. }
  153248. };
  153249. static static_bookblock _resbook_44u_9={
  153250. {
  153251. {0},
  153252. {0,0,&_44u9_p1_0},
  153253. {0,0,&_44u9_p2_0},
  153254. {0,0,&_44u9_p3_0},
  153255. {0,0,&_44u9_p4_0},
  153256. {&_44u9_p5_0,&_44u9_p5_1},
  153257. {&_44u9_p6_0,&_44u9_p6_1},
  153258. {&_44u9_p7_0,&_44u9_p7_1},
  153259. {&_44u9_p8_0,&_44u9_p8_1},
  153260. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153261. }
  153262. };
  153263. static vorbis_residue_template _res_44u_n1[]={
  153264. {1,0, &_residue_44_low_un,
  153265. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153266. &_resbook_44u_n1,&_resbook_44u_n1},
  153267. {1,0, &_residue_44_low_un,
  153268. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153269. &_resbook_44u_n1,&_resbook_44u_n1}
  153270. };
  153271. static vorbis_residue_template _res_44u_0[]={
  153272. {1,0, &_residue_44_low_un,
  153273. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153274. &_resbook_44u_0,&_resbook_44u_0},
  153275. {1,0, &_residue_44_low_un,
  153276. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153277. &_resbook_44u_0,&_resbook_44u_0}
  153278. };
  153279. static vorbis_residue_template _res_44u_1[]={
  153280. {1,0, &_residue_44_low_un,
  153281. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153282. &_resbook_44u_1,&_resbook_44u_1},
  153283. {1,0, &_residue_44_low_un,
  153284. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153285. &_resbook_44u_1,&_resbook_44u_1}
  153286. };
  153287. static vorbis_residue_template _res_44u_2[]={
  153288. {1,0, &_residue_44_low_un,
  153289. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153290. &_resbook_44u_2,&_resbook_44u_2},
  153291. {1,0, &_residue_44_low_un,
  153292. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153293. &_resbook_44u_2,&_resbook_44u_2}
  153294. };
  153295. static vorbis_residue_template _res_44u_3[]={
  153296. {1,0, &_residue_44_low_un,
  153297. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153298. &_resbook_44u_3,&_resbook_44u_3},
  153299. {1,0, &_residue_44_low_un,
  153300. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153301. &_resbook_44u_3,&_resbook_44u_3}
  153302. };
  153303. static vorbis_residue_template _res_44u_4[]={
  153304. {1,0, &_residue_44_low_un,
  153305. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153306. &_resbook_44u_4,&_resbook_44u_4},
  153307. {1,0, &_residue_44_low_un,
  153308. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153309. &_resbook_44u_4,&_resbook_44u_4}
  153310. };
  153311. static vorbis_residue_template _res_44u_5[]={
  153312. {1,0, &_residue_44_mid_un,
  153313. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153314. &_resbook_44u_5,&_resbook_44u_5},
  153315. {1,0, &_residue_44_mid_un,
  153316. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153317. &_resbook_44u_5,&_resbook_44u_5}
  153318. };
  153319. static vorbis_residue_template _res_44u_6[]={
  153320. {1,0, &_residue_44_mid_un,
  153321. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153322. &_resbook_44u_6,&_resbook_44u_6},
  153323. {1,0, &_residue_44_mid_un,
  153324. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153325. &_resbook_44u_6,&_resbook_44u_6}
  153326. };
  153327. static vorbis_residue_template _res_44u_7[]={
  153328. {1,0, &_residue_44_mid_un,
  153329. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153330. &_resbook_44u_7,&_resbook_44u_7},
  153331. {1,0, &_residue_44_mid_un,
  153332. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153333. &_resbook_44u_7,&_resbook_44u_7}
  153334. };
  153335. static vorbis_residue_template _res_44u_8[]={
  153336. {1,0, &_residue_44_hi_un,
  153337. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153338. &_resbook_44u_8,&_resbook_44u_8},
  153339. {1,0, &_residue_44_hi_un,
  153340. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153341. &_resbook_44u_8,&_resbook_44u_8}
  153342. };
  153343. static vorbis_residue_template _res_44u_9[]={
  153344. {1,0, &_residue_44_hi_un,
  153345. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153346. &_resbook_44u_9,&_resbook_44u_9},
  153347. {1,0, &_residue_44_hi_un,
  153348. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153349. &_resbook_44u_9,&_resbook_44u_9}
  153350. };
  153351. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153352. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153353. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153354. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153355. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153356. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153357. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153358. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153359. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153360. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153361. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153362. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153363. };
  153364. /*** End of inlined file: residue_44u.h ***/
  153365. static double rate_mapping_44_un[12]={
  153366. 32000.,48000.,60000.,70000.,80000.,86000.,
  153367. 96000.,110000.,120000.,140000.,160000.,240001.
  153368. };
  153369. ve_setup_data_template ve_setup_44_uncoupled={
  153370. 11,
  153371. rate_mapping_44_un,
  153372. quality_mapping_44,
  153373. -1,
  153374. 40000,
  153375. 50000,
  153376. blocksize_short_44,
  153377. blocksize_long_44,
  153378. _psy_tone_masteratt_44,
  153379. _psy_tone_0dB,
  153380. _psy_tone_suppress,
  153381. _vp_tonemask_adj_otherblock,
  153382. _vp_tonemask_adj_longblock,
  153383. _vp_tonemask_adj_otherblock,
  153384. _psy_noiseguards_44,
  153385. _psy_noisebias_impulse,
  153386. _psy_noisebias_padding,
  153387. _psy_noisebias_trans,
  153388. _psy_noisebias_long,
  153389. _psy_noise_suppress,
  153390. _psy_compand_44,
  153391. _psy_compand_short_mapping,
  153392. _psy_compand_long_mapping,
  153393. {_noise_start_short_44,_noise_start_long_44},
  153394. {_noise_part_short_44,_noise_part_long_44},
  153395. _noise_thresh_44,
  153396. _psy_ath_floater,
  153397. _psy_ath_abs,
  153398. _psy_lowpass_44,
  153399. _psy_global_44,
  153400. _global_mapping_44,
  153401. NULL,
  153402. _floor_books,
  153403. _floor,
  153404. _floor_short_mapping_44,
  153405. _floor_long_mapping_44,
  153406. _mapres_template_44_uncoupled
  153407. };
  153408. /*** End of inlined file: setup_44u.h ***/
  153409. /*** Start of inlined file: setup_32.h ***/
  153410. static double rate_mapping_32[12]={
  153411. 18000.,28000.,35000.,45000.,56000.,60000.,
  153412. 75000.,90000.,100000.,115000.,150000.,190000.,
  153413. };
  153414. static double rate_mapping_32_un[12]={
  153415. 30000.,42000.,52000.,64000.,72000.,78000.,
  153416. 86000.,92000.,110000.,120000.,140000.,190000.,
  153417. };
  153418. static double _psy_lowpass_32[12]={
  153419. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153420. };
  153421. ve_setup_data_template ve_setup_32_stereo={
  153422. 11,
  153423. rate_mapping_32,
  153424. quality_mapping_44,
  153425. 2,
  153426. 26000,
  153427. 40000,
  153428. blocksize_short_44,
  153429. blocksize_long_44,
  153430. _psy_tone_masteratt_44,
  153431. _psy_tone_0dB,
  153432. _psy_tone_suppress,
  153433. _vp_tonemask_adj_otherblock,
  153434. _vp_tonemask_adj_longblock,
  153435. _vp_tonemask_adj_otherblock,
  153436. _psy_noiseguards_44,
  153437. _psy_noisebias_impulse,
  153438. _psy_noisebias_padding,
  153439. _psy_noisebias_trans,
  153440. _psy_noisebias_long,
  153441. _psy_noise_suppress,
  153442. _psy_compand_44,
  153443. _psy_compand_short_mapping,
  153444. _psy_compand_long_mapping,
  153445. {_noise_start_short_44,_noise_start_long_44},
  153446. {_noise_part_short_44,_noise_part_long_44},
  153447. _noise_thresh_44,
  153448. _psy_ath_floater,
  153449. _psy_ath_abs,
  153450. _psy_lowpass_32,
  153451. _psy_global_44,
  153452. _global_mapping_44,
  153453. _psy_stereo_modes_44,
  153454. _floor_books,
  153455. _floor,
  153456. _floor_short_mapping_44,
  153457. _floor_long_mapping_44,
  153458. _mapres_template_44_stereo
  153459. };
  153460. ve_setup_data_template ve_setup_32_uncoupled={
  153461. 11,
  153462. rate_mapping_32_un,
  153463. quality_mapping_44,
  153464. -1,
  153465. 26000,
  153466. 40000,
  153467. blocksize_short_44,
  153468. blocksize_long_44,
  153469. _psy_tone_masteratt_44,
  153470. _psy_tone_0dB,
  153471. _psy_tone_suppress,
  153472. _vp_tonemask_adj_otherblock,
  153473. _vp_tonemask_adj_longblock,
  153474. _vp_tonemask_adj_otherblock,
  153475. _psy_noiseguards_44,
  153476. _psy_noisebias_impulse,
  153477. _psy_noisebias_padding,
  153478. _psy_noisebias_trans,
  153479. _psy_noisebias_long,
  153480. _psy_noise_suppress,
  153481. _psy_compand_44,
  153482. _psy_compand_short_mapping,
  153483. _psy_compand_long_mapping,
  153484. {_noise_start_short_44,_noise_start_long_44},
  153485. {_noise_part_short_44,_noise_part_long_44},
  153486. _noise_thresh_44,
  153487. _psy_ath_floater,
  153488. _psy_ath_abs,
  153489. _psy_lowpass_32,
  153490. _psy_global_44,
  153491. _global_mapping_44,
  153492. NULL,
  153493. _floor_books,
  153494. _floor,
  153495. _floor_short_mapping_44,
  153496. _floor_long_mapping_44,
  153497. _mapres_template_44_uncoupled
  153498. };
  153499. /*** End of inlined file: setup_32.h ***/
  153500. /*** Start of inlined file: setup_8.h ***/
  153501. /*** Start of inlined file: psych_8.h ***/
  153502. static att3 _psy_tone_masteratt_8[3]={
  153503. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153504. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153505. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153506. };
  153507. static vp_adjblock _vp_tonemask_adj_8[3]={
  153508. /* adjust for mode zero */
  153509. /* 63 125 250 500 1 2 4 8 16 */
  153510. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153511. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153512. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153513. };
  153514. static noise3 _psy_noisebias_8[3]={
  153515. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153516. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153517. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153518. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153519. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153520. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153521. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153522. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153523. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153524. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153525. };
  153526. /* stereo mode by base quality level */
  153527. static adj_stereo _psy_stereo_modes_8[3]={
  153528. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153529. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153530. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153531. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153532. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153533. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153534. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153535. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153536. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153537. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153538. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153539. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153540. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153541. };
  153542. static noiseguard _psy_noiseguards_8[2]={
  153543. {10,10,-1},
  153544. {10,10,-1},
  153545. };
  153546. static compandblock _psy_compand_8[2]={
  153547. {{
  153548. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153549. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153550. 12,12,13,13,14,14,15, 15, /* 23dB */
  153551. 16,16,17,17,17,18,18, 19, /* 31dB */
  153552. 19,19,20,21,22,23,24, 25, /* 39dB */
  153553. }},
  153554. {{
  153555. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153556. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153557. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153558. 9,10,11,12,13,14,15, 16, /* 31dB */
  153559. 17,18,19,20,21,22,23, 24, /* 39dB */
  153560. }},
  153561. };
  153562. static double _psy_lowpass_8[3]={3.,4.,4.};
  153563. static int _noise_start_8[2]={
  153564. 64,64,
  153565. };
  153566. static int _noise_part_8[2]={
  153567. 8,8,
  153568. };
  153569. static int _psy_ath_floater_8[3]={
  153570. -100,-100,-105,
  153571. };
  153572. static int _psy_ath_abs_8[3]={
  153573. -130,-130,-140,
  153574. };
  153575. /*** End of inlined file: psych_8.h ***/
  153576. /*** Start of inlined file: residue_8.h ***/
  153577. /***** residue backends *********************************************/
  153578. static static_bookblock _resbook_8s_0={
  153579. {
  153580. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153581. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153582. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153583. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153584. }
  153585. };
  153586. static static_bookblock _resbook_8s_1={
  153587. {
  153588. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153589. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153590. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153591. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153592. }
  153593. };
  153594. static vorbis_residue_template _res_8s_0[]={
  153595. {2,0, &_residue_44_mid,
  153596. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153597. &_resbook_8s_0,&_resbook_8s_0},
  153598. };
  153599. static vorbis_residue_template _res_8s_1[]={
  153600. {2,0, &_residue_44_mid,
  153601. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153602. &_resbook_8s_1,&_resbook_8s_1},
  153603. };
  153604. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153605. { _map_nominal, _res_8s_0 }, /* 0 */
  153606. { _map_nominal, _res_8s_1 }, /* 1 */
  153607. };
  153608. static static_bookblock _resbook_8u_0={
  153609. {
  153610. {0},
  153611. {0,0,&_8u0__p1_0},
  153612. {0,0,&_8u0__p2_0},
  153613. {0,0,&_8u0__p3_0},
  153614. {0,0,&_8u0__p4_0},
  153615. {0,0,&_8u0__p5_0},
  153616. {&_8u0__p6_0,&_8u0__p6_1},
  153617. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153618. }
  153619. };
  153620. static static_bookblock _resbook_8u_1={
  153621. {
  153622. {0},
  153623. {0,0,&_8u1__p1_0},
  153624. {0,0,&_8u1__p2_0},
  153625. {0,0,&_8u1__p3_0},
  153626. {0,0,&_8u1__p4_0},
  153627. {0,0,&_8u1__p5_0},
  153628. {0,0,&_8u1__p6_0},
  153629. {&_8u1__p7_0,&_8u1__p7_1},
  153630. {&_8u1__p8_0,&_8u1__p8_1},
  153631. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153632. }
  153633. };
  153634. static vorbis_residue_template _res_8u_0[]={
  153635. {1,0, &_residue_44_low_un,
  153636. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153637. &_resbook_8u_0,&_resbook_8u_0},
  153638. };
  153639. static vorbis_residue_template _res_8u_1[]={
  153640. {1,0, &_residue_44_mid_un,
  153641. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153642. &_resbook_8u_1,&_resbook_8u_1},
  153643. };
  153644. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153645. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153646. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153647. };
  153648. /*** End of inlined file: residue_8.h ***/
  153649. static int blocksize_8[2]={
  153650. 512,512
  153651. };
  153652. static int _floor_mapping_8[2]={
  153653. 6,6,
  153654. };
  153655. static double rate_mapping_8[3]={
  153656. 6000.,9000.,32000.,
  153657. };
  153658. static double rate_mapping_8_uncoupled[3]={
  153659. 8000.,14000.,42000.,
  153660. };
  153661. static double quality_mapping_8[3]={
  153662. -.1,.0,1.
  153663. };
  153664. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153665. static double _global_mapping_8[3]={ 1., 2., 3. };
  153666. ve_setup_data_template ve_setup_8_stereo={
  153667. 2,
  153668. rate_mapping_8,
  153669. quality_mapping_8,
  153670. 2,
  153671. 8000,
  153672. 9000,
  153673. blocksize_8,
  153674. blocksize_8,
  153675. _psy_tone_masteratt_8,
  153676. _psy_tone_0dB,
  153677. _psy_tone_suppress,
  153678. _vp_tonemask_adj_8,
  153679. NULL,
  153680. _vp_tonemask_adj_8,
  153681. _psy_noiseguards_8,
  153682. _psy_noisebias_8,
  153683. _psy_noisebias_8,
  153684. NULL,
  153685. NULL,
  153686. _psy_noise_suppress,
  153687. _psy_compand_8,
  153688. _psy_compand_8_mapping,
  153689. NULL,
  153690. {_noise_start_8,_noise_start_8},
  153691. {_noise_part_8,_noise_part_8},
  153692. _noise_thresh_5only,
  153693. _psy_ath_floater_8,
  153694. _psy_ath_abs_8,
  153695. _psy_lowpass_8,
  153696. _psy_global_44,
  153697. _global_mapping_8,
  153698. _psy_stereo_modes_8,
  153699. _floor_books,
  153700. _floor,
  153701. _floor_mapping_8,
  153702. NULL,
  153703. _mapres_template_8_stereo
  153704. };
  153705. ve_setup_data_template ve_setup_8_uncoupled={
  153706. 2,
  153707. rate_mapping_8_uncoupled,
  153708. quality_mapping_8,
  153709. -1,
  153710. 8000,
  153711. 9000,
  153712. blocksize_8,
  153713. blocksize_8,
  153714. _psy_tone_masteratt_8,
  153715. _psy_tone_0dB,
  153716. _psy_tone_suppress,
  153717. _vp_tonemask_adj_8,
  153718. NULL,
  153719. _vp_tonemask_adj_8,
  153720. _psy_noiseguards_8,
  153721. _psy_noisebias_8,
  153722. _psy_noisebias_8,
  153723. NULL,
  153724. NULL,
  153725. _psy_noise_suppress,
  153726. _psy_compand_8,
  153727. _psy_compand_8_mapping,
  153728. NULL,
  153729. {_noise_start_8,_noise_start_8},
  153730. {_noise_part_8,_noise_part_8},
  153731. _noise_thresh_5only,
  153732. _psy_ath_floater_8,
  153733. _psy_ath_abs_8,
  153734. _psy_lowpass_8,
  153735. _psy_global_44,
  153736. _global_mapping_8,
  153737. _psy_stereo_modes_8,
  153738. _floor_books,
  153739. _floor,
  153740. _floor_mapping_8,
  153741. NULL,
  153742. _mapres_template_8_uncoupled
  153743. };
  153744. /*** End of inlined file: setup_8.h ***/
  153745. /*** Start of inlined file: setup_11.h ***/
  153746. /*** Start of inlined file: psych_11.h ***/
  153747. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153748. static att3 _psy_tone_masteratt_11[3]={
  153749. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153750. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153751. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153752. };
  153753. static vp_adjblock _vp_tonemask_adj_11[3]={
  153754. /* adjust for mode zero */
  153755. /* 63 125 250 500 1 2 4 8 16 */
  153756. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153757. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153758. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153759. };
  153760. static noise3 _psy_noisebias_11[3]={
  153761. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153762. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153763. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153764. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153765. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153766. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153767. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153768. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153769. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153770. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153771. };
  153772. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153773. /*** End of inlined file: psych_11.h ***/
  153774. static int blocksize_11[2]={
  153775. 512,512
  153776. };
  153777. static int _floor_mapping_11[2]={
  153778. 6,6,
  153779. };
  153780. static double rate_mapping_11[3]={
  153781. 8000.,13000.,44000.,
  153782. };
  153783. static double rate_mapping_11_uncoupled[3]={
  153784. 12000.,20000.,50000.,
  153785. };
  153786. static double quality_mapping_11[3]={
  153787. -.1,.0,1.
  153788. };
  153789. ve_setup_data_template ve_setup_11_stereo={
  153790. 2,
  153791. rate_mapping_11,
  153792. quality_mapping_11,
  153793. 2,
  153794. 9000,
  153795. 15000,
  153796. blocksize_11,
  153797. blocksize_11,
  153798. _psy_tone_masteratt_11,
  153799. _psy_tone_0dB,
  153800. _psy_tone_suppress,
  153801. _vp_tonemask_adj_11,
  153802. NULL,
  153803. _vp_tonemask_adj_11,
  153804. _psy_noiseguards_8,
  153805. _psy_noisebias_11,
  153806. _psy_noisebias_11,
  153807. NULL,
  153808. NULL,
  153809. _psy_noise_suppress,
  153810. _psy_compand_8,
  153811. _psy_compand_8_mapping,
  153812. NULL,
  153813. {_noise_start_8,_noise_start_8},
  153814. {_noise_part_8,_noise_part_8},
  153815. _noise_thresh_11,
  153816. _psy_ath_floater_8,
  153817. _psy_ath_abs_8,
  153818. _psy_lowpass_11,
  153819. _psy_global_44,
  153820. _global_mapping_8,
  153821. _psy_stereo_modes_8,
  153822. _floor_books,
  153823. _floor,
  153824. _floor_mapping_11,
  153825. NULL,
  153826. _mapres_template_8_stereo
  153827. };
  153828. ve_setup_data_template ve_setup_11_uncoupled={
  153829. 2,
  153830. rate_mapping_11_uncoupled,
  153831. quality_mapping_11,
  153832. -1,
  153833. 9000,
  153834. 15000,
  153835. blocksize_11,
  153836. blocksize_11,
  153837. _psy_tone_masteratt_11,
  153838. _psy_tone_0dB,
  153839. _psy_tone_suppress,
  153840. _vp_tonemask_adj_11,
  153841. NULL,
  153842. _vp_tonemask_adj_11,
  153843. _psy_noiseguards_8,
  153844. _psy_noisebias_11,
  153845. _psy_noisebias_11,
  153846. NULL,
  153847. NULL,
  153848. _psy_noise_suppress,
  153849. _psy_compand_8,
  153850. _psy_compand_8_mapping,
  153851. NULL,
  153852. {_noise_start_8,_noise_start_8},
  153853. {_noise_part_8,_noise_part_8},
  153854. _noise_thresh_11,
  153855. _psy_ath_floater_8,
  153856. _psy_ath_abs_8,
  153857. _psy_lowpass_11,
  153858. _psy_global_44,
  153859. _global_mapping_8,
  153860. _psy_stereo_modes_8,
  153861. _floor_books,
  153862. _floor,
  153863. _floor_mapping_11,
  153864. NULL,
  153865. _mapres_template_8_uncoupled
  153866. };
  153867. /*** End of inlined file: setup_11.h ***/
  153868. /*** Start of inlined file: setup_16.h ***/
  153869. /*** Start of inlined file: psych_16.h ***/
  153870. /* stereo mode by base quality level */
  153871. static adj_stereo _psy_stereo_modes_16[4]={
  153872. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153873. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153874. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153875. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153876. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153877. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153878. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153879. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153880. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153881. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153882. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153883. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153884. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153885. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153886. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153887. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153888. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153889. };
  153890. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153891. static att3 _psy_tone_masteratt_16[4]={
  153892. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153893. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153894. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153895. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153896. };
  153897. static vp_adjblock _vp_tonemask_adj_16[4]={
  153898. /* adjust for mode zero */
  153899. /* 63 125 250 500 1 2 4 8 16 */
  153900. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153901. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153902. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153903. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153904. };
  153905. static noise3 _psy_noisebias_16_short[4]={
  153906. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153907. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153908. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153909. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153910. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153911. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153912. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153913. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153914. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153915. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153916. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153917. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153918. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153919. };
  153920. static noise3 _psy_noisebias_16_impulse[4]={
  153921. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153922. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153923. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153924. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153925. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153926. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153927. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153928. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153929. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153930. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153931. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153932. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153933. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153934. };
  153935. static noise3 _psy_noisebias_16[4]={
  153936. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153937. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153938. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153939. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153940. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153941. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153942. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153943. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153944. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153945. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153946. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153947. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153948. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153949. };
  153950. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153951. static int _noise_start_16[3]={ 256,256,9999 };
  153952. static int _noise_part_16[4]={ 8,8,8,8 };
  153953. static int _psy_ath_floater_16[4]={
  153954. -100,-100,-100,-105,
  153955. };
  153956. static int _psy_ath_abs_16[4]={
  153957. -130,-130,-130,-140,
  153958. };
  153959. /*** End of inlined file: psych_16.h ***/
  153960. /*** Start of inlined file: residue_16.h ***/
  153961. /***** residue backends *********************************************/
  153962. static static_bookblock _resbook_16s_0={
  153963. {
  153964. {0},
  153965. {0,0,&_16c0_s_p1_0},
  153966. {0,0,&_16c0_s_p2_0},
  153967. {0,0,&_16c0_s_p3_0},
  153968. {0,0,&_16c0_s_p4_0},
  153969. {0,0,&_16c0_s_p5_0},
  153970. {0,0,&_16c0_s_p6_0},
  153971. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153972. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153973. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153974. }
  153975. };
  153976. static static_bookblock _resbook_16s_1={
  153977. {
  153978. {0},
  153979. {0,0,&_16c1_s_p1_0},
  153980. {0,0,&_16c1_s_p2_0},
  153981. {0,0,&_16c1_s_p3_0},
  153982. {0,0,&_16c1_s_p4_0},
  153983. {0,0,&_16c1_s_p5_0},
  153984. {0,0,&_16c1_s_p6_0},
  153985. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153986. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153987. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153988. }
  153989. };
  153990. static static_bookblock _resbook_16s_2={
  153991. {
  153992. {0},
  153993. {0,0,&_16c2_s_p1_0},
  153994. {0,0,&_16c2_s_p2_0},
  153995. {0,0,&_16c2_s_p3_0},
  153996. {0,0,&_16c2_s_p4_0},
  153997. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153998. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153999. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154000. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154001. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154002. }
  154003. };
  154004. static vorbis_residue_template _res_16s_0[]={
  154005. {2,0, &_residue_44_mid,
  154006. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154007. &_resbook_16s_0,&_resbook_16s_0},
  154008. };
  154009. static vorbis_residue_template _res_16s_1[]={
  154010. {2,0, &_residue_44_mid,
  154011. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154012. &_resbook_16s_1,&_resbook_16s_1},
  154013. {2,0, &_residue_44_mid,
  154014. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154015. &_resbook_16s_1,&_resbook_16s_1}
  154016. };
  154017. static vorbis_residue_template _res_16s_2[]={
  154018. {2,0, &_residue_44_high,
  154019. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154020. &_resbook_16s_2,&_resbook_16s_2},
  154021. {2,0, &_residue_44_high,
  154022. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154023. &_resbook_16s_2,&_resbook_16s_2}
  154024. };
  154025. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154026. { _map_nominal, _res_16s_0 }, /* 0 */
  154027. { _map_nominal, _res_16s_1 }, /* 1 */
  154028. { _map_nominal, _res_16s_2 }, /* 2 */
  154029. };
  154030. static static_bookblock _resbook_16u_0={
  154031. {
  154032. {0},
  154033. {0,0,&_16u0__p1_0},
  154034. {0,0,&_16u0__p2_0},
  154035. {0,0,&_16u0__p3_0},
  154036. {0,0,&_16u0__p4_0},
  154037. {0,0,&_16u0__p5_0},
  154038. {&_16u0__p6_0,&_16u0__p6_1},
  154039. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154040. }
  154041. };
  154042. static static_bookblock _resbook_16u_1={
  154043. {
  154044. {0},
  154045. {0,0,&_16u1__p1_0},
  154046. {0,0,&_16u1__p2_0},
  154047. {0,0,&_16u1__p3_0},
  154048. {0,0,&_16u1__p4_0},
  154049. {0,0,&_16u1__p5_0},
  154050. {0,0,&_16u1__p6_0},
  154051. {&_16u1__p7_0,&_16u1__p7_1},
  154052. {&_16u1__p8_0,&_16u1__p8_1},
  154053. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154054. }
  154055. };
  154056. static static_bookblock _resbook_16u_2={
  154057. {
  154058. {0},
  154059. {0,0,&_16u2_p1_0},
  154060. {0,0,&_16u2_p2_0},
  154061. {0,0,&_16u2_p3_0},
  154062. {0,0,&_16u2_p4_0},
  154063. {&_16u2_p5_0,&_16u2_p5_1},
  154064. {&_16u2_p6_0,&_16u2_p6_1},
  154065. {&_16u2_p7_0,&_16u2_p7_1},
  154066. {&_16u2_p8_0,&_16u2_p8_1},
  154067. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154068. }
  154069. };
  154070. static vorbis_residue_template _res_16u_0[]={
  154071. {1,0, &_residue_44_low_un,
  154072. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154073. &_resbook_16u_0,&_resbook_16u_0},
  154074. };
  154075. static vorbis_residue_template _res_16u_1[]={
  154076. {1,0, &_residue_44_mid_un,
  154077. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154078. &_resbook_16u_1,&_resbook_16u_1},
  154079. {1,0, &_residue_44_mid_un,
  154080. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154081. &_resbook_16u_1,&_resbook_16u_1}
  154082. };
  154083. static vorbis_residue_template _res_16u_2[]={
  154084. {1,0, &_residue_44_hi_un,
  154085. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154086. &_resbook_16u_2,&_resbook_16u_2},
  154087. {1,0, &_residue_44_hi_un,
  154088. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154089. &_resbook_16u_2,&_resbook_16u_2}
  154090. };
  154091. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154092. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154093. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154094. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154095. };
  154096. /*** End of inlined file: residue_16.h ***/
  154097. static int blocksize_16_short[3]={
  154098. 1024,512,512
  154099. };
  154100. static int blocksize_16_long[3]={
  154101. 1024,1024,1024
  154102. };
  154103. static int _floor_mapping_16_short[3]={
  154104. 9,3,3
  154105. };
  154106. static int _floor_mapping_16[3]={
  154107. 9,9,9
  154108. };
  154109. static double rate_mapping_16[4]={
  154110. 12000.,20000.,44000.,86000.
  154111. };
  154112. static double rate_mapping_16_uncoupled[4]={
  154113. 16000.,28000.,64000.,100000.
  154114. };
  154115. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154116. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154117. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154118. ve_setup_data_template ve_setup_16_stereo={
  154119. 3,
  154120. rate_mapping_16,
  154121. quality_mapping_16,
  154122. 2,
  154123. 15000,
  154124. 19000,
  154125. blocksize_16_short,
  154126. blocksize_16_long,
  154127. _psy_tone_masteratt_16,
  154128. _psy_tone_0dB,
  154129. _psy_tone_suppress,
  154130. _vp_tonemask_adj_16,
  154131. _vp_tonemask_adj_16,
  154132. _vp_tonemask_adj_16,
  154133. _psy_noiseguards_8,
  154134. _psy_noisebias_16_impulse,
  154135. _psy_noisebias_16_short,
  154136. _psy_noisebias_16_short,
  154137. _psy_noisebias_16,
  154138. _psy_noise_suppress,
  154139. _psy_compand_8,
  154140. _psy_compand_16_mapping,
  154141. _psy_compand_16_mapping,
  154142. {_noise_start_16,_noise_start_16},
  154143. { _noise_part_16, _noise_part_16},
  154144. _noise_thresh_16,
  154145. _psy_ath_floater_16,
  154146. _psy_ath_abs_16,
  154147. _psy_lowpass_16,
  154148. _psy_global_44,
  154149. _global_mapping_16,
  154150. _psy_stereo_modes_16,
  154151. _floor_books,
  154152. _floor,
  154153. _floor_mapping_16_short,
  154154. _floor_mapping_16,
  154155. _mapres_template_16_stereo
  154156. };
  154157. ve_setup_data_template ve_setup_16_uncoupled={
  154158. 3,
  154159. rate_mapping_16_uncoupled,
  154160. quality_mapping_16,
  154161. -1,
  154162. 15000,
  154163. 19000,
  154164. blocksize_16_short,
  154165. blocksize_16_long,
  154166. _psy_tone_masteratt_16,
  154167. _psy_tone_0dB,
  154168. _psy_tone_suppress,
  154169. _vp_tonemask_adj_16,
  154170. _vp_tonemask_adj_16,
  154171. _vp_tonemask_adj_16,
  154172. _psy_noiseguards_8,
  154173. _psy_noisebias_16_impulse,
  154174. _psy_noisebias_16_short,
  154175. _psy_noisebias_16_short,
  154176. _psy_noisebias_16,
  154177. _psy_noise_suppress,
  154178. _psy_compand_8,
  154179. _psy_compand_16_mapping,
  154180. _psy_compand_16_mapping,
  154181. {_noise_start_16,_noise_start_16},
  154182. { _noise_part_16, _noise_part_16},
  154183. _noise_thresh_16,
  154184. _psy_ath_floater_16,
  154185. _psy_ath_abs_16,
  154186. _psy_lowpass_16,
  154187. _psy_global_44,
  154188. _global_mapping_16,
  154189. _psy_stereo_modes_16,
  154190. _floor_books,
  154191. _floor,
  154192. _floor_mapping_16_short,
  154193. _floor_mapping_16,
  154194. _mapres_template_16_uncoupled
  154195. };
  154196. /*** End of inlined file: setup_16.h ***/
  154197. /*** Start of inlined file: setup_22.h ***/
  154198. static double rate_mapping_22[4]={
  154199. 15000.,20000.,44000.,86000.
  154200. };
  154201. static double rate_mapping_22_uncoupled[4]={
  154202. 16000.,28000.,50000.,90000.
  154203. };
  154204. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154205. ve_setup_data_template ve_setup_22_stereo={
  154206. 3,
  154207. rate_mapping_22,
  154208. quality_mapping_16,
  154209. 2,
  154210. 19000,
  154211. 26000,
  154212. blocksize_16_short,
  154213. blocksize_16_long,
  154214. _psy_tone_masteratt_16,
  154215. _psy_tone_0dB,
  154216. _psy_tone_suppress,
  154217. _vp_tonemask_adj_16,
  154218. _vp_tonemask_adj_16,
  154219. _vp_tonemask_adj_16,
  154220. _psy_noiseguards_8,
  154221. _psy_noisebias_16_impulse,
  154222. _psy_noisebias_16_short,
  154223. _psy_noisebias_16_short,
  154224. _psy_noisebias_16,
  154225. _psy_noise_suppress,
  154226. _psy_compand_8,
  154227. _psy_compand_8_mapping,
  154228. _psy_compand_8_mapping,
  154229. {_noise_start_16,_noise_start_16},
  154230. { _noise_part_16, _noise_part_16},
  154231. _noise_thresh_16,
  154232. _psy_ath_floater_16,
  154233. _psy_ath_abs_16,
  154234. _psy_lowpass_22,
  154235. _psy_global_44,
  154236. _global_mapping_16,
  154237. _psy_stereo_modes_16,
  154238. _floor_books,
  154239. _floor,
  154240. _floor_mapping_16_short,
  154241. _floor_mapping_16,
  154242. _mapres_template_16_stereo
  154243. };
  154244. ve_setup_data_template ve_setup_22_uncoupled={
  154245. 3,
  154246. rate_mapping_22_uncoupled,
  154247. quality_mapping_16,
  154248. -1,
  154249. 19000,
  154250. 26000,
  154251. blocksize_16_short,
  154252. blocksize_16_long,
  154253. _psy_tone_masteratt_16,
  154254. _psy_tone_0dB,
  154255. _psy_tone_suppress,
  154256. _vp_tonemask_adj_16,
  154257. _vp_tonemask_adj_16,
  154258. _vp_tonemask_adj_16,
  154259. _psy_noiseguards_8,
  154260. _psy_noisebias_16_impulse,
  154261. _psy_noisebias_16_short,
  154262. _psy_noisebias_16_short,
  154263. _psy_noisebias_16,
  154264. _psy_noise_suppress,
  154265. _psy_compand_8,
  154266. _psy_compand_8_mapping,
  154267. _psy_compand_8_mapping,
  154268. {_noise_start_16,_noise_start_16},
  154269. { _noise_part_16, _noise_part_16},
  154270. _noise_thresh_16,
  154271. _psy_ath_floater_16,
  154272. _psy_ath_abs_16,
  154273. _psy_lowpass_22,
  154274. _psy_global_44,
  154275. _global_mapping_16,
  154276. _psy_stereo_modes_16,
  154277. _floor_books,
  154278. _floor,
  154279. _floor_mapping_16_short,
  154280. _floor_mapping_16,
  154281. _mapres_template_16_uncoupled
  154282. };
  154283. /*** End of inlined file: setup_22.h ***/
  154284. /*** Start of inlined file: setup_X.h ***/
  154285. static double rate_mapping_X[12]={
  154286. -1.,-1.,-1.,-1.,-1.,-1.,
  154287. -1.,-1.,-1.,-1.,-1.,-1.
  154288. };
  154289. ve_setup_data_template ve_setup_X_stereo={
  154290. 11,
  154291. rate_mapping_X,
  154292. quality_mapping_44,
  154293. 2,
  154294. 50000,
  154295. 200000,
  154296. blocksize_short_44,
  154297. blocksize_long_44,
  154298. _psy_tone_masteratt_44,
  154299. _psy_tone_0dB,
  154300. _psy_tone_suppress,
  154301. _vp_tonemask_adj_otherblock,
  154302. _vp_tonemask_adj_longblock,
  154303. _vp_tonemask_adj_otherblock,
  154304. _psy_noiseguards_44,
  154305. _psy_noisebias_impulse,
  154306. _psy_noisebias_padding,
  154307. _psy_noisebias_trans,
  154308. _psy_noisebias_long,
  154309. _psy_noise_suppress,
  154310. _psy_compand_44,
  154311. _psy_compand_short_mapping,
  154312. _psy_compand_long_mapping,
  154313. {_noise_start_short_44,_noise_start_long_44},
  154314. {_noise_part_short_44,_noise_part_long_44},
  154315. _noise_thresh_44,
  154316. _psy_ath_floater,
  154317. _psy_ath_abs,
  154318. _psy_lowpass_44,
  154319. _psy_global_44,
  154320. _global_mapping_44,
  154321. _psy_stereo_modes_44,
  154322. _floor_books,
  154323. _floor,
  154324. _floor_short_mapping_44,
  154325. _floor_long_mapping_44,
  154326. _mapres_template_44_stereo
  154327. };
  154328. ve_setup_data_template ve_setup_X_uncoupled={
  154329. 11,
  154330. rate_mapping_X,
  154331. quality_mapping_44,
  154332. -1,
  154333. 50000,
  154334. 200000,
  154335. blocksize_short_44,
  154336. blocksize_long_44,
  154337. _psy_tone_masteratt_44,
  154338. _psy_tone_0dB,
  154339. _psy_tone_suppress,
  154340. _vp_tonemask_adj_otherblock,
  154341. _vp_tonemask_adj_longblock,
  154342. _vp_tonemask_adj_otherblock,
  154343. _psy_noiseguards_44,
  154344. _psy_noisebias_impulse,
  154345. _psy_noisebias_padding,
  154346. _psy_noisebias_trans,
  154347. _psy_noisebias_long,
  154348. _psy_noise_suppress,
  154349. _psy_compand_44,
  154350. _psy_compand_short_mapping,
  154351. _psy_compand_long_mapping,
  154352. {_noise_start_short_44,_noise_start_long_44},
  154353. {_noise_part_short_44,_noise_part_long_44},
  154354. _noise_thresh_44,
  154355. _psy_ath_floater,
  154356. _psy_ath_abs,
  154357. _psy_lowpass_44,
  154358. _psy_global_44,
  154359. _global_mapping_44,
  154360. NULL,
  154361. _floor_books,
  154362. _floor,
  154363. _floor_short_mapping_44,
  154364. _floor_long_mapping_44,
  154365. _mapres_template_44_uncoupled
  154366. };
  154367. ve_setup_data_template ve_setup_XX_stereo={
  154368. 2,
  154369. rate_mapping_X,
  154370. quality_mapping_8,
  154371. 2,
  154372. 0,
  154373. 8000,
  154374. blocksize_8,
  154375. blocksize_8,
  154376. _psy_tone_masteratt_8,
  154377. _psy_tone_0dB,
  154378. _psy_tone_suppress,
  154379. _vp_tonemask_adj_8,
  154380. NULL,
  154381. _vp_tonemask_adj_8,
  154382. _psy_noiseguards_8,
  154383. _psy_noisebias_8,
  154384. _psy_noisebias_8,
  154385. NULL,
  154386. NULL,
  154387. _psy_noise_suppress,
  154388. _psy_compand_8,
  154389. _psy_compand_8_mapping,
  154390. NULL,
  154391. {_noise_start_8,_noise_start_8},
  154392. {_noise_part_8,_noise_part_8},
  154393. _noise_thresh_5only,
  154394. _psy_ath_floater_8,
  154395. _psy_ath_abs_8,
  154396. _psy_lowpass_8,
  154397. _psy_global_44,
  154398. _global_mapping_8,
  154399. _psy_stereo_modes_8,
  154400. _floor_books,
  154401. _floor,
  154402. _floor_mapping_8,
  154403. NULL,
  154404. _mapres_template_8_stereo
  154405. };
  154406. ve_setup_data_template ve_setup_XX_uncoupled={
  154407. 2,
  154408. rate_mapping_X,
  154409. quality_mapping_8,
  154410. -1,
  154411. 0,
  154412. 8000,
  154413. blocksize_8,
  154414. blocksize_8,
  154415. _psy_tone_masteratt_8,
  154416. _psy_tone_0dB,
  154417. _psy_tone_suppress,
  154418. _vp_tonemask_adj_8,
  154419. NULL,
  154420. _vp_tonemask_adj_8,
  154421. _psy_noiseguards_8,
  154422. _psy_noisebias_8,
  154423. _psy_noisebias_8,
  154424. NULL,
  154425. NULL,
  154426. _psy_noise_suppress,
  154427. _psy_compand_8,
  154428. _psy_compand_8_mapping,
  154429. NULL,
  154430. {_noise_start_8,_noise_start_8},
  154431. {_noise_part_8,_noise_part_8},
  154432. _noise_thresh_5only,
  154433. _psy_ath_floater_8,
  154434. _psy_ath_abs_8,
  154435. _psy_lowpass_8,
  154436. _psy_global_44,
  154437. _global_mapping_8,
  154438. _psy_stereo_modes_8,
  154439. _floor_books,
  154440. _floor,
  154441. _floor_mapping_8,
  154442. NULL,
  154443. _mapres_template_8_uncoupled
  154444. };
  154445. /*** End of inlined file: setup_X.h ***/
  154446. static ve_setup_data_template *setup_list[]={
  154447. &ve_setup_44_stereo,
  154448. &ve_setup_44_uncoupled,
  154449. &ve_setup_32_stereo,
  154450. &ve_setup_32_uncoupled,
  154451. &ve_setup_22_stereo,
  154452. &ve_setup_22_uncoupled,
  154453. &ve_setup_16_stereo,
  154454. &ve_setup_16_uncoupled,
  154455. &ve_setup_11_stereo,
  154456. &ve_setup_11_uncoupled,
  154457. &ve_setup_8_stereo,
  154458. &ve_setup_8_uncoupled,
  154459. &ve_setup_X_stereo,
  154460. &ve_setup_X_uncoupled,
  154461. &ve_setup_XX_stereo,
  154462. &ve_setup_XX_uncoupled,
  154463. 0
  154464. };
  154465. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154466. if(vi && vi->codec_setup){
  154467. vi->version=0;
  154468. vi->channels=ch;
  154469. vi->rate=rate;
  154470. return(0);
  154471. }
  154472. return(OV_EINVAL);
  154473. }
  154474. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154475. static_codebook ***books,
  154476. vorbis_info_floor1 *in,
  154477. int *x){
  154478. int i,k,is=s;
  154479. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154480. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154481. memcpy(f,in+x[is],sizeof(*f));
  154482. /* fill in the lowpass field, even if it's temporary */
  154483. f->n=ci->blocksizes[block]>>1;
  154484. /* books */
  154485. {
  154486. int partitions=f->partitions;
  154487. int maxclass=-1;
  154488. int maxbook=-1;
  154489. for(i=0;i<partitions;i++)
  154490. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154491. for(i=0;i<=maxclass;i++){
  154492. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154493. f->class_book[i]+=ci->books;
  154494. for(k=0;k<(1<<f->class_subs[i]);k++){
  154495. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154496. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154497. }
  154498. }
  154499. for(i=0;i<=maxbook;i++)
  154500. ci->book_param[ci->books++]=books[x[is]][i];
  154501. }
  154502. /* for now, we're only using floor 1 */
  154503. ci->floor_type[ci->floors]=1;
  154504. ci->floor_param[ci->floors]=f;
  154505. ci->floors++;
  154506. return;
  154507. }
  154508. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154509. vorbis_info_psy_global *in,
  154510. double *x){
  154511. int i,is=s;
  154512. double ds=s-is;
  154513. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154514. vorbis_info_psy_global *g=&ci->psy_g_param;
  154515. memcpy(g,in+(int)x[is],sizeof(*g));
  154516. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154517. is=(int)ds;
  154518. ds-=is;
  154519. if(ds==0 && is>0){
  154520. is--;
  154521. ds=1.;
  154522. }
  154523. /* interpolate the trigger threshholds */
  154524. for(i=0;i<4;i++){
  154525. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154526. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154527. }
  154528. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154529. return;
  154530. }
  154531. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154532. highlevel_encode_setup *hi,
  154533. adj_stereo *p){
  154534. float s=hi->stereo_point_setting;
  154535. int i,is=s;
  154536. double ds=s-is;
  154537. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154538. vorbis_info_psy_global *g=&ci->psy_g_param;
  154539. if(p){
  154540. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154541. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154542. if(hi->managed){
  154543. /* interpolate the kHz threshholds */
  154544. for(i=0;i<PACKETBLOBS;i++){
  154545. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154546. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154547. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154548. g->coupling_pkHz[i]=kHz;
  154549. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154550. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154551. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154552. }
  154553. }else{
  154554. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154555. for(i=0;i<PACKETBLOBS;i++){
  154556. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154557. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154558. g->coupling_pkHz[i]=kHz;
  154559. }
  154560. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154561. for(i=0;i<PACKETBLOBS;i++){
  154562. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154563. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154564. }
  154565. }
  154566. }else{
  154567. for(i=0;i<PACKETBLOBS;i++){
  154568. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154569. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154570. }
  154571. }
  154572. return;
  154573. }
  154574. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154575. int *nn_start,
  154576. int *nn_partition,
  154577. double *nn_thresh,
  154578. int block){
  154579. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154580. vorbis_info_psy *p=ci->psy_param[block];
  154581. highlevel_encode_setup *hi=&ci->hi;
  154582. int is=s;
  154583. if(block>=ci->psys)
  154584. ci->psys=block+1;
  154585. if(!p){
  154586. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154587. ci->psy_param[block]=p;
  154588. }
  154589. memcpy(p,&_psy_info_template,sizeof(*p));
  154590. p->blockflag=block>>1;
  154591. if(hi->noise_normalize_p){
  154592. p->normal_channel_p=1;
  154593. p->normal_point_p=1;
  154594. p->normal_start=nn_start[is];
  154595. p->normal_partition=nn_partition[is];
  154596. p->normal_thresh=nn_thresh[is];
  154597. }
  154598. return;
  154599. }
  154600. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154601. att3 *att,
  154602. int *max,
  154603. vp_adjblock *in){
  154604. int i,is=s;
  154605. double ds=s-is;
  154606. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154607. vorbis_info_psy *p=ci->psy_param[block];
  154608. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154609. filling the values in here */
  154610. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154611. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154612. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154613. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154614. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154615. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154616. for(i=0;i<P_BANDS;i++)
  154617. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154618. return;
  154619. }
  154620. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154621. compandblock *in, double *x){
  154622. int i,is=s;
  154623. double ds=s-is;
  154624. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154625. vorbis_info_psy *p=ci->psy_param[block];
  154626. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154627. is=(int)ds;
  154628. ds-=is;
  154629. if(ds==0 && is>0){
  154630. is--;
  154631. ds=1.;
  154632. }
  154633. /* interpolate the compander settings */
  154634. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154635. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154636. return;
  154637. }
  154638. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154639. int *suppress){
  154640. int is=s;
  154641. double ds=s-is;
  154642. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154643. vorbis_info_psy *p=ci->psy_param[block];
  154644. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154645. return;
  154646. }
  154647. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154648. int *suppress,
  154649. noise3 *in,
  154650. noiseguard *guard,
  154651. double userbias){
  154652. int i,is=s,j;
  154653. double ds=s-is;
  154654. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154655. vorbis_info_psy *p=ci->psy_param[block];
  154656. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154657. p->noisewindowlomin=guard[block].lo;
  154658. p->noisewindowhimin=guard[block].hi;
  154659. p->noisewindowfixed=guard[block].fixed;
  154660. for(j=0;j<P_NOISECURVES;j++)
  154661. for(i=0;i<P_BANDS;i++)
  154662. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154663. /* impulse blocks may take a user specified bias to boost the
  154664. nominal/high noise encoding depth */
  154665. for(j=0;j<P_NOISECURVES;j++){
  154666. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154667. for(i=0;i<P_BANDS;i++){
  154668. p->noiseoff[j][i]+=userbias;
  154669. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154670. }
  154671. }
  154672. return;
  154673. }
  154674. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154675. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154676. vorbis_info_psy *p=ci->psy_param[block];
  154677. p->ath_adjatt=ci->hi.ath_floating_dB;
  154678. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154679. return;
  154680. }
  154681. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154682. int i;
  154683. for(i=0;i<ci->books;i++)
  154684. if(ci->book_param[i]==book)return(i);
  154685. return(ci->books++);
  154686. }
  154687. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154688. int *shortb,int *longb){
  154689. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154690. int is=s;
  154691. int blockshort=shortb[is];
  154692. int blocklong=longb[is];
  154693. ci->blocksizes[0]=blockshort;
  154694. ci->blocksizes[1]=blocklong;
  154695. }
  154696. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154697. int number, int block,
  154698. vorbis_residue_template *res){
  154699. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154700. int i,n;
  154701. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154702. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154703. memcpy(r,res->res,sizeof(*r));
  154704. if(ci->residues<=number)ci->residues=number+1;
  154705. switch(ci->blocksizes[block]){
  154706. case 64:case 128:case 256:
  154707. r->grouping=16;
  154708. break;
  154709. default:
  154710. r->grouping=32;
  154711. break;
  154712. }
  154713. ci->residue_type[number]=res->res_type;
  154714. /* to be adjusted by lowpass/pointlimit later */
  154715. n=r->end=ci->blocksizes[block]>>1;
  154716. if(res->res_type==2)
  154717. n=r->end*=vi->channels;
  154718. /* fill in all the books */
  154719. {
  154720. int booklist=0,k;
  154721. if(ci->hi.managed){
  154722. for(i=0;i<r->partitions;i++)
  154723. for(k=0;k<3;k++)
  154724. if(res->books_base_managed->books[i][k])
  154725. r->secondstages[i]|=(1<<k);
  154726. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154727. ci->book_param[r->groupbook]=res->book_aux_managed;
  154728. for(i=0;i<r->partitions;i++){
  154729. for(k=0;k<3;k++){
  154730. if(res->books_base_managed->books[i][k]){
  154731. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154732. r->booklist[booklist++]=bookid;
  154733. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154734. }
  154735. }
  154736. }
  154737. }else{
  154738. for(i=0;i<r->partitions;i++)
  154739. for(k=0;k<3;k++)
  154740. if(res->books_base->books[i][k])
  154741. r->secondstages[i]|=(1<<k);
  154742. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154743. ci->book_param[r->groupbook]=res->book_aux;
  154744. for(i=0;i<r->partitions;i++){
  154745. for(k=0;k<3;k++){
  154746. if(res->books_base->books[i][k]){
  154747. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154748. r->booklist[booklist++]=bookid;
  154749. ci->book_param[bookid]=res->books_base->books[i][k];
  154750. }
  154751. }
  154752. }
  154753. }
  154754. }
  154755. /* lowpass setup/pointlimit */
  154756. {
  154757. double freq=ci->hi.lowpass_kHz*1000.;
  154758. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154759. double nyq=vi->rate/2.;
  154760. long blocksize=ci->blocksizes[block]>>1;
  154761. /* lowpass needs to be set in the floor and the residue. */
  154762. if(freq>nyq)freq=nyq;
  154763. /* in the floor, the granularity can be very fine; it doesn't alter
  154764. the encoding structure, only the samples used to fit the floor
  154765. approximation */
  154766. f->n=freq/nyq*blocksize;
  154767. /* this res may by limited by the maximum pointlimit of the mode,
  154768. not the lowpass. the floor is always lowpass limited. */
  154769. if(res->limit_type){
  154770. if(ci->hi.managed)
  154771. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154772. else
  154773. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154774. if(freq>nyq)freq=nyq;
  154775. }
  154776. /* in the residue, we're constrained, physically, by partition
  154777. boundaries. We still lowpass 'wherever', but we have to round up
  154778. here to next boundary, or the vorbis spec will round it *down* to
  154779. previous boundary in encode/decode */
  154780. if(ci->residue_type[block]==2)
  154781. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154782. r->grouping;
  154783. else
  154784. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154785. r->grouping;
  154786. }
  154787. }
  154788. /* we assume two maps in this encoder */
  154789. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154790. vorbis_mapping_template *maps){
  154791. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154792. int i,j,is=s,modes=2;
  154793. vorbis_info_mapping0 *map=maps[is].map;
  154794. vorbis_info_mode *mode=_mode_template;
  154795. vorbis_residue_template *res=maps[is].res;
  154796. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154797. for(i=0;i<modes;i++){
  154798. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154799. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154800. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154801. if(i>=ci->modes)ci->modes=i+1;
  154802. ci->map_type[i]=0;
  154803. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154804. if(i>=ci->maps)ci->maps=i+1;
  154805. for(j=0;j<map[i].submaps;j++)
  154806. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154807. ,res+map[i].residuesubmap[j]);
  154808. }
  154809. }
  154810. static double setting_to_approx_bitrate(vorbis_info *vi){
  154811. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154812. highlevel_encode_setup *hi=&ci->hi;
  154813. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154814. int is=hi->base_setting;
  154815. double ds=hi->base_setting-is;
  154816. int ch=vi->channels;
  154817. double *r=setup->rate_mapping;
  154818. if(r==NULL)
  154819. return(-1);
  154820. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154821. }
  154822. static void get_setup_template(vorbis_info *vi,
  154823. long ch,long srate,
  154824. double req,int q_or_bitrate){
  154825. int i=0,j;
  154826. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154827. highlevel_encode_setup *hi=&ci->hi;
  154828. if(q_or_bitrate)req/=ch;
  154829. while(setup_list[i]){
  154830. if(setup_list[i]->coupling_restriction==-1 ||
  154831. setup_list[i]->coupling_restriction==ch){
  154832. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154833. srate<=setup_list[i]->samplerate_max_restriction){
  154834. int mappings=setup_list[i]->mappings;
  154835. double *map=(q_or_bitrate?
  154836. setup_list[i]->rate_mapping:
  154837. setup_list[i]->quality_mapping);
  154838. /* the template matches. Does the requested quality mode
  154839. fall within this template's modes? */
  154840. if(req<map[0]){++i;continue;}
  154841. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154842. for(j=0;j<mappings;j++)
  154843. if(req>=map[j] && req<map[j+1])break;
  154844. /* an all-points match */
  154845. hi->setup=setup_list[i];
  154846. if(j==mappings)
  154847. hi->base_setting=j-.001;
  154848. else{
  154849. float low=map[j];
  154850. float high=map[j+1];
  154851. float del=(req-low)/(high-low);
  154852. hi->base_setting=j+del;
  154853. }
  154854. return;
  154855. }
  154856. }
  154857. i++;
  154858. }
  154859. hi->setup=NULL;
  154860. }
  154861. /* encoders will need to use vorbis_info_init beforehand and call
  154862. vorbis_info clear when all done */
  154863. /* two interfaces; this, more detailed one, and later a convenience
  154864. layer on top */
  154865. /* the final setup call */
  154866. int vorbis_encode_setup_init(vorbis_info *vi){
  154867. int i0=0,singleblock=0;
  154868. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154869. ve_setup_data_template *setup=NULL;
  154870. highlevel_encode_setup *hi=&ci->hi;
  154871. if(ci==NULL)return(OV_EINVAL);
  154872. if(!hi->impulse_block_p)i0=1;
  154873. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154874. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154875. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154876. /* again, bound this to avoid the app shooting itself int he foot
  154877. too badly */
  154878. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154879. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154880. /* get the appropriate setup template; matches the fetch in previous
  154881. stages */
  154882. setup=(ve_setup_data_template *)hi->setup;
  154883. if(setup==NULL)return(OV_EINVAL);
  154884. hi->set_in_stone=1;
  154885. /* choose block sizes from configured sizes as well as paying
  154886. attention to long_block_p and short_block_p. If the configured
  154887. short and long blocks are the same length, we set long_block_p
  154888. and unset short_block_p */
  154889. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154890. setup->blocksize_short,
  154891. setup->blocksize_long);
  154892. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154893. /* floor setup; choose proper floor params. Allocated on the floor
  154894. stack in order; if we alloc only long floor, it's 0 */
  154895. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154896. setup->floor_books,
  154897. setup->floor_params,
  154898. setup->floor_short_mapping);
  154899. if(!singleblock)
  154900. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154901. setup->floor_books,
  154902. setup->floor_params,
  154903. setup->floor_long_mapping);
  154904. /* setup of [mostly] short block detection and stereo*/
  154905. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154906. setup->global_params,
  154907. setup->global_mapping);
  154908. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154909. /* basic psych setup and noise normalization */
  154910. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154911. setup->psy_noise_normal_start[0],
  154912. setup->psy_noise_normal_partition[0],
  154913. setup->psy_noise_normal_thresh,
  154914. 0);
  154915. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154916. setup->psy_noise_normal_start[0],
  154917. setup->psy_noise_normal_partition[0],
  154918. setup->psy_noise_normal_thresh,
  154919. 1);
  154920. if(!singleblock){
  154921. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154922. setup->psy_noise_normal_start[1],
  154923. setup->psy_noise_normal_partition[1],
  154924. setup->psy_noise_normal_thresh,
  154925. 2);
  154926. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154927. setup->psy_noise_normal_start[1],
  154928. setup->psy_noise_normal_partition[1],
  154929. setup->psy_noise_normal_thresh,
  154930. 3);
  154931. }
  154932. /* tone masking setup */
  154933. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154934. setup->psy_tone_masteratt,
  154935. setup->psy_tone_0dB,
  154936. setup->psy_tone_adj_impulse);
  154937. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154938. setup->psy_tone_masteratt,
  154939. setup->psy_tone_0dB,
  154940. setup->psy_tone_adj_other);
  154941. if(!singleblock){
  154942. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154943. setup->psy_tone_masteratt,
  154944. setup->psy_tone_0dB,
  154945. setup->psy_tone_adj_other);
  154946. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154947. setup->psy_tone_masteratt,
  154948. setup->psy_tone_0dB,
  154949. setup->psy_tone_adj_long);
  154950. }
  154951. /* noise companding setup */
  154952. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154953. setup->psy_noise_compand,
  154954. setup->psy_noise_compand_short_mapping);
  154955. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154956. setup->psy_noise_compand,
  154957. setup->psy_noise_compand_short_mapping);
  154958. if(!singleblock){
  154959. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154960. setup->psy_noise_compand,
  154961. setup->psy_noise_compand_long_mapping);
  154962. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154963. setup->psy_noise_compand,
  154964. setup->psy_noise_compand_long_mapping);
  154965. }
  154966. /* peak guarding setup */
  154967. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154968. setup->psy_tone_dBsuppress);
  154969. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154970. setup->psy_tone_dBsuppress);
  154971. if(!singleblock){
  154972. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154973. setup->psy_tone_dBsuppress);
  154974. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154975. setup->psy_tone_dBsuppress);
  154976. }
  154977. /* noise bias setup */
  154978. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154979. setup->psy_noise_dBsuppress,
  154980. setup->psy_noise_bias_impulse,
  154981. setup->psy_noiseguards,
  154982. (i0==0?hi->impulse_noisetune:0.));
  154983. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154984. setup->psy_noise_dBsuppress,
  154985. setup->psy_noise_bias_padding,
  154986. setup->psy_noiseguards,0.);
  154987. if(!singleblock){
  154988. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154989. setup->psy_noise_dBsuppress,
  154990. setup->psy_noise_bias_trans,
  154991. setup->psy_noiseguards,0.);
  154992. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154993. setup->psy_noise_dBsuppress,
  154994. setup->psy_noise_bias_long,
  154995. setup->psy_noiseguards,0.);
  154996. }
  154997. vorbis_encode_ath_setup(vi,0);
  154998. vorbis_encode_ath_setup(vi,1);
  154999. if(!singleblock){
  155000. vorbis_encode_ath_setup(vi,2);
  155001. vorbis_encode_ath_setup(vi,3);
  155002. }
  155003. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155004. /* set bitrate readonlies and management */
  155005. if(hi->bitrate_av>0)
  155006. vi->bitrate_nominal=hi->bitrate_av;
  155007. else{
  155008. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155009. }
  155010. vi->bitrate_lower=hi->bitrate_min;
  155011. vi->bitrate_upper=hi->bitrate_max;
  155012. if(hi->bitrate_av)
  155013. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155014. else
  155015. vi->bitrate_window=0.;
  155016. if(hi->managed){
  155017. ci->bi.avg_rate=hi->bitrate_av;
  155018. ci->bi.min_rate=hi->bitrate_min;
  155019. ci->bi.max_rate=hi->bitrate_max;
  155020. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155021. ci->bi.reservoir_bias=
  155022. hi->bitrate_reservoir_bias;
  155023. ci->bi.slew_damp=hi->bitrate_av_damp;
  155024. }
  155025. return(0);
  155026. }
  155027. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155028. long channels,
  155029. long rate){
  155030. int ret=0,i,is;
  155031. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155032. highlevel_encode_setup *hi=&ci->hi;
  155033. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155034. double ds;
  155035. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155036. if(ret)return(ret);
  155037. is=hi->base_setting;
  155038. ds=hi->base_setting-is;
  155039. hi->short_setting=hi->base_setting;
  155040. hi->long_setting=hi->base_setting;
  155041. hi->managed=0;
  155042. hi->impulse_block_p=1;
  155043. hi->noise_normalize_p=1;
  155044. hi->stereo_point_setting=hi->base_setting;
  155045. hi->lowpass_kHz=
  155046. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155047. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155048. setup->psy_ath_float[is+1]*ds;
  155049. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155050. setup->psy_ath_abs[is+1]*ds;
  155051. hi->amplitude_track_dBpersec=-6.;
  155052. hi->trigger_setting=hi->base_setting;
  155053. for(i=0;i<4;i++){
  155054. hi->block[i].tone_mask_setting=hi->base_setting;
  155055. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155056. hi->block[i].noise_bias_setting=hi->base_setting;
  155057. hi->block[i].noise_compand_setting=hi->base_setting;
  155058. }
  155059. return(ret);
  155060. }
  155061. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155062. long channels,
  155063. long rate,
  155064. float quality){
  155065. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155066. highlevel_encode_setup *hi=&ci->hi;
  155067. quality+=.0000001;
  155068. if(quality>=1.)quality=.9999;
  155069. get_setup_template(vi,channels,rate,quality,0);
  155070. if(!hi->setup)return OV_EIMPL;
  155071. return vorbis_encode_setup_setting(vi,channels,rate);
  155072. }
  155073. int vorbis_encode_init_vbr(vorbis_info *vi,
  155074. long channels,
  155075. long rate,
  155076. float base_quality /* 0. to 1. */
  155077. ){
  155078. int ret=0;
  155079. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155080. if(ret){
  155081. vorbis_info_clear(vi);
  155082. return ret;
  155083. }
  155084. ret=vorbis_encode_setup_init(vi);
  155085. if(ret)
  155086. vorbis_info_clear(vi);
  155087. return(ret);
  155088. }
  155089. int vorbis_encode_setup_managed(vorbis_info *vi,
  155090. long channels,
  155091. long rate,
  155092. long max_bitrate,
  155093. long nominal_bitrate,
  155094. long min_bitrate){
  155095. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155096. highlevel_encode_setup *hi=&ci->hi;
  155097. double tnominal=nominal_bitrate;
  155098. int ret=0;
  155099. if(nominal_bitrate<=0.){
  155100. if(max_bitrate>0.){
  155101. if(min_bitrate>0.)
  155102. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155103. else
  155104. nominal_bitrate=max_bitrate*.875;
  155105. }else{
  155106. if(min_bitrate>0.){
  155107. nominal_bitrate=min_bitrate;
  155108. }else{
  155109. return(OV_EINVAL);
  155110. }
  155111. }
  155112. }
  155113. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155114. if(!hi->setup)return OV_EIMPL;
  155115. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155116. if(ret){
  155117. vorbis_info_clear(vi);
  155118. return ret;
  155119. }
  155120. /* initialize management with sane defaults */
  155121. hi->managed=1;
  155122. hi->bitrate_min=min_bitrate;
  155123. hi->bitrate_max=max_bitrate;
  155124. hi->bitrate_av=tnominal;
  155125. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155126. hi->bitrate_reservoir=nominal_bitrate*2;
  155127. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155128. return(ret);
  155129. }
  155130. int vorbis_encode_init(vorbis_info *vi,
  155131. long channels,
  155132. long rate,
  155133. long max_bitrate,
  155134. long nominal_bitrate,
  155135. long min_bitrate){
  155136. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155137. max_bitrate,
  155138. nominal_bitrate,
  155139. min_bitrate);
  155140. if(ret){
  155141. vorbis_info_clear(vi);
  155142. return(ret);
  155143. }
  155144. ret=vorbis_encode_setup_init(vi);
  155145. if(ret)
  155146. vorbis_info_clear(vi);
  155147. return(ret);
  155148. }
  155149. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155150. if(vi){
  155151. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155152. highlevel_encode_setup *hi=&ci->hi;
  155153. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155154. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155155. switch(number){
  155156. /* now deprecated *****************/
  155157. case OV_ECTL_RATEMANAGE_GET:
  155158. {
  155159. struct ovectl_ratemanage_arg *ai=
  155160. (struct ovectl_ratemanage_arg *)arg;
  155161. ai->management_active=hi->managed;
  155162. ai->bitrate_hard_window=ai->bitrate_av_window=
  155163. (double)hi->bitrate_reservoir/vi->rate;
  155164. ai->bitrate_av_window_center=1.;
  155165. ai->bitrate_hard_min=hi->bitrate_min;
  155166. ai->bitrate_hard_max=hi->bitrate_max;
  155167. ai->bitrate_av_lo=hi->bitrate_av;
  155168. ai->bitrate_av_hi=hi->bitrate_av;
  155169. }
  155170. return(0);
  155171. /* now deprecated *****************/
  155172. case OV_ECTL_RATEMANAGE_SET:
  155173. {
  155174. struct ovectl_ratemanage_arg *ai=
  155175. (struct ovectl_ratemanage_arg *)arg;
  155176. if(ai==NULL){
  155177. hi->managed=0;
  155178. }else{
  155179. hi->managed=ai->management_active;
  155180. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155181. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155182. }
  155183. }
  155184. return 0;
  155185. /* now deprecated *****************/
  155186. case OV_ECTL_RATEMANAGE_AVG:
  155187. {
  155188. struct ovectl_ratemanage_arg *ai=
  155189. (struct ovectl_ratemanage_arg *)arg;
  155190. if(ai==NULL){
  155191. hi->bitrate_av=0;
  155192. }else{
  155193. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155194. }
  155195. }
  155196. return(0);
  155197. /* now deprecated *****************/
  155198. case OV_ECTL_RATEMANAGE_HARD:
  155199. {
  155200. struct ovectl_ratemanage_arg *ai=
  155201. (struct ovectl_ratemanage_arg *)arg;
  155202. if(ai==NULL){
  155203. hi->bitrate_min=0;
  155204. hi->bitrate_max=0;
  155205. }else{
  155206. hi->bitrate_min=ai->bitrate_hard_min;
  155207. hi->bitrate_max=ai->bitrate_hard_max;
  155208. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155209. (hi->bitrate_max+hi->bitrate_min)*.5;
  155210. }
  155211. if(hi->bitrate_reservoir<128.)
  155212. hi->bitrate_reservoir=128.;
  155213. }
  155214. return(0);
  155215. /* replacement ratemanage interface */
  155216. case OV_ECTL_RATEMANAGE2_GET:
  155217. {
  155218. struct ovectl_ratemanage2_arg *ai=
  155219. (struct ovectl_ratemanage2_arg *)arg;
  155220. if(ai==NULL)return OV_EINVAL;
  155221. ai->management_active=hi->managed;
  155222. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155223. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155224. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155225. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155226. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155227. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155228. }
  155229. return (0);
  155230. case OV_ECTL_RATEMANAGE2_SET:
  155231. {
  155232. struct ovectl_ratemanage2_arg *ai=
  155233. (struct ovectl_ratemanage2_arg *)arg;
  155234. if(ai==NULL){
  155235. hi->managed=0;
  155236. }else{
  155237. /* sanity check; only catch invariant violations */
  155238. if(ai->bitrate_limit_min_kbps>0 &&
  155239. ai->bitrate_average_kbps>0 &&
  155240. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155241. return OV_EINVAL;
  155242. if(ai->bitrate_limit_max_kbps>0 &&
  155243. ai->bitrate_average_kbps>0 &&
  155244. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155245. return OV_EINVAL;
  155246. if(ai->bitrate_limit_min_kbps>0 &&
  155247. ai->bitrate_limit_max_kbps>0 &&
  155248. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155249. return OV_EINVAL;
  155250. if(ai->bitrate_average_damping <= 0.)
  155251. return OV_EINVAL;
  155252. if(ai->bitrate_limit_reservoir_bits < 0)
  155253. return OV_EINVAL;
  155254. if(ai->bitrate_limit_reservoir_bias < 0.)
  155255. return OV_EINVAL;
  155256. if(ai->bitrate_limit_reservoir_bias > 1.)
  155257. return OV_EINVAL;
  155258. hi->managed=ai->management_active;
  155259. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155260. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155261. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155262. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155263. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155264. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155265. }
  155266. }
  155267. return 0;
  155268. case OV_ECTL_LOWPASS_GET:
  155269. {
  155270. double *farg=(double *)arg;
  155271. *farg=hi->lowpass_kHz;
  155272. }
  155273. return(0);
  155274. case OV_ECTL_LOWPASS_SET:
  155275. {
  155276. double *farg=(double *)arg;
  155277. hi->lowpass_kHz=*farg;
  155278. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155279. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155280. }
  155281. return(0);
  155282. case OV_ECTL_IBLOCK_GET:
  155283. {
  155284. double *farg=(double *)arg;
  155285. *farg=hi->impulse_noisetune;
  155286. }
  155287. return(0);
  155288. case OV_ECTL_IBLOCK_SET:
  155289. {
  155290. double *farg=(double *)arg;
  155291. hi->impulse_noisetune=*farg;
  155292. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155293. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155294. }
  155295. return(0);
  155296. }
  155297. return(OV_EIMPL);
  155298. }
  155299. return(OV_EINVAL);
  155300. }
  155301. #endif
  155302. /*** End of inlined file: vorbisenc.c ***/
  155303. /*** Start of inlined file: vorbisfile.c ***/
  155304. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155305. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155306. // tasks..
  155307. #if JUCE_MSVC
  155308. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155309. #endif
  155310. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155311. #if JUCE_USE_OGGVORBIS
  155312. #include <stdlib.h>
  155313. #include <stdio.h>
  155314. #include <errno.h>
  155315. #include <string.h>
  155316. #include <math.h>
  155317. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155318. one logical bitstream arranged end to end (the only form of Ogg
  155319. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155320. multiplexing] is not allowed in Vorbis) */
  155321. /* A Vorbis file can be played beginning to end (streamed) without
  155322. worrying ahead of time about chaining (see decoder_example.c). If
  155323. we have the whole file, however, and want random access
  155324. (seeking/scrubbing) or desire to know the total length/time of a
  155325. file, we need to account for the possibility of chaining. */
  155326. /* We can handle things a number of ways; we can determine the entire
  155327. bitstream structure right off the bat, or find pieces on demand.
  155328. This example determines and caches structure for the entire
  155329. bitstream, but builds a virtual decoder on the fly when moving
  155330. between links in the chain. */
  155331. /* There are also different ways to implement seeking. Enough
  155332. information exists in an Ogg bitstream to seek to
  155333. sample-granularity positions in the output. Or, one can seek by
  155334. picking some portion of the stream roughly in the desired area if
  155335. we only want coarse navigation through the stream. */
  155336. /*************************************************************************
  155337. * Many, many internal helpers. The intention is not to be confusing;
  155338. * rampant duplication and monolithic function implementation would be
  155339. * harder to understand anyway. The high level functions are last. Begin
  155340. * grokking near the end of the file */
  155341. /* read a little more data from the file/pipe into the ogg_sync framer
  155342. */
  155343. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155344. over 8k gets what they deserve */
  155345. static long _get_data(OggVorbis_File *vf){
  155346. errno=0;
  155347. if(vf->datasource){
  155348. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155349. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155350. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155351. if(bytes==0 && errno)return(-1);
  155352. return(bytes);
  155353. }else
  155354. return(0);
  155355. }
  155356. /* save a tiny smidge of verbosity to make the code more readable */
  155357. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155358. if(vf->datasource){
  155359. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155360. vf->offset=offset;
  155361. ogg_sync_reset(&vf->oy);
  155362. }else{
  155363. /* shouldn't happen unless someone writes a broken callback */
  155364. return;
  155365. }
  155366. }
  155367. /* The read/seek functions track absolute position within the stream */
  155368. /* from the head of the stream, get the next page. boundary specifies
  155369. if the function is allowed to fetch more data from the stream (and
  155370. how much) or only use internally buffered data.
  155371. boundary: -1) unbounded search
  155372. 0) read no additional data; use cached only
  155373. n) search for a new page beginning for n bytes
  155374. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155375. n) found a page at absolute offset n */
  155376. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155377. ogg_int64_t boundary){
  155378. if(boundary>0)boundary+=vf->offset;
  155379. while(1){
  155380. long more;
  155381. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155382. more=ogg_sync_pageseek(&vf->oy,og);
  155383. if(more<0){
  155384. /* skipped n bytes */
  155385. vf->offset-=more;
  155386. }else{
  155387. if(more==0){
  155388. /* send more paramedics */
  155389. if(!boundary)return(OV_FALSE);
  155390. {
  155391. long ret=_get_data(vf);
  155392. if(ret==0)return(OV_EOF);
  155393. if(ret<0)return(OV_EREAD);
  155394. }
  155395. }else{
  155396. /* got a page. Return the offset at the page beginning,
  155397. advance the internal offset past the page end */
  155398. ogg_int64_t ret=vf->offset;
  155399. vf->offset+=more;
  155400. return(ret);
  155401. }
  155402. }
  155403. }
  155404. }
  155405. /* find the latest page beginning before the current stream cursor
  155406. position. Much dirtier than the above as Ogg doesn't have any
  155407. backward search linkage. no 'readp' as it will certainly have to
  155408. read. */
  155409. /* returns offset or OV_EREAD, OV_FAULT */
  155410. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155411. ogg_int64_t begin=vf->offset;
  155412. ogg_int64_t end=begin;
  155413. ogg_int64_t ret;
  155414. ogg_int64_t offset=-1;
  155415. while(offset==-1){
  155416. begin-=CHUNKSIZE;
  155417. if(begin<0)
  155418. begin=0;
  155419. _seek_helper(vf,begin);
  155420. while(vf->offset<end){
  155421. ret=_get_next_page(vf,og,end-vf->offset);
  155422. if(ret==OV_EREAD)return(OV_EREAD);
  155423. if(ret<0){
  155424. break;
  155425. }else{
  155426. offset=ret;
  155427. }
  155428. }
  155429. }
  155430. /* we have the offset. Actually snork and hold the page now */
  155431. _seek_helper(vf,offset);
  155432. ret=_get_next_page(vf,og,CHUNKSIZE);
  155433. if(ret<0)
  155434. /* this shouldn't be possible */
  155435. return(OV_EFAULT);
  155436. return(offset);
  155437. }
  155438. /* finds each bitstream link one at a time using a bisection search
  155439. (has to begin by knowing the offset of the lb's initial page).
  155440. Recurses for each link so it can alloc the link storage after
  155441. finding them all, then unroll and fill the cache at the same time */
  155442. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155443. ogg_int64_t begin,
  155444. ogg_int64_t searched,
  155445. ogg_int64_t end,
  155446. long currentno,
  155447. long m){
  155448. ogg_int64_t endsearched=end;
  155449. ogg_int64_t next=end;
  155450. ogg_page og;
  155451. ogg_int64_t ret;
  155452. /* the below guards against garbage seperating the last and
  155453. first pages of two links. */
  155454. while(searched<endsearched){
  155455. ogg_int64_t bisect;
  155456. if(endsearched-searched<CHUNKSIZE){
  155457. bisect=searched;
  155458. }else{
  155459. bisect=(searched+endsearched)/2;
  155460. }
  155461. _seek_helper(vf,bisect);
  155462. ret=_get_next_page(vf,&og,-1);
  155463. if(ret==OV_EREAD)return(OV_EREAD);
  155464. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155465. endsearched=bisect;
  155466. if(ret>=0)next=ret;
  155467. }else{
  155468. searched=ret+og.header_len+og.body_len;
  155469. }
  155470. }
  155471. _seek_helper(vf,next);
  155472. ret=_get_next_page(vf,&og,-1);
  155473. if(ret==OV_EREAD)return(OV_EREAD);
  155474. if(searched>=end || ret<0){
  155475. vf->links=m+1;
  155476. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155477. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155478. vf->offsets[m+1]=searched;
  155479. }else{
  155480. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155481. end,ogg_page_serialno(&og),m+1);
  155482. if(ret==OV_EREAD)return(OV_EREAD);
  155483. }
  155484. vf->offsets[m]=begin;
  155485. vf->serialnos[m]=currentno;
  155486. return(0);
  155487. }
  155488. /* uses the local ogg_stream storage in vf; this is important for
  155489. non-streaming input sources */
  155490. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155491. long *serialno,ogg_page *og_ptr){
  155492. ogg_page og;
  155493. ogg_packet op;
  155494. int i,ret;
  155495. if(!og_ptr){
  155496. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155497. if(llret==OV_EREAD)return(OV_EREAD);
  155498. if(llret<0)return OV_ENOTVORBIS;
  155499. og_ptr=&og;
  155500. }
  155501. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155502. if(serialno)*serialno=vf->os.serialno;
  155503. vf->ready_state=STREAMSET;
  155504. /* extract the initial header from the first page and verify that the
  155505. Ogg bitstream is in fact Vorbis data */
  155506. vorbis_info_init(vi);
  155507. vorbis_comment_init(vc);
  155508. i=0;
  155509. while(i<3){
  155510. ogg_stream_pagein(&vf->os,og_ptr);
  155511. while(i<3){
  155512. int result=ogg_stream_packetout(&vf->os,&op);
  155513. if(result==0)break;
  155514. if(result==-1){
  155515. ret=OV_EBADHEADER;
  155516. goto bail_header;
  155517. }
  155518. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155519. goto bail_header;
  155520. }
  155521. i++;
  155522. }
  155523. if(i<3)
  155524. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155525. ret=OV_EBADHEADER;
  155526. goto bail_header;
  155527. }
  155528. }
  155529. return 0;
  155530. bail_header:
  155531. vorbis_info_clear(vi);
  155532. vorbis_comment_clear(vc);
  155533. vf->ready_state=OPENED;
  155534. return ret;
  155535. }
  155536. /* last step of the OggVorbis_File initialization; get all the
  155537. vorbis_info structs and PCM positions. Only called by the seekable
  155538. initialization (local stream storage is hacked slightly; pay
  155539. attention to how that's done) */
  155540. /* this is void and does not propogate errors up because we want to be
  155541. able to open and use damaged bitstreams as well as we can. Just
  155542. watch out for missing information for links in the OggVorbis_File
  155543. struct */
  155544. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155545. ogg_page og;
  155546. int i;
  155547. ogg_int64_t ret;
  155548. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155549. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155550. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155551. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155552. for(i=0;i<vf->links;i++){
  155553. if(i==0){
  155554. /* we already grabbed the initial header earlier. Just set the offset */
  155555. vf->dataoffsets[i]=dataoffset;
  155556. _seek_helper(vf,dataoffset);
  155557. }else{
  155558. /* seek to the location of the initial header */
  155559. _seek_helper(vf,vf->offsets[i]);
  155560. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155561. vf->dataoffsets[i]=-1;
  155562. }else{
  155563. vf->dataoffsets[i]=vf->offset;
  155564. }
  155565. }
  155566. /* fetch beginning PCM offset */
  155567. if(vf->dataoffsets[i]!=-1){
  155568. ogg_int64_t accumulated=0;
  155569. long lastblock=-1;
  155570. int result;
  155571. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155572. while(1){
  155573. ogg_packet op;
  155574. ret=_get_next_page(vf,&og,-1);
  155575. if(ret<0)
  155576. /* this should not be possible unless the file is
  155577. truncated/mangled */
  155578. break;
  155579. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155580. break;
  155581. /* count blocksizes of all frames in the page */
  155582. ogg_stream_pagein(&vf->os,&og);
  155583. while((result=ogg_stream_packetout(&vf->os,&op))){
  155584. if(result>0){ /* ignore holes */
  155585. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155586. if(lastblock!=-1)
  155587. accumulated+=(lastblock+thisblock)>>2;
  155588. lastblock=thisblock;
  155589. }
  155590. }
  155591. if(ogg_page_granulepos(&og)!=-1){
  155592. /* pcm offset of last packet on the first audio page */
  155593. accumulated= ogg_page_granulepos(&og)-accumulated;
  155594. break;
  155595. }
  155596. }
  155597. /* less than zero? This is a stream with samples trimmed off
  155598. the beginning, a normal occurrence; set the offset to zero */
  155599. if(accumulated<0)accumulated=0;
  155600. vf->pcmlengths[i*2]=accumulated;
  155601. }
  155602. /* get the PCM length of this link. To do this,
  155603. get the last page of the stream */
  155604. {
  155605. ogg_int64_t end=vf->offsets[i+1];
  155606. _seek_helper(vf,end);
  155607. while(1){
  155608. ret=_get_prev_page(vf,&og);
  155609. if(ret<0){
  155610. /* this should not be possible */
  155611. vorbis_info_clear(vf->vi+i);
  155612. vorbis_comment_clear(vf->vc+i);
  155613. break;
  155614. }
  155615. if(ogg_page_granulepos(&og)!=-1){
  155616. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155617. break;
  155618. }
  155619. vf->offset=ret;
  155620. }
  155621. }
  155622. }
  155623. }
  155624. static int _make_decode_ready(OggVorbis_File *vf){
  155625. if(vf->ready_state>STREAMSET)return 0;
  155626. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155627. if(vf->seekable){
  155628. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155629. return OV_EBADLINK;
  155630. }else{
  155631. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155632. return OV_EBADLINK;
  155633. }
  155634. vorbis_block_init(&vf->vd,&vf->vb);
  155635. vf->ready_state=INITSET;
  155636. vf->bittrack=0.f;
  155637. vf->samptrack=0.f;
  155638. return 0;
  155639. }
  155640. static int _open_seekable2(OggVorbis_File *vf){
  155641. long serialno=vf->current_serialno;
  155642. ogg_int64_t dataoffset=vf->offset, end;
  155643. ogg_page og;
  155644. /* we're partially open and have a first link header state in
  155645. storage in vf */
  155646. /* we can seek, so set out learning all about this file */
  155647. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155648. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155649. /* We get the offset for the last page of the physical bitstream.
  155650. Most OggVorbis files will contain a single logical bitstream */
  155651. end=_get_prev_page(vf,&og);
  155652. if(end<0)return(end);
  155653. /* more than one logical bitstream? */
  155654. if(ogg_page_serialno(&og)!=serialno){
  155655. /* Chained bitstream. Bisect-search each logical bitstream
  155656. section. Do so based on serial number only */
  155657. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155658. }else{
  155659. /* Only one logical bitstream */
  155660. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155661. }
  155662. /* the initial header memory is referenced by vf after; don't free it */
  155663. _prefetch_all_headers(vf,dataoffset);
  155664. return(ov_raw_seek(vf,0));
  155665. }
  155666. /* clear out the current logical bitstream decoder */
  155667. static void _decode_clear(OggVorbis_File *vf){
  155668. vorbis_dsp_clear(&vf->vd);
  155669. vorbis_block_clear(&vf->vb);
  155670. vf->ready_state=OPENED;
  155671. }
  155672. /* fetch and process a packet. Handles the case where we're at a
  155673. bitstream boundary and dumps the decoding machine. If the decoding
  155674. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155675. date (seek and read both use this. seek uses a special hack with
  155676. readp).
  155677. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155678. 0) need more data (only if readp==0)
  155679. 1) got a packet
  155680. */
  155681. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155682. ogg_packet *op_in,
  155683. int readp,
  155684. int spanp){
  155685. ogg_page og;
  155686. /* handle one packet. Try to fetch it from current stream state */
  155687. /* extract packets from page */
  155688. while(1){
  155689. /* process a packet if we can. If the machine isn't loaded,
  155690. neither is a page */
  155691. if(vf->ready_state==INITSET){
  155692. while(1) {
  155693. ogg_packet op;
  155694. ogg_packet *op_ptr=(op_in?op_in:&op);
  155695. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155696. ogg_int64_t granulepos;
  155697. op_in=NULL;
  155698. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155699. if(result>0){
  155700. /* got a packet. process it */
  155701. granulepos=op_ptr->granulepos;
  155702. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155703. header handling. The
  155704. header packets aren't
  155705. audio, so if/when we
  155706. submit them,
  155707. vorbis_synthesis will
  155708. reject them */
  155709. /* suck in the synthesis data and track bitrate */
  155710. {
  155711. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155712. /* for proper use of libvorbis within libvorbisfile,
  155713. oldsamples will always be zero. */
  155714. if(oldsamples)return(OV_EFAULT);
  155715. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155716. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155717. vf->bittrack+=op_ptr->bytes*8;
  155718. }
  155719. /* update the pcm offset. */
  155720. if(granulepos!=-1 && !op_ptr->e_o_s){
  155721. int link=(vf->seekable?vf->current_link:0);
  155722. int i,samples;
  155723. /* this packet has a pcm_offset on it (the last packet
  155724. completed on a page carries the offset) After processing
  155725. (above), we know the pcm position of the *last* sample
  155726. ready to be returned. Find the offset of the *first*
  155727. As an aside, this trick is inaccurate if we begin
  155728. reading anew right at the last page; the end-of-stream
  155729. granulepos declares the last frame in the stream, and the
  155730. last packet of the last page may be a partial frame.
  155731. So, we need a previous granulepos from an in-sequence page
  155732. to have a reference point. Thus the !op_ptr->e_o_s clause
  155733. above */
  155734. if(vf->seekable && link>0)
  155735. granulepos-=vf->pcmlengths[link*2];
  155736. if(granulepos<0)granulepos=0; /* actually, this
  155737. shouldn't be possible
  155738. here unless the stream
  155739. is very broken */
  155740. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155741. granulepos-=samples;
  155742. for(i=0;i<link;i++)
  155743. granulepos+=vf->pcmlengths[i*2+1];
  155744. vf->pcm_offset=granulepos;
  155745. }
  155746. return(1);
  155747. }
  155748. }
  155749. else
  155750. break;
  155751. }
  155752. }
  155753. if(vf->ready_state>=OPENED){
  155754. ogg_int64_t ret;
  155755. if(!readp)return(0);
  155756. if((ret=_get_next_page(vf,&og,-1))<0){
  155757. return(OV_EOF); /* eof.
  155758. leave unitialized */
  155759. }
  155760. /* bitrate tracking; add the header's bytes here, the body bytes
  155761. are done by packet above */
  155762. vf->bittrack+=og.header_len*8;
  155763. /* has our decoding just traversed a bitstream boundary? */
  155764. if(vf->ready_state==INITSET){
  155765. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155766. if(!spanp)
  155767. return(OV_EOF);
  155768. _decode_clear(vf);
  155769. if(!vf->seekable){
  155770. vorbis_info_clear(vf->vi);
  155771. vorbis_comment_clear(vf->vc);
  155772. }
  155773. }
  155774. }
  155775. }
  155776. /* Do we need to load a new machine before submitting the page? */
  155777. /* This is different in the seekable and non-seekable cases.
  155778. In the seekable case, we already have all the header
  155779. information loaded and cached; we just initialize the machine
  155780. with it and continue on our merry way.
  155781. In the non-seekable (streaming) case, we'll only be at a
  155782. boundary if we just left the previous logical bitstream and
  155783. we're now nominally at the header of the next bitstream
  155784. */
  155785. if(vf->ready_state!=INITSET){
  155786. int link;
  155787. if(vf->ready_state<STREAMSET){
  155788. if(vf->seekable){
  155789. vf->current_serialno=ogg_page_serialno(&og);
  155790. /* match the serialno to bitstream section. We use this rather than
  155791. offset positions to avoid problems near logical bitstream
  155792. boundaries */
  155793. for(link=0;link<vf->links;link++)
  155794. if(vf->serialnos[link]==vf->current_serialno)break;
  155795. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155796. stream. error out,
  155797. leave machine
  155798. uninitialized */
  155799. vf->current_link=link;
  155800. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155801. vf->ready_state=STREAMSET;
  155802. }else{
  155803. /* we're streaming */
  155804. /* fetch the three header packets, build the info struct */
  155805. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155806. if(ret)return(ret);
  155807. vf->current_link++;
  155808. link=0;
  155809. }
  155810. }
  155811. {
  155812. int ret=_make_decode_ready(vf);
  155813. if(ret<0)return ret;
  155814. }
  155815. }
  155816. ogg_stream_pagein(&vf->os,&og);
  155817. }
  155818. }
  155819. /* if, eg, 64 bit stdio is configured by default, this will build with
  155820. fseek64 */
  155821. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155822. if(f==NULL)return(-1);
  155823. return fseek(f,off,whence);
  155824. }
  155825. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155826. long ibytes, ov_callbacks callbacks){
  155827. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155828. int ret;
  155829. memset(vf,0,sizeof(*vf));
  155830. vf->datasource=f;
  155831. vf->callbacks = callbacks;
  155832. /* init the framing state */
  155833. ogg_sync_init(&vf->oy);
  155834. /* perhaps some data was previously read into a buffer for testing
  155835. against other stream types. Allow initialization from this
  155836. previously read data (as we may be reading from a non-seekable
  155837. stream) */
  155838. if(initial){
  155839. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155840. memcpy(buffer,initial,ibytes);
  155841. ogg_sync_wrote(&vf->oy,ibytes);
  155842. }
  155843. /* can we seek? Stevens suggests the seek test was portable */
  155844. if(offsettest!=-1)vf->seekable=1;
  155845. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155846. entry for partial open */
  155847. vf->links=1;
  155848. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155849. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155850. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155851. /* Try to fetch the headers, maintaining all the storage */
  155852. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155853. vf->datasource=NULL;
  155854. ov_clear(vf);
  155855. }else
  155856. vf->ready_state=PARTOPEN;
  155857. return(ret);
  155858. }
  155859. static int _ov_open2(OggVorbis_File *vf){
  155860. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155861. vf->ready_state=OPENED;
  155862. if(vf->seekable){
  155863. int ret=_open_seekable2(vf);
  155864. if(ret){
  155865. vf->datasource=NULL;
  155866. ov_clear(vf);
  155867. }
  155868. return(ret);
  155869. }else
  155870. vf->ready_state=STREAMSET;
  155871. return 0;
  155872. }
  155873. /* clear out the OggVorbis_File struct */
  155874. int ov_clear(OggVorbis_File *vf){
  155875. if(vf){
  155876. vorbis_block_clear(&vf->vb);
  155877. vorbis_dsp_clear(&vf->vd);
  155878. ogg_stream_clear(&vf->os);
  155879. if(vf->vi && vf->links){
  155880. int i;
  155881. for(i=0;i<vf->links;i++){
  155882. vorbis_info_clear(vf->vi+i);
  155883. vorbis_comment_clear(vf->vc+i);
  155884. }
  155885. _ogg_free(vf->vi);
  155886. _ogg_free(vf->vc);
  155887. }
  155888. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155889. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155890. if(vf->serialnos)_ogg_free(vf->serialnos);
  155891. if(vf->offsets)_ogg_free(vf->offsets);
  155892. ogg_sync_clear(&vf->oy);
  155893. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155894. memset(vf,0,sizeof(*vf));
  155895. }
  155896. #ifdef DEBUG_LEAKS
  155897. _VDBG_dump();
  155898. #endif
  155899. return(0);
  155900. }
  155901. /* inspects the OggVorbis file and finds/documents all the logical
  155902. bitstreams contained in it. Tries to be tolerant of logical
  155903. bitstream sections that are truncated/woogie.
  155904. return: -1) error
  155905. 0) OK
  155906. */
  155907. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155908. ov_callbacks callbacks){
  155909. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155910. if(ret)return ret;
  155911. return _ov_open2(vf);
  155912. }
  155913. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155914. ov_callbacks callbacks = {
  155915. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155916. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155917. (int (*)(void *)) fclose,
  155918. (long (*)(void *)) ftell
  155919. };
  155920. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155921. }
  155922. /* cheap hack for game usage where downsampling is desirable; there's
  155923. no need for SRC as we can just do it cheaply in libvorbis. */
  155924. int ov_halfrate(OggVorbis_File *vf,int flag){
  155925. int i;
  155926. if(vf->vi==NULL)return OV_EINVAL;
  155927. if(!vf->seekable)return OV_EINVAL;
  155928. if(vf->ready_state>=STREAMSET)
  155929. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155930. will be able to swap this on the fly, but
  155931. for now dumping the decode machine is needed
  155932. to reinit the MDCT lookups. 1.1 libvorbis
  155933. is planned to be able to switch on the fly */
  155934. for(i=0;i<vf->links;i++){
  155935. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155936. ov_halfrate(vf,0);
  155937. return OV_EINVAL;
  155938. }
  155939. }
  155940. return 0;
  155941. }
  155942. int ov_halfrate_p(OggVorbis_File *vf){
  155943. if(vf->vi==NULL)return OV_EINVAL;
  155944. return vorbis_synthesis_halfrate_p(vf->vi);
  155945. }
  155946. /* Only partially open the vorbis file; test for Vorbisness, and load
  155947. the headers for the first chain. Do not seek (although test for
  155948. seekability). Use ov_test_open to finish opening the file, else
  155949. ov_clear to close/free it. Same return codes as open. */
  155950. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155951. ov_callbacks callbacks)
  155952. {
  155953. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155954. }
  155955. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155956. ov_callbacks callbacks = {
  155957. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155958. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155959. (int (*)(void *)) fclose,
  155960. (long (*)(void *)) ftell
  155961. };
  155962. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155963. }
  155964. int ov_test_open(OggVorbis_File *vf){
  155965. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155966. return _ov_open2(vf);
  155967. }
  155968. /* How many logical bitstreams in this physical bitstream? */
  155969. long ov_streams(OggVorbis_File *vf){
  155970. return vf->links;
  155971. }
  155972. /* Is the FILE * associated with vf seekable? */
  155973. long ov_seekable(OggVorbis_File *vf){
  155974. return vf->seekable;
  155975. }
  155976. /* returns the bitrate for a given logical bitstream or the entire
  155977. physical bitstream. If the file is open for random access, it will
  155978. find the *actual* average bitrate. If the file is streaming, it
  155979. returns the nominal bitrate (if set) else the average of the
  155980. upper/lower bounds (if set) else -1 (unset).
  155981. If you want the actual bitrate field settings, get them from the
  155982. vorbis_info structs */
  155983. long ov_bitrate(OggVorbis_File *vf,int i){
  155984. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155985. if(i>=vf->links)return(OV_EINVAL);
  155986. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155987. if(i<0){
  155988. ogg_int64_t bits=0;
  155989. int i;
  155990. float br;
  155991. for(i=0;i<vf->links;i++)
  155992. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155993. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155994. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155995. * so this is slightly transformed to make it work.
  155996. */
  155997. br = bits/ov_time_total(vf,-1);
  155998. return(rint(br));
  155999. }else{
  156000. if(vf->seekable){
  156001. /* return the actual bitrate */
  156002. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156003. }else{
  156004. /* return nominal if set */
  156005. if(vf->vi[i].bitrate_nominal>0){
  156006. return vf->vi[i].bitrate_nominal;
  156007. }else{
  156008. if(vf->vi[i].bitrate_upper>0){
  156009. if(vf->vi[i].bitrate_lower>0){
  156010. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156011. }else{
  156012. return vf->vi[i].bitrate_upper;
  156013. }
  156014. }
  156015. return(OV_FALSE);
  156016. }
  156017. }
  156018. }
  156019. }
  156020. /* returns the actual bitrate since last call. returns -1 if no
  156021. additional data to offer since last call (or at beginning of stream),
  156022. EINVAL if stream is only partially open
  156023. */
  156024. long ov_bitrate_instant(OggVorbis_File *vf){
  156025. int link=(vf->seekable?vf->current_link:0);
  156026. long ret;
  156027. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156028. if(vf->samptrack==0)return(OV_FALSE);
  156029. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156030. vf->bittrack=0.f;
  156031. vf->samptrack=0.f;
  156032. return(ret);
  156033. }
  156034. /* Guess */
  156035. long ov_serialnumber(OggVorbis_File *vf,int i){
  156036. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156037. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156038. if(i<0){
  156039. return(vf->current_serialno);
  156040. }else{
  156041. return(vf->serialnos[i]);
  156042. }
  156043. }
  156044. /* returns: total raw (compressed) length of content if i==-1
  156045. raw (compressed) length of that logical bitstream for i==0 to n
  156046. OV_EINVAL if the stream is not seekable (we can't know the length)
  156047. or if stream is only partially open
  156048. */
  156049. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156050. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156051. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156052. if(i<0){
  156053. ogg_int64_t acc=0;
  156054. int i;
  156055. for(i=0;i<vf->links;i++)
  156056. acc+=ov_raw_total(vf,i);
  156057. return(acc);
  156058. }else{
  156059. return(vf->offsets[i+1]-vf->offsets[i]);
  156060. }
  156061. }
  156062. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156063. (samples) of that logical bitstream for i==0 to n
  156064. OV_EINVAL if the stream is not seekable (we can't know the
  156065. length) or only partially open
  156066. */
  156067. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156068. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156069. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156070. if(i<0){
  156071. ogg_int64_t acc=0;
  156072. int i;
  156073. for(i=0;i<vf->links;i++)
  156074. acc+=ov_pcm_total(vf,i);
  156075. return(acc);
  156076. }else{
  156077. return(vf->pcmlengths[i*2+1]);
  156078. }
  156079. }
  156080. /* returns: total seconds of content if i==-1
  156081. seconds in that logical bitstream for i==0 to n
  156082. OV_EINVAL if the stream is not seekable (we can't know the
  156083. length) or only partially open
  156084. */
  156085. double ov_time_total(OggVorbis_File *vf,int i){
  156086. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156087. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156088. if(i<0){
  156089. double acc=0;
  156090. int i;
  156091. for(i=0;i<vf->links;i++)
  156092. acc+=ov_time_total(vf,i);
  156093. return(acc);
  156094. }else{
  156095. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156096. }
  156097. }
  156098. /* seek to an offset relative to the *compressed* data. This also
  156099. scans packets to update the PCM cursor. It will cross a logical
  156100. bitstream boundary, but only if it can't get any packets out of the
  156101. tail of the bitstream we seek to (so no surprises).
  156102. returns zero on success, nonzero on failure */
  156103. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156104. ogg_stream_state work_os;
  156105. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156106. if(!vf->seekable)
  156107. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156108. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156109. /* don't yet clear out decoding machine (if it's initialized), in
  156110. the case we're in the same link. Restart the decode lapping, and
  156111. let _fetch_and_process_packet deal with a potential bitstream
  156112. boundary */
  156113. vf->pcm_offset=-1;
  156114. ogg_stream_reset_serialno(&vf->os,
  156115. vf->current_serialno); /* must set serialno */
  156116. vorbis_synthesis_restart(&vf->vd);
  156117. _seek_helper(vf,pos);
  156118. /* we need to make sure the pcm_offset is set, but we don't want to
  156119. advance the raw cursor past good packets just to get to the first
  156120. with a granulepos. That's not equivalent behavior to beginning
  156121. decoding as immediately after the seek position as possible.
  156122. So, a hack. We use two stream states; a local scratch state and
  156123. the shared vf->os stream state. We use the local state to
  156124. scan, and the shared state as a buffer for later decode.
  156125. Unfortuantely, on the last page we still advance to last packet
  156126. because the granulepos on the last page is not necessarily on a
  156127. packet boundary, and we need to make sure the granpos is
  156128. correct.
  156129. */
  156130. {
  156131. ogg_page og;
  156132. ogg_packet op;
  156133. int lastblock=0;
  156134. int accblock=0;
  156135. int thisblock;
  156136. int eosflag;
  156137. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156138. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156139. return from not necessarily
  156140. starting from the beginning */
  156141. while(1){
  156142. if(vf->ready_state>=STREAMSET){
  156143. /* snarf/scan a packet if we can */
  156144. int result=ogg_stream_packetout(&work_os,&op);
  156145. if(result>0){
  156146. if(vf->vi[vf->current_link].codec_setup){
  156147. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156148. if(thisblock<0){
  156149. ogg_stream_packetout(&vf->os,NULL);
  156150. thisblock=0;
  156151. }else{
  156152. if(eosflag)
  156153. ogg_stream_packetout(&vf->os,NULL);
  156154. else
  156155. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156156. }
  156157. if(op.granulepos!=-1){
  156158. int i,link=vf->current_link;
  156159. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156160. if(granulepos<0)granulepos=0;
  156161. for(i=0;i<link;i++)
  156162. granulepos+=vf->pcmlengths[i*2+1];
  156163. vf->pcm_offset=granulepos-accblock;
  156164. break;
  156165. }
  156166. lastblock=thisblock;
  156167. continue;
  156168. }else
  156169. ogg_stream_packetout(&vf->os,NULL);
  156170. }
  156171. }
  156172. if(!lastblock){
  156173. if(_get_next_page(vf,&og,-1)<0){
  156174. vf->pcm_offset=ov_pcm_total(vf,-1);
  156175. break;
  156176. }
  156177. }else{
  156178. /* huh? Bogus stream with packets but no granulepos */
  156179. vf->pcm_offset=-1;
  156180. break;
  156181. }
  156182. /* has our decoding just traversed a bitstream boundary? */
  156183. if(vf->ready_state>=STREAMSET)
  156184. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156185. _decode_clear(vf); /* clear out stream state */
  156186. ogg_stream_clear(&work_os);
  156187. }
  156188. if(vf->ready_state<STREAMSET){
  156189. int link;
  156190. vf->current_serialno=ogg_page_serialno(&og);
  156191. for(link=0;link<vf->links;link++)
  156192. if(vf->serialnos[link]==vf->current_serialno)break;
  156193. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156194. error out, leave
  156195. machine uninitialized */
  156196. vf->current_link=link;
  156197. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156198. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156199. vf->ready_state=STREAMSET;
  156200. }
  156201. ogg_stream_pagein(&vf->os,&og);
  156202. ogg_stream_pagein(&work_os,&og);
  156203. eosflag=ogg_page_eos(&og);
  156204. }
  156205. }
  156206. ogg_stream_clear(&work_os);
  156207. vf->bittrack=0.f;
  156208. vf->samptrack=0.f;
  156209. return(0);
  156210. seek_error:
  156211. /* dump the machine so we're in a known state */
  156212. vf->pcm_offset=-1;
  156213. ogg_stream_clear(&work_os);
  156214. _decode_clear(vf);
  156215. return OV_EBADLINK;
  156216. }
  156217. /* Page granularity seek (faster than sample granularity because we
  156218. don't do the last bit of decode to find a specific sample).
  156219. Seek to the last [granule marked] page preceeding the specified pos
  156220. location, such that decoding past the returned point will quickly
  156221. arrive at the requested position. */
  156222. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156223. int link=-1;
  156224. ogg_int64_t result=0;
  156225. ogg_int64_t total=ov_pcm_total(vf,-1);
  156226. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156227. if(!vf->seekable)return(OV_ENOSEEK);
  156228. if(pos<0 || pos>total)return(OV_EINVAL);
  156229. /* which bitstream section does this pcm offset occur in? */
  156230. for(link=vf->links-1;link>=0;link--){
  156231. total-=vf->pcmlengths[link*2+1];
  156232. if(pos>=total)break;
  156233. }
  156234. /* search within the logical bitstream for the page with the highest
  156235. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156236. missing pages or incorrect frame number information in the
  156237. bitstream could make our task impossible. Account for that (it
  156238. would be an error condition) */
  156239. /* new search algorithm by HB (Nicholas Vinen) */
  156240. {
  156241. ogg_int64_t end=vf->offsets[link+1];
  156242. ogg_int64_t begin=vf->offsets[link];
  156243. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156244. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156245. ogg_int64_t target=pos-total+begintime;
  156246. ogg_int64_t best=begin;
  156247. ogg_page og;
  156248. while(begin<end){
  156249. ogg_int64_t bisect;
  156250. if(end-begin<CHUNKSIZE){
  156251. bisect=begin;
  156252. }else{
  156253. /* take a (pretty decent) guess. */
  156254. bisect=begin +
  156255. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156256. if(bisect<=begin)
  156257. bisect=begin+1;
  156258. }
  156259. _seek_helper(vf,bisect);
  156260. while(begin<end){
  156261. result=_get_next_page(vf,&og,end-vf->offset);
  156262. if(result==OV_EREAD) goto seek_error;
  156263. if(result<0){
  156264. if(bisect<=begin+1)
  156265. end=begin; /* found it */
  156266. else{
  156267. if(bisect==0) goto seek_error;
  156268. bisect-=CHUNKSIZE;
  156269. if(bisect<=begin)bisect=begin+1;
  156270. _seek_helper(vf,bisect);
  156271. }
  156272. }else{
  156273. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156274. if(granulepos==-1)continue;
  156275. if(granulepos<target){
  156276. best=result; /* raw offset of packet with granulepos */
  156277. begin=vf->offset; /* raw offset of next page */
  156278. begintime=granulepos;
  156279. if(target-begintime>44100)break;
  156280. bisect=begin; /* *not* begin + 1 */
  156281. }else{
  156282. if(bisect<=begin+1)
  156283. end=begin; /* found it */
  156284. else{
  156285. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156286. end=result;
  156287. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156288. if(bisect<=begin)bisect=begin+1;
  156289. _seek_helper(vf,bisect);
  156290. }else{
  156291. end=result;
  156292. endtime=granulepos;
  156293. break;
  156294. }
  156295. }
  156296. }
  156297. }
  156298. }
  156299. }
  156300. /* found our page. seek to it, update pcm offset. Easier case than
  156301. raw_seek, don't keep packets preceeding granulepos. */
  156302. {
  156303. ogg_page og;
  156304. ogg_packet op;
  156305. /* seek */
  156306. _seek_helper(vf,best);
  156307. vf->pcm_offset=-1;
  156308. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156309. if(link!=vf->current_link){
  156310. /* Different link; dump entire decode machine */
  156311. _decode_clear(vf);
  156312. vf->current_link=link;
  156313. vf->current_serialno=ogg_page_serialno(&og);
  156314. vf->ready_state=STREAMSET;
  156315. }else{
  156316. vorbis_synthesis_restart(&vf->vd);
  156317. }
  156318. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156319. ogg_stream_pagein(&vf->os,&og);
  156320. /* pull out all but last packet; the one with granulepos */
  156321. while(1){
  156322. result=ogg_stream_packetpeek(&vf->os,&op);
  156323. if(result==0){
  156324. /* !!! the packet finishing this page originated on a
  156325. preceeding page. Keep fetching previous pages until we
  156326. get one with a granulepos or without the 'continued' flag
  156327. set. Then just use raw_seek for simplicity. */
  156328. _seek_helper(vf,best);
  156329. while(1){
  156330. result=_get_prev_page(vf,&og);
  156331. if(result<0) goto seek_error;
  156332. if(ogg_page_granulepos(&og)>-1 ||
  156333. !ogg_page_continued(&og)){
  156334. return ov_raw_seek(vf,result);
  156335. }
  156336. vf->offset=result;
  156337. }
  156338. }
  156339. if(result<0){
  156340. result = OV_EBADPACKET;
  156341. goto seek_error;
  156342. }
  156343. if(op.granulepos!=-1){
  156344. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156345. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156346. vf->pcm_offset+=total;
  156347. break;
  156348. }else
  156349. result=ogg_stream_packetout(&vf->os,NULL);
  156350. }
  156351. }
  156352. }
  156353. /* verify result */
  156354. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156355. result=OV_EFAULT;
  156356. goto seek_error;
  156357. }
  156358. vf->bittrack=0.f;
  156359. vf->samptrack=0.f;
  156360. return(0);
  156361. seek_error:
  156362. /* dump machine so we're in a known state */
  156363. vf->pcm_offset=-1;
  156364. _decode_clear(vf);
  156365. return (int)result;
  156366. }
  156367. /* seek to a sample offset relative to the decompressed pcm stream
  156368. returns zero on success, nonzero on failure */
  156369. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156370. int thisblock,lastblock=0;
  156371. int ret=ov_pcm_seek_page(vf,pos);
  156372. if(ret<0)return(ret);
  156373. if((ret=_make_decode_ready(vf)))return ret;
  156374. /* discard leading packets we don't need for the lapping of the
  156375. position we want; don't decode them */
  156376. while(1){
  156377. ogg_packet op;
  156378. ogg_page og;
  156379. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156380. if(ret>0){
  156381. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156382. if(thisblock<0){
  156383. ogg_stream_packetout(&vf->os,NULL);
  156384. continue; /* non audio packet */
  156385. }
  156386. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156387. if(vf->pcm_offset+((thisblock+
  156388. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156389. /* remove the packet from packet queue and track its granulepos */
  156390. ogg_stream_packetout(&vf->os,NULL);
  156391. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156392. only tracking, no
  156393. pcm_decode */
  156394. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156395. /* end of logical stream case is hard, especially with exact
  156396. length positioning. */
  156397. if(op.granulepos>-1){
  156398. int i;
  156399. /* always believe the stream markers */
  156400. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156401. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156402. for(i=0;i<vf->current_link;i++)
  156403. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156404. }
  156405. lastblock=thisblock;
  156406. }else{
  156407. if(ret<0 && ret!=OV_HOLE)break;
  156408. /* suck in a new page */
  156409. if(_get_next_page(vf,&og,-1)<0)break;
  156410. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156411. if(vf->ready_state<STREAMSET){
  156412. int link;
  156413. vf->current_serialno=ogg_page_serialno(&og);
  156414. for(link=0;link<vf->links;link++)
  156415. if(vf->serialnos[link]==vf->current_serialno)break;
  156416. if(link==vf->links)return(OV_EBADLINK);
  156417. vf->current_link=link;
  156418. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156419. vf->ready_state=STREAMSET;
  156420. ret=_make_decode_ready(vf);
  156421. if(ret)return ret;
  156422. lastblock=0;
  156423. }
  156424. ogg_stream_pagein(&vf->os,&og);
  156425. }
  156426. }
  156427. vf->bittrack=0.f;
  156428. vf->samptrack=0.f;
  156429. /* discard samples until we reach the desired position. Crossing a
  156430. logical bitstream boundary with abandon is OK. */
  156431. while(vf->pcm_offset<pos){
  156432. ogg_int64_t target=pos-vf->pcm_offset;
  156433. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156434. if(samples>target)samples=target;
  156435. vorbis_synthesis_read(&vf->vd,samples);
  156436. vf->pcm_offset+=samples;
  156437. if(samples<target)
  156438. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156439. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156440. }
  156441. return 0;
  156442. }
  156443. /* seek to a playback time relative to the decompressed pcm stream
  156444. returns zero on success, nonzero on failure */
  156445. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156446. /* translate time to PCM position and call ov_pcm_seek */
  156447. int link=-1;
  156448. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156449. double time_total=ov_time_total(vf,-1);
  156450. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156451. if(!vf->seekable)return(OV_ENOSEEK);
  156452. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156453. /* which bitstream section does this time offset occur in? */
  156454. for(link=vf->links-1;link>=0;link--){
  156455. pcm_total-=vf->pcmlengths[link*2+1];
  156456. time_total-=ov_time_total(vf,link);
  156457. if(seconds>=time_total)break;
  156458. }
  156459. /* enough information to convert time offset to pcm offset */
  156460. {
  156461. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156462. return(ov_pcm_seek(vf,target));
  156463. }
  156464. }
  156465. /* page-granularity version of ov_time_seek
  156466. returns zero on success, nonzero on failure */
  156467. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156468. /* translate time to PCM position and call ov_pcm_seek */
  156469. int link=-1;
  156470. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156471. double time_total=ov_time_total(vf,-1);
  156472. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156473. if(!vf->seekable)return(OV_ENOSEEK);
  156474. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156475. /* which bitstream section does this time offset occur in? */
  156476. for(link=vf->links-1;link>=0;link--){
  156477. pcm_total-=vf->pcmlengths[link*2+1];
  156478. time_total-=ov_time_total(vf,link);
  156479. if(seconds>=time_total)break;
  156480. }
  156481. /* enough information to convert time offset to pcm offset */
  156482. {
  156483. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156484. return(ov_pcm_seek_page(vf,target));
  156485. }
  156486. }
  156487. /* tell the current stream offset cursor. Note that seek followed by
  156488. tell will likely not give the set offset due to caching */
  156489. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156490. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156491. return(vf->offset);
  156492. }
  156493. /* return PCM offset (sample) of next PCM sample to be read */
  156494. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156495. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156496. return(vf->pcm_offset);
  156497. }
  156498. /* return time offset (seconds) of next PCM sample to be read */
  156499. double ov_time_tell(OggVorbis_File *vf){
  156500. int link=0;
  156501. ogg_int64_t pcm_total=0;
  156502. double time_total=0.f;
  156503. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156504. if(vf->seekable){
  156505. pcm_total=ov_pcm_total(vf,-1);
  156506. time_total=ov_time_total(vf,-1);
  156507. /* which bitstream section does this time offset occur in? */
  156508. for(link=vf->links-1;link>=0;link--){
  156509. pcm_total-=vf->pcmlengths[link*2+1];
  156510. time_total-=ov_time_total(vf,link);
  156511. if(vf->pcm_offset>=pcm_total)break;
  156512. }
  156513. }
  156514. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156515. }
  156516. /* link: -1) return the vorbis_info struct for the bitstream section
  156517. currently being decoded
  156518. 0-n) to request information for a specific bitstream section
  156519. In the case of a non-seekable bitstream, any call returns the
  156520. current bitstream. NULL in the case that the machine is not
  156521. initialized */
  156522. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156523. if(vf->seekable){
  156524. if(link<0)
  156525. if(vf->ready_state>=STREAMSET)
  156526. return vf->vi+vf->current_link;
  156527. else
  156528. return vf->vi;
  156529. else
  156530. if(link>=vf->links)
  156531. return NULL;
  156532. else
  156533. return vf->vi+link;
  156534. }else{
  156535. return vf->vi;
  156536. }
  156537. }
  156538. /* grr, strong typing, grr, no templates/inheritence, grr */
  156539. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156540. if(vf->seekable){
  156541. if(link<0)
  156542. if(vf->ready_state>=STREAMSET)
  156543. return vf->vc+vf->current_link;
  156544. else
  156545. return vf->vc;
  156546. else
  156547. if(link>=vf->links)
  156548. return NULL;
  156549. else
  156550. return vf->vc+link;
  156551. }else{
  156552. return vf->vc;
  156553. }
  156554. }
  156555. static int host_is_big_endian() {
  156556. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156557. unsigned char *bytewise = (unsigned char *)&pattern;
  156558. if (bytewise[0] == 0xfe) return 1;
  156559. return 0;
  156560. }
  156561. /* up to this point, everything could more or less hide the multiple
  156562. logical bitstream nature of chaining from the toplevel application
  156563. if the toplevel application didn't particularly care. However, at
  156564. the point that we actually read audio back, the multiple-section
  156565. nature must surface: Multiple bitstream sections do not necessarily
  156566. have to have the same number of channels or sampling rate.
  156567. ov_read returns the sequential logical bitstream number currently
  156568. being decoded along with the PCM data in order that the toplevel
  156569. application can take action on channel/sample rate changes. This
  156570. number will be incremented even for streamed (non-seekable) streams
  156571. (for seekable streams, it represents the actual logical bitstream
  156572. index within the physical bitstream. Note that the accessor
  156573. functions above are aware of this dichotomy).
  156574. input values: buffer) a buffer to hold packed PCM data for return
  156575. length) the byte length requested to be placed into buffer
  156576. bigendianp) should the data be packed LSB first (0) or
  156577. MSB first (1)
  156578. word) word size for output. currently 1 (byte) or
  156579. 2 (16 bit short)
  156580. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156581. 0) EOF
  156582. n) number of bytes of PCM actually returned. The
  156583. below works on a packet-by-packet basis, so the
  156584. return length is not related to the 'length' passed
  156585. in, just guaranteed to fit.
  156586. *section) set to the logical bitstream number */
  156587. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156588. int bigendianp,int word,int sgned,int *bitstream){
  156589. int i,j;
  156590. int host_endian = host_is_big_endian();
  156591. float **pcm;
  156592. long samples;
  156593. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156594. while(1){
  156595. if(vf->ready_state==INITSET){
  156596. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156597. if(samples)break;
  156598. }
  156599. /* suck in another packet */
  156600. {
  156601. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156602. if(ret==OV_EOF)
  156603. return(0);
  156604. if(ret<=0)
  156605. return(ret);
  156606. }
  156607. }
  156608. if(samples>0){
  156609. /* yay! proceed to pack data into the byte buffer */
  156610. long channels=ov_info(vf,-1)->channels;
  156611. long bytespersample=word * channels;
  156612. vorbis_fpu_control fpu;
  156613. (void) fpu; // (to avoid a warning about it being unused)
  156614. if(samples>length/bytespersample)samples=length/bytespersample;
  156615. if(samples <= 0)
  156616. return OV_EINVAL;
  156617. /* a tight loop to pack each size */
  156618. {
  156619. int val;
  156620. if(word==1){
  156621. int off=(sgned?0:128);
  156622. vorbis_fpu_setround(&fpu);
  156623. for(j=0;j<samples;j++)
  156624. for(i=0;i<channels;i++){
  156625. val=vorbis_ftoi(pcm[i][j]*128.f);
  156626. if(val>127)val=127;
  156627. else if(val<-128)val=-128;
  156628. *buffer++=val+off;
  156629. }
  156630. vorbis_fpu_restore(fpu);
  156631. }else{
  156632. int off=(sgned?0:32768);
  156633. if(host_endian==bigendianp){
  156634. if(sgned){
  156635. vorbis_fpu_setround(&fpu);
  156636. for(i=0;i<channels;i++) { /* It's faster in this order */
  156637. float *src=pcm[i];
  156638. short *dest=((short *)buffer)+i;
  156639. for(j=0;j<samples;j++) {
  156640. val=vorbis_ftoi(src[j]*32768.f);
  156641. if(val>32767)val=32767;
  156642. else if(val<-32768)val=-32768;
  156643. *dest=val;
  156644. dest+=channels;
  156645. }
  156646. }
  156647. vorbis_fpu_restore(fpu);
  156648. }else{
  156649. vorbis_fpu_setround(&fpu);
  156650. for(i=0;i<channels;i++) {
  156651. float *src=pcm[i];
  156652. short *dest=((short *)buffer)+i;
  156653. for(j=0;j<samples;j++) {
  156654. val=vorbis_ftoi(src[j]*32768.f);
  156655. if(val>32767)val=32767;
  156656. else if(val<-32768)val=-32768;
  156657. *dest=val+off;
  156658. dest+=channels;
  156659. }
  156660. }
  156661. vorbis_fpu_restore(fpu);
  156662. }
  156663. }else if(bigendianp){
  156664. vorbis_fpu_setround(&fpu);
  156665. for(j=0;j<samples;j++)
  156666. for(i=0;i<channels;i++){
  156667. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156668. if(val>32767)val=32767;
  156669. else if(val<-32768)val=-32768;
  156670. val+=off;
  156671. *buffer++=(val>>8);
  156672. *buffer++=(val&0xff);
  156673. }
  156674. vorbis_fpu_restore(fpu);
  156675. }else{
  156676. int val;
  156677. vorbis_fpu_setround(&fpu);
  156678. for(j=0;j<samples;j++)
  156679. for(i=0;i<channels;i++){
  156680. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156681. if(val>32767)val=32767;
  156682. else if(val<-32768)val=-32768;
  156683. val+=off;
  156684. *buffer++=(val&0xff);
  156685. *buffer++=(val>>8);
  156686. }
  156687. vorbis_fpu_restore(fpu);
  156688. }
  156689. }
  156690. }
  156691. vorbis_synthesis_read(&vf->vd,samples);
  156692. vf->pcm_offset+=samples;
  156693. if(bitstream)*bitstream=vf->current_link;
  156694. return(samples*bytespersample);
  156695. }else{
  156696. return(samples);
  156697. }
  156698. }
  156699. /* input values: pcm_channels) a float vector per channel of output
  156700. length) the sample length being read by the app
  156701. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156702. 0) EOF
  156703. n) number of samples of PCM actually returned. The
  156704. below works on a packet-by-packet basis, so the
  156705. return length is not related to the 'length' passed
  156706. in, just guaranteed to fit.
  156707. *section) set to the logical bitstream number */
  156708. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156709. int *bitstream){
  156710. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156711. while(1){
  156712. if(vf->ready_state==INITSET){
  156713. float **pcm;
  156714. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156715. if(samples){
  156716. if(pcm_channels)*pcm_channels=pcm;
  156717. if(samples>length)samples=length;
  156718. vorbis_synthesis_read(&vf->vd,samples);
  156719. vf->pcm_offset+=samples;
  156720. if(bitstream)*bitstream=vf->current_link;
  156721. return samples;
  156722. }
  156723. }
  156724. /* suck in another packet */
  156725. {
  156726. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156727. if(ret==OV_EOF)return(0);
  156728. if(ret<=0)return(ret);
  156729. }
  156730. }
  156731. }
  156732. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156733. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156734. ogg_int64_t off);
  156735. static void _ov_splice(float **pcm,float **lappcm,
  156736. int n1, int n2,
  156737. int ch1, int ch2,
  156738. float *w1, float *w2){
  156739. int i,j;
  156740. float *w=w1;
  156741. int n=n1;
  156742. if(n1>n2){
  156743. n=n2;
  156744. w=w2;
  156745. }
  156746. /* splice */
  156747. for(j=0;j<ch1 && j<ch2;j++){
  156748. float *s=lappcm[j];
  156749. float *d=pcm[j];
  156750. for(i=0;i<n;i++){
  156751. float wd=w[i]*w[i];
  156752. float ws=1.-wd;
  156753. d[i]=d[i]*wd + s[i]*ws;
  156754. }
  156755. }
  156756. /* window from zero */
  156757. for(;j<ch2;j++){
  156758. float *d=pcm[j];
  156759. for(i=0;i<n;i++){
  156760. float wd=w[i]*w[i];
  156761. d[i]=d[i]*wd;
  156762. }
  156763. }
  156764. }
  156765. /* make sure vf is INITSET */
  156766. static int _ov_initset(OggVorbis_File *vf){
  156767. while(1){
  156768. if(vf->ready_state==INITSET)break;
  156769. /* suck in another packet */
  156770. {
  156771. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156772. if(ret<0 && ret!=OV_HOLE)return(ret);
  156773. }
  156774. }
  156775. return 0;
  156776. }
  156777. /* make sure vf is INITSET and that we have a primed buffer; if
  156778. we're crosslapping at a stream section boundary, this also makes
  156779. sure we're sanity checking against the right stream information */
  156780. static int _ov_initprime(OggVorbis_File *vf){
  156781. vorbis_dsp_state *vd=&vf->vd;
  156782. while(1){
  156783. if(vf->ready_state==INITSET)
  156784. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156785. /* suck in another packet */
  156786. {
  156787. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156788. if(ret<0 && ret!=OV_HOLE)return(ret);
  156789. }
  156790. }
  156791. return 0;
  156792. }
  156793. /* grab enough data for lapping from vf; this may be in the form of
  156794. unreturned, already-decoded pcm, remaining PCM we will need to
  156795. decode, or synthetic postextrapolation from last packets. */
  156796. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156797. float **lappcm,int lapsize){
  156798. int lapcount=0,i;
  156799. float **pcm;
  156800. /* try first to decode the lapping data */
  156801. while(lapcount<lapsize){
  156802. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156803. if(samples){
  156804. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156805. for(i=0;i<vi->channels;i++)
  156806. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156807. lapcount+=samples;
  156808. vorbis_synthesis_read(vd,samples);
  156809. }else{
  156810. /* suck in another packet */
  156811. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156812. if(ret==OV_EOF)break;
  156813. }
  156814. }
  156815. if(lapcount<lapsize){
  156816. /* failed to get lapping data from normal decode; pry it from the
  156817. postextrapolation buffering, or the second half of the MDCT
  156818. from the last packet */
  156819. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156820. if(samples==0){
  156821. for(i=0;i<vi->channels;i++)
  156822. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156823. lapcount=lapsize;
  156824. }else{
  156825. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156826. for(i=0;i<vi->channels;i++)
  156827. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156828. lapcount+=samples;
  156829. }
  156830. }
  156831. }
  156832. /* this sets up crosslapping of a sample by using trailing data from
  156833. sample 1 and lapping it into the windowing buffer of sample 2 */
  156834. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156835. vorbis_info *vi1,*vi2;
  156836. float **lappcm;
  156837. float **pcm;
  156838. float *w1,*w2;
  156839. int n1,n2,i,ret,hs1,hs2;
  156840. if(vf1==vf2)return(0); /* degenerate case */
  156841. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156842. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156843. /* the relevant overlap buffers must be pre-checked and pre-primed
  156844. before looking at settings in the event that priming would cross
  156845. a bitstream boundary. So, do it now */
  156846. ret=_ov_initset(vf1);
  156847. if(ret)return(ret);
  156848. ret=_ov_initprime(vf2);
  156849. if(ret)return(ret);
  156850. vi1=ov_info(vf1,-1);
  156851. vi2=ov_info(vf2,-1);
  156852. hs1=ov_halfrate_p(vf1);
  156853. hs2=ov_halfrate_p(vf2);
  156854. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156855. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156856. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156857. w1=vorbis_window(&vf1->vd,0);
  156858. w2=vorbis_window(&vf2->vd,0);
  156859. for(i=0;i<vi1->channels;i++)
  156860. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156861. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156862. /* have a lapping buffer from vf1; now to splice it into the lapping
  156863. buffer of vf2 */
  156864. /* consolidate and expose the buffer. */
  156865. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156866. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156867. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156868. /* splice */
  156869. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156870. /* done */
  156871. return(0);
  156872. }
  156873. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156874. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156875. vorbis_info *vi;
  156876. float **lappcm;
  156877. float **pcm;
  156878. float *w1,*w2;
  156879. int n1,n2,ch1,ch2,hs;
  156880. int i,ret;
  156881. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156882. ret=_ov_initset(vf);
  156883. if(ret)return(ret);
  156884. vi=ov_info(vf,-1);
  156885. hs=ov_halfrate_p(vf);
  156886. ch1=vi->channels;
  156887. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156888. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156889. persistent; even if the decode state
  156890. from this link gets dumped, this
  156891. window array continues to exist */
  156892. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156893. for(i=0;i<ch1;i++)
  156894. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156895. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156896. /* have lapping data; seek and prime the buffer */
  156897. ret=localseek(vf,pos);
  156898. if(ret)return ret;
  156899. ret=_ov_initprime(vf);
  156900. if(ret)return(ret);
  156901. /* Guard against cross-link changes; they're perfectly legal */
  156902. vi=ov_info(vf,-1);
  156903. ch2=vi->channels;
  156904. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156905. w2=vorbis_window(&vf->vd,0);
  156906. /* consolidate and expose the buffer. */
  156907. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156908. /* splice */
  156909. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156910. /* done */
  156911. return(0);
  156912. }
  156913. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156914. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156915. }
  156916. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156917. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156918. }
  156919. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156920. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156921. }
  156922. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156923. int (*localseek)(OggVorbis_File *,double)){
  156924. vorbis_info *vi;
  156925. float **lappcm;
  156926. float **pcm;
  156927. float *w1,*w2;
  156928. int n1,n2,ch1,ch2,hs;
  156929. int i,ret;
  156930. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156931. ret=_ov_initset(vf);
  156932. if(ret)return(ret);
  156933. vi=ov_info(vf,-1);
  156934. hs=ov_halfrate_p(vf);
  156935. ch1=vi->channels;
  156936. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156937. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156938. persistent; even if the decode state
  156939. from this link gets dumped, this
  156940. window array continues to exist */
  156941. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156942. for(i=0;i<ch1;i++)
  156943. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156944. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156945. /* have lapping data; seek and prime the buffer */
  156946. ret=localseek(vf,pos);
  156947. if(ret)return ret;
  156948. ret=_ov_initprime(vf);
  156949. if(ret)return(ret);
  156950. /* Guard against cross-link changes; they're perfectly legal */
  156951. vi=ov_info(vf,-1);
  156952. ch2=vi->channels;
  156953. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156954. w2=vorbis_window(&vf->vd,0);
  156955. /* consolidate and expose the buffer. */
  156956. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156957. /* splice */
  156958. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156959. /* done */
  156960. return(0);
  156961. }
  156962. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156963. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156964. }
  156965. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156966. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156967. }
  156968. #endif
  156969. /*** End of inlined file: vorbisfile.c ***/
  156970. /*** Start of inlined file: window.c ***/
  156971. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156972. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156973. // tasks..
  156974. #if JUCE_MSVC
  156975. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156976. #endif
  156977. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156978. #if JUCE_USE_OGGVORBIS
  156979. #include <stdlib.h>
  156980. #include <math.h>
  156981. static float vwin64[32] = {
  156982. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156983. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156984. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156985. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156986. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156987. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156988. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156989. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156990. };
  156991. static float vwin128[64] = {
  156992. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156993. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156994. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156995. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156996. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156997. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156998. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156999. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157000. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157001. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157002. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157003. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157004. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157005. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157006. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157007. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157008. };
  157009. static float vwin256[128] = {
  157010. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157011. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157012. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157013. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157014. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157015. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157016. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157017. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157018. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157019. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157020. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157021. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157022. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157023. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157024. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157025. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157026. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157027. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157028. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157029. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157030. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157031. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157032. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157033. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157034. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157035. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157036. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157037. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157038. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157039. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157040. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157041. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157042. };
  157043. static float vwin512[256] = {
  157044. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157045. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157046. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157047. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157048. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157049. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157050. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157051. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157052. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157053. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157054. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157055. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157056. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157057. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157058. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157059. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157060. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157061. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157062. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157063. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157064. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157065. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157066. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157067. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157068. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157069. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157070. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157071. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157072. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157073. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157074. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157075. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157076. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157077. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157078. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157079. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157080. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157081. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157082. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157083. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157084. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157085. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157086. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157087. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157088. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157089. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157090. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157091. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157092. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157093. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157094. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157095. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157096. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157097. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157098. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157099. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157100. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157101. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157102. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157103. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157104. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157105. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157106. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157107. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157108. };
  157109. static float vwin1024[512] = {
  157110. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157111. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157112. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157113. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157114. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157115. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157116. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157117. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157118. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157119. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157120. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157121. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157122. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157123. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157124. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157125. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157126. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157127. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157128. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157129. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157130. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157131. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157132. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157133. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157134. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157135. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157136. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157137. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157138. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157139. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157140. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157141. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157142. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157143. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157144. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157145. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157146. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157147. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157148. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157149. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157150. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157151. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157152. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157153. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157154. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157155. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157156. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157157. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157158. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157159. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157160. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157161. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157162. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157163. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157164. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157165. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157166. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157167. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157168. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157169. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157170. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157171. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157172. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157173. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157174. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157175. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157176. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157177. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157178. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157179. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157180. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157181. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157182. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157183. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157184. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157185. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157186. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157187. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157188. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157189. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157190. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157191. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157192. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157193. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157194. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157195. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157196. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157197. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157198. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157199. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157200. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157201. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157202. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157203. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157204. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157205. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157206. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157207. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157208. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157209. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157210. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157211. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157212. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157213. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157214. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157215. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157216. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157217. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157218. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157219. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157220. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157221. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157222. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157223. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157224. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157225. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157226. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157227. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157228. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157229. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157230. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157231. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157232. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157233. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157234. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157235. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157236. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157237. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157238. };
  157239. static float vwin2048[1024] = {
  157240. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157241. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157242. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157243. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157244. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157245. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157246. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157247. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157248. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157249. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157250. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157251. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157252. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157253. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157254. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157255. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157256. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157257. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157258. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157259. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157260. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157261. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157262. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157263. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157264. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157265. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157266. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157267. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157268. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157269. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157270. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157271. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157272. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157273. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157274. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157275. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157276. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157277. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157278. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157279. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157280. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157281. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157282. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157283. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157284. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157285. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157286. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157287. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157288. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157289. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157290. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157291. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157292. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157293. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157294. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157295. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157296. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157297. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157298. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157299. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157300. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157301. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157302. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157303. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157304. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157305. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157306. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157307. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157308. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157309. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157310. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157311. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157312. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157313. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157314. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157315. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157316. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157317. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157318. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157319. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157320. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157321. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157322. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157323. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157324. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157325. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157326. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157327. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157328. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157329. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157330. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157331. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157332. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157333. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157334. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157335. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157336. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157337. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157338. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157339. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157340. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157341. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157342. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157343. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157344. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157345. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157346. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157347. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157348. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157349. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157350. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157351. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157352. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157353. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157354. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157355. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157356. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157357. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157358. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157359. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157360. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157361. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157362. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157363. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157364. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157365. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157366. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157367. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157368. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157369. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157370. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157371. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157372. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157373. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157374. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157375. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157376. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157377. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157378. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157379. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157380. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157381. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157382. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157383. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157384. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157385. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157386. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157387. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157388. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157389. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157390. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157391. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157392. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157393. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157394. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157395. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157396. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157397. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157398. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157399. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157400. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157401. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157402. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157403. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157404. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157405. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157406. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157407. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157408. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157409. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157410. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157411. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157412. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157413. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157414. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157415. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157416. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157417. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157418. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157419. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157420. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157421. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157422. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157423. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157424. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157425. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157426. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157427. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157428. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157429. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157430. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157431. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157432. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157433. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157434. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157435. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157436. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157437. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157438. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157439. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157440. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157441. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157442. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157443. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157444. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157445. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157446. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157447. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157448. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157449. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157450. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157451. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157452. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157453. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157454. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157455. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157456. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157457. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157458. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157459. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157460. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157461. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157462. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157463. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157464. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157465. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157466. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157467. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157468. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157469. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157470. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157471. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157472. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157473. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157474. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157475. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157476. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157477. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157478. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157479. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157480. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157481. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157482. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157483. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157484. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157485. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157486. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157487. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157488. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157489. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157490. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157491. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157492. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157493. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157494. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157495. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157496. };
  157497. static float vwin4096[2048] = {
  157498. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157499. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157500. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157501. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157502. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157503. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157504. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157505. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157506. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157507. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157508. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157509. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157510. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157511. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157512. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157513. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157514. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157515. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157516. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157517. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157518. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157519. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157520. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157521. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157522. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157523. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157524. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157525. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157526. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157527. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157528. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157529. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157530. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157531. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157532. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157533. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157534. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157535. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157536. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157537. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157538. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157539. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157540. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157541. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157542. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157543. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157544. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157545. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157546. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157547. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157548. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157549. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157550. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157551. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157552. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157553. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157554. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157555. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157556. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157557. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157558. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157559. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157560. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157561. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157562. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157563. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157564. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157565. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157566. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157567. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157568. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157569. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157570. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157571. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157572. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157573. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157574. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157575. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157576. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157577. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157578. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157579. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157580. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157581. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157582. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157583. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157584. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157585. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157586. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157587. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157588. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157589. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157590. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157591. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157592. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157593. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157594. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157595. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157596. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157597. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157598. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157599. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157600. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157601. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157602. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157603. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157604. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157605. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157606. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157607. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157608. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157609. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157610. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157611. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157612. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157613. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157614. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157615. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157616. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157617. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157618. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157619. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157620. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157621. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157622. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157623. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157624. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157625. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157626. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157627. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157628. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157629. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157630. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157631. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157632. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157633. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157634. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157635. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157636. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157637. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157638. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157639. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157640. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157641. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157642. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157643. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157644. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157645. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157646. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157647. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157648. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157649. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157650. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157651. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157652. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157653. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157654. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157655. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157656. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157657. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157658. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157659. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157660. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157661. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157662. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157663. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157664. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157665. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157666. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157667. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157668. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157669. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157670. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157671. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157672. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157673. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157674. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157675. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157676. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157677. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157678. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157679. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157680. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157681. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157682. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157683. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157684. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157685. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157686. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157687. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157688. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157689. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157690. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157691. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157692. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157693. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157694. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157695. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157696. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157697. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157698. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157699. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157700. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157701. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157702. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157703. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157704. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157705. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157706. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157707. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157708. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157709. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157710. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157711. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157712. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157713. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157714. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157715. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157716. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157717. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157718. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157719. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157720. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157721. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157722. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157723. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157724. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157725. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157726. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157727. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157728. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157729. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157730. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157731. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157732. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157733. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157734. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157735. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157736. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157737. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157738. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157739. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157740. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157741. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157742. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157743. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157744. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157745. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157746. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157747. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157748. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157749. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157750. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157751. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157752. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157753. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157754. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157755. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157756. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157757. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157758. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157759. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157760. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157761. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157762. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157763. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157764. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157765. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157766. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157767. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157768. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157769. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157770. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157771. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157772. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157773. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157774. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157775. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157776. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157777. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157778. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157779. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157780. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157781. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157782. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157783. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157784. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157785. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157786. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157787. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157788. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157789. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157790. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157791. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157792. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157793. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157794. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157795. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157796. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157797. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157798. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157799. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157800. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157801. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157802. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157803. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157804. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157805. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157806. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157807. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157808. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157809. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157810. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157811. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157812. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157813. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157814. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157815. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157816. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157817. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157818. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157819. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157820. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157821. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157822. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157823. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157824. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157825. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157826. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157827. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157828. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157829. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157830. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157831. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157832. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157833. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157834. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157835. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157836. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157837. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157838. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157839. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157840. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157841. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157842. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157843. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157844. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157845. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157846. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157847. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157848. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157849. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157850. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157851. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157852. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157853. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157854. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157855. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157856. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157857. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157858. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157859. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157860. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157861. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157862. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157863. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157864. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157865. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157866. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157867. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157868. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157869. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157870. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157871. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157872. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157873. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157874. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157875. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157876. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157877. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157878. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157879. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157880. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157881. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157882. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157883. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157884. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157885. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157886. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157887. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157888. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157889. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157890. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157891. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157892. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157893. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157894. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157895. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157896. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157897. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157898. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157899. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157900. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157901. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157902. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157903. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157904. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157905. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157906. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157907. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157908. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157909. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157910. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157911. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157912. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157913. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157914. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157915. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157916. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157917. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157918. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157919. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157920. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157921. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157922. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157923. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157924. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157925. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157926. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157927. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157928. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157929. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157930. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157931. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157932. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157933. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157934. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157935. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157936. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157937. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157938. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157939. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157940. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157941. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157942. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157943. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157944. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157945. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157946. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157947. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157948. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157949. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157950. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157951. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157952. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157953. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157954. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157955. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157956. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157957. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157958. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157959. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157960. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157961. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157962. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157963. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157964. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157965. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157966. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157967. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157968. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157969. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157970. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157971. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157972. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157973. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157974. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157975. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157976. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157977. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157978. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157979. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157980. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157981. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157982. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157983. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157984. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157985. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157986. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157987. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157988. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157989. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157990. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157991. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157992. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157993. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157994. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157995. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157996. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157997. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157998. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157999. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158000. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158001. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158002. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158003. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158004. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158005. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158006. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158007. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158008. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158009. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158010. };
  158011. static float vwin8192[4096] = {
  158012. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158013. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158014. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158015. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158016. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158017. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158018. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158019. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158020. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158021. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158022. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158023. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158024. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158025. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158026. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158027. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158028. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158029. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158030. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158031. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158032. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158033. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158034. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158035. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158036. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158037. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158038. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158039. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158040. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158041. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158042. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158043. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158044. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158045. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158046. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158047. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158048. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158049. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158050. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158051. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158052. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158053. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158054. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158055. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158056. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158057. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158058. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158059. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158060. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158061. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158062. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158063. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158064. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158065. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158066. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158067. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158068. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158069. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158070. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158071. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158072. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158073. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158074. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158075. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158076. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158077. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158078. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158079. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158080. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158081. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158082. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158083. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158084. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158085. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158086. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158087. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158088. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158089. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158090. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158091. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158092. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158093. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158094. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158095. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158096. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158097. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158098. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158099. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158100. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158101. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158102. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158103. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158104. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158105. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158106. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158107. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158108. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158109. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158110. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158111. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158112. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158113. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158114. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158115. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158116. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158117. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158118. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158119. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158120. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158121. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158122. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158123. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158124. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158125. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158126. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158127. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158128. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158129. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158130. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158131. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158132. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158133. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158134. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158135. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158136. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158137. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158138. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158139. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158140. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158141. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158142. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158143. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158144. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158145. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158146. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158147. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158148. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158149. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158150. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158151. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158152. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158153. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158154. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158155. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158156. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158157. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158158. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158159. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158160. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158161. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158162. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158163. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158164. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158165. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158166. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158167. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158168. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158169. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158170. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158171. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158172. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158173. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158174. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158175. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158176. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158177. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158178. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158179. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158180. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158181. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158182. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158183. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158184. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158185. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158186. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158187. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158188. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158189. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158190. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158191. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158192. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158193. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158194. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158195. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158196. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158197. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158198. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158199. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158200. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158201. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158202. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158203. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158204. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158205. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158206. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158207. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158208. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158209. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158210. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158211. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158212. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158213. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158214. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158215. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158216. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158217. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158218. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158219. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158220. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158221. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158222. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158223. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158224. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158225. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158226. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158227. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158228. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158229. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158230. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158231. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158232. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158233. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158234. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158235. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158236. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158237. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158238. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158239. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158240. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158241. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158242. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158243. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158244. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158245. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158246. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158247. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158248. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158249. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158250. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158251. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158252. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158253. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158254. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158255. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158256. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158257. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158258. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158259. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158260. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158261. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158262. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158263. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158264. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158265. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158266. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158267. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158268. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158269. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158270. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158271. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158272. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158273. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158274. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158275. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158276. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158277. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158278. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158279. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158280. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158281. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158282. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158283. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158284. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158285. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158286. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158287. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158288. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158289. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158290. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158291. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158292. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158293. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158294. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158295. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158296. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158297. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158298. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158299. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158300. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158301. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158302. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158303. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158304. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158305. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158306. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158307. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158308. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158309. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158310. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158311. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158312. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158313. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158314. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158315. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158316. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158317. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158318. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158319. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158320. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158321. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158322. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158323. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158324. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158325. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158326. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158327. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158328. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158329. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158330. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158331. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158332. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158333. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158334. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158335. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158336. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158337. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158338. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158339. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158340. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158341. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158342. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158343. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158344. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158345. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158346. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158347. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158348. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158349. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158350. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158351. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158352. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158353. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158354. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158355. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158356. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158357. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158358. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158359. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158360. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158361. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158362. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158363. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158364. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158365. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158366. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158367. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158368. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158369. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158370. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158371. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158372. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158373. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158374. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158375. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158376. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158377. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158378. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158379. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158380. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158381. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158382. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158383. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158384. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158385. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158386. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158387. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158388. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158389. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158390. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158391. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158392. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158393. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158394. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158395. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158396. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158397. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158398. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158399. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158400. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158401. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158402. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158403. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158404. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158405. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158406. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158407. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158408. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158409. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158410. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158411. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158412. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158413. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158414. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158415. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158416. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158417. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158418. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158419. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158420. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158421. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158422. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158423. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158424. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158425. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158426. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158427. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158428. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158429. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158430. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158431. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158432. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158433. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158434. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158435. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158436. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158437. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158438. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158439. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158440. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158441. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158442. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158443. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158444. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158445. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158446. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158447. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158448. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158449. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158450. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158451. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158452. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158453. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158454. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158455. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158456. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158457. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158458. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158459. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158460. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158461. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158462. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158463. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158464. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158465. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158466. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158467. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158468. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158469. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158470. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158471. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158472. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158473. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158474. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158475. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158476. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158477. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158478. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158479. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158480. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158481. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158482. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158483. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158484. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158485. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158486. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158487. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158488. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158489. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158490. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158491. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158492. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158493. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158494. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158495. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158496. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158497. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158498. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158499. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158500. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158501. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158502. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158503. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158504. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158505. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158506. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158507. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158508. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158509. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158510. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158511. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158512. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158513. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158514. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158515. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158516. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158517. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158518. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158519. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158520. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158521. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158522. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158523. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158524. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158525. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158526. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158527. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158528. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158529. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158530. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158531. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158532. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158533. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158534. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158535. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158536. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158537. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158538. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158539. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158540. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158541. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158542. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158543. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158544. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158545. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158546. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158547. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158548. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158549. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158550. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158551. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158552. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158553. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158554. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158555. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158556. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158557. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158558. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158559. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158560. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158561. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158562. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158563. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158564. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158565. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158566. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158567. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158568. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158569. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158570. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158571. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158572. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158573. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158574. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158575. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158576. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158577. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158578. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158579. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158580. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158581. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158582. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158583. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158584. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158585. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158586. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158587. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158588. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158589. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158590. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158591. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158592. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158593. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158594. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158595. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158596. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158597. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158598. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158599. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158600. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158601. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158602. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158603. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158604. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158605. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158606. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158607. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158608. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158609. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158610. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158611. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158612. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158613. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158614. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158615. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158616. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158617. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158618. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158619. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158620. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158621. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158622. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158623. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158624. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158625. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158626. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158627. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158628. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158629. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158630. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158631. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158632. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158633. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158634. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158635. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158636. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158637. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158638. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158639. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158640. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158641. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158642. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158643. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158644. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158645. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158646. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158647. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158648. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158649. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158650. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158651. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158652. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158653. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158654. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158655. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158656. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158657. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158658. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158659. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158660. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158661. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158662. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158663. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158664. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158665. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158666. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158667. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158668. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158669. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158670. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158671. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158672. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158673. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158674. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158675. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158676. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158677. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158678. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158679. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158680. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158681. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158682. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158683. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158684. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158685. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158686. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158687. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158688. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158689. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158690. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158691. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158692. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158693. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158694. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158695. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158696. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158697. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158698. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158699. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158700. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158701. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158702. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158703. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158704. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158705. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158706. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158707. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158708. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158709. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158710. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158711. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158712. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158713. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158714. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158715. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158716. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158717. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158718. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158719. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158720. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158721. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158722. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158723. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158724. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158725. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158726. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158727. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158728. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158729. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158730. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158731. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158732. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158733. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158734. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158735. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158736. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158737. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158738. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158739. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158740. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158741. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158742. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158743. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158744. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158745. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158746. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158747. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158748. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158749. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158750. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158751. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158752. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158753. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158754. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158755. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158756. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158757. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158758. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158759. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158760. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158761. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158762. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158763. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158764. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158765. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158766. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158767. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158768. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158769. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158770. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158771. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158772. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158773. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158774. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158775. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158776. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158777. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158778. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158779. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158780. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158781. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158782. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158783. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158784. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158785. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158786. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158787. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158788. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158789. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158790. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158791. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158792. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158793. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158794. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158795. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158796. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158797. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158798. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158799. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158800. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158801. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158802. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158803. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158804. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158805. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158806. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158807. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158808. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158809. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158810. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158811. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158812. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158813. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158814. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158815. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158816. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158817. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158818. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158819. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158820. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158821. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158822. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158823. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158824. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158825. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158826. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158827. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158828. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158829. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158830. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158831. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158832. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158833. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158834. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158835. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158836. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158837. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158838. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158839. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158840. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158841. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158842. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158843. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158844. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158845. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158846. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158847. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158848. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158849. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158850. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158851. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158852. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158853. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158854. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158855. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158856. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158857. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158858. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158859. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158860. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158861. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158862. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158863. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158864. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158865. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158866. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158867. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158868. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158869. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158870. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158871. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158872. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158873. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158874. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158875. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158876. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158877. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158878. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158879. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158880. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158881. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158882. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158883. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158884. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158885. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158886. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158887. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158888. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158889. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158890. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158891. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158892. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158893. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158894. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158895. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158896. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158897. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158898. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158899. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158900. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158901. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158902. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158903. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158904. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158905. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158906. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158907. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158908. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158909. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158910. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158911. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158912. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158913. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158914. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158915. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158916. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158917. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158918. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158919. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158920. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158921. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158922. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158923. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158924. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158925. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158926. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158927. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158928. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158929. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158930. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158931. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158932. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158933. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158934. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158935. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158936. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158937. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158938. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158939. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158940. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158941. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158942. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158943. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158944. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158945. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158946. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158947. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158948. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158949. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158950. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158951. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158952. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158953. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158954. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158955. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158956. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158957. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158958. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158959. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158960. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158961. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158962. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158963. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158964. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158965. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158966. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158967. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158968. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158969. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158970. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158971. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158972. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158973. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158974. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158975. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158976. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158977. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158978. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158979. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158980. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158981. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158982. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158983. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158984. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158985. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158986. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158987. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158988. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158989. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158990. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158991. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158992. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158993. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158994. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158995. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158996. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158997. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158998. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158999. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159000. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159001. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159002. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159003. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159004. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159005. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159006. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159007. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159008. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159009. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159010. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159011. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159012. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159013. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159014. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159015. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159016. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159017. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159018. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159019. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159020. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159021. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159022. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159023. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159024. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159025. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159026. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159027. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159028. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159029. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159030. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159031. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159032. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159033. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159034. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159035. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159036. };
  159037. static float *vwin[8] = {
  159038. vwin64,
  159039. vwin128,
  159040. vwin256,
  159041. vwin512,
  159042. vwin1024,
  159043. vwin2048,
  159044. vwin4096,
  159045. vwin8192,
  159046. };
  159047. float *_vorbis_window_get(int n){
  159048. return vwin[n];
  159049. }
  159050. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159051. int lW,int W,int nW){
  159052. lW=(W?lW:0);
  159053. nW=(W?nW:0);
  159054. {
  159055. float *windowLW=vwin[winno[lW]];
  159056. float *windowNW=vwin[winno[nW]];
  159057. long n=blocksizes[W];
  159058. long ln=blocksizes[lW];
  159059. long rn=blocksizes[nW];
  159060. long leftbegin=n/4-ln/4;
  159061. long leftend=leftbegin+ln/2;
  159062. long rightbegin=n/2+n/4-rn/4;
  159063. long rightend=rightbegin+rn/2;
  159064. int i,p;
  159065. for(i=0;i<leftbegin;i++)
  159066. d[i]=0.f;
  159067. for(p=0;i<leftend;i++,p++)
  159068. d[i]*=windowLW[p];
  159069. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159070. d[i]*=windowNW[p];
  159071. for(;i<n;i++)
  159072. d[i]=0.f;
  159073. }
  159074. }
  159075. #endif
  159076. /*** End of inlined file: window.c ***/
  159077. #else
  159078. #include <vorbis/vorbisenc.h>
  159079. #include <vorbis/codec.h>
  159080. #include <vorbis/vorbisfile.h>
  159081. #endif
  159082. }
  159083. #undef max
  159084. #undef min
  159085. BEGIN_JUCE_NAMESPACE
  159086. static const char* const oggFormatName = "Ogg-Vorbis file";
  159087. static const char* const oggExtensions[] = { ".ogg", 0 };
  159088. class OggReader : public AudioFormatReader
  159089. {
  159090. OggVorbisNamespace::OggVorbis_File ovFile;
  159091. OggVorbisNamespace::ov_callbacks callbacks;
  159092. AudioSampleBuffer reservoir;
  159093. int reservoirStart, samplesInReservoir;
  159094. public:
  159095. OggReader (InputStream* const inp)
  159096. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159097. reservoir (2, 4096),
  159098. reservoirStart (0),
  159099. samplesInReservoir (0)
  159100. {
  159101. using namespace OggVorbisNamespace;
  159102. sampleRate = 0;
  159103. usesFloatingPointData = true;
  159104. callbacks.read_func = &oggReadCallback;
  159105. callbacks.seek_func = &oggSeekCallback;
  159106. callbacks.close_func = &oggCloseCallback;
  159107. callbacks.tell_func = &oggTellCallback;
  159108. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159109. if (err == 0)
  159110. {
  159111. vorbis_info* info = ov_info (&ovFile, -1);
  159112. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159113. numChannels = info->channels;
  159114. bitsPerSample = 16;
  159115. sampleRate = info->rate;
  159116. reservoir.setSize (numChannels,
  159117. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159118. }
  159119. }
  159120. ~OggReader()
  159121. {
  159122. OggVorbisNamespace::ov_clear (&ovFile);
  159123. }
  159124. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159125. int64 startSampleInFile, int numSamples)
  159126. {
  159127. while (numSamples > 0)
  159128. {
  159129. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159130. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159131. {
  159132. // got a few samples overlapping, so use them before seeking..
  159133. const int numToUse = jmin (numSamples, numAvailable);
  159134. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159135. if (destSamples[i] != 0)
  159136. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159137. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159138. sizeof (float) * numToUse);
  159139. startSampleInFile += numToUse;
  159140. numSamples -= numToUse;
  159141. startOffsetInDestBuffer += numToUse;
  159142. if (numSamples == 0)
  159143. break;
  159144. }
  159145. if (startSampleInFile < reservoirStart
  159146. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159147. {
  159148. // buffer miss, so refill the reservoir
  159149. int bitStream = 0;
  159150. reservoirStart = jmax (0, (int) startSampleInFile);
  159151. samplesInReservoir = reservoir.getNumSamples();
  159152. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159153. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159154. int offset = 0;
  159155. int numToRead = samplesInReservoir;
  159156. while (numToRead > 0)
  159157. {
  159158. float** dataIn = 0;
  159159. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159160. if (samps <= 0)
  159161. break;
  159162. jassert (samps <= numToRead);
  159163. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159164. {
  159165. memcpy (reservoir.getSampleData (i, offset),
  159166. dataIn[i],
  159167. sizeof (float) * samps);
  159168. }
  159169. numToRead -= samps;
  159170. offset += samps;
  159171. }
  159172. if (numToRead > 0)
  159173. reservoir.clear (offset, numToRead);
  159174. }
  159175. }
  159176. if (numSamples > 0)
  159177. {
  159178. for (int i = numDestChannels; --i >= 0;)
  159179. if (destSamples[i] != 0)
  159180. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159181. sizeof (int) * numSamples);
  159182. }
  159183. return true;
  159184. }
  159185. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159186. {
  159187. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159188. }
  159189. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159190. {
  159191. InputStream* const in = static_cast <InputStream*> (datasource);
  159192. if (whence == SEEK_CUR)
  159193. offset += in->getPosition();
  159194. else if (whence == SEEK_END)
  159195. offset += in->getTotalLength();
  159196. in->setPosition (offset);
  159197. return 0;
  159198. }
  159199. static int oggCloseCallback (void*)
  159200. {
  159201. return 0;
  159202. }
  159203. static long oggTellCallback (void* datasource)
  159204. {
  159205. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159206. }
  159207. private:
  159208. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  159209. };
  159210. class OggWriter : public AudioFormatWriter
  159211. {
  159212. OggVorbisNamespace::ogg_stream_state os;
  159213. OggVorbisNamespace::ogg_page og;
  159214. OggVorbisNamespace::ogg_packet op;
  159215. OggVorbisNamespace::vorbis_info vi;
  159216. OggVorbisNamespace::vorbis_comment vc;
  159217. OggVorbisNamespace::vorbis_dsp_state vd;
  159218. OggVorbisNamespace::vorbis_block vb;
  159219. public:
  159220. bool ok;
  159221. OggWriter (OutputStream* const out,
  159222. const double sampleRate,
  159223. const int numChannels,
  159224. const int bitsPerSample,
  159225. const int qualityIndex)
  159226. : AudioFormatWriter (out, TRANS (oggFormatName),
  159227. sampleRate,
  159228. numChannels,
  159229. bitsPerSample)
  159230. {
  159231. using namespace OggVorbisNamespace;
  159232. ok = false;
  159233. vorbis_info_init (&vi);
  159234. if (vorbis_encode_init_vbr (&vi,
  159235. numChannels,
  159236. (int) sampleRate,
  159237. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159238. {
  159239. vorbis_comment_init (&vc);
  159240. if (JUCEApplication::getInstance() != 0)
  159241. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159242. vorbis_analysis_init (&vd, &vi);
  159243. vorbis_block_init (&vd, &vb);
  159244. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159245. ogg_packet header;
  159246. ogg_packet header_comm;
  159247. ogg_packet header_code;
  159248. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159249. ogg_stream_packetin (&os, &header);
  159250. ogg_stream_packetin (&os, &header_comm);
  159251. ogg_stream_packetin (&os, &header_code);
  159252. for (;;)
  159253. {
  159254. if (ogg_stream_flush (&os, &og) == 0)
  159255. break;
  159256. output->write (og.header, og.header_len);
  159257. output->write (og.body, og.body_len);
  159258. }
  159259. ok = true;
  159260. }
  159261. }
  159262. ~OggWriter()
  159263. {
  159264. using namespace OggVorbisNamespace;
  159265. if (ok)
  159266. {
  159267. // write a zero-length packet to show ogg that we're finished..
  159268. write (0, 0);
  159269. ogg_stream_clear (&os);
  159270. vorbis_block_clear (&vb);
  159271. vorbis_dsp_clear (&vd);
  159272. vorbis_comment_clear (&vc);
  159273. vorbis_info_clear (&vi);
  159274. output->flush();
  159275. }
  159276. else
  159277. {
  159278. vorbis_info_clear (&vi);
  159279. output = 0; // to stop the base class deleting this, as it needs to be returned
  159280. // to the caller of createWriter()
  159281. }
  159282. }
  159283. bool write (const int** samplesToWrite, int numSamples)
  159284. {
  159285. using namespace OggVorbisNamespace;
  159286. if (! ok)
  159287. return false;
  159288. if (numSamples > 0)
  159289. {
  159290. const double gain = 1.0 / 0x80000000u;
  159291. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159292. for (int i = numChannels; --i >= 0;)
  159293. {
  159294. float* const dst = vorbisBuffer[i];
  159295. const int* const src = samplesToWrite [i];
  159296. if (src != 0 && dst != 0)
  159297. {
  159298. for (int j = 0; j < numSamples; ++j)
  159299. dst[j] = (float) (src[j] * gain);
  159300. }
  159301. }
  159302. }
  159303. vorbis_analysis_wrote (&vd, numSamples);
  159304. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159305. {
  159306. vorbis_analysis (&vb, 0);
  159307. vorbis_bitrate_addblock (&vb);
  159308. while (vorbis_bitrate_flushpacket (&vd, &op))
  159309. {
  159310. ogg_stream_packetin (&os, &op);
  159311. for (;;)
  159312. {
  159313. if (ogg_stream_pageout (&os, &og) == 0)
  159314. break;
  159315. output->write (og.header, og.header_len);
  159316. output->write (og.body, og.body_len);
  159317. if (ogg_page_eos (&og))
  159318. break;
  159319. }
  159320. }
  159321. }
  159322. return true;
  159323. }
  159324. private:
  159325. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159326. };
  159327. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159328. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159329. {
  159330. }
  159331. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159332. {
  159333. }
  159334. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159335. {
  159336. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159337. return Array <int> (rates);
  159338. }
  159339. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159340. {
  159341. const int depths[] = { 32, 0 };
  159342. return Array <int> (depths);
  159343. }
  159344. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159345. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159346. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159347. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159348. const bool deleteStreamIfOpeningFails)
  159349. {
  159350. ScopedPointer <OggReader> r (new OggReader (in));
  159351. if (r->sampleRate != 0)
  159352. return r.release();
  159353. if (! deleteStreamIfOpeningFails)
  159354. r->input = 0;
  159355. return 0;
  159356. }
  159357. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159358. double sampleRate,
  159359. unsigned int numChannels,
  159360. int bitsPerSample,
  159361. const StringPairArray& /*metadataValues*/,
  159362. int qualityOptionIndex)
  159363. {
  159364. ScopedPointer <OggWriter> w (new OggWriter (out,
  159365. sampleRate,
  159366. numChannels,
  159367. bitsPerSample,
  159368. qualityOptionIndex));
  159369. return w->ok ? w.release() : 0;
  159370. }
  159371. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159372. {
  159373. StringArray s;
  159374. s.add ("Low Quality");
  159375. s.add ("Medium Quality");
  159376. s.add ("High Quality");
  159377. return s;
  159378. }
  159379. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159380. {
  159381. FileInputStream* const in = source.createInputStream();
  159382. if (in != 0)
  159383. {
  159384. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159385. if (r != 0)
  159386. {
  159387. const int64 numSamps = r->lengthInSamples;
  159388. r = 0;
  159389. const int64 fileNumSamps = source.getSize() / 4;
  159390. const double ratio = numSamps / (double) fileNumSamps;
  159391. if (ratio > 12.0)
  159392. return 0;
  159393. else if (ratio > 6.0)
  159394. return 1;
  159395. else
  159396. return 2;
  159397. }
  159398. }
  159399. return 1;
  159400. }
  159401. END_JUCE_NAMESPACE
  159402. #endif
  159403. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159404. #endif
  159405. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159406. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159407. #if JUCE_MSVC
  159408. #pragma warning (push)
  159409. #endif
  159410. namespace jpeglibNamespace
  159411. {
  159412. #if JUCE_INCLUDE_JPEGLIB_CODE
  159413. #if JUCE_MINGW
  159414. typedef unsigned char boolean;
  159415. #endif
  159416. #define JPEG_INTERNALS
  159417. #undef FAR
  159418. /*** Start of inlined file: jpeglib.h ***/
  159419. #ifndef JPEGLIB_H
  159420. #define JPEGLIB_H
  159421. /*
  159422. * First we include the configuration files that record how this
  159423. * installation of the JPEG library is set up. jconfig.h can be
  159424. * generated automatically for many systems. jmorecfg.h contains
  159425. * manual configuration options that most people need not worry about.
  159426. */
  159427. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159428. /*** Start of inlined file: jconfig.h ***/
  159429. /* see jconfig.doc for explanations */
  159430. // disable all the warnings under MSVC
  159431. #ifdef _MSC_VER
  159432. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159433. #endif
  159434. #ifdef __BORLANDC__
  159435. #pragma warn -8057
  159436. #pragma warn -8019
  159437. #pragma warn -8004
  159438. #pragma warn -8008
  159439. #endif
  159440. #define HAVE_PROTOTYPES
  159441. #define HAVE_UNSIGNED_CHAR
  159442. #define HAVE_UNSIGNED_SHORT
  159443. /* #define void char */
  159444. /* #define const */
  159445. #undef CHAR_IS_UNSIGNED
  159446. #define HAVE_STDDEF_H
  159447. #define HAVE_STDLIB_H
  159448. #undef NEED_BSD_STRINGS
  159449. #undef NEED_SYS_TYPES_H
  159450. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159451. #undef NEED_SHORT_EXTERNAL_NAMES
  159452. #undef INCOMPLETE_TYPES_BROKEN
  159453. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159454. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159455. typedef unsigned char boolean;
  159456. #endif
  159457. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159458. #ifdef JPEG_INTERNALS
  159459. #undef RIGHT_SHIFT_IS_UNSIGNED
  159460. #endif /* JPEG_INTERNALS */
  159461. #ifdef JPEG_CJPEG_DJPEG
  159462. #define BMP_SUPPORTED /* BMP image file format */
  159463. #define GIF_SUPPORTED /* GIF image file format */
  159464. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159465. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159466. #define TARGA_SUPPORTED /* Targa image file format */
  159467. #define TWO_FILE_COMMANDLINE /* optional */
  159468. #define USE_SETMODE /* Microsoft has setmode() */
  159469. #undef NEED_SIGNAL_CATCHER
  159470. #undef DONT_USE_B_MODE
  159471. #undef PROGRESS_REPORT /* optional */
  159472. #endif /* JPEG_CJPEG_DJPEG */
  159473. /*** End of inlined file: jconfig.h ***/
  159474. /* widely used configuration options */
  159475. #endif
  159476. /*** Start of inlined file: jmorecfg.h ***/
  159477. /*
  159478. * Define BITS_IN_JSAMPLE as either
  159479. * 8 for 8-bit sample values (the usual setting)
  159480. * 12 for 12-bit sample values
  159481. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159482. * JPEG standard, and the IJG code does not support anything else!
  159483. * We do not support run-time selection of data precision, sorry.
  159484. */
  159485. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159486. /*
  159487. * Maximum number of components (color channels) allowed in JPEG image.
  159488. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159489. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159490. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159491. * really short on memory. (Each allowed component costs a hundred or so
  159492. * bytes of storage, whether actually used in an image or not.)
  159493. */
  159494. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159495. /*
  159496. * Basic data types.
  159497. * You may need to change these if you have a machine with unusual data
  159498. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159499. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159500. * but it had better be at least 16.
  159501. */
  159502. /* Representation of a single sample (pixel element value).
  159503. * We frequently allocate large arrays of these, so it's important to keep
  159504. * them small. But if you have memory to burn and access to char or short
  159505. * arrays is very slow on your hardware, you might want to change these.
  159506. */
  159507. #if BITS_IN_JSAMPLE == 8
  159508. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159509. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159510. */
  159511. #ifdef HAVE_UNSIGNED_CHAR
  159512. typedef unsigned char JSAMPLE;
  159513. #define GETJSAMPLE(value) ((int) (value))
  159514. #else /* not HAVE_UNSIGNED_CHAR */
  159515. typedef char JSAMPLE;
  159516. #ifdef CHAR_IS_UNSIGNED
  159517. #define GETJSAMPLE(value) ((int) (value))
  159518. #else
  159519. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159520. #endif /* CHAR_IS_UNSIGNED */
  159521. #endif /* HAVE_UNSIGNED_CHAR */
  159522. #define MAXJSAMPLE 255
  159523. #define CENTERJSAMPLE 128
  159524. #endif /* BITS_IN_JSAMPLE == 8 */
  159525. #if BITS_IN_JSAMPLE == 12
  159526. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159527. * On nearly all machines "short" will do nicely.
  159528. */
  159529. typedef short JSAMPLE;
  159530. #define GETJSAMPLE(value) ((int) (value))
  159531. #define MAXJSAMPLE 4095
  159532. #define CENTERJSAMPLE 2048
  159533. #endif /* BITS_IN_JSAMPLE == 12 */
  159534. /* Representation of a DCT frequency coefficient.
  159535. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159536. * Again, we allocate large arrays of these, but you can change to int
  159537. * if you have memory to burn and "short" is really slow.
  159538. */
  159539. typedef short JCOEF;
  159540. /* Compressed datastreams are represented as arrays of JOCTET.
  159541. * These must be EXACTLY 8 bits wide, at least once they are written to
  159542. * external storage. Note that when using the stdio data source/destination
  159543. * managers, this is also the data type passed to fread/fwrite.
  159544. */
  159545. #ifdef HAVE_UNSIGNED_CHAR
  159546. typedef unsigned char JOCTET;
  159547. #define GETJOCTET(value) (value)
  159548. #else /* not HAVE_UNSIGNED_CHAR */
  159549. typedef char JOCTET;
  159550. #ifdef CHAR_IS_UNSIGNED
  159551. #define GETJOCTET(value) (value)
  159552. #else
  159553. #define GETJOCTET(value) ((value) & 0xFF)
  159554. #endif /* CHAR_IS_UNSIGNED */
  159555. #endif /* HAVE_UNSIGNED_CHAR */
  159556. /* These typedefs are used for various table entries and so forth.
  159557. * They must be at least as wide as specified; but making them too big
  159558. * won't cost a huge amount of memory, so we don't provide special
  159559. * extraction code like we did for JSAMPLE. (In other words, these
  159560. * typedefs live at a different point on the speed/space tradeoff curve.)
  159561. */
  159562. /* UINT8 must hold at least the values 0..255. */
  159563. #ifdef HAVE_UNSIGNED_CHAR
  159564. typedef unsigned char UINT8;
  159565. #else /* not HAVE_UNSIGNED_CHAR */
  159566. #ifdef CHAR_IS_UNSIGNED
  159567. typedef char UINT8;
  159568. #else /* not CHAR_IS_UNSIGNED */
  159569. typedef short UINT8;
  159570. #endif /* CHAR_IS_UNSIGNED */
  159571. #endif /* HAVE_UNSIGNED_CHAR */
  159572. /* UINT16 must hold at least the values 0..65535. */
  159573. #ifdef HAVE_UNSIGNED_SHORT
  159574. typedef unsigned short UINT16;
  159575. #else /* not HAVE_UNSIGNED_SHORT */
  159576. typedef unsigned int UINT16;
  159577. #endif /* HAVE_UNSIGNED_SHORT */
  159578. /* INT16 must hold at least the values -32768..32767. */
  159579. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159580. typedef short INT16;
  159581. #endif
  159582. /* INT32 must hold at least signed 32-bit values. */
  159583. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159584. typedef long INT32;
  159585. #endif
  159586. /* Datatype used for image dimensions. The JPEG standard only supports
  159587. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159588. * "unsigned int" is sufficient on all machines. However, if you need to
  159589. * handle larger images and you don't mind deviating from the spec, you
  159590. * can change this datatype.
  159591. */
  159592. typedef unsigned int JDIMENSION;
  159593. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159594. /* These macros are used in all function definitions and extern declarations.
  159595. * You could modify them if you need to change function linkage conventions;
  159596. * in particular, you'll need to do that to make the library a Windows DLL.
  159597. * Another application is to make all functions global for use with debuggers
  159598. * or code profilers that require it.
  159599. */
  159600. /* a function called through method pointers: */
  159601. #define METHODDEF(type) static type
  159602. /* a function used only in its module: */
  159603. #define LOCAL(type) static type
  159604. /* a function referenced thru EXTERNs: */
  159605. #define GLOBAL(type) type
  159606. /* a reference to a GLOBAL function: */
  159607. #define EXTERN(type) extern type
  159608. /* This macro is used to declare a "method", that is, a function pointer.
  159609. * We want to supply prototype parameters if the compiler can cope.
  159610. * Note that the arglist parameter must be parenthesized!
  159611. * Again, you can customize this if you need special linkage keywords.
  159612. */
  159613. #ifdef HAVE_PROTOTYPES
  159614. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159615. #else
  159616. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159617. #endif
  159618. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159619. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159620. * by just saying "FAR *" where such a pointer is needed. In a few places
  159621. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159622. */
  159623. #ifdef NEED_FAR_POINTERS
  159624. #define FAR far
  159625. #else
  159626. #define FAR
  159627. #endif
  159628. /*
  159629. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159630. * in standard header files. Or you may have conflicts with application-
  159631. * specific header files that you want to include together with these files.
  159632. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159633. */
  159634. #ifndef HAVE_BOOLEAN
  159635. typedef int boolean;
  159636. #endif
  159637. #ifndef FALSE /* in case these macros already exist */
  159638. #define FALSE 0 /* values of boolean */
  159639. #endif
  159640. #ifndef TRUE
  159641. #define TRUE 1
  159642. #endif
  159643. /*
  159644. * The remaining options affect code selection within the JPEG library,
  159645. * but they don't need to be visible to most applications using the library.
  159646. * To minimize application namespace pollution, the symbols won't be
  159647. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159648. */
  159649. #ifdef JPEG_INTERNALS
  159650. #define JPEG_INTERNAL_OPTIONS
  159651. #endif
  159652. #ifdef JPEG_INTERNAL_OPTIONS
  159653. /*
  159654. * These defines indicate whether to include various optional functions.
  159655. * Undefining some of these symbols will produce a smaller but less capable
  159656. * library. Note that you can leave certain source files out of the
  159657. * compilation/linking process if you've #undef'd the corresponding symbols.
  159658. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159659. */
  159660. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159661. /* Capability options common to encoder and decoder: */
  159662. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159663. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159664. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159665. /* Encoder capability options: */
  159666. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159667. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159668. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159669. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159670. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159671. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159672. * precision, so jchuff.c normally uses entropy optimization to compute
  159673. * usable tables for higher precision. If you don't want to do optimization,
  159674. * you'll have to supply different default Huffman tables.
  159675. * The exact same statements apply for progressive JPEG: the default tables
  159676. * don't work for progressive mode. (This may get fixed, however.)
  159677. */
  159678. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159679. /* Decoder capability options: */
  159680. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159681. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159682. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159683. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159684. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159685. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159686. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159687. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159688. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159689. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159690. /* more capability options later, no doubt */
  159691. /*
  159692. * Ordering of RGB data in scanlines passed to or from the application.
  159693. * If your application wants to deal with data in the order B,G,R, just
  159694. * change these macros. You can also deal with formats such as R,G,B,X
  159695. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159696. * the offsets will also change the order in which colormap data is organized.
  159697. * RESTRICTIONS:
  159698. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159699. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159700. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159701. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159702. * is not 3 (they don't understand about dummy color components!). So you
  159703. * can't use color quantization if you change that value.
  159704. */
  159705. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159706. #define RGB_GREEN 1 /* Offset of Green */
  159707. #define RGB_BLUE 2 /* Offset of Blue */
  159708. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159709. /* Definitions for speed-related optimizations. */
  159710. /* If your compiler supports inline functions, define INLINE
  159711. * as the inline keyword; otherwise define it as empty.
  159712. */
  159713. #ifndef INLINE
  159714. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159715. #define INLINE __inline__
  159716. #endif
  159717. #ifndef INLINE
  159718. #define INLINE /* default is to define it as empty */
  159719. #endif
  159720. #endif
  159721. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159722. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159723. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159724. */
  159725. #ifndef MULTIPLIER
  159726. #define MULTIPLIER int /* type for fastest integer multiply */
  159727. #endif
  159728. /* FAST_FLOAT should be either float or double, whichever is done faster
  159729. * by your compiler. (Note that this type is only used in the floating point
  159730. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159731. * Typically, float is faster in ANSI C compilers, while double is faster in
  159732. * pre-ANSI compilers (because they insist on converting to double anyway).
  159733. * The code below therefore chooses float if we have ANSI-style prototypes.
  159734. */
  159735. #ifndef FAST_FLOAT
  159736. #ifdef HAVE_PROTOTYPES
  159737. #define FAST_FLOAT float
  159738. #else
  159739. #define FAST_FLOAT double
  159740. #endif
  159741. #endif
  159742. #endif /* JPEG_INTERNAL_OPTIONS */
  159743. /*** End of inlined file: jmorecfg.h ***/
  159744. /* seldom changed options */
  159745. /* Version ID for the JPEG library.
  159746. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159747. */
  159748. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159749. /* Various constants determining the sizes of things.
  159750. * All of these are specified by the JPEG standard, so don't change them
  159751. * if you want to be compatible.
  159752. */
  159753. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159754. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159755. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159756. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159757. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159758. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159759. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159760. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159761. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159762. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159763. * to handle it. We even let you do this from the jconfig.h file. However,
  159764. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159765. * sometimes emits noncompliant files doesn't mean you should too.
  159766. */
  159767. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159768. #ifndef D_MAX_BLOCKS_IN_MCU
  159769. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159770. #endif
  159771. /* Data structures for images (arrays of samples and of DCT coefficients).
  159772. * On 80x86 machines, the image arrays are too big for near pointers,
  159773. * but the pointer arrays can fit in near memory.
  159774. */
  159775. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159776. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159777. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159778. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159779. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159780. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159781. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159782. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159783. /* Types for JPEG compression parameters and working tables. */
  159784. /* DCT coefficient quantization tables. */
  159785. typedef struct {
  159786. /* This array gives the coefficient quantizers in natural array order
  159787. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159788. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159789. */
  159790. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159791. /* This field is used only during compression. It's initialized FALSE when
  159792. * the table is created, and set TRUE when it's been output to the file.
  159793. * You could suppress output of a table by setting this to TRUE.
  159794. * (See jpeg_suppress_tables for an example.)
  159795. */
  159796. boolean sent_table; /* TRUE when table has been output */
  159797. } JQUANT_TBL;
  159798. /* Huffman coding tables. */
  159799. typedef struct {
  159800. /* These two fields directly represent the contents of a JPEG DHT marker */
  159801. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159802. /* length k bits; bits[0] is unused */
  159803. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159804. /* This field is used only during compression. It's initialized FALSE when
  159805. * the table is created, and set TRUE when it's been output to the file.
  159806. * You could suppress output of a table by setting this to TRUE.
  159807. * (See jpeg_suppress_tables for an example.)
  159808. */
  159809. boolean sent_table; /* TRUE when table has been output */
  159810. } JHUFF_TBL;
  159811. /* Basic info about one component (color channel). */
  159812. typedef struct {
  159813. /* These values are fixed over the whole image. */
  159814. /* For compression, they must be supplied by parameter setup; */
  159815. /* for decompression, they are read from the SOF marker. */
  159816. int component_id; /* identifier for this component (0..255) */
  159817. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159818. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159819. int v_samp_factor; /* vertical sampling factor (1..4) */
  159820. int quant_tbl_no; /* quantization table selector (0..3) */
  159821. /* These values may vary between scans. */
  159822. /* For compression, they must be supplied by parameter setup; */
  159823. /* for decompression, they are read from the SOS marker. */
  159824. /* The decompressor output side may not use these variables. */
  159825. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159826. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159827. /* Remaining fields should be treated as private by applications. */
  159828. /* These values are computed during compression or decompression startup: */
  159829. /* Component's size in DCT blocks.
  159830. * Any dummy blocks added to complete an MCU are not counted; therefore
  159831. * these values do not depend on whether a scan is interleaved or not.
  159832. */
  159833. JDIMENSION width_in_blocks;
  159834. JDIMENSION height_in_blocks;
  159835. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159836. * For decompression this is the size of the output from one DCT block,
  159837. * reflecting any scaling we choose to apply during the IDCT step.
  159838. * Values of 1,2,4,8 are likely to be supported. Note that different
  159839. * components may receive different IDCT scalings.
  159840. */
  159841. int DCT_scaled_size;
  159842. /* The downsampled dimensions are the component's actual, unpadded number
  159843. * of samples at the main buffer (preprocessing/compression interface), thus
  159844. * downsampled_width = ceil(image_width * Hi/Hmax)
  159845. * and similarly for height. For decompression, IDCT scaling is included, so
  159846. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159847. */
  159848. JDIMENSION downsampled_width; /* actual width in samples */
  159849. JDIMENSION downsampled_height; /* actual height in samples */
  159850. /* This flag is used only for decompression. In cases where some of the
  159851. * components will be ignored (eg grayscale output from YCbCr image),
  159852. * we can skip most computations for the unused components.
  159853. */
  159854. boolean component_needed; /* do we need the value of this component? */
  159855. /* These values are computed before starting a scan of the component. */
  159856. /* The decompressor output side may not use these variables. */
  159857. int MCU_width; /* number of blocks per MCU, horizontally */
  159858. int MCU_height; /* number of blocks per MCU, vertically */
  159859. int MCU_blocks; /* MCU_width * MCU_height */
  159860. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159861. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159862. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159863. /* Saved quantization table for component; NULL if none yet saved.
  159864. * See jdinput.c comments about the need for this information.
  159865. * This field is currently used only for decompression.
  159866. */
  159867. JQUANT_TBL * quant_table;
  159868. /* Private per-component storage for DCT or IDCT subsystem. */
  159869. void * dct_table;
  159870. } jpeg_component_info;
  159871. /* The script for encoding a multiple-scan file is an array of these: */
  159872. typedef struct {
  159873. int comps_in_scan; /* number of components encoded in this scan */
  159874. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159875. int Ss, Se; /* progressive JPEG spectral selection parms */
  159876. int Ah, Al; /* progressive JPEG successive approx. parms */
  159877. } jpeg_scan_info;
  159878. /* The decompressor can save APPn and COM markers in a list of these: */
  159879. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159880. struct jpeg_marker_struct {
  159881. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159882. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159883. unsigned int original_length; /* # bytes of data in the file */
  159884. unsigned int data_length; /* # bytes of data saved at data[] */
  159885. JOCTET FAR * data; /* the data contained in the marker */
  159886. /* the marker length word is not counted in data_length or original_length */
  159887. };
  159888. /* Known color spaces. */
  159889. typedef enum {
  159890. JCS_UNKNOWN, /* error/unspecified */
  159891. JCS_GRAYSCALE, /* monochrome */
  159892. JCS_RGB, /* red/green/blue */
  159893. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159894. JCS_CMYK, /* C/M/Y/K */
  159895. JCS_YCCK /* Y/Cb/Cr/K */
  159896. } J_COLOR_SPACE;
  159897. /* DCT/IDCT algorithm options. */
  159898. typedef enum {
  159899. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159900. JDCT_IFAST, /* faster, less accurate integer method */
  159901. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159902. } J_DCT_METHOD;
  159903. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159904. #define JDCT_DEFAULT JDCT_ISLOW
  159905. #endif
  159906. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159907. #define JDCT_FASTEST JDCT_IFAST
  159908. #endif
  159909. /* Dithering options for decompression. */
  159910. typedef enum {
  159911. JDITHER_NONE, /* no dithering */
  159912. JDITHER_ORDERED, /* simple ordered dither */
  159913. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159914. } J_DITHER_MODE;
  159915. /* Common fields between JPEG compression and decompression master structs. */
  159916. #define jpeg_common_fields \
  159917. struct jpeg_error_mgr * err; /* Error handler module */\
  159918. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159919. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159920. void * client_data; /* Available for use by application */\
  159921. boolean is_decompressor; /* So common code can tell which is which */\
  159922. int global_state /* For checking call sequence validity */
  159923. /* Routines that are to be used by both halves of the library are declared
  159924. * to receive a pointer to this structure. There are no actual instances of
  159925. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159926. */
  159927. struct jpeg_common_struct {
  159928. jpeg_common_fields; /* Fields common to both master struct types */
  159929. /* Additional fields follow in an actual jpeg_compress_struct or
  159930. * jpeg_decompress_struct. All three structs must agree on these
  159931. * initial fields! (This would be a lot cleaner in C++.)
  159932. */
  159933. };
  159934. typedef struct jpeg_common_struct * j_common_ptr;
  159935. typedef struct jpeg_compress_struct * j_compress_ptr;
  159936. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159937. /* Master record for a compression instance */
  159938. struct jpeg_compress_struct {
  159939. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159940. /* Destination for compressed data */
  159941. struct jpeg_destination_mgr * dest;
  159942. /* Description of source image --- these fields must be filled in by
  159943. * outer application before starting compression. in_color_space must
  159944. * be correct before you can even call jpeg_set_defaults().
  159945. */
  159946. JDIMENSION image_width; /* input image width */
  159947. JDIMENSION image_height; /* input image height */
  159948. int input_components; /* # of color components in input image */
  159949. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159950. double input_gamma; /* image gamma of input image */
  159951. /* Compression parameters --- these fields must be set before calling
  159952. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159953. * initialize everything to reasonable defaults, then changing anything
  159954. * the application specifically wants to change. That way you won't get
  159955. * burnt when new parameters are added. Also note that there are several
  159956. * helper routines to simplify changing parameters.
  159957. */
  159958. int data_precision; /* bits of precision in image data */
  159959. int num_components; /* # of color components in JPEG image */
  159960. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159961. jpeg_component_info * comp_info;
  159962. /* comp_info[i] describes component that appears i'th in SOF */
  159963. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159964. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159965. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159966. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159967. /* ptrs to Huffman coding tables, or NULL if not defined */
  159968. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159969. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159970. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159971. int num_scans; /* # of entries in scan_info array */
  159972. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159973. /* The default value of scan_info is NULL, which causes a single-scan
  159974. * sequential JPEG file to be emitted. To create a multi-scan file,
  159975. * set num_scans and scan_info to point to an array of scan definitions.
  159976. */
  159977. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159978. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159979. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159980. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159981. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159982. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159983. /* The restart interval can be specified in absolute MCUs by setting
  159984. * restart_interval, or in MCU rows by setting restart_in_rows
  159985. * (in which case the correct restart_interval will be figured
  159986. * for each scan).
  159987. */
  159988. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159989. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159990. /* Parameters controlling emission of special markers. */
  159991. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159992. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159993. UINT8 JFIF_minor_version;
  159994. /* These three values are not used by the JPEG code, merely copied */
  159995. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159996. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159997. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159998. UINT8 density_unit; /* JFIF code for pixel size units */
  159999. UINT16 X_density; /* Horizontal pixel density */
  160000. UINT16 Y_density; /* Vertical pixel density */
  160001. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160002. /* State variable: index of next scanline to be written to
  160003. * jpeg_write_scanlines(). Application may use this to control its
  160004. * processing loop, e.g., "while (next_scanline < image_height)".
  160005. */
  160006. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160007. /* Remaining fields are known throughout compressor, but generally
  160008. * should not be touched by a surrounding application.
  160009. */
  160010. /*
  160011. * These fields are computed during compression startup
  160012. */
  160013. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160014. int max_h_samp_factor; /* largest h_samp_factor */
  160015. int max_v_samp_factor; /* largest v_samp_factor */
  160016. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160017. /* The coefficient controller receives data in units of MCU rows as defined
  160018. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160019. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160020. * "iMCU" (interleaved MCU) row.
  160021. */
  160022. /*
  160023. * These fields are valid during any one scan.
  160024. * They describe the components and MCUs actually appearing in the scan.
  160025. */
  160026. int comps_in_scan; /* # of JPEG components in this scan */
  160027. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160028. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160029. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160030. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160031. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160032. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160033. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160034. /* i'th block in an MCU */
  160035. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160036. /*
  160037. * Links to compression subobjects (methods and private variables of modules)
  160038. */
  160039. struct jpeg_comp_master * master;
  160040. struct jpeg_c_main_controller * main;
  160041. struct jpeg_c_prep_controller * prep;
  160042. struct jpeg_c_coef_controller * coef;
  160043. struct jpeg_marker_writer * marker;
  160044. struct jpeg_color_converter * cconvert;
  160045. struct jpeg_downsampler * downsample;
  160046. struct jpeg_forward_dct * fdct;
  160047. struct jpeg_entropy_encoder * entropy;
  160048. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160049. int script_space_size;
  160050. };
  160051. /* Master record for a decompression instance */
  160052. struct jpeg_decompress_struct {
  160053. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160054. /* Source of compressed data */
  160055. struct jpeg_source_mgr * src;
  160056. /* Basic description of image --- filled in by jpeg_read_header(). */
  160057. /* Application may inspect these values to decide how to process image. */
  160058. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160059. JDIMENSION image_height; /* nominal image height */
  160060. int num_components; /* # of color components in JPEG image */
  160061. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160062. /* Decompression processing parameters --- these fields must be set before
  160063. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160064. * them to default values.
  160065. */
  160066. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160067. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160068. double output_gamma; /* image gamma wanted in output */
  160069. boolean buffered_image; /* TRUE=multiple output passes */
  160070. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160071. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160072. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160073. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160074. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160075. /* the following are ignored if not quantize_colors: */
  160076. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160077. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160078. int desired_number_of_colors; /* max # colors to use in created colormap */
  160079. /* these are significant only in buffered-image mode: */
  160080. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160081. boolean enable_external_quant;/* enable future use of external colormap */
  160082. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160083. /* Description of actual output image that will be returned to application.
  160084. * These fields are computed by jpeg_start_decompress().
  160085. * You can also use jpeg_calc_output_dimensions() to determine these values
  160086. * in advance of calling jpeg_start_decompress().
  160087. */
  160088. JDIMENSION output_width; /* scaled image width */
  160089. JDIMENSION output_height; /* scaled image height */
  160090. int out_color_components; /* # of color components in out_color_space */
  160091. int output_components; /* # of color components returned */
  160092. /* output_components is 1 (a colormap index) when quantizing colors;
  160093. * otherwise it equals out_color_components.
  160094. */
  160095. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160096. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160097. * high, space and time will be wasted due to unnecessary data copying.
  160098. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160099. */
  160100. /* When quantizing colors, the output colormap is described by these fields.
  160101. * The application can supply a colormap by setting colormap non-NULL before
  160102. * calling jpeg_start_decompress; otherwise a colormap is created during
  160103. * jpeg_start_decompress or jpeg_start_output.
  160104. * The map has out_color_components rows and actual_number_of_colors columns.
  160105. */
  160106. int actual_number_of_colors; /* number of entries in use */
  160107. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160108. /* State variables: these variables indicate the progress of decompression.
  160109. * The application may examine these but must not modify them.
  160110. */
  160111. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160112. * Application may use this to control its processing loop, e.g.,
  160113. * "while (output_scanline < output_height)".
  160114. */
  160115. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160116. /* Current input scan number and number of iMCU rows completed in scan.
  160117. * These indicate the progress of the decompressor input side.
  160118. */
  160119. int input_scan_number; /* Number of SOS markers seen so far */
  160120. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160121. /* The "output scan number" is the notional scan being displayed by the
  160122. * output side. The decompressor will not allow output scan/row number
  160123. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160124. */
  160125. int output_scan_number; /* Nominal scan number being displayed */
  160126. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160127. /* Current progression status. coef_bits[c][i] indicates the precision
  160128. * with which component c's DCT coefficient i (in zigzag order) is known.
  160129. * It is -1 when no data has yet been received, otherwise it is the point
  160130. * transform (shift) value for the most recent scan of the coefficient
  160131. * (thus, 0 at completion of the progression).
  160132. * This pointer is NULL when reading a non-progressive file.
  160133. */
  160134. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160135. /* Internal JPEG parameters --- the application usually need not look at
  160136. * these fields. Note that the decompressor output side may not use
  160137. * any parameters that can change between scans.
  160138. */
  160139. /* Quantization and Huffman tables are carried forward across input
  160140. * datastreams when processing abbreviated JPEG datastreams.
  160141. */
  160142. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160143. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160144. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160145. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160146. /* ptrs to Huffman coding tables, or NULL if not defined */
  160147. /* These parameters are never carried across datastreams, since they
  160148. * are given in SOF/SOS markers or defined to be reset by SOI.
  160149. */
  160150. int data_precision; /* bits of precision in image data */
  160151. jpeg_component_info * comp_info;
  160152. /* comp_info[i] describes component that appears i'th in SOF */
  160153. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160154. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160155. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160156. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160157. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160158. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160159. /* These fields record data obtained from optional markers recognized by
  160160. * the JPEG library.
  160161. */
  160162. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160163. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160164. UINT8 JFIF_major_version; /* JFIF version number */
  160165. UINT8 JFIF_minor_version;
  160166. UINT8 density_unit; /* JFIF code for pixel size units */
  160167. UINT16 X_density; /* Horizontal pixel density */
  160168. UINT16 Y_density; /* Vertical pixel density */
  160169. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160170. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160171. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160172. /* Aside from the specific data retained from APPn markers known to the
  160173. * library, the uninterpreted contents of any or all APPn and COM markers
  160174. * can be saved in a list for examination by the application.
  160175. */
  160176. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160177. /* Remaining fields are known throughout decompressor, but generally
  160178. * should not be touched by a surrounding application.
  160179. */
  160180. /*
  160181. * These fields are computed during decompression startup
  160182. */
  160183. int max_h_samp_factor; /* largest h_samp_factor */
  160184. int max_v_samp_factor; /* largest v_samp_factor */
  160185. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160186. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160187. /* The coefficient controller's input and output progress is measured in
  160188. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160189. * in fully interleaved JPEG scans, but are used whether the scan is
  160190. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160191. * rows of each component. Therefore, the IDCT output contains
  160192. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160193. */
  160194. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160195. /*
  160196. * These fields are valid during any one scan.
  160197. * They describe the components and MCUs actually appearing in the scan.
  160198. * Note that the decompressor output side must not use these fields.
  160199. */
  160200. int comps_in_scan; /* # of JPEG components in this scan */
  160201. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160202. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160203. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160204. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160205. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160206. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160207. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160208. /* i'th block in an MCU */
  160209. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160210. /* This field is shared between entropy decoder and marker parser.
  160211. * It is either zero or the code of a JPEG marker that has been
  160212. * read from the data source, but has not yet been processed.
  160213. */
  160214. int unread_marker;
  160215. /*
  160216. * Links to decompression subobjects (methods, private variables of modules)
  160217. */
  160218. struct jpeg_decomp_master * master;
  160219. struct jpeg_d_main_controller * main;
  160220. struct jpeg_d_coef_controller * coef;
  160221. struct jpeg_d_post_controller * post;
  160222. struct jpeg_input_controller * inputctl;
  160223. struct jpeg_marker_reader * marker;
  160224. struct jpeg_entropy_decoder * entropy;
  160225. struct jpeg_inverse_dct * idct;
  160226. struct jpeg_upsampler * upsample;
  160227. struct jpeg_color_deconverter * cconvert;
  160228. struct jpeg_color_quantizer * cquantize;
  160229. };
  160230. /* "Object" declarations for JPEG modules that may be supplied or called
  160231. * directly by the surrounding application.
  160232. * As with all objects in the JPEG library, these structs only define the
  160233. * publicly visible methods and state variables of a module. Additional
  160234. * private fields may exist after the public ones.
  160235. */
  160236. /* Error handler object */
  160237. struct jpeg_error_mgr {
  160238. /* Error exit handler: does not return to caller */
  160239. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160240. /* Conditionally emit a trace or warning message */
  160241. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160242. /* Routine that actually outputs a trace or error message */
  160243. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160244. /* Format a message string for the most recent JPEG error or message */
  160245. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160246. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160247. /* Reset error state variables at start of a new image */
  160248. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160249. /* The message ID code and any parameters are saved here.
  160250. * A message can have one string parameter or up to 8 int parameters.
  160251. */
  160252. int msg_code;
  160253. #define JMSG_STR_PARM_MAX 80
  160254. union {
  160255. int i[8];
  160256. char s[JMSG_STR_PARM_MAX];
  160257. } msg_parm;
  160258. /* Standard state variables for error facility */
  160259. int trace_level; /* max msg_level that will be displayed */
  160260. /* For recoverable corrupt-data errors, we emit a warning message,
  160261. * but keep going unless emit_message chooses to abort. emit_message
  160262. * should count warnings in num_warnings. The surrounding application
  160263. * can check for bad data by seeing if num_warnings is nonzero at the
  160264. * end of processing.
  160265. */
  160266. long num_warnings; /* number of corrupt-data warnings */
  160267. /* These fields point to the table(s) of error message strings.
  160268. * An application can change the table pointer to switch to a different
  160269. * message list (typically, to change the language in which errors are
  160270. * reported). Some applications may wish to add additional error codes
  160271. * that will be handled by the JPEG library error mechanism; the second
  160272. * table pointer is used for this purpose.
  160273. *
  160274. * First table includes all errors generated by JPEG library itself.
  160275. * Error code 0 is reserved for a "no such error string" message.
  160276. */
  160277. const char * const * jpeg_message_table; /* Library errors */
  160278. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160279. /* Second table can be added by application (see cjpeg/djpeg for example).
  160280. * It contains strings numbered first_addon_message..last_addon_message.
  160281. */
  160282. const char * const * addon_message_table; /* Non-library errors */
  160283. int first_addon_message; /* code for first string in addon table */
  160284. int last_addon_message; /* code for last string in addon table */
  160285. };
  160286. /* Progress monitor object */
  160287. struct jpeg_progress_mgr {
  160288. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160289. long pass_counter; /* work units completed in this pass */
  160290. long pass_limit; /* total number of work units in this pass */
  160291. int completed_passes; /* passes completed so far */
  160292. int total_passes; /* total number of passes expected */
  160293. };
  160294. /* Data destination object for compression */
  160295. struct jpeg_destination_mgr {
  160296. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160297. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160298. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160299. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160300. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160301. };
  160302. /* Data source object for decompression */
  160303. struct jpeg_source_mgr {
  160304. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160305. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160306. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160307. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160308. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160309. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160310. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160311. };
  160312. /* Memory manager object.
  160313. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160314. * and "really big" objects (virtual arrays with backing store if needed).
  160315. * The memory manager does not allow individual objects to be freed; rather,
  160316. * each created object is assigned to a pool, and whole pools can be freed
  160317. * at once. This is faster and more convenient than remembering exactly what
  160318. * to free, especially where malloc()/free() are not too speedy.
  160319. * NB: alloc routines never return NULL. They exit to error_exit if not
  160320. * successful.
  160321. */
  160322. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160323. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160324. #define JPOOL_NUMPOOLS 2
  160325. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160326. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160327. struct jpeg_memory_mgr {
  160328. /* Method pointers */
  160329. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160330. size_t sizeofobject));
  160331. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160332. size_t sizeofobject));
  160333. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160334. JDIMENSION samplesperrow,
  160335. JDIMENSION numrows));
  160336. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160337. JDIMENSION blocksperrow,
  160338. JDIMENSION numrows));
  160339. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160340. int pool_id,
  160341. boolean pre_zero,
  160342. JDIMENSION samplesperrow,
  160343. JDIMENSION numrows,
  160344. JDIMENSION maxaccess));
  160345. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160346. int pool_id,
  160347. boolean pre_zero,
  160348. JDIMENSION blocksperrow,
  160349. JDIMENSION numrows,
  160350. JDIMENSION maxaccess));
  160351. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160352. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160353. jvirt_sarray_ptr ptr,
  160354. JDIMENSION start_row,
  160355. JDIMENSION num_rows,
  160356. boolean writable));
  160357. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160358. jvirt_barray_ptr ptr,
  160359. JDIMENSION start_row,
  160360. JDIMENSION num_rows,
  160361. boolean writable));
  160362. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160363. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160364. /* Limit on memory allocation for this JPEG object. (Note that this is
  160365. * merely advisory, not a guaranteed maximum; it only affects the space
  160366. * used for virtual-array buffers.) May be changed by outer application
  160367. * after creating the JPEG object.
  160368. */
  160369. long max_memory_to_use;
  160370. /* Maximum allocation request accepted by alloc_large. */
  160371. long max_alloc_chunk;
  160372. };
  160373. /* Routine signature for application-supplied marker processing methods.
  160374. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160375. */
  160376. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160377. /* Declarations for routines called by application.
  160378. * The JPP macro hides prototype parameters from compilers that can't cope.
  160379. * Note JPP requires double parentheses.
  160380. */
  160381. #ifdef HAVE_PROTOTYPES
  160382. #define JPP(arglist) arglist
  160383. #else
  160384. #define JPP(arglist) ()
  160385. #endif
  160386. /* Short forms of external names for systems with brain-damaged linkers.
  160387. * We shorten external names to be unique in the first six letters, which
  160388. * is good enough for all known systems.
  160389. * (If your compiler itself needs names to be unique in less than 15
  160390. * characters, you are out of luck. Get a better compiler.)
  160391. */
  160392. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160393. #define jpeg_std_error jStdError
  160394. #define jpeg_CreateCompress jCreaCompress
  160395. #define jpeg_CreateDecompress jCreaDecompress
  160396. #define jpeg_destroy_compress jDestCompress
  160397. #define jpeg_destroy_decompress jDestDecompress
  160398. #define jpeg_stdio_dest jStdDest
  160399. #define jpeg_stdio_src jStdSrc
  160400. #define jpeg_set_defaults jSetDefaults
  160401. #define jpeg_set_colorspace jSetColorspace
  160402. #define jpeg_default_colorspace jDefColorspace
  160403. #define jpeg_set_quality jSetQuality
  160404. #define jpeg_set_linear_quality jSetLQuality
  160405. #define jpeg_add_quant_table jAddQuantTable
  160406. #define jpeg_quality_scaling jQualityScaling
  160407. #define jpeg_simple_progression jSimProgress
  160408. #define jpeg_suppress_tables jSuppressTables
  160409. #define jpeg_alloc_quant_table jAlcQTable
  160410. #define jpeg_alloc_huff_table jAlcHTable
  160411. #define jpeg_start_compress jStrtCompress
  160412. #define jpeg_write_scanlines jWrtScanlines
  160413. #define jpeg_finish_compress jFinCompress
  160414. #define jpeg_write_raw_data jWrtRawData
  160415. #define jpeg_write_marker jWrtMarker
  160416. #define jpeg_write_m_header jWrtMHeader
  160417. #define jpeg_write_m_byte jWrtMByte
  160418. #define jpeg_write_tables jWrtTables
  160419. #define jpeg_read_header jReadHeader
  160420. #define jpeg_start_decompress jStrtDecompress
  160421. #define jpeg_read_scanlines jReadScanlines
  160422. #define jpeg_finish_decompress jFinDecompress
  160423. #define jpeg_read_raw_data jReadRawData
  160424. #define jpeg_has_multiple_scans jHasMultScn
  160425. #define jpeg_start_output jStrtOutput
  160426. #define jpeg_finish_output jFinOutput
  160427. #define jpeg_input_complete jInComplete
  160428. #define jpeg_new_colormap jNewCMap
  160429. #define jpeg_consume_input jConsumeInput
  160430. #define jpeg_calc_output_dimensions jCalcDimensions
  160431. #define jpeg_save_markers jSaveMarkers
  160432. #define jpeg_set_marker_processor jSetMarker
  160433. #define jpeg_read_coefficients jReadCoefs
  160434. #define jpeg_write_coefficients jWrtCoefs
  160435. #define jpeg_copy_critical_parameters jCopyCrit
  160436. #define jpeg_abort_compress jAbrtCompress
  160437. #define jpeg_abort_decompress jAbrtDecompress
  160438. #define jpeg_abort jAbort
  160439. #define jpeg_destroy jDestroy
  160440. #define jpeg_resync_to_restart jResyncRestart
  160441. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160442. /* Default error-management setup */
  160443. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160444. JPP((struct jpeg_error_mgr * err));
  160445. /* Initialization of JPEG compression objects.
  160446. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160447. * names that applications should call. These expand to calls on
  160448. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160449. * passed for version mismatch checking.
  160450. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160451. */
  160452. #define jpeg_create_compress(cinfo) \
  160453. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160454. (size_t) sizeof(struct jpeg_compress_struct))
  160455. #define jpeg_create_decompress(cinfo) \
  160456. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160457. (size_t) sizeof(struct jpeg_decompress_struct))
  160458. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160459. int version, size_t structsize));
  160460. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160461. int version, size_t structsize));
  160462. /* Destruction of JPEG compression objects */
  160463. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160464. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160465. /* Standard data source and destination managers: stdio streams. */
  160466. /* Caller is responsible for opening the file before and closing after. */
  160467. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160468. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160469. /* Default parameter setup for compression */
  160470. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160471. /* Compression parameter setup aids */
  160472. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160473. J_COLOR_SPACE colorspace));
  160474. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160475. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160476. boolean force_baseline));
  160477. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160478. int scale_factor,
  160479. boolean force_baseline));
  160480. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160481. const unsigned int *basic_table,
  160482. int scale_factor,
  160483. boolean force_baseline));
  160484. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160485. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160486. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160487. boolean suppress));
  160488. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160489. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160490. /* Main entry points for compression */
  160491. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160492. boolean write_all_tables));
  160493. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160494. JSAMPARRAY scanlines,
  160495. JDIMENSION num_lines));
  160496. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160497. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160498. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160499. JSAMPIMAGE data,
  160500. JDIMENSION num_lines));
  160501. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160502. EXTERN(void) jpeg_write_marker
  160503. JPP((j_compress_ptr cinfo, int marker,
  160504. const JOCTET * dataptr, unsigned int datalen));
  160505. /* Same, but piecemeal. */
  160506. EXTERN(void) jpeg_write_m_header
  160507. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160508. EXTERN(void) jpeg_write_m_byte
  160509. JPP((j_compress_ptr cinfo, int val));
  160510. /* Alternate compression function: just write an abbreviated table file */
  160511. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160512. /* Decompression startup: read start of JPEG datastream to see what's there */
  160513. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160514. boolean require_image));
  160515. /* Return value is one of: */
  160516. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160517. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160518. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160519. /* If you pass require_image = TRUE (normal case), you need not check for
  160520. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160521. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160522. * give a suspension return (the stdio source module doesn't).
  160523. */
  160524. /* Main entry points for decompression */
  160525. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160526. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160527. JSAMPARRAY scanlines,
  160528. JDIMENSION max_lines));
  160529. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160530. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160531. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160532. JSAMPIMAGE data,
  160533. JDIMENSION max_lines));
  160534. /* Additional entry points for buffered-image mode. */
  160535. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160536. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160537. int scan_number));
  160538. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160539. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160540. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160541. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160542. /* Return value is one of: */
  160543. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160544. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160545. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160546. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160547. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160548. /* Precalculate output dimensions for current decompression parameters. */
  160549. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160550. /* Control saving of COM and APPn markers into marker_list. */
  160551. EXTERN(void) jpeg_save_markers
  160552. JPP((j_decompress_ptr cinfo, int marker_code,
  160553. unsigned int length_limit));
  160554. /* Install a special processing method for COM or APPn markers. */
  160555. EXTERN(void) jpeg_set_marker_processor
  160556. JPP((j_decompress_ptr cinfo, int marker_code,
  160557. jpeg_marker_parser_method routine));
  160558. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160559. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160560. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160561. jvirt_barray_ptr * coef_arrays));
  160562. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160563. j_compress_ptr dstinfo));
  160564. /* If you choose to abort compression or decompression before completing
  160565. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160566. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160567. * if you're done with the JPEG object, but if you want to clean it up and
  160568. * reuse it, call this:
  160569. */
  160570. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160571. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160572. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160573. * flavor of JPEG object. These may be more convenient in some places.
  160574. */
  160575. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160576. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160577. /* Default restart-marker-resync procedure for use by data source modules */
  160578. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160579. int desired));
  160580. /* These marker codes are exported since applications and data source modules
  160581. * are likely to want to use them.
  160582. */
  160583. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160584. #define JPEG_EOI 0xD9 /* EOI marker code */
  160585. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160586. #define JPEG_COM 0xFE /* COM marker code */
  160587. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160588. * for structure definitions that are never filled in, keep it quiet by
  160589. * supplying dummy definitions for the various substructures.
  160590. */
  160591. #ifdef INCOMPLETE_TYPES_BROKEN
  160592. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160593. struct jvirt_sarray_control { long dummy; };
  160594. struct jvirt_barray_control { long dummy; };
  160595. struct jpeg_comp_master { long dummy; };
  160596. struct jpeg_c_main_controller { long dummy; };
  160597. struct jpeg_c_prep_controller { long dummy; };
  160598. struct jpeg_c_coef_controller { long dummy; };
  160599. struct jpeg_marker_writer { long dummy; };
  160600. struct jpeg_color_converter { long dummy; };
  160601. struct jpeg_downsampler { long dummy; };
  160602. struct jpeg_forward_dct { long dummy; };
  160603. struct jpeg_entropy_encoder { long dummy; };
  160604. struct jpeg_decomp_master { long dummy; };
  160605. struct jpeg_d_main_controller { long dummy; };
  160606. struct jpeg_d_coef_controller { long dummy; };
  160607. struct jpeg_d_post_controller { long dummy; };
  160608. struct jpeg_input_controller { long dummy; };
  160609. struct jpeg_marker_reader { long dummy; };
  160610. struct jpeg_entropy_decoder { long dummy; };
  160611. struct jpeg_inverse_dct { long dummy; };
  160612. struct jpeg_upsampler { long dummy; };
  160613. struct jpeg_color_deconverter { long dummy; };
  160614. struct jpeg_color_quantizer { long dummy; };
  160615. #endif /* JPEG_INTERNALS */
  160616. #endif /* INCOMPLETE_TYPES_BROKEN */
  160617. /*
  160618. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160619. * The internal structure declarations are read only when that is true.
  160620. * Applications using the library should not include jpegint.h, but may wish
  160621. * to include jerror.h.
  160622. */
  160623. #ifdef JPEG_INTERNALS
  160624. /*** Start of inlined file: jpegint.h ***/
  160625. /* Declarations for both compression & decompression */
  160626. typedef enum { /* Operating modes for buffer controllers */
  160627. JBUF_PASS_THRU, /* Plain stripwise operation */
  160628. /* Remaining modes require a full-image buffer to have been created */
  160629. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160630. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160631. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160632. } J_BUF_MODE;
  160633. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160634. #define CSTATE_START 100 /* after create_compress */
  160635. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160636. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160637. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160638. #define DSTATE_START 200 /* after create_decompress */
  160639. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160640. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160641. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160642. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160643. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160644. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160645. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160646. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160647. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160648. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160649. /* Declarations for compression modules */
  160650. /* Master control module */
  160651. struct jpeg_comp_master {
  160652. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160653. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160654. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160655. /* State variables made visible to other modules */
  160656. boolean call_pass_startup; /* True if pass_startup must be called */
  160657. boolean is_last_pass; /* True during last pass */
  160658. };
  160659. /* Main buffer control (downsampled-data buffer) */
  160660. struct jpeg_c_main_controller {
  160661. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160662. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160663. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160664. JDIMENSION in_rows_avail));
  160665. };
  160666. /* Compression preprocessing (downsampling input buffer control) */
  160667. struct jpeg_c_prep_controller {
  160668. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160669. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160670. JSAMPARRAY input_buf,
  160671. JDIMENSION *in_row_ctr,
  160672. JDIMENSION in_rows_avail,
  160673. JSAMPIMAGE output_buf,
  160674. JDIMENSION *out_row_group_ctr,
  160675. JDIMENSION out_row_groups_avail));
  160676. };
  160677. /* Coefficient buffer control */
  160678. struct jpeg_c_coef_controller {
  160679. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160680. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160681. JSAMPIMAGE input_buf));
  160682. };
  160683. /* Colorspace conversion */
  160684. struct jpeg_color_converter {
  160685. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160686. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160687. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160688. JDIMENSION output_row, int num_rows));
  160689. };
  160690. /* Downsampling */
  160691. struct jpeg_downsampler {
  160692. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160693. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160694. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160695. JSAMPIMAGE output_buf,
  160696. JDIMENSION out_row_group_index));
  160697. boolean need_context_rows; /* TRUE if need rows above & below */
  160698. };
  160699. /* Forward DCT (also controls coefficient quantization) */
  160700. struct jpeg_forward_dct {
  160701. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160702. /* perhaps this should be an array??? */
  160703. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160704. jpeg_component_info * compptr,
  160705. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160706. JDIMENSION start_row, JDIMENSION start_col,
  160707. JDIMENSION num_blocks));
  160708. };
  160709. /* Entropy encoding */
  160710. struct jpeg_entropy_encoder {
  160711. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160712. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160713. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160714. };
  160715. /* Marker writing */
  160716. struct jpeg_marker_writer {
  160717. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160718. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160719. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160720. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160721. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160722. /* These routines are exported to allow insertion of extra markers */
  160723. /* Probably only COM and APPn markers should be written this way */
  160724. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160725. unsigned int datalen));
  160726. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160727. };
  160728. /* Declarations for decompression modules */
  160729. /* Master control module */
  160730. struct jpeg_decomp_master {
  160731. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160732. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160733. /* State variables made visible to other modules */
  160734. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160735. };
  160736. /* Input control module */
  160737. struct jpeg_input_controller {
  160738. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160739. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160740. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160741. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160742. /* State variables made visible to other modules */
  160743. boolean has_multiple_scans; /* True if file has multiple scans */
  160744. boolean eoi_reached; /* True when EOI has been consumed */
  160745. };
  160746. /* Main buffer control (downsampled-data buffer) */
  160747. struct jpeg_d_main_controller {
  160748. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160749. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160750. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160751. JDIMENSION out_rows_avail));
  160752. };
  160753. /* Coefficient buffer control */
  160754. struct jpeg_d_coef_controller {
  160755. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160756. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160757. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160758. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160759. JSAMPIMAGE output_buf));
  160760. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160761. jvirt_barray_ptr *coef_arrays;
  160762. };
  160763. /* Decompression postprocessing (color quantization buffer control) */
  160764. struct jpeg_d_post_controller {
  160765. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160766. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160767. JSAMPIMAGE input_buf,
  160768. JDIMENSION *in_row_group_ctr,
  160769. JDIMENSION in_row_groups_avail,
  160770. JSAMPARRAY output_buf,
  160771. JDIMENSION *out_row_ctr,
  160772. JDIMENSION out_rows_avail));
  160773. };
  160774. /* Marker reading & parsing */
  160775. struct jpeg_marker_reader {
  160776. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160777. /* Read markers until SOS or EOI.
  160778. * Returns same codes as are defined for jpeg_consume_input:
  160779. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160780. */
  160781. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160782. /* Read a restart marker --- exported for use by entropy decoder only */
  160783. jpeg_marker_parser_method read_restart_marker;
  160784. /* State of marker reader --- nominally internal, but applications
  160785. * supplying COM or APPn handlers might like to know the state.
  160786. */
  160787. boolean saw_SOI; /* found SOI? */
  160788. boolean saw_SOF; /* found SOF? */
  160789. int next_restart_num; /* next restart number expected (0-7) */
  160790. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160791. };
  160792. /* Entropy decoding */
  160793. struct jpeg_entropy_decoder {
  160794. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160795. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160796. JBLOCKROW *MCU_data));
  160797. /* This is here to share code between baseline and progressive decoders; */
  160798. /* other modules probably should not use it */
  160799. boolean insufficient_data; /* set TRUE after emitting warning */
  160800. };
  160801. /* Inverse DCT (also performs dequantization) */
  160802. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160803. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160804. JCOEFPTR coef_block,
  160805. JSAMPARRAY output_buf, JDIMENSION output_col));
  160806. struct jpeg_inverse_dct {
  160807. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160808. /* It is useful to allow each component to have a separate IDCT method. */
  160809. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160810. };
  160811. /* Upsampling (note that upsampler must also call color converter) */
  160812. struct jpeg_upsampler {
  160813. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160814. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160815. JSAMPIMAGE input_buf,
  160816. JDIMENSION *in_row_group_ctr,
  160817. JDIMENSION in_row_groups_avail,
  160818. JSAMPARRAY output_buf,
  160819. JDIMENSION *out_row_ctr,
  160820. JDIMENSION out_rows_avail));
  160821. boolean need_context_rows; /* TRUE if need rows above & below */
  160822. };
  160823. /* Colorspace conversion */
  160824. struct jpeg_color_deconverter {
  160825. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160826. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160827. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160828. JSAMPARRAY output_buf, int num_rows));
  160829. };
  160830. /* Color quantization or color precision reduction */
  160831. struct jpeg_color_quantizer {
  160832. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160833. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160834. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160835. int num_rows));
  160836. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160837. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160838. };
  160839. /* Miscellaneous useful macros */
  160840. #undef MAX
  160841. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160842. #undef MIN
  160843. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160844. /* We assume that right shift corresponds to signed division by 2 with
  160845. * rounding towards minus infinity. This is correct for typical "arithmetic
  160846. * shift" instructions that shift in copies of the sign bit. But some
  160847. * C compilers implement >> with an unsigned shift. For these machines you
  160848. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160849. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160850. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160851. * included in the variables of any routine using RIGHT_SHIFT.
  160852. */
  160853. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160854. #define SHIFT_TEMPS INT32 shift_temp;
  160855. #define RIGHT_SHIFT(x,shft) \
  160856. ((shift_temp = (x)) < 0 ? \
  160857. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160858. (shift_temp >> (shft)))
  160859. #else
  160860. #define SHIFT_TEMPS
  160861. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160862. #endif
  160863. /* Short forms of external names for systems with brain-damaged linkers. */
  160864. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160865. #define jinit_compress_master jICompress
  160866. #define jinit_c_master_control jICMaster
  160867. #define jinit_c_main_controller jICMainC
  160868. #define jinit_c_prep_controller jICPrepC
  160869. #define jinit_c_coef_controller jICCoefC
  160870. #define jinit_color_converter jICColor
  160871. #define jinit_downsampler jIDownsampler
  160872. #define jinit_forward_dct jIFDCT
  160873. #define jinit_huff_encoder jIHEncoder
  160874. #define jinit_phuff_encoder jIPHEncoder
  160875. #define jinit_marker_writer jIMWriter
  160876. #define jinit_master_decompress jIDMaster
  160877. #define jinit_d_main_controller jIDMainC
  160878. #define jinit_d_coef_controller jIDCoefC
  160879. #define jinit_d_post_controller jIDPostC
  160880. #define jinit_input_controller jIInCtlr
  160881. #define jinit_marker_reader jIMReader
  160882. #define jinit_huff_decoder jIHDecoder
  160883. #define jinit_phuff_decoder jIPHDecoder
  160884. #define jinit_inverse_dct jIIDCT
  160885. #define jinit_upsampler jIUpsampler
  160886. #define jinit_color_deconverter jIDColor
  160887. #define jinit_1pass_quantizer jI1Quant
  160888. #define jinit_2pass_quantizer jI2Quant
  160889. #define jinit_merged_upsampler jIMUpsampler
  160890. #define jinit_memory_mgr jIMemMgr
  160891. #define jdiv_round_up jDivRound
  160892. #define jround_up jRound
  160893. #define jcopy_sample_rows jCopySamples
  160894. #define jcopy_block_row jCopyBlocks
  160895. #define jzero_far jZeroFar
  160896. #define jpeg_zigzag_order jZIGTable
  160897. #define jpeg_natural_order jZAGTable
  160898. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160899. /* Compression module initialization routines */
  160900. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160901. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160902. boolean transcode_only));
  160903. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160904. boolean need_full_buffer));
  160905. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160906. boolean need_full_buffer));
  160907. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160908. boolean need_full_buffer));
  160909. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160910. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160911. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160912. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160913. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160914. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160915. /* Decompression module initialization routines */
  160916. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160917. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160918. boolean need_full_buffer));
  160919. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160920. boolean need_full_buffer));
  160921. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160922. boolean need_full_buffer));
  160923. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160924. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160925. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160926. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160927. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160928. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160929. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160930. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160931. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160932. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160933. /* Memory manager initialization */
  160934. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160935. /* Utility routines in jutils.c */
  160936. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160937. EXTERN(long) jround_up JPP((long a, long b));
  160938. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160939. JSAMPARRAY output_array, int dest_row,
  160940. int num_rows, JDIMENSION num_cols));
  160941. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160942. JDIMENSION num_blocks));
  160943. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160944. /* Constant tables in jutils.c */
  160945. #if 0 /* This table is not actually needed in v6a */
  160946. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160947. #endif
  160948. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160949. /* Suppress undefined-structure complaints if necessary. */
  160950. #ifdef INCOMPLETE_TYPES_BROKEN
  160951. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160952. struct jvirt_sarray_control { long dummy; };
  160953. struct jvirt_barray_control { long dummy; };
  160954. #endif
  160955. #endif /* INCOMPLETE_TYPES_BROKEN */
  160956. /*** End of inlined file: jpegint.h ***/
  160957. /* fetch private declarations */
  160958. /*** Start of inlined file: jerror.h ***/
  160959. /*
  160960. * To define the enum list of message codes, include this file without
  160961. * defining macro JMESSAGE. To create a message string table, include it
  160962. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160963. */
  160964. #ifndef JMESSAGE
  160965. #ifndef JERROR_H
  160966. /* First time through, define the enum list */
  160967. #define JMAKE_ENUM_LIST
  160968. #else
  160969. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160970. #define JMESSAGE(code,string)
  160971. #endif /* JERROR_H */
  160972. #endif /* JMESSAGE */
  160973. #ifdef JMAKE_ENUM_LIST
  160974. typedef enum {
  160975. #define JMESSAGE(code,string) code ,
  160976. #endif /* JMAKE_ENUM_LIST */
  160977. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160978. /* For maintenance convenience, list is alphabetical by message code name */
  160979. JMESSAGE(JERR_ARITH_NOTIMPL,
  160980. "Sorry, there are legal restrictions on arithmetic coding")
  160981. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160982. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160983. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160984. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160985. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160986. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160987. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160988. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160989. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160990. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160991. JMESSAGE(JERR_BAD_LIB_VERSION,
  160992. "Wrong JPEG library version: library is %d, caller expects %d")
  160993. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160994. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160995. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160996. JMESSAGE(JERR_BAD_PROGRESSION,
  160997. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160998. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160999. "Invalid progressive parameters at scan script entry %d")
  161000. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161001. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161002. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161003. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161004. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161005. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161006. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161007. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161008. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161009. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161010. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161011. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161012. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161013. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161014. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161015. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161016. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161017. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161018. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161019. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161020. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161021. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161022. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161023. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161024. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161025. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161026. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161027. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161028. "Cannot transcode due to multiple use of quantization table %d")
  161029. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161030. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161031. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161032. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161033. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161034. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161035. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161036. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161037. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161038. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161039. JMESSAGE(JERR_QUANT_COMPONENTS,
  161040. "Cannot quantize more than %d color components")
  161041. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161042. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161043. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161044. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161045. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161046. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161047. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161048. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161049. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161050. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161051. JMESSAGE(JERR_TFILE_WRITE,
  161052. "Write failed on temporary file --- out of disk space?")
  161053. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161054. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161055. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161056. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161057. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161058. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161059. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161060. JMESSAGE(JMSG_VERSION, JVERSION)
  161061. JMESSAGE(JTRC_16BIT_TABLES,
  161062. "Caution: quantization tables are too coarse for baseline JPEG")
  161063. JMESSAGE(JTRC_ADOBE,
  161064. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161065. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161066. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161067. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161068. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161069. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161070. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161071. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161072. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161073. JMESSAGE(JTRC_EOI, "End Of Image")
  161074. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161075. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161076. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161077. "Warning: thumbnail image size does not match data length %u")
  161078. JMESSAGE(JTRC_JFIF_EXTENSION,
  161079. "JFIF extension marker: type 0x%02x, length %u")
  161080. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161081. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161082. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161083. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161084. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161085. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161086. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161087. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161088. JMESSAGE(JTRC_RST, "RST%d")
  161089. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161090. "Smoothing not supported with nonstandard sampling ratios")
  161091. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161092. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161093. JMESSAGE(JTRC_SOI, "Start of Image")
  161094. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161095. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161096. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161097. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161098. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161099. JMESSAGE(JTRC_THUMB_JPEG,
  161100. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161101. JMESSAGE(JTRC_THUMB_PALETTE,
  161102. "JFIF extension marker: palette thumbnail image, length %u")
  161103. JMESSAGE(JTRC_THUMB_RGB,
  161104. "JFIF extension marker: RGB thumbnail image, length %u")
  161105. JMESSAGE(JTRC_UNKNOWN_IDS,
  161106. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161107. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161108. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161109. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161110. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161111. "Inconsistent progression sequence for component %d coefficient %d")
  161112. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161113. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161114. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161115. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161116. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161117. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161118. JMESSAGE(JWRN_MUST_RESYNC,
  161119. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161120. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161121. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161122. #ifdef JMAKE_ENUM_LIST
  161123. JMSG_LASTMSGCODE
  161124. } J_MESSAGE_CODE;
  161125. #undef JMAKE_ENUM_LIST
  161126. #endif /* JMAKE_ENUM_LIST */
  161127. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161128. #undef JMESSAGE
  161129. #ifndef JERROR_H
  161130. #define JERROR_H
  161131. /* Macros to simplify using the error and trace message stuff */
  161132. /* The first parameter is either type of cinfo pointer */
  161133. /* Fatal errors (print message and exit) */
  161134. #define ERREXIT(cinfo,code) \
  161135. ((cinfo)->err->msg_code = (code), \
  161136. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161137. #define ERREXIT1(cinfo,code,p1) \
  161138. ((cinfo)->err->msg_code = (code), \
  161139. (cinfo)->err->msg_parm.i[0] = (p1), \
  161140. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161141. #define ERREXIT2(cinfo,code,p1,p2) \
  161142. ((cinfo)->err->msg_code = (code), \
  161143. (cinfo)->err->msg_parm.i[0] = (p1), \
  161144. (cinfo)->err->msg_parm.i[1] = (p2), \
  161145. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161146. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161147. ((cinfo)->err->msg_code = (code), \
  161148. (cinfo)->err->msg_parm.i[0] = (p1), \
  161149. (cinfo)->err->msg_parm.i[1] = (p2), \
  161150. (cinfo)->err->msg_parm.i[2] = (p3), \
  161151. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161152. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161153. ((cinfo)->err->msg_code = (code), \
  161154. (cinfo)->err->msg_parm.i[0] = (p1), \
  161155. (cinfo)->err->msg_parm.i[1] = (p2), \
  161156. (cinfo)->err->msg_parm.i[2] = (p3), \
  161157. (cinfo)->err->msg_parm.i[3] = (p4), \
  161158. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161159. #define ERREXITS(cinfo,code,str) \
  161160. ((cinfo)->err->msg_code = (code), \
  161161. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161162. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161163. #define MAKESTMT(stuff) do { stuff } while (0)
  161164. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161165. #define WARNMS(cinfo,code) \
  161166. ((cinfo)->err->msg_code = (code), \
  161167. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161168. #define WARNMS1(cinfo,code,p1) \
  161169. ((cinfo)->err->msg_code = (code), \
  161170. (cinfo)->err->msg_parm.i[0] = (p1), \
  161171. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161172. #define WARNMS2(cinfo,code,p1,p2) \
  161173. ((cinfo)->err->msg_code = (code), \
  161174. (cinfo)->err->msg_parm.i[0] = (p1), \
  161175. (cinfo)->err->msg_parm.i[1] = (p2), \
  161176. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161177. /* Informational/debugging messages */
  161178. #define TRACEMS(cinfo,lvl,code) \
  161179. ((cinfo)->err->msg_code = (code), \
  161180. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161181. #define TRACEMS1(cinfo,lvl,code,p1) \
  161182. ((cinfo)->err->msg_code = (code), \
  161183. (cinfo)->err->msg_parm.i[0] = (p1), \
  161184. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161185. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161186. ((cinfo)->err->msg_code = (code), \
  161187. (cinfo)->err->msg_parm.i[0] = (p1), \
  161188. (cinfo)->err->msg_parm.i[1] = (p2), \
  161189. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161190. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161191. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161192. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161193. (cinfo)->err->msg_code = (code); \
  161194. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161195. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161196. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161197. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161198. (cinfo)->err->msg_code = (code); \
  161199. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161200. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161201. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161202. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161203. _mp[4] = (p5); \
  161204. (cinfo)->err->msg_code = (code); \
  161205. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161206. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161207. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161208. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161209. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161210. (cinfo)->err->msg_code = (code); \
  161211. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161212. #define TRACEMSS(cinfo,lvl,code,str) \
  161213. ((cinfo)->err->msg_code = (code), \
  161214. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161215. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161216. #endif /* JERROR_H */
  161217. /*** End of inlined file: jerror.h ***/
  161218. /* fetch error codes too */
  161219. #endif
  161220. #endif /* JPEGLIB_H */
  161221. /*** End of inlined file: jpeglib.h ***/
  161222. /*** Start of inlined file: jcapimin.c ***/
  161223. #define JPEG_INTERNALS
  161224. /*** Start of inlined file: jinclude.h ***/
  161225. /* Include auto-config file to find out which system include files we need. */
  161226. #ifndef __jinclude_h__
  161227. #define __jinclude_h__
  161228. /*** Start of inlined file: jconfig.h ***/
  161229. /* see jconfig.doc for explanations */
  161230. // disable all the warnings under MSVC
  161231. #ifdef _MSC_VER
  161232. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161233. #endif
  161234. #ifdef __BORLANDC__
  161235. #pragma warn -8057
  161236. #pragma warn -8019
  161237. #pragma warn -8004
  161238. #pragma warn -8008
  161239. #endif
  161240. #define HAVE_PROTOTYPES
  161241. #define HAVE_UNSIGNED_CHAR
  161242. #define HAVE_UNSIGNED_SHORT
  161243. /* #define void char */
  161244. /* #define const */
  161245. #undef CHAR_IS_UNSIGNED
  161246. #define HAVE_STDDEF_H
  161247. #define HAVE_STDLIB_H
  161248. #undef NEED_BSD_STRINGS
  161249. #undef NEED_SYS_TYPES_H
  161250. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161251. #undef NEED_SHORT_EXTERNAL_NAMES
  161252. #undef INCOMPLETE_TYPES_BROKEN
  161253. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161254. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161255. typedef unsigned char boolean;
  161256. #endif
  161257. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161258. #ifdef JPEG_INTERNALS
  161259. #undef RIGHT_SHIFT_IS_UNSIGNED
  161260. #endif /* JPEG_INTERNALS */
  161261. #ifdef JPEG_CJPEG_DJPEG
  161262. #define BMP_SUPPORTED /* BMP image file format */
  161263. #define GIF_SUPPORTED /* GIF image file format */
  161264. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161265. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161266. #define TARGA_SUPPORTED /* Targa image file format */
  161267. #define TWO_FILE_COMMANDLINE /* optional */
  161268. #define USE_SETMODE /* Microsoft has setmode() */
  161269. #undef NEED_SIGNAL_CATCHER
  161270. #undef DONT_USE_B_MODE
  161271. #undef PROGRESS_REPORT /* optional */
  161272. #endif /* JPEG_CJPEG_DJPEG */
  161273. /*** End of inlined file: jconfig.h ***/
  161274. /* auto configuration options */
  161275. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161276. /*
  161277. * We need the NULL macro and size_t typedef.
  161278. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161279. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161280. * pull in <sys/types.h> as well.
  161281. * Note that the core JPEG library does not require <stdio.h>;
  161282. * only the default error handler and data source/destination modules do.
  161283. * But we must pull it in because of the references to FILE in jpeglib.h.
  161284. * You can remove those references if you want to compile without <stdio.h>.
  161285. */
  161286. #ifdef HAVE_STDDEF_H
  161287. #include <stddef.h>
  161288. #endif
  161289. #ifdef HAVE_STDLIB_H
  161290. #include <stdlib.h>
  161291. #endif
  161292. #ifdef NEED_SYS_TYPES_H
  161293. #include <sys/types.h>
  161294. #endif
  161295. #include <stdio.h>
  161296. /*
  161297. * We need memory copying and zeroing functions, plus strncpy().
  161298. * ANSI and System V implementations declare these in <string.h>.
  161299. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161300. * Some systems may declare memset and memcpy in <memory.h>.
  161301. *
  161302. * NOTE: we assume the size parameters to these functions are of type size_t.
  161303. * Change the casts in these macros if not!
  161304. */
  161305. #ifdef NEED_BSD_STRINGS
  161306. #include <strings.h>
  161307. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161308. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161309. #else /* not BSD, assume ANSI/SysV string lib */
  161310. #include <string.h>
  161311. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161312. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161313. #endif
  161314. /*
  161315. * In ANSI C, and indeed any rational implementation, size_t is also the
  161316. * type returned by sizeof(). However, it seems there are some irrational
  161317. * implementations out there, in which sizeof() returns an int even though
  161318. * size_t is defined as long or unsigned long. To ensure consistent results
  161319. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161320. */
  161321. #define SIZEOF(object) ((size_t) sizeof(object))
  161322. /*
  161323. * The modules that use fread() and fwrite() always invoke them through
  161324. * these macros. On some systems you may need to twiddle the argument casts.
  161325. * CAUTION: argument order is different from underlying functions!
  161326. */
  161327. #define JFREAD(file,buf,sizeofbuf) \
  161328. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161329. #define JFWRITE(file,buf,sizeofbuf) \
  161330. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161331. typedef enum { /* JPEG marker codes */
  161332. M_SOF0 = 0xc0,
  161333. M_SOF1 = 0xc1,
  161334. M_SOF2 = 0xc2,
  161335. M_SOF3 = 0xc3,
  161336. M_SOF5 = 0xc5,
  161337. M_SOF6 = 0xc6,
  161338. M_SOF7 = 0xc7,
  161339. M_JPG = 0xc8,
  161340. M_SOF9 = 0xc9,
  161341. M_SOF10 = 0xca,
  161342. M_SOF11 = 0xcb,
  161343. M_SOF13 = 0xcd,
  161344. M_SOF14 = 0xce,
  161345. M_SOF15 = 0xcf,
  161346. M_DHT = 0xc4,
  161347. M_DAC = 0xcc,
  161348. M_RST0 = 0xd0,
  161349. M_RST1 = 0xd1,
  161350. M_RST2 = 0xd2,
  161351. M_RST3 = 0xd3,
  161352. M_RST4 = 0xd4,
  161353. M_RST5 = 0xd5,
  161354. M_RST6 = 0xd6,
  161355. M_RST7 = 0xd7,
  161356. M_SOI = 0xd8,
  161357. M_EOI = 0xd9,
  161358. M_SOS = 0xda,
  161359. M_DQT = 0xdb,
  161360. M_DNL = 0xdc,
  161361. M_DRI = 0xdd,
  161362. M_DHP = 0xde,
  161363. M_EXP = 0xdf,
  161364. M_APP0 = 0xe0,
  161365. M_APP1 = 0xe1,
  161366. M_APP2 = 0xe2,
  161367. M_APP3 = 0xe3,
  161368. M_APP4 = 0xe4,
  161369. M_APP5 = 0xe5,
  161370. M_APP6 = 0xe6,
  161371. M_APP7 = 0xe7,
  161372. M_APP8 = 0xe8,
  161373. M_APP9 = 0xe9,
  161374. M_APP10 = 0xea,
  161375. M_APP11 = 0xeb,
  161376. M_APP12 = 0xec,
  161377. M_APP13 = 0xed,
  161378. M_APP14 = 0xee,
  161379. M_APP15 = 0xef,
  161380. M_JPG0 = 0xf0,
  161381. M_JPG13 = 0xfd,
  161382. M_COM = 0xfe,
  161383. M_TEM = 0x01,
  161384. M_ERROR = 0x100
  161385. } JPEG_MARKER;
  161386. /*
  161387. * Figure F.12: extend sign bit.
  161388. * On some machines, a shift and add will be faster than a table lookup.
  161389. */
  161390. #ifdef AVOID_TABLES
  161391. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161392. #else
  161393. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161394. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161395. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161396. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161397. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161398. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161399. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161400. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161401. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161402. #endif /* AVOID_TABLES */
  161403. #endif
  161404. /*** End of inlined file: jinclude.h ***/
  161405. /*
  161406. * Initialization of a JPEG compression object.
  161407. * The error manager must already be set up (in case memory manager fails).
  161408. */
  161409. GLOBAL(void)
  161410. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161411. {
  161412. int i;
  161413. /* Guard against version mismatches between library and caller. */
  161414. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161415. if (version != JPEG_LIB_VERSION)
  161416. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161417. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161418. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161419. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161420. /* For debugging purposes, we zero the whole master structure.
  161421. * But the application has already set the err pointer, and may have set
  161422. * client_data, so we have to save and restore those fields.
  161423. * Note: if application hasn't set client_data, tools like Purify may
  161424. * complain here.
  161425. */
  161426. {
  161427. struct jpeg_error_mgr * err = cinfo->err;
  161428. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161429. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161430. cinfo->err = err;
  161431. cinfo->client_data = client_data;
  161432. }
  161433. cinfo->is_decompressor = FALSE;
  161434. /* Initialize a memory manager instance for this object */
  161435. jinit_memory_mgr((j_common_ptr) cinfo);
  161436. /* Zero out pointers to permanent structures. */
  161437. cinfo->progress = NULL;
  161438. cinfo->dest = NULL;
  161439. cinfo->comp_info = NULL;
  161440. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161441. cinfo->quant_tbl_ptrs[i] = NULL;
  161442. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161443. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161444. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161445. }
  161446. cinfo->script_space = NULL;
  161447. cinfo->input_gamma = 1.0; /* in case application forgets */
  161448. /* OK, I'm ready */
  161449. cinfo->global_state = CSTATE_START;
  161450. }
  161451. /*
  161452. * Destruction of a JPEG compression object
  161453. */
  161454. GLOBAL(void)
  161455. jpeg_destroy_compress (j_compress_ptr cinfo)
  161456. {
  161457. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161458. }
  161459. /*
  161460. * Abort processing of a JPEG compression operation,
  161461. * but don't destroy the object itself.
  161462. */
  161463. GLOBAL(void)
  161464. jpeg_abort_compress (j_compress_ptr cinfo)
  161465. {
  161466. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161467. }
  161468. /*
  161469. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161470. * Marks all currently defined tables as already written (if suppress)
  161471. * or not written (if !suppress). This will control whether they get emitted
  161472. * by a subsequent jpeg_start_compress call.
  161473. *
  161474. * This routine is exported for use by applications that want to produce
  161475. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161476. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161477. * jcparam.o would be linked whether the application used it or not.
  161478. */
  161479. GLOBAL(void)
  161480. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161481. {
  161482. int i;
  161483. JQUANT_TBL * qtbl;
  161484. JHUFF_TBL * htbl;
  161485. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161486. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161487. qtbl->sent_table = suppress;
  161488. }
  161489. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161490. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161491. htbl->sent_table = suppress;
  161492. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161493. htbl->sent_table = suppress;
  161494. }
  161495. }
  161496. /*
  161497. * Finish JPEG compression.
  161498. *
  161499. * If a multipass operating mode was selected, this may do a great deal of
  161500. * work including most of the actual output.
  161501. */
  161502. GLOBAL(void)
  161503. jpeg_finish_compress (j_compress_ptr cinfo)
  161504. {
  161505. JDIMENSION iMCU_row;
  161506. if (cinfo->global_state == CSTATE_SCANNING ||
  161507. cinfo->global_state == CSTATE_RAW_OK) {
  161508. /* Terminate first pass */
  161509. if (cinfo->next_scanline < cinfo->image_height)
  161510. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161511. (*cinfo->master->finish_pass) (cinfo);
  161512. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161513. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161514. /* Perform any remaining passes */
  161515. while (! cinfo->master->is_last_pass) {
  161516. (*cinfo->master->prepare_for_pass) (cinfo);
  161517. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161518. if (cinfo->progress != NULL) {
  161519. cinfo->progress->pass_counter = (long) iMCU_row;
  161520. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161521. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161522. }
  161523. /* We bypass the main controller and invoke coef controller directly;
  161524. * all work is being done from the coefficient buffer.
  161525. */
  161526. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161527. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161528. }
  161529. (*cinfo->master->finish_pass) (cinfo);
  161530. }
  161531. /* Write EOI, do final cleanup */
  161532. (*cinfo->marker->write_file_trailer) (cinfo);
  161533. (*cinfo->dest->term_destination) (cinfo);
  161534. /* We can use jpeg_abort to release memory and reset global_state */
  161535. jpeg_abort((j_common_ptr) cinfo);
  161536. }
  161537. /*
  161538. * Write a special marker.
  161539. * This is only recommended for writing COM or APPn markers.
  161540. * Must be called after jpeg_start_compress() and before
  161541. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161542. */
  161543. GLOBAL(void)
  161544. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161545. const JOCTET *dataptr, unsigned int datalen)
  161546. {
  161547. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161548. if (cinfo->next_scanline != 0 ||
  161549. (cinfo->global_state != CSTATE_SCANNING &&
  161550. cinfo->global_state != CSTATE_RAW_OK &&
  161551. cinfo->global_state != CSTATE_WRCOEFS))
  161552. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161553. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161554. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161555. while (datalen--) {
  161556. (*write_marker_byte) (cinfo, *dataptr);
  161557. dataptr++;
  161558. }
  161559. }
  161560. /* Same, but piecemeal. */
  161561. GLOBAL(void)
  161562. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161563. {
  161564. if (cinfo->next_scanline != 0 ||
  161565. (cinfo->global_state != CSTATE_SCANNING &&
  161566. cinfo->global_state != CSTATE_RAW_OK &&
  161567. cinfo->global_state != CSTATE_WRCOEFS))
  161568. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161569. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161570. }
  161571. GLOBAL(void)
  161572. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161573. {
  161574. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161575. }
  161576. /*
  161577. * Alternate compression function: just write an abbreviated table file.
  161578. * Before calling this, all parameters and a data destination must be set up.
  161579. *
  161580. * To produce a pair of files containing abbreviated tables and abbreviated
  161581. * image data, one would proceed as follows:
  161582. *
  161583. * initialize JPEG object
  161584. * set JPEG parameters
  161585. * set destination to table file
  161586. * jpeg_write_tables(cinfo);
  161587. * set destination to image file
  161588. * jpeg_start_compress(cinfo, FALSE);
  161589. * write data...
  161590. * jpeg_finish_compress(cinfo);
  161591. *
  161592. * jpeg_write_tables has the side effect of marking all tables written
  161593. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161594. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161595. */
  161596. GLOBAL(void)
  161597. jpeg_write_tables (j_compress_ptr cinfo)
  161598. {
  161599. if (cinfo->global_state != CSTATE_START)
  161600. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161601. /* (Re)initialize error mgr and destination modules */
  161602. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161603. (*cinfo->dest->init_destination) (cinfo);
  161604. /* Initialize the marker writer ... bit of a crock to do it here. */
  161605. jinit_marker_writer(cinfo);
  161606. /* Write them tables! */
  161607. (*cinfo->marker->write_tables_only) (cinfo);
  161608. /* And clean up. */
  161609. (*cinfo->dest->term_destination) (cinfo);
  161610. /*
  161611. * In library releases up through v6a, we called jpeg_abort() here to free
  161612. * any working memory allocated by the destination manager and marker
  161613. * writer. Some applications had a problem with that: they allocated space
  161614. * of their own from the library memory manager, and didn't want it to go
  161615. * away during write_tables. So now we do nothing. This will cause a
  161616. * memory leak if an app calls write_tables repeatedly without doing a full
  161617. * compression cycle or otherwise resetting the JPEG object. However, that
  161618. * seems less bad than unexpectedly freeing memory in the normal case.
  161619. * An app that prefers the old behavior can call jpeg_abort for itself after
  161620. * each call to jpeg_write_tables().
  161621. */
  161622. }
  161623. /*** End of inlined file: jcapimin.c ***/
  161624. /*** Start of inlined file: jcapistd.c ***/
  161625. #define JPEG_INTERNALS
  161626. /*
  161627. * Compression initialization.
  161628. * Before calling this, all parameters and a data destination must be set up.
  161629. *
  161630. * We require a write_all_tables parameter as a failsafe check when writing
  161631. * multiple datastreams from the same compression object. Since prior runs
  161632. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161633. * would emit an abbreviated stream (no tables) by default. This may be what
  161634. * is wanted, but for safety's sake it should not be the default behavior:
  161635. * programmers should have to make a deliberate choice to emit abbreviated
  161636. * images. Therefore the documentation and examples should encourage people
  161637. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161638. * wrong thing.
  161639. */
  161640. GLOBAL(void)
  161641. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161642. {
  161643. if (cinfo->global_state != CSTATE_START)
  161644. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161645. if (write_all_tables)
  161646. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161647. /* (Re)initialize error mgr and destination modules */
  161648. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161649. (*cinfo->dest->init_destination) (cinfo);
  161650. /* Perform master selection of active modules */
  161651. jinit_compress_master(cinfo);
  161652. /* Set up for the first pass */
  161653. (*cinfo->master->prepare_for_pass) (cinfo);
  161654. /* Ready for application to drive first pass through jpeg_write_scanlines
  161655. * or jpeg_write_raw_data.
  161656. */
  161657. cinfo->next_scanline = 0;
  161658. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161659. }
  161660. /*
  161661. * Write some scanlines of data to the JPEG compressor.
  161662. *
  161663. * The return value will be the number of lines actually written.
  161664. * This should be less than the supplied num_lines only in case that
  161665. * the data destination module has requested suspension of the compressor,
  161666. * or if more than image_height scanlines are passed in.
  161667. *
  161668. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161669. * this likely signals an application programmer error. However,
  161670. * excess scanlines passed in the last valid call are *silently* ignored,
  161671. * so that the application need not adjust num_lines for end-of-image
  161672. * when using a multiple-scanline buffer.
  161673. */
  161674. GLOBAL(JDIMENSION)
  161675. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161676. JDIMENSION num_lines)
  161677. {
  161678. JDIMENSION row_ctr, rows_left;
  161679. if (cinfo->global_state != CSTATE_SCANNING)
  161680. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161681. if (cinfo->next_scanline >= cinfo->image_height)
  161682. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161683. /* Call progress monitor hook if present */
  161684. if (cinfo->progress != NULL) {
  161685. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161686. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161687. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161688. }
  161689. /* Give master control module another chance if this is first call to
  161690. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161691. * delayed so that application can write COM, etc, markers between
  161692. * jpeg_start_compress and jpeg_write_scanlines.
  161693. */
  161694. if (cinfo->master->call_pass_startup)
  161695. (*cinfo->master->pass_startup) (cinfo);
  161696. /* Ignore any extra scanlines at bottom of image. */
  161697. rows_left = cinfo->image_height - cinfo->next_scanline;
  161698. if (num_lines > rows_left)
  161699. num_lines = rows_left;
  161700. row_ctr = 0;
  161701. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161702. cinfo->next_scanline += row_ctr;
  161703. return row_ctr;
  161704. }
  161705. /*
  161706. * Alternate entry point to write raw data.
  161707. * Processes exactly one iMCU row per call, unless suspended.
  161708. */
  161709. GLOBAL(JDIMENSION)
  161710. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161711. JDIMENSION num_lines)
  161712. {
  161713. JDIMENSION lines_per_iMCU_row;
  161714. if (cinfo->global_state != CSTATE_RAW_OK)
  161715. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161716. if (cinfo->next_scanline >= cinfo->image_height) {
  161717. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161718. return 0;
  161719. }
  161720. /* Call progress monitor hook if present */
  161721. if (cinfo->progress != NULL) {
  161722. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161723. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161724. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161725. }
  161726. /* Give master control module another chance if this is first call to
  161727. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161728. * delayed so that application can write COM, etc, markers between
  161729. * jpeg_start_compress and jpeg_write_raw_data.
  161730. */
  161731. if (cinfo->master->call_pass_startup)
  161732. (*cinfo->master->pass_startup) (cinfo);
  161733. /* Verify that at least one iMCU row has been passed. */
  161734. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161735. if (num_lines < lines_per_iMCU_row)
  161736. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161737. /* Directly compress the row. */
  161738. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161739. /* If compressor did not consume the whole row, suspend processing. */
  161740. return 0;
  161741. }
  161742. /* OK, we processed one iMCU row. */
  161743. cinfo->next_scanline += lines_per_iMCU_row;
  161744. return lines_per_iMCU_row;
  161745. }
  161746. /*** End of inlined file: jcapistd.c ***/
  161747. /*** Start of inlined file: jccoefct.c ***/
  161748. #define JPEG_INTERNALS
  161749. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161750. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161751. * step is run during the first pass, and subsequent passes need only read
  161752. * the buffered coefficients.
  161753. */
  161754. #ifdef ENTROPY_OPT_SUPPORTED
  161755. #define FULL_COEF_BUFFER_SUPPORTED
  161756. #else
  161757. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161758. #define FULL_COEF_BUFFER_SUPPORTED
  161759. #endif
  161760. #endif
  161761. /* Private buffer controller object */
  161762. typedef struct {
  161763. struct jpeg_c_coef_controller pub; /* public fields */
  161764. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161765. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161766. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161767. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161768. /* For single-pass compression, it's sufficient to buffer just one MCU
  161769. * (although this may prove a bit slow in practice). We allocate a
  161770. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161771. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161772. * it's not really very big; this is to keep the module interfaces unchanged
  161773. * when a large coefficient buffer is necessary.)
  161774. * In multi-pass modes, this array points to the current MCU's blocks
  161775. * within the virtual arrays.
  161776. */
  161777. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161778. /* In multi-pass modes, we need a virtual block array for each component. */
  161779. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161780. } my_coef_controller;
  161781. typedef my_coef_controller * my_coef_ptr;
  161782. /* Forward declarations */
  161783. METHODDEF(boolean) compress_data
  161784. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161785. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161786. METHODDEF(boolean) compress_first_pass
  161787. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161788. METHODDEF(boolean) compress_output
  161789. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161790. #endif
  161791. LOCAL(void)
  161792. start_iMCU_row (j_compress_ptr cinfo)
  161793. /* Reset within-iMCU-row counters for a new row */
  161794. {
  161795. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161796. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161797. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161798. * But at the bottom of the image, process only what's left.
  161799. */
  161800. if (cinfo->comps_in_scan > 1) {
  161801. coef->MCU_rows_per_iMCU_row = 1;
  161802. } else {
  161803. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161804. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161805. else
  161806. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161807. }
  161808. coef->mcu_ctr = 0;
  161809. coef->MCU_vert_offset = 0;
  161810. }
  161811. /*
  161812. * Initialize for a processing pass.
  161813. */
  161814. METHODDEF(void)
  161815. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161816. {
  161817. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161818. coef->iMCU_row_num = 0;
  161819. start_iMCU_row(cinfo);
  161820. switch (pass_mode) {
  161821. case JBUF_PASS_THRU:
  161822. if (coef->whole_image[0] != NULL)
  161823. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161824. coef->pub.compress_data = compress_data;
  161825. break;
  161826. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161827. case JBUF_SAVE_AND_PASS:
  161828. if (coef->whole_image[0] == NULL)
  161829. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161830. coef->pub.compress_data = compress_first_pass;
  161831. break;
  161832. case JBUF_CRANK_DEST:
  161833. if (coef->whole_image[0] == NULL)
  161834. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161835. coef->pub.compress_data = compress_output;
  161836. break;
  161837. #endif
  161838. default:
  161839. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161840. break;
  161841. }
  161842. }
  161843. /*
  161844. * Process some data in the single-pass case.
  161845. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161846. * per call, ie, v_samp_factor block rows for each component in the image.
  161847. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161848. *
  161849. * NB: input_buf contains a plane for each component in image,
  161850. * which we index according to the component's SOF position.
  161851. */
  161852. METHODDEF(boolean)
  161853. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161854. {
  161855. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161856. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161857. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161858. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161859. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161860. JDIMENSION ypos, xpos;
  161861. jpeg_component_info *compptr;
  161862. /* Loop to write as much as one whole iMCU row */
  161863. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161864. yoffset++) {
  161865. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161866. MCU_col_num++) {
  161867. /* Determine where data comes from in input_buf and do the DCT thing.
  161868. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161869. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161870. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161871. * specially. The data in them does not matter for image reconstruction,
  161872. * so we fill them with values that will encode to the smallest amount of
  161873. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161874. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161875. */
  161876. blkn = 0;
  161877. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161878. compptr = cinfo->cur_comp_info[ci];
  161879. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161880. : compptr->last_col_width;
  161881. xpos = MCU_col_num * compptr->MCU_sample_width;
  161882. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161883. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161884. if (coef->iMCU_row_num < last_iMCU_row ||
  161885. yoffset+yindex < compptr->last_row_height) {
  161886. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161887. input_buf[compptr->component_index],
  161888. coef->MCU_buffer[blkn],
  161889. ypos, xpos, (JDIMENSION) blockcnt);
  161890. if (blockcnt < compptr->MCU_width) {
  161891. /* Create some dummy blocks at the right edge of the image. */
  161892. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161893. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161894. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161895. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161896. }
  161897. }
  161898. } else {
  161899. /* Create a row of dummy blocks at the bottom of the image. */
  161900. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161901. compptr->MCU_width * SIZEOF(JBLOCK));
  161902. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161903. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161904. }
  161905. }
  161906. blkn += compptr->MCU_width;
  161907. ypos += DCTSIZE;
  161908. }
  161909. }
  161910. /* Try to write the MCU. In event of a suspension failure, we will
  161911. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161912. */
  161913. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161914. /* Suspension forced; update state counters and exit */
  161915. coef->MCU_vert_offset = yoffset;
  161916. coef->mcu_ctr = MCU_col_num;
  161917. return FALSE;
  161918. }
  161919. }
  161920. /* Completed an MCU row, but perhaps not an iMCU row */
  161921. coef->mcu_ctr = 0;
  161922. }
  161923. /* Completed the iMCU row, advance counters for next one */
  161924. coef->iMCU_row_num++;
  161925. start_iMCU_row(cinfo);
  161926. return TRUE;
  161927. }
  161928. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161929. /*
  161930. * Process some data in the first pass of a multi-pass case.
  161931. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161932. * per call, ie, v_samp_factor block rows for each component in the image.
  161933. * This amount of data is read from the source buffer, DCT'd and quantized,
  161934. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161935. * as needed at the right and lower edges. (The dummy blocks are constructed
  161936. * in the virtual arrays, which have been padded appropriately.) This makes
  161937. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161938. *
  161939. * We must also emit the data to the entropy encoder. This is conveniently
  161940. * done by calling compress_output() after we've loaded the current strip
  161941. * of the virtual arrays.
  161942. *
  161943. * NB: input_buf contains a plane for each component in image. All
  161944. * components are DCT'd and loaded into the virtual arrays in this pass.
  161945. * However, it may be that only a subset of the components are emitted to
  161946. * the entropy encoder during this first pass; be careful about looking
  161947. * at the scan-dependent variables (MCU dimensions, etc).
  161948. */
  161949. METHODDEF(boolean)
  161950. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161951. {
  161952. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161953. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161954. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161955. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161956. JCOEF lastDC;
  161957. jpeg_component_info *compptr;
  161958. JBLOCKARRAY buffer;
  161959. JBLOCKROW thisblockrow, lastblockrow;
  161960. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161961. ci++, compptr++) {
  161962. /* Align the virtual buffer for this component. */
  161963. buffer = (*cinfo->mem->access_virt_barray)
  161964. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161965. coef->iMCU_row_num * compptr->v_samp_factor,
  161966. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161967. /* Count non-dummy DCT block rows in this iMCU row. */
  161968. if (coef->iMCU_row_num < last_iMCU_row)
  161969. block_rows = compptr->v_samp_factor;
  161970. else {
  161971. /* NB: can't use last_row_height here, since may not be set! */
  161972. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161973. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161974. }
  161975. blocks_across = compptr->width_in_blocks;
  161976. h_samp_factor = compptr->h_samp_factor;
  161977. /* Count number of dummy blocks to be added at the right margin. */
  161978. ndummy = (int) (blocks_across % h_samp_factor);
  161979. if (ndummy > 0)
  161980. ndummy = h_samp_factor - ndummy;
  161981. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161982. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161983. */
  161984. for (block_row = 0; block_row < block_rows; block_row++) {
  161985. thisblockrow = buffer[block_row];
  161986. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161987. input_buf[ci], thisblockrow,
  161988. (JDIMENSION) (block_row * DCTSIZE),
  161989. (JDIMENSION) 0, blocks_across);
  161990. if (ndummy > 0) {
  161991. /* Create dummy blocks at the right edge of the image. */
  161992. thisblockrow += blocks_across; /* => first dummy block */
  161993. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161994. lastDC = thisblockrow[-1][0];
  161995. for (bi = 0; bi < ndummy; bi++) {
  161996. thisblockrow[bi][0] = lastDC;
  161997. }
  161998. }
  161999. }
  162000. /* If at end of image, create dummy block rows as needed.
  162001. * The tricky part here is that within each MCU, we want the DC values
  162002. * of the dummy blocks to match the last real block's DC value.
  162003. * This squeezes a few more bytes out of the resulting file...
  162004. */
  162005. if (coef->iMCU_row_num == last_iMCU_row) {
  162006. blocks_across += ndummy; /* include lower right corner */
  162007. MCUs_across = blocks_across / h_samp_factor;
  162008. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162009. block_row++) {
  162010. thisblockrow = buffer[block_row];
  162011. lastblockrow = buffer[block_row-1];
  162012. jzero_far((void FAR *) thisblockrow,
  162013. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162014. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162015. lastDC = lastblockrow[h_samp_factor-1][0];
  162016. for (bi = 0; bi < h_samp_factor; bi++) {
  162017. thisblockrow[bi][0] = lastDC;
  162018. }
  162019. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162020. lastblockrow += h_samp_factor;
  162021. }
  162022. }
  162023. }
  162024. }
  162025. /* NB: compress_output will increment iMCU_row_num if successful.
  162026. * A suspension return will result in redoing all the work above next time.
  162027. */
  162028. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162029. return compress_output(cinfo, input_buf);
  162030. }
  162031. /*
  162032. * Process some data in subsequent passes of a multi-pass case.
  162033. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162034. * per call, ie, v_samp_factor block rows for each component in the scan.
  162035. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162036. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162037. *
  162038. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162039. */
  162040. METHODDEF(boolean)
  162041. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162042. {
  162043. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162044. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162045. int blkn, ci, xindex, yindex, yoffset;
  162046. JDIMENSION start_col;
  162047. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162048. JBLOCKROW buffer_ptr;
  162049. jpeg_component_info *compptr;
  162050. /* Align the virtual buffers for the components used in this scan.
  162051. * NB: during first pass, this is safe only because the buffers will
  162052. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162053. */
  162054. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162055. compptr = cinfo->cur_comp_info[ci];
  162056. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162057. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162058. coef->iMCU_row_num * compptr->v_samp_factor,
  162059. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162060. }
  162061. /* Loop to process one whole iMCU row */
  162062. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162063. yoffset++) {
  162064. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162065. MCU_col_num++) {
  162066. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162067. blkn = 0; /* index of current DCT block within MCU */
  162068. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162069. compptr = cinfo->cur_comp_info[ci];
  162070. start_col = MCU_col_num * compptr->MCU_width;
  162071. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162072. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162073. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162074. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162075. }
  162076. }
  162077. }
  162078. /* Try to write the MCU. */
  162079. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162080. /* Suspension forced; update state counters and exit */
  162081. coef->MCU_vert_offset = yoffset;
  162082. coef->mcu_ctr = MCU_col_num;
  162083. return FALSE;
  162084. }
  162085. }
  162086. /* Completed an MCU row, but perhaps not an iMCU row */
  162087. coef->mcu_ctr = 0;
  162088. }
  162089. /* Completed the iMCU row, advance counters for next one */
  162090. coef->iMCU_row_num++;
  162091. start_iMCU_row(cinfo);
  162092. return TRUE;
  162093. }
  162094. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162095. /*
  162096. * Initialize coefficient buffer controller.
  162097. */
  162098. GLOBAL(void)
  162099. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162100. {
  162101. my_coef_ptr coef;
  162102. coef = (my_coef_ptr)
  162103. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162104. SIZEOF(my_coef_controller));
  162105. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162106. coef->pub.start_pass = start_pass_coef;
  162107. /* Create the coefficient buffer. */
  162108. if (need_full_buffer) {
  162109. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162110. /* Allocate a full-image virtual array for each component, */
  162111. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162112. int ci;
  162113. jpeg_component_info *compptr;
  162114. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162115. ci++, compptr++) {
  162116. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162117. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162118. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162119. (long) compptr->h_samp_factor),
  162120. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162121. (long) compptr->v_samp_factor),
  162122. (JDIMENSION) compptr->v_samp_factor);
  162123. }
  162124. #else
  162125. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162126. #endif
  162127. } else {
  162128. /* We only need a single-MCU buffer. */
  162129. JBLOCKROW buffer;
  162130. int i;
  162131. buffer = (JBLOCKROW)
  162132. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162133. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162134. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162135. coef->MCU_buffer[i] = buffer + i;
  162136. }
  162137. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162138. }
  162139. }
  162140. /*** End of inlined file: jccoefct.c ***/
  162141. /*** Start of inlined file: jccolor.c ***/
  162142. #define JPEG_INTERNALS
  162143. /* Private subobject */
  162144. typedef struct {
  162145. struct jpeg_color_converter pub; /* public fields */
  162146. /* Private state for RGB->YCC conversion */
  162147. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162148. } my_color_converter;
  162149. typedef my_color_converter * my_cconvert_ptr;
  162150. /**************** RGB -> YCbCr conversion: most common case **************/
  162151. /*
  162152. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162153. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162154. * The conversion equations to be implemented are therefore
  162155. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162156. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162157. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162158. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162159. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162160. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162161. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162162. * were not represented exactly. Now we sacrifice exact representation of
  162163. * maximum red and maximum blue in order to get exact grayscales.
  162164. *
  162165. * To avoid floating-point arithmetic, we represent the fractional constants
  162166. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162167. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162168. *
  162169. * For even more speed, we avoid doing any multiplications in the inner loop
  162170. * by precalculating the constants times R,G,B for all possible values.
  162171. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162172. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162173. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162174. * colorspace anyway.
  162175. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162176. * in the tables to save adding them separately in the inner loop.
  162177. */
  162178. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162179. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162180. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162181. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162182. /* We allocate one big table and divide it up into eight parts, instead of
  162183. * doing eight alloc_small requests. This lets us use a single table base
  162184. * address, which can be held in a register in the inner loops on many
  162185. * machines (more than can hold all eight addresses, anyway).
  162186. */
  162187. #define R_Y_OFF 0 /* offset to R => Y section */
  162188. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162189. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162190. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162191. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162192. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162193. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162194. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162195. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162196. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162197. /*
  162198. * Initialize for RGB->YCC colorspace conversion.
  162199. */
  162200. METHODDEF(void)
  162201. rgb_ycc_start (j_compress_ptr cinfo)
  162202. {
  162203. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162204. INT32 * rgb_ycc_tab;
  162205. INT32 i;
  162206. /* Allocate and fill in the conversion tables. */
  162207. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162208. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162209. (TABLE_SIZE * SIZEOF(INT32)));
  162210. for (i = 0; i <= MAXJSAMPLE; i++) {
  162211. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162212. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162213. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162214. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162215. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162216. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162217. * This ensures that the maximum output will round to MAXJSAMPLE
  162218. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162219. */
  162220. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162221. /* B=>Cb and R=>Cr tables are the same
  162222. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162223. */
  162224. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162225. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162226. }
  162227. }
  162228. /*
  162229. * Convert some rows of samples to the JPEG colorspace.
  162230. *
  162231. * Note that we change from the application's interleaved-pixel format
  162232. * to our internal noninterleaved, one-plane-per-component format.
  162233. * The input buffer is therefore three times as wide as the output buffer.
  162234. *
  162235. * A starting row offset is provided only for the output buffer. The caller
  162236. * can easily adjust the passed input_buf value to accommodate any row
  162237. * offset required on that side.
  162238. */
  162239. METHODDEF(void)
  162240. rgb_ycc_convert (j_compress_ptr cinfo,
  162241. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162242. JDIMENSION output_row, int num_rows)
  162243. {
  162244. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162245. register int r, g, b;
  162246. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162247. register JSAMPROW inptr;
  162248. register JSAMPROW outptr0, outptr1, outptr2;
  162249. register JDIMENSION col;
  162250. JDIMENSION num_cols = cinfo->image_width;
  162251. while (--num_rows >= 0) {
  162252. inptr = *input_buf++;
  162253. outptr0 = output_buf[0][output_row];
  162254. outptr1 = output_buf[1][output_row];
  162255. outptr2 = output_buf[2][output_row];
  162256. output_row++;
  162257. for (col = 0; col < num_cols; col++) {
  162258. r = GETJSAMPLE(inptr[RGB_RED]);
  162259. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162260. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162261. inptr += RGB_PIXELSIZE;
  162262. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162263. * must be too; we do not need an explicit range-limiting operation.
  162264. * Hence the value being shifted is never negative, and we don't
  162265. * need the general RIGHT_SHIFT macro.
  162266. */
  162267. /* Y */
  162268. outptr0[col] = (JSAMPLE)
  162269. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162270. >> SCALEBITS);
  162271. /* Cb */
  162272. outptr1[col] = (JSAMPLE)
  162273. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162274. >> SCALEBITS);
  162275. /* Cr */
  162276. outptr2[col] = (JSAMPLE)
  162277. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162278. >> SCALEBITS);
  162279. }
  162280. }
  162281. }
  162282. /**************** Cases other than RGB -> YCbCr **************/
  162283. /*
  162284. * Convert some rows of samples to the JPEG colorspace.
  162285. * This version handles RGB->grayscale conversion, which is the same
  162286. * as the RGB->Y portion of RGB->YCbCr.
  162287. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162288. */
  162289. METHODDEF(void)
  162290. rgb_gray_convert (j_compress_ptr cinfo,
  162291. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162292. JDIMENSION output_row, int num_rows)
  162293. {
  162294. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162295. register int r, g, b;
  162296. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162297. register JSAMPROW inptr;
  162298. register JSAMPROW outptr;
  162299. register JDIMENSION col;
  162300. JDIMENSION num_cols = cinfo->image_width;
  162301. while (--num_rows >= 0) {
  162302. inptr = *input_buf++;
  162303. outptr = output_buf[0][output_row];
  162304. output_row++;
  162305. for (col = 0; col < num_cols; col++) {
  162306. r = GETJSAMPLE(inptr[RGB_RED]);
  162307. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162308. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162309. inptr += RGB_PIXELSIZE;
  162310. /* Y */
  162311. outptr[col] = (JSAMPLE)
  162312. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162313. >> SCALEBITS);
  162314. }
  162315. }
  162316. }
  162317. /*
  162318. * Convert some rows of samples to the JPEG colorspace.
  162319. * This version handles Adobe-style CMYK->YCCK conversion,
  162320. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162321. * conversion as above, while passing K (black) unchanged.
  162322. * We assume rgb_ycc_start has been called.
  162323. */
  162324. METHODDEF(void)
  162325. cmyk_ycck_convert (j_compress_ptr cinfo,
  162326. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162327. JDIMENSION output_row, int num_rows)
  162328. {
  162329. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162330. register int r, g, b;
  162331. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162332. register JSAMPROW inptr;
  162333. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162334. register JDIMENSION col;
  162335. JDIMENSION num_cols = cinfo->image_width;
  162336. while (--num_rows >= 0) {
  162337. inptr = *input_buf++;
  162338. outptr0 = output_buf[0][output_row];
  162339. outptr1 = output_buf[1][output_row];
  162340. outptr2 = output_buf[2][output_row];
  162341. outptr3 = output_buf[3][output_row];
  162342. output_row++;
  162343. for (col = 0; col < num_cols; col++) {
  162344. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162345. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162346. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162347. /* K passes through as-is */
  162348. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162349. inptr += 4;
  162350. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162351. * must be too; we do not need an explicit range-limiting operation.
  162352. * Hence the value being shifted is never negative, and we don't
  162353. * need the general RIGHT_SHIFT macro.
  162354. */
  162355. /* Y */
  162356. outptr0[col] = (JSAMPLE)
  162357. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162358. >> SCALEBITS);
  162359. /* Cb */
  162360. outptr1[col] = (JSAMPLE)
  162361. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162362. >> SCALEBITS);
  162363. /* Cr */
  162364. outptr2[col] = (JSAMPLE)
  162365. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162366. >> SCALEBITS);
  162367. }
  162368. }
  162369. }
  162370. /*
  162371. * Convert some rows of samples to the JPEG colorspace.
  162372. * This version handles grayscale output with no conversion.
  162373. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162374. */
  162375. METHODDEF(void)
  162376. grayscale_convert (j_compress_ptr cinfo,
  162377. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162378. JDIMENSION output_row, int num_rows)
  162379. {
  162380. register JSAMPROW inptr;
  162381. register JSAMPROW outptr;
  162382. register JDIMENSION col;
  162383. JDIMENSION num_cols = cinfo->image_width;
  162384. int instride = cinfo->input_components;
  162385. while (--num_rows >= 0) {
  162386. inptr = *input_buf++;
  162387. outptr = output_buf[0][output_row];
  162388. output_row++;
  162389. for (col = 0; col < num_cols; col++) {
  162390. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162391. inptr += instride;
  162392. }
  162393. }
  162394. }
  162395. /*
  162396. * Convert some rows of samples to the JPEG colorspace.
  162397. * This version handles multi-component colorspaces without conversion.
  162398. * We assume input_components == num_components.
  162399. */
  162400. METHODDEF(void)
  162401. null_convert (j_compress_ptr cinfo,
  162402. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162403. JDIMENSION output_row, int num_rows)
  162404. {
  162405. register JSAMPROW inptr;
  162406. register JSAMPROW outptr;
  162407. register JDIMENSION col;
  162408. register int ci;
  162409. int nc = cinfo->num_components;
  162410. JDIMENSION num_cols = cinfo->image_width;
  162411. while (--num_rows >= 0) {
  162412. /* It seems fastest to make a separate pass for each component. */
  162413. for (ci = 0; ci < nc; ci++) {
  162414. inptr = *input_buf;
  162415. outptr = output_buf[ci][output_row];
  162416. for (col = 0; col < num_cols; col++) {
  162417. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162418. inptr += nc;
  162419. }
  162420. }
  162421. input_buf++;
  162422. output_row++;
  162423. }
  162424. }
  162425. /*
  162426. * Empty method for start_pass.
  162427. */
  162428. METHODDEF(void)
  162429. null_method (j_compress_ptr)
  162430. {
  162431. /* no work needed */
  162432. }
  162433. /*
  162434. * Module initialization routine for input colorspace conversion.
  162435. */
  162436. GLOBAL(void)
  162437. jinit_color_converter (j_compress_ptr cinfo)
  162438. {
  162439. my_cconvert_ptr cconvert;
  162440. cconvert = (my_cconvert_ptr)
  162441. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162442. SIZEOF(my_color_converter));
  162443. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162444. /* set start_pass to null method until we find out differently */
  162445. cconvert->pub.start_pass = null_method;
  162446. /* Make sure input_components agrees with in_color_space */
  162447. switch (cinfo->in_color_space) {
  162448. case JCS_GRAYSCALE:
  162449. if (cinfo->input_components != 1)
  162450. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162451. break;
  162452. case JCS_RGB:
  162453. #if RGB_PIXELSIZE != 3
  162454. if (cinfo->input_components != RGB_PIXELSIZE)
  162455. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162456. break;
  162457. #endif /* else share code with YCbCr */
  162458. case JCS_YCbCr:
  162459. if (cinfo->input_components != 3)
  162460. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162461. break;
  162462. case JCS_CMYK:
  162463. case JCS_YCCK:
  162464. if (cinfo->input_components != 4)
  162465. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162466. break;
  162467. default: /* JCS_UNKNOWN can be anything */
  162468. if (cinfo->input_components < 1)
  162469. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162470. break;
  162471. }
  162472. /* Check num_components, set conversion method based on requested space */
  162473. switch (cinfo->jpeg_color_space) {
  162474. case JCS_GRAYSCALE:
  162475. if (cinfo->num_components != 1)
  162476. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162477. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162478. cconvert->pub.color_convert = grayscale_convert;
  162479. else if (cinfo->in_color_space == JCS_RGB) {
  162480. cconvert->pub.start_pass = rgb_ycc_start;
  162481. cconvert->pub.color_convert = rgb_gray_convert;
  162482. } else if (cinfo->in_color_space == JCS_YCbCr)
  162483. cconvert->pub.color_convert = grayscale_convert;
  162484. else
  162485. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162486. break;
  162487. case JCS_RGB:
  162488. if (cinfo->num_components != 3)
  162489. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162490. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162491. cconvert->pub.color_convert = null_convert;
  162492. else
  162493. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162494. break;
  162495. case JCS_YCbCr:
  162496. if (cinfo->num_components != 3)
  162497. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162498. if (cinfo->in_color_space == JCS_RGB) {
  162499. cconvert->pub.start_pass = rgb_ycc_start;
  162500. cconvert->pub.color_convert = rgb_ycc_convert;
  162501. } else if (cinfo->in_color_space == JCS_YCbCr)
  162502. cconvert->pub.color_convert = null_convert;
  162503. else
  162504. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162505. break;
  162506. case JCS_CMYK:
  162507. if (cinfo->num_components != 4)
  162508. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162509. if (cinfo->in_color_space == JCS_CMYK)
  162510. cconvert->pub.color_convert = null_convert;
  162511. else
  162512. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162513. break;
  162514. case JCS_YCCK:
  162515. if (cinfo->num_components != 4)
  162516. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162517. if (cinfo->in_color_space == JCS_CMYK) {
  162518. cconvert->pub.start_pass = rgb_ycc_start;
  162519. cconvert->pub.color_convert = cmyk_ycck_convert;
  162520. } else if (cinfo->in_color_space == JCS_YCCK)
  162521. cconvert->pub.color_convert = null_convert;
  162522. else
  162523. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162524. break;
  162525. default: /* allow null conversion of JCS_UNKNOWN */
  162526. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162527. cinfo->num_components != cinfo->input_components)
  162528. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162529. cconvert->pub.color_convert = null_convert;
  162530. break;
  162531. }
  162532. }
  162533. /*** End of inlined file: jccolor.c ***/
  162534. #undef FIX
  162535. /*** Start of inlined file: jcdctmgr.c ***/
  162536. #define JPEG_INTERNALS
  162537. /*** Start of inlined file: jdct.h ***/
  162538. /*
  162539. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162540. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162541. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162542. * implementations use an array of type FAST_FLOAT, instead.)
  162543. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162544. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162545. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162546. * convention improves accuracy in integer implementations and saves some
  162547. * work in floating-point ones.
  162548. * Quantization of the output coefficients is done by jcdctmgr.c.
  162549. */
  162550. #ifndef __jdct_h__
  162551. #define __jdct_h__
  162552. #if BITS_IN_JSAMPLE == 8
  162553. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162554. #else
  162555. typedef INT32 DCTELEM; /* must have 32 bits */
  162556. #endif
  162557. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162558. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162559. /*
  162560. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162561. * to an output sample array. The routine must dequantize the input data as
  162562. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162563. * pointed to by compptr->dct_table. The output data is to be placed into the
  162564. * sample array starting at a specified column. (Any row offset needed will
  162565. * be applied to the array pointer before it is passed to the IDCT code.)
  162566. * Note that the number of samples emitted by the IDCT routine is
  162567. * DCT_scaled_size * DCT_scaled_size.
  162568. */
  162569. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162570. /*
  162571. * Each IDCT routine has its own ideas about the best dct_table element type.
  162572. */
  162573. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162574. #if BITS_IN_JSAMPLE == 8
  162575. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162576. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162577. #else
  162578. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162579. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162580. #endif
  162581. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162582. /*
  162583. * Each IDCT routine is responsible for range-limiting its results and
  162584. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162585. * be quite far out of range if the input data is corrupt, so a bulletproof
  162586. * range-limiting step is required. We use a mask-and-table-lookup method
  162587. * to do the combined operations quickly. See the comments with
  162588. * prepare_range_limit_table (in jdmaster.c) for more info.
  162589. */
  162590. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162591. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162592. /* Short forms of external names for systems with brain-damaged linkers. */
  162593. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162594. #define jpeg_fdct_islow jFDislow
  162595. #define jpeg_fdct_ifast jFDifast
  162596. #define jpeg_fdct_float jFDfloat
  162597. #define jpeg_idct_islow jRDislow
  162598. #define jpeg_idct_ifast jRDifast
  162599. #define jpeg_idct_float jRDfloat
  162600. #define jpeg_idct_4x4 jRD4x4
  162601. #define jpeg_idct_2x2 jRD2x2
  162602. #define jpeg_idct_1x1 jRD1x1
  162603. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162604. /* Extern declarations for the forward and inverse DCT routines. */
  162605. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162606. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162607. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162608. EXTERN(void) jpeg_idct_islow
  162609. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162610. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162611. EXTERN(void) jpeg_idct_ifast
  162612. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162613. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162614. EXTERN(void) jpeg_idct_float
  162615. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162616. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162617. EXTERN(void) jpeg_idct_4x4
  162618. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162619. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162620. EXTERN(void) jpeg_idct_2x2
  162621. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162622. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162623. EXTERN(void) jpeg_idct_1x1
  162624. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162625. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162626. /*
  162627. * Macros for handling fixed-point arithmetic; these are used by many
  162628. * but not all of the DCT/IDCT modules.
  162629. *
  162630. * All values are expected to be of type INT32.
  162631. * Fractional constants are scaled left by CONST_BITS bits.
  162632. * CONST_BITS is defined within each module using these macros,
  162633. * and may differ from one module to the next.
  162634. */
  162635. #define ONE ((INT32) 1)
  162636. #define CONST_SCALE (ONE << CONST_BITS)
  162637. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162638. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162639. * thus causing a lot of useless floating-point operations at run time.
  162640. */
  162641. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162642. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162643. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162644. * the fudge factor is correct for either sign of X.
  162645. */
  162646. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162647. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162648. * This macro is used only when the two inputs will actually be no more than
  162649. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162650. * full 32x32 multiply. This provides a useful speedup on many machines.
  162651. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162652. * in C, but some C compilers will do the right thing if you provide the
  162653. * correct combination of casts.
  162654. */
  162655. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162656. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162657. #endif
  162658. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162659. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162660. #endif
  162661. #ifndef MULTIPLY16C16 /* default definition */
  162662. #define MULTIPLY16C16(var,const) ((var) * (const))
  162663. #endif
  162664. /* Same except both inputs are variables. */
  162665. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162666. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162667. #endif
  162668. #ifndef MULTIPLY16V16 /* default definition */
  162669. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162670. #endif
  162671. #endif
  162672. /*** End of inlined file: jdct.h ***/
  162673. /* Private declarations for DCT subsystem */
  162674. /* Private subobject for this module */
  162675. typedef struct {
  162676. struct jpeg_forward_dct pub; /* public fields */
  162677. /* Pointer to the DCT routine actually in use */
  162678. forward_DCT_method_ptr do_dct;
  162679. /* The actual post-DCT divisors --- not identical to the quant table
  162680. * entries, because of scaling (especially for an unnormalized DCT).
  162681. * Each table is given in normal array order.
  162682. */
  162683. DCTELEM * divisors[NUM_QUANT_TBLS];
  162684. #ifdef DCT_FLOAT_SUPPORTED
  162685. /* Same as above for the floating-point case. */
  162686. float_DCT_method_ptr do_float_dct;
  162687. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162688. #endif
  162689. } my_fdct_controller;
  162690. typedef my_fdct_controller * my_fdct_ptr;
  162691. /*
  162692. * Initialize for a processing pass.
  162693. * Verify that all referenced Q-tables are present, and set up
  162694. * the divisor table for each one.
  162695. * In the current implementation, DCT of all components is done during
  162696. * the first pass, even if only some components will be output in the
  162697. * first scan. Hence all components should be examined here.
  162698. */
  162699. METHODDEF(void)
  162700. start_pass_fdctmgr (j_compress_ptr cinfo)
  162701. {
  162702. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162703. int ci, qtblno, i;
  162704. jpeg_component_info *compptr;
  162705. JQUANT_TBL * qtbl;
  162706. DCTELEM * dtbl;
  162707. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162708. ci++, compptr++) {
  162709. qtblno = compptr->quant_tbl_no;
  162710. /* Make sure specified quantization table is present */
  162711. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162712. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162713. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162714. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162715. /* Compute divisors for this quant table */
  162716. /* We may do this more than once for same table, but it's not a big deal */
  162717. switch (cinfo->dct_method) {
  162718. #ifdef DCT_ISLOW_SUPPORTED
  162719. case JDCT_ISLOW:
  162720. /* For LL&M IDCT method, divisors are equal to raw quantization
  162721. * coefficients multiplied by 8 (to counteract scaling).
  162722. */
  162723. if (fdct->divisors[qtblno] == NULL) {
  162724. fdct->divisors[qtblno] = (DCTELEM *)
  162725. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162726. DCTSIZE2 * SIZEOF(DCTELEM));
  162727. }
  162728. dtbl = fdct->divisors[qtblno];
  162729. for (i = 0; i < DCTSIZE2; i++) {
  162730. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162731. }
  162732. break;
  162733. #endif
  162734. #ifdef DCT_IFAST_SUPPORTED
  162735. case JDCT_IFAST:
  162736. {
  162737. /* For AA&N IDCT method, divisors are equal to quantization
  162738. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162739. * scalefactor[0] = 1
  162740. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162741. * We apply a further scale factor of 8.
  162742. */
  162743. #define CONST_BITS 14
  162744. static const INT16 aanscales[DCTSIZE2] = {
  162745. /* precomputed values scaled up by 14 bits */
  162746. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162747. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162748. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162749. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162750. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162751. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162752. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162753. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162754. };
  162755. SHIFT_TEMPS
  162756. if (fdct->divisors[qtblno] == NULL) {
  162757. fdct->divisors[qtblno] = (DCTELEM *)
  162758. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162759. DCTSIZE2 * SIZEOF(DCTELEM));
  162760. }
  162761. dtbl = fdct->divisors[qtblno];
  162762. for (i = 0; i < DCTSIZE2; i++) {
  162763. dtbl[i] = (DCTELEM)
  162764. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162765. (INT32) aanscales[i]),
  162766. CONST_BITS-3);
  162767. }
  162768. }
  162769. break;
  162770. #endif
  162771. #ifdef DCT_FLOAT_SUPPORTED
  162772. case JDCT_FLOAT:
  162773. {
  162774. /* For float AA&N IDCT method, divisors are equal to quantization
  162775. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162776. * scalefactor[0] = 1
  162777. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162778. * We apply a further scale factor of 8.
  162779. * What's actually stored is 1/divisor so that the inner loop can
  162780. * use a multiplication rather than a division.
  162781. */
  162782. FAST_FLOAT * fdtbl;
  162783. int row, col;
  162784. static const double aanscalefactor[DCTSIZE] = {
  162785. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162786. 1.0, 0.785694958, 0.541196100, 0.275899379
  162787. };
  162788. if (fdct->float_divisors[qtblno] == NULL) {
  162789. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162790. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162791. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162792. }
  162793. fdtbl = fdct->float_divisors[qtblno];
  162794. i = 0;
  162795. for (row = 0; row < DCTSIZE; row++) {
  162796. for (col = 0; col < DCTSIZE; col++) {
  162797. fdtbl[i] = (FAST_FLOAT)
  162798. (1.0 / (((double) qtbl->quantval[i] *
  162799. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162800. i++;
  162801. }
  162802. }
  162803. }
  162804. break;
  162805. #endif
  162806. default:
  162807. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162808. break;
  162809. }
  162810. }
  162811. }
  162812. /*
  162813. * Perform forward DCT on one or more blocks of a component.
  162814. *
  162815. * The input samples are taken from the sample_data[] array starting at
  162816. * position start_row/start_col, and moving to the right for any additional
  162817. * blocks. The quantized coefficients are returned in coef_blocks[].
  162818. */
  162819. METHODDEF(void)
  162820. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162821. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162822. JDIMENSION start_row, JDIMENSION start_col,
  162823. JDIMENSION num_blocks)
  162824. /* This version is used for integer DCT implementations. */
  162825. {
  162826. /* This routine is heavily used, so it's worth coding it tightly. */
  162827. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162828. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162829. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162830. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162831. JDIMENSION bi;
  162832. sample_data += start_row; /* fold in the vertical offset once */
  162833. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162834. /* Load data into workspace, applying unsigned->signed conversion */
  162835. { register DCTELEM *workspaceptr;
  162836. register JSAMPROW elemptr;
  162837. register int elemr;
  162838. workspaceptr = workspace;
  162839. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162840. elemptr = sample_data[elemr] + start_col;
  162841. #if DCTSIZE == 8 /* unroll the inner loop */
  162842. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162843. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162844. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162845. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162846. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162847. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162848. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162849. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162850. #else
  162851. { register int elemc;
  162852. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162853. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162854. }
  162855. }
  162856. #endif
  162857. }
  162858. }
  162859. /* Perform the DCT */
  162860. (*do_dct) (workspace);
  162861. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162862. { register DCTELEM temp, qval;
  162863. register int i;
  162864. register JCOEFPTR output_ptr = coef_blocks[bi];
  162865. for (i = 0; i < DCTSIZE2; i++) {
  162866. qval = divisors[i];
  162867. temp = workspace[i];
  162868. /* Divide the coefficient value by qval, ensuring proper rounding.
  162869. * Since C does not specify the direction of rounding for negative
  162870. * quotients, we have to force the dividend positive for portability.
  162871. *
  162872. * In most files, at least half of the output values will be zero
  162873. * (at default quantization settings, more like three-quarters...)
  162874. * so we should ensure that this case is fast. On many machines,
  162875. * a comparison is enough cheaper than a divide to make a special test
  162876. * a win. Since both inputs will be nonnegative, we need only test
  162877. * for a < b to discover whether a/b is 0.
  162878. * If your machine's division is fast enough, define FAST_DIVIDE.
  162879. */
  162880. #ifdef FAST_DIVIDE
  162881. #define DIVIDE_BY(a,b) a /= b
  162882. #else
  162883. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162884. #endif
  162885. if (temp < 0) {
  162886. temp = -temp;
  162887. temp += qval>>1; /* for rounding */
  162888. DIVIDE_BY(temp, qval);
  162889. temp = -temp;
  162890. } else {
  162891. temp += qval>>1; /* for rounding */
  162892. DIVIDE_BY(temp, qval);
  162893. }
  162894. output_ptr[i] = (JCOEF) temp;
  162895. }
  162896. }
  162897. }
  162898. }
  162899. #ifdef DCT_FLOAT_SUPPORTED
  162900. METHODDEF(void)
  162901. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162902. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162903. JDIMENSION start_row, JDIMENSION start_col,
  162904. JDIMENSION num_blocks)
  162905. /* This version is used for floating-point DCT implementations. */
  162906. {
  162907. /* This routine is heavily used, so it's worth coding it tightly. */
  162908. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162909. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162910. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162911. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162912. JDIMENSION bi;
  162913. sample_data += start_row; /* fold in the vertical offset once */
  162914. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162915. /* Load data into workspace, applying unsigned->signed conversion */
  162916. { register FAST_FLOAT *workspaceptr;
  162917. register JSAMPROW elemptr;
  162918. register int elemr;
  162919. workspaceptr = workspace;
  162920. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162921. elemptr = sample_data[elemr] + start_col;
  162922. #if DCTSIZE == 8 /* unroll the inner loop */
  162923. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162924. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162925. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162926. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162927. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162928. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162929. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162930. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162931. #else
  162932. { register int elemc;
  162933. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162934. *workspaceptr++ = (FAST_FLOAT)
  162935. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162936. }
  162937. }
  162938. #endif
  162939. }
  162940. }
  162941. /* Perform the DCT */
  162942. (*do_dct) (workspace);
  162943. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162944. { register FAST_FLOAT temp;
  162945. register int i;
  162946. register JCOEFPTR output_ptr = coef_blocks[bi];
  162947. for (i = 0; i < DCTSIZE2; i++) {
  162948. /* Apply the quantization and scaling factor */
  162949. temp = workspace[i] * divisors[i];
  162950. /* Round to nearest integer.
  162951. * Since C does not specify the direction of rounding for negative
  162952. * quotients, we have to force the dividend positive for portability.
  162953. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162954. * code should work for either 16-bit or 32-bit ints.
  162955. */
  162956. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162957. }
  162958. }
  162959. }
  162960. }
  162961. #endif /* DCT_FLOAT_SUPPORTED */
  162962. /*
  162963. * Initialize FDCT manager.
  162964. */
  162965. GLOBAL(void)
  162966. jinit_forward_dct (j_compress_ptr cinfo)
  162967. {
  162968. my_fdct_ptr fdct;
  162969. int i;
  162970. fdct = (my_fdct_ptr)
  162971. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162972. SIZEOF(my_fdct_controller));
  162973. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162974. fdct->pub.start_pass = start_pass_fdctmgr;
  162975. switch (cinfo->dct_method) {
  162976. #ifdef DCT_ISLOW_SUPPORTED
  162977. case JDCT_ISLOW:
  162978. fdct->pub.forward_DCT = forward_DCT;
  162979. fdct->do_dct = jpeg_fdct_islow;
  162980. break;
  162981. #endif
  162982. #ifdef DCT_IFAST_SUPPORTED
  162983. case JDCT_IFAST:
  162984. fdct->pub.forward_DCT = forward_DCT;
  162985. fdct->do_dct = jpeg_fdct_ifast;
  162986. break;
  162987. #endif
  162988. #ifdef DCT_FLOAT_SUPPORTED
  162989. case JDCT_FLOAT:
  162990. fdct->pub.forward_DCT = forward_DCT_float;
  162991. fdct->do_float_dct = jpeg_fdct_float;
  162992. break;
  162993. #endif
  162994. default:
  162995. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162996. break;
  162997. }
  162998. /* Mark divisor tables unallocated */
  162999. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163000. fdct->divisors[i] = NULL;
  163001. #ifdef DCT_FLOAT_SUPPORTED
  163002. fdct->float_divisors[i] = NULL;
  163003. #endif
  163004. }
  163005. }
  163006. /*** End of inlined file: jcdctmgr.c ***/
  163007. #undef CONST_BITS
  163008. /*** Start of inlined file: jchuff.c ***/
  163009. #define JPEG_INTERNALS
  163010. /*** Start of inlined file: jchuff.h ***/
  163011. /* The legal range of a DCT coefficient is
  163012. * -1024 .. +1023 for 8-bit data;
  163013. * -16384 .. +16383 for 12-bit data.
  163014. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163015. */
  163016. #ifndef _jchuff_h_
  163017. #define _jchuff_h_
  163018. #if BITS_IN_JSAMPLE == 8
  163019. #define MAX_COEF_BITS 10
  163020. #else
  163021. #define MAX_COEF_BITS 14
  163022. #endif
  163023. /* Derived data constructed for each Huffman table */
  163024. typedef struct {
  163025. unsigned int ehufco[256]; /* code for each symbol */
  163026. char ehufsi[256]; /* length of code for each symbol */
  163027. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163028. } c_derived_tbl;
  163029. /* Short forms of external names for systems with brain-damaged linkers. */
  163030. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163031. #define jpeg_make_c_derived_tbl jMkCDerived
  163032. #define jpeg_gen_optimal_table jGenOptTbl
  163033. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163034. /* Expand a Huffman table definition into the derived format */
  163035. EXTERN(void) jpeg_make_c_derived_tbl
  163036. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163037. c_derived_tbl ** pdtbl));
  163038. /* Generate an optimal table definition given the specified counts */
  163039. EXTERN(void) jpeg_gen_optimal_table
  163040. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163041. #endif
  163042. /*** End of inlined file: jchuff.h ***/
  163043. /* Declarations shared with jcphuff.c */
  163044. /* Expanded entropy encoder object for Huffman encoding.
  163045. *
  163046. * The savable_state subrecord contains fields that change within an MCU,
  163047. * but must not be updated permanently until we complete the MCU.
  163048. */
  163049. typedef struct {
  163050. INT32 put_buffer; /* current bit-accumulation buffer */
  163051. int put_bits; /* # of bits now in it */
  163052. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163053. } savable_state;
  163054. /* This macro is to work around compilers with missing or broken
  163055. * structure assignment. You'll need to fix this code if you have
  163056. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163057. */
  163058. #ifndef NO_STRUCT_ASSIGN
  163059. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163060. #else
  163061. #if MAX_COMPS_IN_SCAN == 4
  163062. #define ASSIGN_STATE(dest,src) \
  163063. ((dest).put_buffer = (src).put_buffer, \
  163064. (dest).put_bits = (src).put_bits, \
  163065. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163066. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163067. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163068. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163069. #endif
  163070. #endif
  163071. typedef struct {
  163072. struct jpeg_entropy_encoder pub; /* public fields */
  163073. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163074. /* These fields are NOT loaded into local working state. */
  163075. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163076. int next_restart_num; /* next restart number to write (0-7) */
  163077. /* Pointers to derived tables (these workspaces have image lifespan) */
  163078. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163079. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163080. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163081. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163082. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163083. #endif
  163084. } huff_entropy_encoder;
  163085. typedef huff_entropy_encoder * huff_entropy_ptr;
  163086. /* Working state while writing an MCU.
  163087. * This struct contains all the fields that are needed by subroutines.
  163088. */
  163089. typedef struct {
  163090. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163091. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163092. savable_state cur; /* Current bit buffer & DC state */
  163093. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163094. } working_state;
  163095. /* Forward declarations */
  163096. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163097. JBLOCKROW *MCU_data));
  163098. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163099. #ifdef ENTROPY_OPT_SUPPORTED
  163100. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163101. JBLOCKROW *MCU_data));
  163102. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163103. #endif
  163104. /*
  163105. * Initialize for a Huffman-compressed scan.
  163106. * If gather_statistics is TRUE, we do not output anything during the scan,
  163107. * just count the Huffman symbols used and generate Huffman code tables.
  163108. */
  163109. METHODDEF(void)
  163110. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163111. {
  163112. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163113. int ci, dctbl, actbl;
  163114. jpeg_component_info * compptr;
  163115. if (gather_statistics) {
  163116. #ifdef ENTROPY_OPT_SUPPORTED
  163117. entropy->pub.encode_mcu = encode_mcu_gather;
  163118. entropy->pub.finish_pass = finish_pass_gather;
  163119. #else
  163120. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163121. #endif
  163122. } else {
  163123. entropy->pub.encode_mcu = encode_mcu_huff;
  163124. entropy->pub.finish_pass = finish_pass_huff;
  163125. }
  163126. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163127. compptr = cinfo->cur_comp_info[ci];
  163128. dctbl = compptr->dc_tbl_no;
  163129. actbl = compptr->ac_tbl_no;
  163130. if (gather_statistics) {
  163131. #ifdef ENTROPY_OPT_SUPPORTED
  163132. /* Check for invalid table indexes */
  163133. /* (make_c_derived_tbl does this in the other path) */
  163134. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163135. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163136. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163137. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163138. /* Allocate and zero the statistics tables */
  163139. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163140. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163141. entropy->dc_count_ptrs[dctbl] = (long *)
  163142. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163143. 257 * SIZEOF(long));
  163144. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163145. if (entropy->ac_count_ptrs[actbl] == NULL)
  163146. entropy->ac_count_ptrs[actbl] = (long *)
  163147. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163148. 257 * SIZEOF(long));
  163149. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163150. #endif
  163151. } else {
  163152. /* Compute derived values for Huffman tables */
  163153. /* We may do this more than once for a table, but it's not expensive */
  163154. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163155. & entropy->dc_derived_tbls[dctbl]);
  163156. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163157. & entropy->ac_derived_tbls[actbl]);
  163158. }
  163159. /* Initialize DC predictions to 0 */
  163160. entropy->saved.last_dc_val[ci] = 0;
  163161. }
  163162. /* Initialize bit buffer to empty */
  163163. entropy->saved.put_buffer = 0;
  163164. entropy->saved.put_bits = 0;
  163165. /* Initialize restart stuff */
  163166. entropy->restarts_to_go = cinfo->restart_interval;
  163167. entropy->next_restart_num = 0;
  163168. }
  163169. /*
  163170. * Compute the derived values for a Huffman table.
  163171. * This routine also performs some validation checks on the table.
  163172. *
  163173. * Note this is also used by jcphuff.c.
  163174. */
  163175. GLOBAL(void)
  163176. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163177. c_derived_tbl ** pdtbl)
  163178. {
  163179. JHUFF_TBL *htbl;
  163180. c_derived_tbl *dtbl;
  163181. int p, i, l, lastp, si, maxsymbol;
  163182. char huffsize[257];
  163183. unsigned int huffcode[257];
  163184. unsigned int code;
  163185. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163186. * paralleling the order of the symbols themselves in htbl->huffval[].
  163187. */
  163188. /* Find the input Huffman table */
  163189. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163190. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163191. htbl =
  163192. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163193. if (htbl == NULL)
  163194. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163195. /* Allocate a workspace if we haven't already done so. */
  163196. if (*pdtbl == NULL)
  163197. *pdtbl = (c_derived_tbl *)
  163198. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163199. SIZEOF(c_derived_tbl));
  163200. dtbl = *pdtbl;
  163201. /* Figure C.1: make table of Huffman code length for each symbol */
  163202. p = 0;
  163203. for (l = 1; l <= 16; l++) {
  163204. i = (int) htbl->bits[l];
  163205. if (i < 0 || p + i > 256) /* protect against table overrun */
  163206. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163207. while (i--)
  163208. huffsize[p++] = (char) l;
  163209. }
  163210. huffsize[p] = 0;
  163211. lastp = p;
  163212. /* Figure C.2: generate the codes themselves */
  163213. /* We also validate that the counts represent a legal Huffman code tree. */
  163214. code = 0;
  163215. si = huffsize[0];
  163216. p = 0;
  163217. while (huffsize[p]) {
  163218. while (((int) huffsize[p]) == si) {
  163219. huffcode[p++] = code;
  163220. code++;
  163221. }
  163222. /* code is now 1 more than the last code used for codelength si; but
  163223. * it must still fit in si bits, since no code is allowed to be all ones.
  163224. */
  163225. if (((INT32) code) >= (((INT32) 1) << si))
  163226. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163227. code <<= 1;
  163228. si++;
  163229. }
  163230. /* Figure C.3: generate encoding tables */
  163231. /* These are code and size indexed by symbol value */
  163232. /* Set all codeless symbols to have code length 0;
  163233. * this lets us detect duplicate VAL entries here, and later
  163234. * allows emit_bits to detect any attempt to emit such symbols.
  163235. */
  163236. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163237. /* This is also a convenient place to check for out-of-range
  163238. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163239. * but only 0..15 for DC. (We could constrain them further
  163240. * based on data depth and mode, but this seems enough.)
  163241. */
  163242. maxsymbol = isDC ? 15 : 255;
  163243. for (p = 0; p < lastp; p++) {
  163244. i = htbl->huffval[p];
  163245. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163246. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163247. dtbl->ehufco[i] = huffcode[p];
  163248. dtbl->ehufsi[i] = huffsize[p];
  163249. }
  163250. }
  163251. /* Outputting bytes to the file */
  163252. /* Emit a byte, taking 'action' if must suspend. */
  163253. #define emit_byte(state,val,action) \
  163254. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163255. if (--(state)->free_in_buffer == 0) \
  163256. if (! dump_buffer(state)) \
  163257. { action; } }
  163258. LOCAL(boolean)
  163259. dump_buffer (working_state * state)
  163260. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163261. {
  163262. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163263. if (! (*dest->empty_output_buffer) (state->cinfo))
  163264. return FALSE;
  163265. /* After a successful buffer dump, must reset buffer pointers */
  163266. state->next_output_byte = dest->next_output_byte;
  163267. state->free_in_buffer = dest->free_in_buffer;
  163268. return TRUE;
  163269. }
  163270. /* Outputting bits to the file */
  163271. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163272. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163273. * in one call, and we never retain more than 7 bits in put_buffer
  163274. * between calls, so 24 bits are sufficient.
  163275. */
  163276. INLINE
  163277. LOCAL(boolean)
  163278. emit_bits (working_state * state, unsigned int code, int size)
  163279. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163280. {
  163281. /* This routine is heavily used, so it's worth coding tightly. */
  163282. register INT32 put_buffer = (INT32) code;
  163283. register int put_bits = state->cur.put_bits;
  163284. /* if size is 0, caller used an invalid Huffman table entry */
  163285. if (size == 0)
  163286. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163287. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163288. put_bits += size; /* new number of bits in buffer */
  163289. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163290. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163291. while (put_bits >= 8) {
  163292. int c = (int) ((put_buffer >> 16) & 0xFF);
  163293. emit_byte(state, c, return FALSE);
  163294. if (c == 0xFF) { /* need to stuff a zero byte? */
  163295. emit_byte(state, 0, return FALSE);
  163296. }
  163297. put_buffer <<= 8;
  163298. put_bits -= 8;
  163299. }
  163300. state->cur.put_buffer = put_buffer; /* update state variables */
  163301. state->cur.put_bits = put_bits;
  163302. return TRUE;
  163303. }
  163304. LOCAL(boolean)
  163305. flush_bits (working_state * state)
  163306. {
  163307. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163308. return FALSE;
  163309. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163310. state->cur.put_bits = 0;
  163311. return TRUE;
  163312. }
  163313. /* Encode a single block's worth of coefficients */
  163314. LOCAL(boolean)
  163315. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163316. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163317. {
  163318. register int temp, temp2;
  163319. register int nbits;
  163320. register int k, r, i;
  163321. /* Encode the DC coefficient difference per section F.1.2.1 */
  163322. temp = temp2 = block[0] - last_dc_val;
  163323. if (temp < 0) {
  163324. temp = -temp; /* temp is abs value of input */
  163325. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163326. /* This code assumes we are on a two's complement machine */
  163327. temp2--;
  163328. }
  163329. /* Find the number of bits needed for the magnitude of the coefficient */
  163330. nbits = 0;
  163331. while (temp) {
  163332. nbits++;
  163333. temp >>= 1;
  163334. }
  163335. /* Check for out-of-range coefficient values.
  163336. * Since we're encoding a difference, the range limit is twice as much.
  163337. */
  163338. if (nbits > MAX_COEF_BITS+1)
  163339. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163340. /* Emit the Huffman-coded symbol for the number of bits */
  163341. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163342. return FALSE;
  163343. /* Emit that number of bits of the value, if positive, */
  163344. /* or the complement of its magnitude, if negative. */
  163345. if (nbits) /* emit_bits rejects calls with size 0 */
  163346. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163347. return FALSE;
  163348. /* Encode the AC coefficients per section F.1.2.2 */
  163349. r = 0; /* r = run length of zeros */
  163350. for (k = 1; k < DCTSIZE2; k++) {
  163351. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163352. r++;
  163353. } else {
  163354. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163355. while (r > 15) {
  163356. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163357. return FALSE;
  163358. r -= 16;
  163359. }
  163360. temp2 = temp;
  163361. if (temp < 0) {
  163362. temp = -temp; /* temp is abs value of input */
  163363. /* This code assumes we are on a two's complement machine */
  163364. temp2--;
  163365. }
  163366. /* Find the number of bits needed for the magnitude of the coefficient */
  163367. nbits = 1; /* there must be at least one 1 bit */
  163368. while ((temp >>= 1))
  163369. nbits++;
  163370. /* Check for out-of-range coefficient values */
  163371. if (nbits > MAX_COEF_BITS)
  163372. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163373. /* Emit Huffman symbol for run length / number of bits */
  163374. i = (r << 4) + nbits;
  163375. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163376. return FALSE;
  163377. /* Emit that number of bits of the value, if positive, */
  163378. /* or the complement of its magnitude, if negative. */
  163379. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163380. return FALSE;
  163381. r = 0;
  163382. }
  163383. }
  163384. /* If the last coef(s) were zero, emit an end-of-block code */
  163385. if (r > 0)
  163386. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163387. return FALSE;
  163388. return TRUE;
  163389. }
  163390. /*
  163391. * Emit a restart marker & resynchronize predictions.
  163392. */
  163393. LOCAL(boolean)
  163394. emit_restart (working_state * state, int restart_num)
  163395. {
  163396. int ci;
  163397. if (! flush_bits(state))
  163398. return FALSE;
  163399. emit_byte(state, 0xFF, return FALSE);
  163400. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163401. /* Re-initialize DC predictions to 0 */
  163402. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163403. state->cur.last_dc_val[ci] = 0;
  163404. /* The restart counter is not updated until we successfully write the MCU. */
  163405. return TRUE;
  163406. }
  163407. /*
  163408. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163409. */
  163410. METHODDEF(boolean)
  163411. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163412. {
  163413. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163414. working_state state;
  163415. int blkn, ci;
  163416. jpeg_component_info * compptr;
  163417. /* Load up working state */
  163418. state.next_output_byte = cinfo->dest->next_output_byte;
  163419. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163420. ASSIGN_STATE(state.cur, entropy->saved);
  163421. state.cinfo = cinfo;
  163422. /* Emit restart marker if needed */
  163423. if (cinfo->restart_interval) {
  163424. if (entropy->restarts_to_go == 0)
  163425. if (! emit_restart(&state, entropy->next_restart_num))
  163426. return FALSE;
  163427. }
  163428. /* Encode the MCU data blocks */
  163429. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163430. ci = cinfo->MCU_membership[blkn];
  163431. compptr = cinfo->cur_comp_info[ci];
  163432. if (! encode_one_block(&state,
  163433. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163434. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163435. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163436. return FALSE;
  163437. /* Update last_dc_val */
  163438. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163439. }
  163440. /* Completed MCU, so update state */
  163441. cinfo->dest->next_output_byte = state.next_output_byte;
  163442. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163443. ASSIGN_STATE(entropy->saved, state.cur);
  163444. /* Update restart-interval state too */
  163445. if (cinfo->restart_interval) {
  163446. if (entropy->restarts_to_go == 0) {
  163447. entropy->restarts_to_go = cinfo->restart_interval;
  163448. entropy->next_restart_num++;
  163449. entropy->next_restart_num &= 7;
  163450. }
  163451. entropy->restarts_to_go--;
  163452. }
  163453. return TRUE;
  163454. }
  163455. /*
  163456. * Finish up at the end of a Huffman-compressed scan.
  163457. */
  163458. METHODDEF(void)
  163459. finish_pass_huff (j_compress_ptr cinfo)
  163460. {
  163461. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163462. working_state state;
  163463. /* Load up working state ... flush_bits needs it */
  163464. state.next_output_byte = cinfo->dest->next_output_byte;
  163465. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163466. ASSIGN_STATE(state.cur, entropy->saved);
  163467. state.cinfo = cinfo;
  163468. /* Flush out the last data */
  163469. if (! flush_bits(&state))
  163470. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163471. /* Update state */
  163472. cinfo->dest->next_output_byte = state.next_output_byte;
  163473. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163474. ASSIGN_STATE(entropy->saved, state.cur);
  163475. }
  163476. /*
  163477. * Huffman coding optimization.
  163478. *
  163479. * We first scan the supplied data and count the number of uses of each symbol
  163480. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163481. * Then we build a Huffman coding tree for the observed counts.
  163482. * Symbols which are not needed at all for the particular image are not
  163483. * assigned any code, which saves space in the DHT marker as well as in
  163484. * the compressed data.
  163485. */
  163486. #ifdef ENTROPY_OPT_SUPPORTED
  163487. /* Process a single block's worth of coefficients */
  163488. LOCAL(void)
  163489. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163490. long dc_counts[], long ac_counts[])
  163491. {
  163492. register int temp;
  163493. register int nbits;
  163494. register int k, r;
  163495. /* Encode the DC coefficient difference per section F.1.2.1 */
  163496. temp = block[0] - last_dc_val;
  163497. if (temp < 0)
  163498. temp = -temp;
  163499. /* Find the number of bits needed for the magnitude of the coefficient */
  163500. nbits = 0;
  163501. while (temp) {
  163502. nbits++;
  163503. temp >>= 1;
  163504. }
  163505. /* Check for out-of-range coefficient values.
  163506. * Since we're encoding a difference, the range limit is twice as much.
  163507. */
  163508. if (nbits > MAX_COEF_BITS+1)
  163509. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163510. /* Count the Huffman symbol for the number of bits */
  163511. dc_counts[nbits]++;
  163512. /* Encode the AC coefficients per section F.1.2.2 */
  163513. r = 0; /* r = run length of zeros */
  163514. for (k = 1; k < DCTSIZE2; k++) {
  163515. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163516. r++;
  163517. } else {
  163518. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163519. while (r > 15) {
  163520. ac_counts[0xF0]++;
  163521. r -= 16;
  163522. }
  163523. /* Find the number of bits needed for the magnitude of the coefficient */
  163524. if (temp < 0)
  163525. temp = -temp;
  163526. /* Find the number of bits needed for the magnitude of the coefficient */
  163527. nbits = 1; /* there must be at least one 1 bit */
  163528. while ((temp >>= 1))
  163529. nbits++;
  163530. /* Check for out-of-range coefficient values */
  163531. if (nbits > MAX_COEF_BITS)
  163532. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163533. /* Count Huffman symbol for run length / number of bits */
  163534. ac_counts[(r << 4) + nbits]++;
  163535. r = 0;
  163536. }
  163537. }
  163538. /* If the last coef(s) were zero, emit an end-of-block code */
  163539. if (r > 0)
  163540. ac_counts[0]++;
  163541. }
  163542. /*
  163543. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163544. * No data is actually output, so no suspension return is possible.
  163545. */
  163546. METHODDEF(boolean)
  163547. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163548. {
  163549. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163550. int blkn, ci;
  163551. jpeg_component_info * compptr;
  163552. /* Take care of restart intervals if needed */
  163553. if (cinfo->restart_interval) {
  163554. if (entropy->restarts_to_go == 0) {
  163555. /* Re-initialize DC predictions to 0 */
  163556. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163557. entropy->saved.last_dc_val[ci] = 0;
  163558. /* Update restart state */
  163559. entropy->restarts_to_go = cinfo->restart_interval;
  163560. }
  163561. entropy->restarts_to_go--;
  163562. }
  163563. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163564. ci = cinfo->MCU_membership[blkn];
  163565. compptr = cinfo->cur_comp_info[ci];
  163566. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163567. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163568. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163569. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163570. }
  163571. return TRUE;
  163572. }
  163573. /*
  163574. * Generate the best Huffman code table for the given counts, fill htbl.
  163575. * Note this is also used by jcphuff.c.
  163576. *
  163577. * The JPEG standard requires that no symbol be assigned a codeword of all
  163578. * one bits (so that padding bits added at the end of a compressed segment
  163579. * can't look like a valid code). Because of the canonical ordering of
  163580. * codewords, this just means that there must be an unused slot in the
  163581. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163582. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163583. * with count 1. In theory that's not optimal; giving it count zero but
  163584. * including it in the symbol set anyway should give a better Huffman code.
  163585. * But the theoretically better code actually seems to come out worse in
  163586. * practice, because it produces more all-ones bytes (which incur stuffed
  163587. * zero bytes in the final file). In any case the difference is tiny.
  163588. *
  163589. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163590. * If some symbols have a very small but nonzero probability, the Huffman tree
  163591. * must be adjusted to meet the code length restriction. We currently use
  163592. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163593. * optimal; it may not choose the best possible limited-length code. But
  163594. * typically only very-low-frequency symbols will be given less-than-optimal
  163595. * lengths, so the code is almost optimal. Experimental comparisons against
  163596. * an optimal limited-length-code algorithm indicate that the difference is
  163597. * microscopic --- usually less than a hundredth of a percent of total size.
  163598. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163599. */
  163600. GLOBAL(void)
  163601. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163602. {
  163603. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163604. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163605. int codesize[257]; /* codesize[k] = code length of symbol k */
  163606. int others[257]; /* next symbol in current branch of tree */
  163607. int c1, c2;
  163608. int p, i, j;
  163609. long v;
  163610. /* This algorithm is explained in section K.2 of the JPEG standard */
  163611. MEMZERO(bits, SIZEOF(bits));
  163612. MEMZERO(codesize, SIZEOF(codesize));
  163613. for (i = 0; i < 257; i++)
  163614. others[i] = -1; /* init links to empty */
  163615. freq[256] = 1; /* make sure 256 has a nonzero count */
  163616. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163617. * that no real symbol is given code-value of all ones, because 256
  163618. * will be placed last in the largest codeword category.
  163619. */
  163620. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163621. for (;;) {
  163622. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163623. /* In case of ties, take the larger symbol number */
  163624. c1 = -1;
  163625. v = 1000000000L;
  163626. for (i = 0; i <= 256; i++) {
  163627. if (freq[i] && freq[i] <= v) {
  163628. v = freq[i];
  163629. c1 = i;
  163630. }
  163631. }
  163632. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163633. /* In case of ties, take the larger symbol number */
  163634. c2 = -1;
  163635. v = 1000000000L;
  163636. for (i = 0; i <= 256; i++) {
  163637. if (freq[i] && freq[i] <= v && i != c1) {
  163638. v = freq[i];
  163639. c2 = i;
  163640. }
  163641. }
  163642. /* Done if we've merged everything into one frequency */
  163643. if (c2 < 0)
  163644. break;
  163645. /* Else merge the two counts/trees */
  163646. freq[c1] += freq[c2];
  163647. freq[c2] = 0;
  163648. /* Increment the codesize of everything in c1's tree branch */
  163649. codesize[c1]++;
  163650. while (others[c1] >= 0) {
  163651. c1 = others[c1];
  163652. codesize[c1]++;
  163653. }
  163654. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163655. /* Increment the codesize of everything in c2's tree branch */
  163656. codesize[c2]++;
  163657. while (others[c2] >= 0) {
  163658. c2 = others[c2];
  163659. codesize[c2]++;
  163660. }
  163661. }
  163662. /* Now count the number of symbols of each code length */
  163663. for (i = 0; i <= 256; i++) {
  163664. if (codesize[i]) {
  163665. /* The JPEG standard seems to think that this can't happen, */
  163666. /* but I'm paranoid... */
  163667. if (codesize[i] > MAX_CLEN)
  163668. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163669. bits[codesize[i]]++;
  163670. }
  163671. }
  163672. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163673. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163674. * Here is what the JPEG spec says about how this next bit works:
  163675. * Since symbols are paired for the longest Huffman code, the symbols are
  163676. * removed from this length category two at a time. The prefix for the pair
  163677. * (which is one bit shorter) is allocated to one of the pair; then,
  163678. * skipping the BITS entry for that prefix length, a code word from the next
  163679. * shortest nonzero BITS entry is converted into a prefix for two code words
  163680. * one bit longer.
  163681. */
  163682. for (i = MAX_CLEN; i > 16; i--) {
  163683. while (bits[i] > 0) {
  163684. j = i - 2; /* find length of new prefix to be used */
  163685. while (bits[j] == 0)
  163686. j--;
  163687. bits[i] -= 2; /* remove two symbols */
  163688. bits[i-1]++; /* one goes in this length */
  163689. bits[j+1] += 2; /* two new symbols in this length */
  163690. bits[j]--; /* symbol of this length is now a prefix */
  163691. }
  163692. }
  163693. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163694. while (bits[i] == 0) /* find largest codelength still in use */
  163695. i--;
  163696. bits[i]--;
  163697. /* Return final symbol counts (only for lengths 0..16) */
  163698. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163699. /* Return a list of the symbols sorted by code length */
  163700. /* It's not real clear to me why we don't need to consider the codelength
  163701. * changes made above, but the JPEG spec seems to think this works.
  163702. */
  163703. p = 0;
  163704. for (i = 1; i <= MAX_CLEN; i++) {
  163705. for (j = 0; j <= 255; j++) {
  163706. if (codesize[j] == i) {
  163707. htbl->huffval[p] = (UINT8) j;
  163708. p++;
  163709. }
  163710. }
  163711. }
  163712. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163713. htbl->sent_table = FALSE;
  163714. }
  163715. /*
  163716. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163717. */
  163718. METHODDEF(void)
  163719. finish_pass_gather (j_compress_ptr cinfo)
  163720. {
  163721. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163722. int ci, dctbl, actbl;
  163723. jpeg_component_info * compptr;
  163724. JHUFF_TBL **htblptr;
  163725. boolean did_dc[NUM_HUFF_TBLS];
  163726. boolean did_ac[NUM_HUFF_TBLS];
  163727. /* It's important not to apply jpeg_gen_optimal_table more than once
  163728. * per table, because it clobbers the input frequency counts!
  163729. */
  163730. MEMZERO(did_dc, SIZEOF(did_dc));
  163731. MEMZERO(did_ac, SIZEOF(did_ac));
  163732. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163733. compptr = cinfo->cur_comp_info[ci];
  163734. dctbl = compptr->dc_tbl_no;
  163735. actbl = compptr->ac_tbl_no;
  163736. if (! did_dc[dctbl]) {
  163737. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163738. if (*htblptr == NULL)
  163739. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163740. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163741. did_dc[dctbl] = TRUE;
  163742. }
  163743. if (! did_ac[actbl]) {
  163744. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163745. if (*htblptr == NULL)
  163746. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163747. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163748. did_ac[actbl] = TRUE;
  163749. }
  163750. }
  163751. }
  163752. #endif /* ENTROPY_OPT_SUPPORTED */
  163753. /*
  163754. * Module initialization routine for Huffman entropy encoding.
  163755. */
  163756. GLOBAL(void)
  163757. jinit_huff_encoder (j_compress_ptr cinfo)
  163758. {
  163759. huff_entropy_ptr entropy;
  163760. int i;
  163761. entropy = (huff_entropy_ptr)
  163762. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163763. SIZEOF(huff_entropy_encoder));
  163764. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163765. entropy->pub.start_pass = start_pass_huff;
  163766. /* Mark tables unallocated */
  163767. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163768. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163769. #ifdef ENTROPY_OPT_SUPPORTED
  163770. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163771. #endif
  163772. }
  163773. }
  163774. /*** End of inlined file: jchuff.c ***/
  163775. #undef emit_byte
  163776. /*** Start of inlined file: jcinit.c ***/
  163777. #define JPEG_INTERNALS
  163778. /*
  163779. * Master selection of compression modules.
  163780. * This is done once at the start of processing an image. We determine
  163781. * which modules will be used and give them appropriate initialization calls.
  163782. */
  163783. GLOBAL(void)
  163784. jinit_compress_master (j_compress_ptr cinfo)
  163785. {
  163786. /* Initialize master control (includes parameter checking/processing) */
  163787. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163788. /* Preprocessing */
  163789. if (! cinfo->raw_data_in) {
  163790. jinit_color_converter(cinfo);
  163791. jinit_downsampler(cinfo);
  163792. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163793. }
  163794. /* Forward DCT */
  163795. jinit_forward_dct(cinfo);
  163796. /* Entropy encoding: either Huffman or arithmetic coding. */
  163797. if (cinfo->arith_code) {
  163798. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163799. } else {
  163800. if (cinfo->progressive_mode) {
  163801. #ifdef C_PROGRESSIVE_SUPPORTED
  163802. jinit_phuff_encoder(cinfo);
  163803. #else
  163804. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163805. #endif
  163806. } else
  163807. jinit_huff_encoder(cinfo);
  163808. }
  163809. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163810. jinit_c_coef_controller(cinfo,
  163811. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163812. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163813. jinit_marker_writer(cinfo);
  163814. /* We can now tell the memory manager to allocate virtual arrays. */
  163815. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163816. /* Write the datastream header (SOI) immediately.
  163817. * Frame and scan headers are postponed till later.
  163818. * This lets application insert special markers after the SOI.
  163819. */
  163820. (*cinfo->marker->write_file_header) (cinfo);
  163821. }
  163822. /*** End of inlined file: jcinit.c ***/
  163823. /*** Start of inlined file: jcmainct.c ***/
  163824. #define JPEG_INTERNALS
  163825. /* Note: currently, there is no operating mode in which a full-image buffer
  163826. * is needed at this step. If there were, that mode could not be used with
  163827. * "raw data" input, since this module is bypassed in that case. However,
  163828. * we've left the code here for possible use in special applications.
  163829. */
  163830. #undef FULL_MAIN_BUFFER_SUPPORTED
  163831. /* Private buffer controller object */
  163832. typedef struct {
  163833. struct jpeg_c_main_controller pub; /* public fields */
  163834. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163835. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163836. boolean suspended; /* remember if we suspended output */
  163837. J_BUF_MODE pass_mode; /* current operating mode */
  163838. /* If using just a strip buffer, this points to the entire set of buffers
  163839. * (we allocate one for each component). In the full-image case, this
  163840. * points to the currently accessible strips of the virtual arrays.
  163841. */
  163842. JSAMPARRAY buffer[MAX_COMPONENTS];
  163843. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163844. /* If using full-image storage, this array holds pointers to virtual-array
  163845. * control blocks for each component. Unused if not full-image storage.
  163846. */
  163847. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163848. #endif
  163849. } my_main_controller;
  163850. typedef my_main_controller * my_main_ptr;
  163851. /* Forward declarations */
  163852. METHODDEF(void) process_data_simple_main
  163853. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163854. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163855. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163856. METHODDEF(void) process_data_buffer_main
  163857. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163858. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163859. #endif
  163860. /*
  163861. * Initialize for a processing pass.
  163862. */
  163863. METHODDEF(void)
  163864. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163865. {
  163866. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163867. /* Do nothing in raw-data mode. */
  163868. if (cinfo->raw_data_in)
  163869. return;
  163870. main_->cur_iMCU_row = 0; /* initialize counters */
  163871. main_->rowgroup_ctr = 0;
  163872. main_->suspended = FALSE;
  163873. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163874. switch (pass_mode) {
  163875. case JBUF_PASS_THRU:
  163876. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163877. if (main_->whole_image[0] != NULL)
  163878. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163879. #endif
  163880. main_->pub.process_data = process_data_simple_main;
  163881. break;
  163882. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163883. case JBUF_SAVE_SOURCE:
  163884. case JBUF_CRANK_DEST:
  163885. case JBUF_SAVE_AND_PASS:
  163886. if (main_->whole_image[0] == NULL)
  163887. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163888. main_->pub.process_data = process_data_buffer_main;
  163889. break;
  163890. #endif
  163891. default:
  163892. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163893. break;
  163894. }
  163895. }
  163896. /*
  163897. * Process some data.
  163898. * This routine handles the simple pass-through mode,
  163899. * where we have only a strip buffer.
  163900. */
  163901. METHODDEF(void)
  163902. process_data_simple_main (j_compress_ptr cinfo,
  163903. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163904. JDIMENSION in_rows_avail)
  163905. {
  163906. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163907. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163908. /* Read input data if we haven't filled the main buffer yet */
  163909. if (main_->rowgroup_ctr < DCTSIZE)
  163910. (*cinfo->prep->pre_process_data) (cinfo,
  163911. input_buf, in_row_ctr, in_rows_avail,
  163912. main_->buffer, &main_->rowgroup_ctr,
  163913. (JDIMENSION) DCTSIZE);
  163914. /* If we don't have a full iMCU row buffered, return to application for
  163915. * more data. Note that preprocessor will always pad to fill the iMCU row
  163916. * at the bottom of the image.
  163917. */
  163918. if (main_->rowgroup_ctr != DCTSIZE)
  163919. return;
  163920. /* Send the completed row to the compressor */
  163921. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163922. /* If compressor did not consume the whole row, then we must need to
  163923. * suspend processing and return to the application. In this situation
  163924. * we pretend we didn't yet consume the last input row; otherwise, if
  163925. * it happened to be the last row of the image, the application would
  163926. * think we were done.
  163927. */
  163928. if (! main_->suspended) {
  163929. (*in_row_ctr)--;
  163930. main_->suspended = TRUE;
  163931. }
  163932. return;
  163933. }
  163934. /* We did finish the row. Undo our little suspension hack if a previous
  163935. * call suspended; then mark the main buffer empty.
  163936. */
  163937. if (main_->suspended) {
  163938. (*in_row_ctr)++;
  163939. main_->suspended = FALSE;
  163940. }
  163941. main_->rowgroup_ctr = 0;
  163942. main_->cur_iMCU_row++;
  163943. }
  163944. }
  163945. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163946. /*
  163947. * Process some data.
  163948. * This routine handles all of the modes that use a full-size buffer.
  163949. */
  163950. METHODDEF(void)
  163951. process_data_buffer_main (j_compress_ptr cinfo,
  163952. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163953. JDIMENSION in_rows_avail)
  163954. {
  163955. my_main_ptr main = (my_main_ptr) cinfo->main;
  163956. int ci;
  163957. jpeg_component_info *compptr;
  163958. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163959. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163960. /* Realign the virtual buffers if at the start of an iMCU row. */
  163961. if (main->rowgroup_ctr == 0) {
  163962. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163963. ci++, compptr++) {
  163964. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163965. ((j_common_ptr) cinfo, main->whole_image[ci],
  163966. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163967. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163968. }
  163969. /* In a read pass, pretend we just read some source data. */
  163970. if (! writing) {
  163971. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163972. main->rowgroup_ctr = DCTSIZE;
  163973. }
  163974. }
  163975. /* If a write pass, read input data until the current iMCU row is full. */
  163976. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163977. if (writing) {
  163978. (*cinfo->prep->pre_process_data) (cinfo,
  163979. input_buf, in_row_ctr, in_rows_avail,
  163980. main->buffer, &main->rowgroup_ctr,
  163981. (JDIMENSION) DCTSIZE);
  163982. /* Return to application if we need more data to fill the iMCU row. */
  163983. if (main->rowgroup_ctr < DCTSIZE)
  163984. return;
  163985. }
  163986. /* Emit data, unless this is a sink-only pass. */
  163987. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163988. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163989. /* If compressor did not consume the whole row, then we must need to
  163990. * suspend processing and return to the application. In this situation
  163991. * we pretend we didn't yet consume the last input row; otherwise, if
  163992. * it happened to be the last row of the image, the application would
  163993. * think we were done.
  163994. */
  163995. if (! main->suspended) {
  163996. (*in_row_ctr)--;
  163997. main->suspended = TRUE;
  163998. }
  163999. return;
  164000. }
  164001. /* We did finish the row. Undo our little suspension hack if a previous
  164002. * call suspended; then mark the main buffer empty.
  164003. */
  164004. if (main->suspended) {
  164005. (*in_row_ctr)++;
  164006. main->suspended = FALSE;
  164007. }
  164008. }
  164009. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164010. main->rowgroup_ctr = 0;
  164011. main->cur_iMCU_row++;
  164012. }
  164013. }
  164014. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164015. /*
  164016. * Initialize main buffer controller.
  164017. */
  164018. GLOBAL(void)
  164019. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164020. {
  164021. my_main_ptr main_;
  164022. int ci;
  164023. jpeg_component_info *compptr;
  164024. main_ = (my_main_ptr)
  164025. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164026. SIZEOF(my_main_controller));
  164027. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164028. main_->pub.start_pass = start_pass_main;
  164029. /* We don't need to create a buffer in raw-data mode. */
  164030. if (cinfo->raw_data_in)
  164031. return;
  164032. /* Create the buffer. It holds downsampled data, so each component
  164033. * may be of a different size.
  164034. */
  164035. if (need_full_buffer) {
  164036. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164037. /* Allocate a full-image virtual array for each component */
  164038. /* Note we pad the bottom to a multiple of the iMCU height */
  164039. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164040. ci++, compptr++) {
  164041. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164042. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164043. compptr->width_in_blocks * DCTSIZE,
  164044. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164045. (long) compptr->v_samp_factor) * DCTSIZE,
  164046. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164047. }
  164048. #else
  164049. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164050. #endif
  164051. } else {
  164052. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164053. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164054. #endif
  164055. /* Allocate a strip buffer for each component */
  164056. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164057. ci++, compptr++) {
  164058. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164059. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164060. compptr->width_in_blocks * DCTSIZE,
  164061. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164062. }
  164063. }
  164064. }
  164065. /*** End of inlined file: jcmainct.c ***/
  164066. /*** Start of inlined file: jcmarker.c ***/
  164067. #define JPEG_INTERNALS
  164068. /* Private state */
  164069. typedef struct {
  164070. struct jpeg_marker_writer pub; /* public fields */
  164071. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164072. } my_marker_writer;
  164073. typedef my_marker_writer * my_marker_ptr;
  164074. /*
  164075. * Basic output routines.
  164076. *
  164077. * Note that we do not support suspension while writing a marker.
  164078. * Therefore, an application using suspension must ensure that there is
  164079. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164080. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164081. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164082. * modes are not supported at all with suspension, so those two are the only
  164083. * points where markers will be written.
  164084. */
  164085. LOCAL(void)
  164086. emit_byte (j_compress_ptr cinfo, int val)
  164087. /* Emit a byte */
  164088. {
  164089. struct jpeg_destination_mgr * dest = cinfo->dest;
  164090. *(dest->next_output_byte)++ = (JOCTET) val;
  164091. if (--dest->free_in_buffer == 0) {
  164092. if (! (*dest->empty_output_buffer) (cinfo))
  164093. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164094. }
  164095. }
  164096. LOCAL(void)
  164097. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164098. /* Emit a marker code */
  164099. {
  164100. emit_byte(cinfo, 0xFF);
  164101. emit_byte(cinfo, (int) mark);
  164102. }
  164103. LOCAL(void)
  164104. emit_2bytes (j_compress_ptr cinfo, int value)
  164105. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164106. {
  164107. emit_byte(cinfo, (value >> 8) & 0xFF);
  164108. emit_byte(cinfo, value & 0xFF);
  164109. }
  164110. /*
  164111. * Routines to write specific marker types.
  164112. */
  164113. LOCAL(int)
  164114. emit_dqt (j_compress_ptr cinfo, int index)
  164115. /* Emit a DQT marker */
  164116. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164117. {
  164118. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164119. int prec;
  164120. int i;
  164121. if (qtbl == NULL)
  164122. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164123. prec = 0;
  164124. for (i = 0; i < DCTSIZE2; i++) {
  164125. if (qtbl->quantval[i] > 255)
  164126. prec = 1;
  164127. }
  164128. if (! qtbl->sent_table) {
  164129. emit_marker(cinfo, M_DQT);
  164130. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164131. emit_byte(cinfo, index + (prec<<4));
  164132. for (i = 0; i < DCTSIZE2; i++) {
  164133. /* The table entries must be emitted in zigzag order. */
  164134. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164135. if (prec)
  164136. emit_byte(cinfo, (int) (qval >> 8));
  164137. emit_byte(cinfo, (int) (qval & 0xFF));
  164138. }
  164139. qtbl->sent_table = TRUE;
  164140. }
  164141. return prec;
  164142. }
  164143. LOCAL(void)
  164144. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164145. /* Emit a DHT marker */
  164146. {
  164147. JHUFF_TBL * htbl;
  164148. int length, i;
  164149. if (is_ac) {
  164150. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164151. index += 0x10; /* output index has AC bit set */
  164152. } else {
  164153. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164154. }
  164155. if (htbl == NULL)
  164156. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164157. if (! htbl->sent_table) {
  164158. emit_marker(cinfo, M_DHT);
  164159. length = 0;
  164160. for (i = 1; i <= 16; i++)
  164161. length += htbl->bits[i];
  164162. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164163. emit_byte(cinfo, index);
  164164. for (i = 1; i <= 16; i++)
  164165. emit_byte(cinfo, htbl->bits[i]);
  164166. for (i = 0; i < length; i++)
  164167. emit_byte(cinfo, htbl->huffval[i]);
  164168. htbl->sent_table = TRUE;
  164169. }
  164170. }
  164171. LOCAL(void)
  164172. emit_dac (j_compress_ptr)
  164173. /* Emit a DAC marker */
  164174. /* Since the useful info is so small, we want to emit all the tables in */
  164175. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164176. {
  164177. #ifdef C_ARITH_CODING_SUPPORTED
  164178. char dc_in_use[NUM_ARITH_TBLS];
  164179. char ac_in_use[NUM_ARITH_TBLS];
  164180. int length, i;
  164181. jpeg_component_info *compptr;
  164182. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164183. dc_in_use[i] = ac_in_use[i] = 0;
  164184. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164185. compptr = cinfo->cur_comp_info[i];
  164186. dc_in_use[compptr->dc_tbl_no] = 1;
  164187. ac_in_use[compptr->ac_tbl_no] = 1;
  164188. }
  164189. length = 0;
  164190. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164191. length += dc_in_use[i] + ac_in_use[i];
  164192. emit_marker(cinfo, M_DAC);
  164193. emit_2bytes(cinfo, length*2 + 2);
  164194. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164195. if (dc_in_use[i]) {
  164196. emit_byte(cinfo, i);
  164197. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164198. }
  164199. if (ac_in_use[i]) {
  164200. emit_byte(cinfo, i + 0x10);
  164201. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164202. }
  164203. }
  164204. #endif /* C_ARITH_CODING_SUPPORTED */
  164205. }
  164206. LOCAL(void)
  164207. emit_dri (j_compress_ptr cinfo)
  164208. /* Emit a DRI marker */
  164209. {
  164210. emit_marker(cinfo, M_DRI);
  164211. emit_2bytes(cinfo, 4); /* fixed length */
  164212. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164213. }
  164214. LOCAL(void)
  164215. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164216. /* Emit a SOF marker */
  164217. {
  164218. int ci;
  164219. jpeg_component_info *compptr;
  164220. emit_marker(cinfo, code);
  164221. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164222. /* Make sure image isn't bigger than SOF field can handle */
  164223. if ((long) cinfo->image_height > 65535L ||
  164224. (long) cinfo->image_width > 65535L)
  164225. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164226. emit_byte(cinfo, cinfo->data_precision);
  164227. emit_2bytes(cinfo, (int) cinfo->image_height);
  164228. emit_2bytes(cinfo, (int) cinfo->image_width);
  164229. emit_byte(cinfo, cinfo->num_components);
  164230. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164231. ci++, compptr++) {
  164232. emit_byte(cinfo, compptr->component_id);
  164233. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164234. emit_byte(cinfo, compptr->quant_tbl_no);
  164235. }
  164236. }
  164237. LOCAL(void)
  164238. emit_sos (j_compress_ptr cinfo)
  164239. /* Emit a SOS marker */
  164240. {
  164241. int i, td, ta;
  164242. jpeg_component_info *compptr;
  164243. emit_marker(cinfo, M_SOS);
  164244. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164245. emit_byte(cinfo, cinfo->comps_in_scan);
  164246. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164247. compptr = cinfo->cur_comp_info[i];
  164248. emit_byte(cinfo, compptr->component_id);
  164249. td = compptr->dc_tbl_no;
  164250. ta = compptr->ac_tbl_no;
  164251. if (cinfo->progressive_mode) {
  164252. /* Progressive mode: only DC or only AC tables are used in one scan;
  164253. * furthermore, Huffman coding of DC refinement uses no table at all.
  164254. * We emit 0 for unused field(s); this is recommended by the P&M text
  164255. * but does not seem to be specified in the standard.
  164256. */
  164257. if (cinfo->Ss == 0) {
  164258. ta = 0; /* DC scan */
  164259. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164260. td = 0; /* no DC table either */
  164261. } else {
  164262. td = 0; /* AC scan */
  164263. }
  164264. }
  164265. emit_byte(cinfo, (td << 4) + ta);
  164266. }
  164267. emit_byte(cinfo, cinfo->Ss);
  164268. emit_byte(cinfo, cinfo->Se);
  164269. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164270. }
  164271. LOCAL(void)
  164272. emit_jfif_app0 (j_compress_ptr cinfo)
  164273. /* Emit a JFIF-compliant APP0 marker */
  164274. {
  164275. /*
  164276. * Length of APP0 block (2 bytes)
  164277. * Block ID (4 bytes - ASCII "JFIF")
  164278. * Zero byte (1 byte to terminate the ID string)
  164279. * Version Major, Minor (2 bytes - major first)
  164280. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164281. * Xdpu (2 bytes - dots per unit horizontal)
  164282. * Ydpu (2 bytes - dots per unit vertical)
  164283. * Thumbnail X size (1 byte)
  164284. * Thumbnail Y size (1 byte)
  164285. */
  164286. emit_marker(cinfo, M_APP0);
  164287. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164288. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164289. emit_byte(cinfo, 0x46);
  164290. emit_byte(cinfo, 0x49);
  164291. emit_byte(cinfo, 0x46);
  164292. emit_byte(cinfo, 0);
  164293. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164294. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164295. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164296. emit_2bytes(cinfo, (int) cinfo->X_density);
  164297. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164298. emit_byte(cinfo, 0); /* No thumbnail image */
  164299. emit_byte(cinfo, 0);
  164300. }
  164301. LOCAL(void)
  164302. emit_adobe_app14 (j_compress_ptr cinfo)
  164303. /* Emit an Adobe APP14 marker */
  164304. {
  164305. /*
  164306. * Length of APP14 block (2 bytes)
  164307. * Block ID (5 bytes - ASCII "Adobe")
  164308. * Version Number (2 bytes - currently 100)
  164309. * Flags0 (2 bytes - currently 0)
  164310. * Flags1 (2 bytes - currently 0)
  164311. * Color transform (1 byte)
  164312. *
  164313. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164314. * now in circulation seem to use Version = 100, so that's what we write.
  164315. *
  164316. * We write the color transform byte as 1 if the JPEG color space is
  164317. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164318. * whether the encoder performed a transformation, which is pretty useless.
  164319. */
  164320. emit_marker(cinfo, M_APP14);
  164321. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164322. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164323. emit_byte(cinfo, 0x64);
  164324. emit_byte(cinfo, 0x6F);
  164325. emit_byte(cinfo, 0x62);
  164326. emit_byte(cinfo, 0x65);
  164327. emit_2bytes(cinfo, 100); /* Version */
  164328. emit_2bytes(cinfo, 0); /* Flags0 */
  164329. emit_2bytes(cinfo, 0); /* Flags1 */
  164330. switch (cinfo->jpeg_color_space) {
  164331. case JCS_YCbCr:
  164332. emit_byte(cinfo, 1); /* Color transform = 1 */
  164333. break;
  164334. case JCS_YCCK:
  164335. emit_byte(cinfo, 2); /* Color transform = 2 */
  164336. break;
  164337. default:
  164338. emit_byte(cinfo, 0); /* Color transform = 0 */
  164339. break;
  164340. }
  164341. }
  164342. /*
  164343. * These routines allow writing an arbitrary marker with parameters.
  164344. * The only intended use is to emit COM or APPn markers after calling
  164345. * write_file_header and before calling write_frame_header.
  164346. * Other uses are not guaranteed to produce desirable results.
  164347. * Counting the parameter bytes properly is the caller's responsibility.
  164348. */
  164349. METHODDEF(void)
  164350. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164351. /* Emit an arbitrary marker header */
  164352. {
  164353. if (datalen > (unsigned int) 65533) /* safety check */
  164354. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164355. emit_marker(cinfo, (JPEG_MARKER) marker);
  164356. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164357. }
  164358. METHODDEF(void)
  164359. write_marker_byte (j_compress_ptr cinfo, int val)
  164360. /* Emit one byte of marker parameters following write_marker_header */
  164361. {
  164362. emit_byte(cinfo, val);
  164363. }
  164364. /*
  164365. * Write datastream header.
  164366. * This consists of an SOI and optional APPn markers.
  164367. * We recommend use of the JFIF marker, but not the Adobe marker,
  164368. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164369. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164370. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164371. * Note that an application can write additional header markers after
  164372. * jpeg_start_compress returns.
  164373. */
  164374. METHODDEF(void)
  164375. write_file_header (j_compress_ptr cinfo)
  164376. {
  164377. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164378. emit_marker(cinfo, M_SOI); /* first the SOI */
  164379. /* SOI is defined to reset restart interval to 0 */
  164380. marker->last_restart_interval = 0;
  164381. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164382. emit_jfif_app0(cinfo);
  164383. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164384. emit_adobe_app14(cinfo);
  164385. }
  164386. /*
  164387. * Write frame header.
  164388. * This consists of DQT and SOFn markers.
  164389. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164390. * This avoids compatibility problems with incorrect implementations that
  164391. * try to error-check the quant table numbers as soon as they see the SOF.
  164392. */
  164393. METHODDEF(void)
  164394. write_frame_header (j_compress_ptr cinfo)
  164395. {
  164396. int ci, prec;
  164397. boolean is_baseline;
  164398. jpeg_component_info *compptr;
  164399. /* Emit DQT for each quantization table.
  164400. * Note that emit_dqt() suppresses any duplicate tables.
  164401. */
  164402. prec = 0;
  164403. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164404. ci++, compptr++) {
  164405. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164406. }
  164407. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164408. /* Check for a non-baseline specification.
  164409. * Note we assume that Huffman table numbers won't be changed later.
  164410. */
  164411. if (cinfo->arith_code || cinfo->progressive_mode ||
  164412. cinfo->data_precision != 8) {
  164413. is_baseline = FALSE;
  164414. } else {
  164415. is_baseline = TRUE;
  164416. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164417. ci++, compptr++) {
  164418. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164419. is_baseline = FALSE;
  164420. }
  164421. if (prec && is_baseline) {
  164422. is_baseline = FALSE;
  164423. /* If it's baseline except for quantizer size, warn the user */
  164424. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164425. }
  164426. }
  164427. /* Emit the proper SOF marker */
  164428. if (cinfo->arith_code) {
  164429. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164430. } else {
  164431. if (cinfo->progressive_mode)
  164432. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164433. else if (is_baseline)
  164434. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164435. else
  164436. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164437. }
  164438. }
  164439. /*
  164440. * Write scan header.
  164441. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164442. * Compressed data will be written following the SOS.
  164443. */
  164444. METHODDEF(void)
  164445. write_scan_header (j_compress_ptr cinfo)
  164446. {
  164447. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164448. int i;
  164449. jpeg_component_info *compptr;
  164450. if (cinfo->arith_code) {
  164451. /* Emit arith conditioning info. We may have some duplication
  164452. * if the file has multiple scans, but it's so small it's hardly
  164453. * worth worrying about.
  164454. */
  164455. emit_dac(cinfo);
  164456. } else {
  164457. /* Emit Huffman tables.
  164458. * Note that emit_dht() suppresses any duplicate tables.
  164459. */
  164460. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164461. compptr = cinfo->cur_comp_info[i];
  164462. if (cinfo->progressive_mode) {
  164463. /* Progressive mode: only DC or only AC tables are used in one scan */
  164464. if (cinfo->Ss == 0) {
  164465. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164466. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164467. } else {
  164468. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164469. }
  164470. } else {
  164471. /* Sequential mode: need both DC and AC tables */
  164472. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164473. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164474. }
  164475. }
  164476. }
  164477. /* Emit DRI if required --- note that DRI value could change for each scan.
  164478. * We avoid wasting space with unnecessary DRIs, however.
  164479. */
  164480. if (cinfo->restart_interval != marker->last_restart_interval) {
  164481. emit_dri(cinfo);
  164482. marker->last_restart_interval = cinfo->restart_interval;
  164483. }
  164484. emit_sos(cinfo);
  164485. }
  164486. /*
  164487. * Write datastream trailer.
  164488. */
  164489. METHODDEF(void)
  164490. write_file_trailer (j_compress_ptr cinfo)
  164491. {
  164492. emit_marker(cinfo, M_EOI);
  164493. }
  164494. /*
  164495. * Write an abbreviated table-specification datastream.
  164496. * This consists of SOI, DQT and DHT tables, and EOI.
  164497. * Any table that is defined and not marked sent_table = TRUE will be
  164498. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164499. */
  164500. METHODDEF(void)
  164501. write_tables_only (j_compress_ptr cinfo)
  164502. {
  164503. int i;
  164504. emit_marker(cinfo, M_SOI);
  164505. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164506. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164507. (void) emit_dqt(cinfo, i);
  164508. }
  164509. if (! cinfo->arith_code) {
  164510. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164511. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164512. emit_dht(cinfo, i, FALSE);
  164513. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164514. emit_dht(cinfo, i, TRUE);
  164515. }
  164516. }
  164517. emit_marker(cinfo, M_EOI);
  164518. }
  164519. /*
  164520. * Initialize the marker writer module.
  164521. */
  164522. GLOBAL(void)
  164523. jinit_marker_writer (j_compress_ptr cinfo)
  164524. {
  164525. my_marker_ptr marker;
  164526. /* Create the subobject */
  164527. marker = (my_marker_ptr)
  164528. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164529. SIZEOF(my_marker_writer));
  164530. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164531. /* Initialize method pointers */
  164532. marker->pub.write_file_header = write_file_header;
  164533. marker->pub.write_frame_header = write_frame_header;
  164534. marker->pub.write_scan_header = write_scan_header;
  164535. marker->pub.write_file_trailer = write_file_trailer;
  164536. marker->pub.write_tables_only = write_tables_only;
  164537. marker->pub.write_marker_header = write_marker_header;
  164538. marker->pub.write_marker_byte = write_marker_byte;
  164539. /* Initialize private state */
  164540. marker->last_restart_interval = 0;
  164541. }
  164542. /*** End of inlined file: jcmarker.c ***/
  164543. /*** Start of inlined file: jcmaster.c ***/
  164544. #define JPEG_INTERNALS
  164545. /* Private state */
  164546. typedef enum {
  164547. main_pass, /* input data, also do first output step */
  164548. huff_opt_pass, /* Huffman code optimization pass */
  164549. output_pass /* data output pass */
  164550. } c_pass_type;
  164551. typedef struct {
  164552. struct jpeg_comp_master pub; /* public fields */
  164553. c_pass_type pass_type; /* the type of the current pass */
  164554. int pass_number; /* # of passes completed */
  164555. int total_passes; /* total # of passes needed */
  164556. int scan_number; /* current index in scan_info[] */
  164557. } my_comp_master;
  164558. typedef my_comp_master * my_master_ptr;
  164559. /*
  164560. * Support routines that do various essential calculations.
  164561. */
  164562. LOCAL(void)
  164563. initial_setup (j_compress_ptr cinfo)
  164564. /* Do computations that are needed before master selection phase */
  164565. {
  164566. int ci;
  164567. jpeg_component_info *compptr;
  164568. long samplesperrow;
  164569. JDIMENSION jd_samplesperrow;
  164570. /* Sanity check on image dimensions */
  164571. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164572. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164573. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164574. /* Make sure image isn't bigger than I can handle */
  164575. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164576. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164577. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164578. /* Width of an input scanline must be representable as JDIMENSION. */
  164579. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164580. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164581. if ((long) jd_samplesperrow != samplesperrow)
  164582. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164583. /* For now, precision must match compiled-in value... */
  164584. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164585. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164586. /* Check that number of components won't exceed internal array sizes */
  164587. if (cinfo->num_components > MAX_COMPONENTS)
  164588. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164589. MAX_COMPONENTS);
  164590. /* Compute maximum sampling factors; check factor validity */
  164591. cinfo->max_h_samp_factor = 1;
  164592. cinfo->max_v_samp_factor = 1;
  164593. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164594. ci++, compptr++) {
  164595. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164596. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164597. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164598. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164599. compptr->h_samp_factor);
  164600. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164601. compptr->v_samp_factor);
  164602. }
  164603. /* Compute dimensions of components */
  164604. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164605. ci++, compptr++) {
  164606. /* Fill in the correct component_index value; don't rely on application */
  164607. compptr->component_index = ci;
  164608. /* For compression, we never do DCT scaling. */
  164609. compptr->DCT_scaled_size = DCTSIZE;
  164610. /* Size in DCT blocks */
  164611. compptr->width_in_blocks = (JDIMENSION)
  164612. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164613. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164614. compptr->height_in_blocks = (JDIMENSION)
  164615. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164616. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164617. /* Size in samples */
  164618. compptr->downsampled_width = (JDIMENSION)
  164619. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164620. (long) cinfo->max_h_samp_factor);
  164621. compptr->downsampled_height = (JDIMENSION)
  164622. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164623. (long) cinfo->max_v_samp_factor);
  164624. /* Mark component needed (this flag isn't actually used for compression) */
  164625. compptr->component_needed = TRUE;
  164626. }
  164627. /* Compute number of fully interleaved MCU rows (number of times that
  164628. * main controller will call coefficient controller).
  164629. */
  164630. cinfo->total_iMCU_rows = (JDIMENSION)
  164631. jdiv_round_up((long) cinfo->image_height,
  164632. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164633. }
  164634. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164635. LOCAL(void)
  164636. validate_script (j_compress_ptr cinfo)
  164637. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164638. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164639. */
  164640. {
  164641. const jpeg_scan_info * scanptr;
  164642. int scanno, ncomps, ci, coefi, thisi;
  164643. int Ss, Se, Ah, Al;
  164644. boolean component_sent[MAX_COMPONENTS];
  164645. #ifdef C_PROGRESSIVE_SUPPORTED
  164646. int * last_bitpos_ptr;
  164647. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164648. /* -1 until that coefficient has been seen; then last Al for it */
  164649. #endif
  164650. if (cinfo->num_scans <= 0)
  164651. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164652. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164653. * for progressive JPEG, no scan can have this.
  164654. */
  164655. scanptr = cinfo->scan_info;
  164656. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164657. #ifdef C_PROGRESSIVE_SUPPORTED
  164658. cinfo->progressive_mode = TRUE;
  164659. last_bitpos_ptr = & last_bitpos[0][0];
  164660. for (ci = 0; ci < cinfo->num_components; ci++)
  164661. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164662. *last_bitpos_ptr++ = -1;
  164663. #else
  164664. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164665. #endif
  164666. } else {
  164667. cinfo->progressive_mode = FALSE;
  164668. for (ci = 0; ci < cinfo->num_components; ci++)
  164669. component_sent[ci] = FALSE;
  164670. }
  164671. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164672. /* Validate component indexes */
  164673. ncomps = scanptr->comps_in_scan;
  164674. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164675. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164676. for (ci = 0; ci < ncomps; ci++) {
  164677. thisi = scanptr->component_index[ci];
  164678. if (thisi < 0 || thisi >= cinfo->num_components)
  164679. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164680. /* Components must appear in SOF order within each scan */
  164681. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164682. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164683. }
  164684. /* Validate progression parameters */
  164685. Ss = scanptr->Ss;
  164686. Se = scanptr->Se;
  164687. Ah = scanptr->Ah;
  164688. Al = scanptr->Al;
  164689. if (cinfo->progressive_mode) {
  164690. #ifdef C_PROGRESSIVE_SUPPORTED
  164691. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164692. * seems wrong: the upper bound ought to depend on data precision.
  164693. * Perhaps they really meant 0..N+1 for N-bit precision.
  164694. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164695. * out-of-range reconstructed DC values during the first DC scan,
  164696. * which might cause problems for some decoders.
  164697. */
  164698. #if BITS_IN_JSAMPLE == 8
  164699. #define MAX_AH_AL 10
  164700. #else
  164701. #define MAX_AH_AL 13
  164702. #endif
  164703. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164704. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164705. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164706. if (Ss == 0) {
  164707. if (Se != 0) /* DC and AC together not OK */
  164708. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164709. } else {
  164710. if (ncomps != 1) /* AC scans must be for only one component */
  164711. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164712. }
  164713. for (ci = 0; ci < ncomps; ci++) {
  164714. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164715. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164716. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164717. for (coefi = Ss; coefi <= Se; coefi++) {
  164718. if (last_bitpos_ptr[coefi] < 0) {
  164719. /* first scan of this coefficient */
  164720. if (Ah != 0)
  164721. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164722. } else {
  164723. /* not first scan */
  164724. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164725. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164726. }
  164727. last_bitpos_ptr[coefi] = Al;
  164728. }
  164729. }
  164730. #endif
  164731. } else {
  164732. /* For sequential JPEG, all progression parameters must be these: */
  164733. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164734. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164735. /* Make sure components are not sent twice */
  164736. for (ci = 0; ci < ncomps; ci++) {
  164737. thisi = scanptr->component_index[ci];
  164738. if (component_sent[thisi])
  164739. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164740. component_sent[thisi] = TRUE;
  164741. }
  164742. }
  164743. }
  164744. /* Now verify that everything got sent. */
  164745. if (cinfo->progressive_mode) {
  164746. #ifdef C_PROGRESSIVE_SUPPORTED
  164747. /* For progressive mode, we only check that at least some DC data
  164748. * got sent for each component; the spec does not require that all bits
  164749. * of all coefficients be transmitted. Would it be wiser to enforce
  164750. * transmission of all coefficient bits??
  164751. */
  164752. for (ci = 0; ci < cinfo->num_components; ci++) {
  164753. if (last_bitpos[ci][0] < 0)
  164754. ERREXIT(cinfo, JERR_MISSING_DATA);
  164755. }
  164756. #endif
  164757. } else {
  164758. for (ci = 0; ci < cinfo->num_components; ci++) {
  164759. if (! component_sent[ci])
  164760. ERREXIT(cinfo, JERR_MISSING_DATA);
  164761. }
  164762. }
  164763. }
  164764. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164765. LOCAL(void)
  164766. select_scan_parameters (j_compress_ptr cinfo)
  164767. /* Set up the scan parameters for the current scan */
  164768. {
  164769. int ci;
  164770. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164771. if (cinfo->scan_info != NULL) {
  164772. /* Prepare for current scan --- the script is already validated */
  164773. my_master_ptr master = (my_master_ptr) cinfo->master;
  164774. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164775. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164776. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164777. cinfo->cur_comp_info[ci] =
  164778. &cinfo->comp_info[scanptr->component_index[ci]];
  164779. }
  164780. cinfo->Ss = scanptr->Ss;
  164781. cinfo->Se = scanptr->Se;
  164782. cinfo->Ah = scanptr->Ah;
  164783. cinfo->Al = scanptr->Al;
  164784. }
  164785. else
  164786. #endif
  164787. {
  164788. /* Prepare for single sequential-JPEG scan containing all components */
  164789. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164790. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164791. MAX_COMPS_IN_SCAN);
  164792. cinfo->comps_in_scan = cinfo->num_components;
  164793. for (ci = 0; ci < cinfo->num_components; ci++) {
  164794. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164795. }
  164796. cinfo->Ss = 0;
  164797. cinfo->Se = DCTSIZE2-1;
  164798. cinfo->Ah = 0;
  164799. cinfo->Al = 0;
  164800. }
  164801. }
  164802. LOCAL(void)
  164803. per_scan_setup (j_compress_ptr cinfo)
  164804. /* Do computations that are needed before processing a JPEG scan */
  164805. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164806. {
  164807. int ci, mcublks, tmp;
  164808. jpeg_component_info *compptr;
  164809. if (cinfo->comps_in_scan == 1) {
  164810. /* Noninterleaved (single-component) scan */
  164811. compptr = cinfo->cur_comp_info[0];
  164812. /* Overall image size in MCUs */
  164813. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164814. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164815. /* For noninterleaved scan, always one block per MCU */
  164816. compptr->MCU_width = 1;
  164817. compptr->MCU_height = 1;
  164818. compptr->MCU_blocks = 1;
  164819. compptr->MCU_sample_width = DCTSIZE;
  164820. compptr->last_col_width = 1;
  164821. /* For noninterleaved scans, it is convenient to define last_row_height
  164822. * as the number of block rows present in the last iMCU row.
  164823. */
  164824. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164825. if (tmp == 0) tmp = compptr->v_samp_factor;
  164826. compptr->last_row_height = tmp;
  164827. /* Prepare array describing MCU composition */
  164828. cinfo->blocks_in_MCU = 1;
  164829. cinfo->MCU_membership[0] = 0;
  164830. } else {
  164831. /* Interleaved (multi-component) scan */
  164832. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164833. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164834. MAX_COMPS_IN_SCAN);
  164835. /* Overall image size in MCUs */
  164836. cinfo->MCUs_per_row = (JDIMENSION)
  164837. jdiv_round_up((long) cinfo->image_width,
  164838. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164839. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164840. jdiv_round_up((long) cinfo->image_height,
  164841. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164842. cinfo->blocks_in_MCU = 0;
  164843. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164844. compptr = cinfo->cur_comp_info[ci];
  164845. /* Sampling factors give # of blocks of component in each MCU */
  164846. compptr->MCU_width = compptr->h_samp_factor;
  164847. compptr->MCU_height = compptr->v_samp_factor;
  164848. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164849. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164850. /* Figure number of non-dummy blocks in last MCU column & row */
  164851. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164852. if (tmp == 0) tmp = compptr->MCU_width;
  164853. compptr->last_col_width = tmp;
  164854. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164855. if (tmp == 0) tmp = compptr->MCU_height;
  164856. compptr->last_row_height = tmp;
  164857. /* Prepare array describing MCU composition */
  164858. mcublks = compptr->MCU_blocks;
  164859. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164860. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164861. while (mcublks-- > 0) {
  164862. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164863. }
  164864. }
  164865. }
  164866. /* Convert restart specified in rows to actual MCU count. */
  164867. /* Note that count must fit in 16 bits, so we provide limiting. */
  164868. if (cinfo->restart_in_rows > 0) {
  164869. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164870. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164871. }
  164872. }
  164873. /*
  164874. * Per-pass setup.
  164875. * This is called at the beginning of each pass. We determine which modules
  164876. * will be active during this pass and give them appropriate start_pass calls.
  164877. * We also set is_last_pass to indicate whether any more passes will be
  164878. * required.
  164879. */
  164880. METHODDEF(void)
  164881. prepare_for_pass (j_compress_ptr cinfo)
  164882. {
  164883. my_master_ptr master = (my_master_ptr) cinfo->master;
  164884. switch (master->pass_type) {
  164885. case main_pass:
  164886. /* Initial pass: will collect input data, and do either Huffman
  164887. * optimization or data output for the first scan.
  164888. */
  164889. select_scan_parameters(cinfo);
  164890. per_scan_setup(cinfo);
  164891. if (! cinfo->raw_data_in) {
  164892. (*cinfo->cconvert->start_pass) (cinfo);
  164893. (*cinfo->downsample->start_pass) (cinfo);
  164894. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164895. }
  164896. (*cinfo->fdct->start_pass) (cinfo);
  164897. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164898. (*cinfo->coef->start_pass) (cinfo,
  164899. (master->total_passes > 1 ?
  164900. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164901. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164902. if (cinfo->optimize_coding) {
  164903. /* No immediate data output; postpone writing frame/scan headers */
  164904. master->pub.call_pass_startup = FALSE;
  164905. } else {
  164906. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164907. master->pub.call_pass_startup = TRUE;
  164908. }
  164909. break;
  164910. #ifdef ENTROPY_OPT_SUPPORTED
  164911. case huff_opt_pass:
  164912. /* Do Huffman optimization for a scan after the first one. */
  164913. select_scan_parameters(cinfo);
  164914. per_scan_setup(cinfo);
  164915. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164916. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164917. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164918. master->pub.call_pass_startup = FALSE;
  164919. break;
  164920. }
  164921. /* Special case: Huffman DC refinement scans need no Huffman table
  164922. * and therefore we can skip the optimization pass for them.
  164923. */
  164924. master->pass_type = output_pass;
  164925. master->pass_number++;
  164926. /*FALLTHROUGH*/
  164927. #endif
  164928. case output_pass:
  164929. /* Do a data-output pass. */
  164930. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164931. if (! cinfo->optimize_coding) {
  164932. select_scan_parameters(cinfo);
  164933. per_scan_setup(cinfo);
  164934. }
  164935. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164936. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164937. /* We emit frame/scan headers now */
  164938. if (master->scan_number == 0)
  164939. (*cinfo->marker->write_frame_header) (cinfo);
  164940. (*cinfo->marker->write_scan_header) (cinfo);
  164941. master->pub.call_pass_startup = FALSE;
  164942. break;
  164943. default:
  164944. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164945. }
  164946. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164947. /* Set up progress monitor's pass info if present */
  164948. if (cinfo->progress != NULL) {
  164949. cinfo->progress->completed_passes = master->pass_number;
  164950. cinfo->progress->total_passes = master->total_passes;
  164951. }
  164952. }
  164953. /*
  164954. * Special start-of-pass hook.
  164955. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164956. * In single-pass processing, we need this hook because we don't want to
  164957. * write frame/scan headers during jpeg_start_compress; we want to let the
  164958. * application write COM markers etc. between jpeg_start_compress and the
  164959. * jpeg_write_scanlines loop.
  164960. * In multi-pass processing, this routine is not used.
  164961. */
  164962. METHODDEF(void)
  164963. pass_startup (j_compress_ptr cinfo)
  164964. {
  164965. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164966. (*cinfo->marker->write_frame_header) (cinfo);
  164967. (*cinfo->marker->write_scan_header) (cinfo);
  164968. }
  164969. /*
  164970. * Finish up at end of pass.
  164971. */
  164972. METHODDEF(void)
  164973. finish_pass_master (j_compress_ptr cinfo)
  164974. {
  164975. my_master_ptr master = (my_master_ptr) cinfo->master;
  164976. /* The entropy coder always needs an end-of-pass call,
  164977. * either to analyze statistics or to flush its output buffer.
  164978. */
  164979. (*cinfo->entropy->finish_pass) (cinfo);
  164980. /* Update state for next pass */
  164981. switch (master->pass_type) {
  164982. case main_pass:
  164983. /* next pass is either output of scan 0 (after optimization)
  164984. * or output of scan 1 (if no optimization).
  164985. */
  164986. master->pass_type = output_pass;
  164987. if (! cinfo->optimize_coding)
  164988. master->scan_number++;
  164989. break;
  164990. case huff_opt_pass:
  164991. /* next pass is always output of current scan */
  164992. master->pass_type = output_pass;
  164993. break;
  164994. case output_pass:
  164995. /* next pass is either optimization or output of next scan */
  164996. if (cinfo->optimize_coding)
  164997. master->pass_type = huff_opt_pass;
  164998. master->scan_number++;
  164999. break;
  165000. }
  165001. master->pass_number++;
  165002. }
  165003. /*
  165004. * Initialize master compression control.
  165005. */
  165006. GLOBAL(void)
  165007. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165008. {
  165009. my_master_ptr master;
  165010. master = (my_master_ptr)
  165011. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165012. SIZEOF(my_comp_master));
  165013. cinfo->master = (struct jpeg_comp_master *) master;
  165014. master->pub.prepare_for_pass = prepare_for_pass;
  165015. master->pub.pass_startup = pass_startup;
  165016. master->pub.finish_pass = finish_pass_master;
  165017. master->pub.is_last_pass = FALSE;
  165018. /* Validate parameters, determine derived values */
  165019. initial_setup(cinfo);
  165020. if (cinfo->scan_info != NULL) {
  165021. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165022. validate_script(cinfo);
  165023. #else
  165024. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165025. #endif
  165026. } else {
  165027. cinfo->progressive_mode = FALSE;
  165028. cinfo->num_scans = 1;
  165029. }
  165030. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165031. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165032. /* Initialize my private state */
  165033. if (transcode_only) {
  165034. /* no main pass in transcoding */
  165035. if (cinfo->optimize_coding)
  165036. master->pass_type = huff_opt_pass;
  165037. else
  165038. master->pass_type = output_pass;
  165039. } else {
  165040. /* for normal compression, first pass is always this type: */
  165041. master->pass_type = main_pass;
  165042. }
  165043. master->scan_number = 0;
  165044. master->pass_number = 0;
  165045. if (cinfo->optimize_coding)
  165046. master->total_passes = cinfo->num_scans * 2;
  165047. else
  165048. master->total_passes = cinfo->num_scans;
  165049. }
  165050. /*** End of inlined file: jcmaster.c ***/
  165051. /*** Start of inlined file: jcomapi.c ***/
  165052. #define JPEG_INTERNALS
  165053. /*
  165054. * Abort processing of a JPEG compression or decompression operation,
  165055. * but don't destroy the object itself.
  165056. *
  165057. * For this, we merely clean up all the nonpermanent memory pools.
  165058. * Note that temp files (virtual arrays) are not allowed to belong to
  165059. * the permanent pool, so we will be able to close all temp files here.
  165060. * Closing a data source or destination, if necessary, is the application's
  165061. * responsibility.
  165062. */
  165063. GLOBAL(void)
  165064. jpeg_abort (j_common_ptr cinfo)
  165065. {
  165066. int pool;
  165067. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165068. if (cinfo->mem == NULL)
  165069. return;
  165070. /* Releasing pools in reverse order might help avoid fragmentation
  165071. * with some (brain-damaged) malloc libraries.
  165072. */
  165073. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165074. (*cinfo->mem->free_pool) (cinfo, pool);
  165075. }
  165076. /* Reset overall state for possible reuse of object */
  165077. if (cinfo->is_decompressor) {
  165078. cinfo->global_state = DSTATE_START;
  165079. /* Try to keep application from accessing now-deleted marker list.
  165080. * A bit kludgy to do it here, but this is the most central place.
  165081. */
  165082. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165083. } else {
  165084. cinfo->global_state = CSTATE_START;
  165085. }
  165086. }
  165087. /*
  165088. * Destruction of a JPEG object.
  165089. *
  165090. * Everything gets deallocated except the master jpeg_compress_struct itself
  165091. * and the error manager struct. Both of these are supplied by the application
  165092. * and must be freed, if necessary, by the application. (Often they are on
  165093. * the stack and so don't need to be freed anyway.)
  165094. * Closing a data source or destination, if necessary, is the application's
  165095. * responsibility.
  165096. */
  165097. GLOBAL(void)
  165098. jpeg_destroy (j_common_ptr cinfo)
  165099. {
  165100. /* We need only tell the memory manager to release everything. */
  165101. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165102. if (cinfo->mem != NULL)
  165103. (*cinfo->mem->self_destruct) (cinfo);
  165104. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165105. cinfo->global_state = 0; /* mark it destroyed */
  165106. }
  165107. /*
  165108. * Convenience routines for allocating quantization and Huffman tables.
  165109. * (Would jutils.c be a more reasonable place to put these?)
  165110. */
  165111. GLOBAL(JQUANT_TBL *)
  165112. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165113. {
  165114. JQUANT_TBL *tbl;
  165115. tbl = (JQUANT_TBL *)
  165116. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165117. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165118. return tbl;
  165119. }
  165120. GLOBAL(JHUFF_TBL *)
  165121. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165122. {
  165123. JHUFF_TBL *tbl;
  165124. tbl = (JHUFF_TBL *)
  165125. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165126. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165127. return tbl;
  165128. }
  165129. /*** End of inlined file: jcomapi.c ***/
  165130. /*** Start of inlined file: jcparam.c ***/
  165131. #define JPEG_INTERNALS
  165132. /*
  165133. * Quantization table setup routines
  165134. */
  165135. GLOBAL(void)
  165136. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165137. const unsigned int *basic_table,
  165138. int scale_factor, boolean force_baseline)
  165139. /* Define a quantization table equal to the basic_table times
  165140. * a scale factor (given as a percentage).
  165141. * If force_baseline is TRUE, the computed quantization table entries
  165142. * are limited to 1..255 for JPEG baseline compatibility.
  165143. */
  165144. {
  165145. JQUANT_TBL ** qtblptr;
  165146. int i;
  165147. long temp;
  165148. /* Safety check to ensure start_compress not called yet. */
  165149. if (cinfo->global_state != CSTATE_START)
  165150. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165151. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165152. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165153. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165154. if (*qtblptr == NULL)
  165155. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165156. for (i = 0; i < DCTSIZE2; i++) {
  165157. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165158. /* limit the values to the valid range */
  165159. if (temp <= 0L) temp = 1L;
  165160. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165161. if (force_baseline && temp > 255L)
  165162. temp = 255L; /* limit to baseline range if requested */
  165163. (*qtblptr)->quantval[i] = (UINT16) temp;
  165164. }
  165165. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165166. (*qtblptr)->sent_table = FALSE;
  165167. }
  165168. GLOBAL(void)
  165169. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165170. boolean force_baseline)
  165171. /* Set or change the 'quality' (quantization) setting, using default tables
  165172. * and a straight percentage-scaling quality scale. In most cases it's better
  165173. * to use jpeg_set_quality (below); this entry point is provided for
  165174. * applications that insist on a linear percentage scaling.
  165175. */
  165176. {
  165177. /* These are the sample quantization tables given in JPEG spec section K.1.
  165178. * The spec says that the values given produce "good" quality, and
  165179. * when divided by 2, "very good" quality.
  165180. */
  165181. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165182. 16, 11, 10, 16, 24, 40, 51, 61,
  165183. 12, 12, 14, 19, 26, 58, 60, 55,
  165184. 14, 13, 16, 24, 40, 57, 69, 56,
  165185. 14, 17, 22, 29, 51, 87, 80, 62,
  165186. 18, 22, 37, 56, 68, 109, 103, 77,
  165187. 24, 35, 55, 64, 81, 104, 113, 92,
  165188. 49, 64, 78, 87, 103, 121, 120, 101,
  165189. 72, 92, 95, 98, 112, 100, 103, 99
  165190. };
  165191. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165192. 17, 18, 24, 47, 99, 99, 99, 99,
  165193. 18, 21, 26, 66, 99, 99, 99, 99,
  165194. 24, 26, 56, 99, 99, 99, 99, 99,
  165195. 47, 66, 99, 99, 99, 99, 99, 99,
  165196. 99, 99, 99, 99, 99, 99, 99, 99,
  165197. 99, 99, 99, 99, 99, 99, 99, 99,
  165198. 99, 99, 99, 99, 99, 99, 99, 99,
  165199. 99, 99, 99, 99, 99, 99, 99, 99
  165200. };
  165201. /* Set up two quantization tables using the specified scaling */
  165202. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165203. scale_factor, force_baseline);
  165204. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165205. scale_factor, force_baseline);
  165206. }
  165207. GLOBAL(int)
  165208. jpeg_quality_scaling (int quality)
  165209. /* Convert a user-specified quality rating to a percentage scaling factor
  165210. * for an underlying quantization table, using our recommended scaling curve.
  165211. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165212. */
  165213. {
  165214. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165215. if (quality <= 0) quality = 1;
  165216. if (quality > 100) quality = 100;
  165217. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165218. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165219. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165220. * to make all the table entries 1 (hence, minimum quantization loss).
  165221. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165222. */
  165223. if (quality < 50)
  165224. quality = 5000 / quality;
  165225. else
  165226. quality = 200 - quality*2;
  165227. return quality;
  165228. }
  165229. GLOBAL(void)
  165230. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165231. /* Set or change the 'quality' (quantization) setting, using default tables.
  165232. * This is the standard quality-adjusting entry point for typical user
  165233. * interfaces; only those who want detailed control over quantization tables
  165234. * would use the preceding three routines directly.
  165235. */
  165236. {
  165237. /* Convert user 0-100 rating to percentage scaling */
  165238. quality = jpeg_quality_scaling(quality);
  165239. /* Set up standard quality tables */
  165240. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165241. }
  165242. /*
  165243. * Huffman table setup routines
  165244. */
  165245. LOCAL(void)
  165246. add_huff_table (j_compress_ptr cinfo,
  165247. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165248. /* Define a Huffman table */
  165249. {
  165250. int nsymbols, len;
  165251. if (*htblptr == NULL)
  165252. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165253. /* Copy the number-of-symbols-of-each-code-length counts */
  165254. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165255. /* Validate the counts. We do this here mainly so we can copy the right
  165256. * number of symbols from the val[] array, without risking marching off
  165257. * the end of memory. jchuff.c will do a more thorough test later.
  165258. */
  165259. nsymbols = 0;
  165260. for (len = 1; len <= 16; len++)
  165261. nsymbols += bits[len];
  165262. if (nsymbols < 1 || nsymbols > 256)
  165263. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165264. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165265. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165266. (*htblptr)->sent_table = FALSE;
  165267. }
  165268. LOCAL(void)
  165269. std_huff_tables (j_compress_ptr cinfo)
  165270. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165271. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165272. {
  165273. static const UINT8 bits_dc_luminance[17] =
  165274. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165275. static const UINT8 val_dc_luminance[] =
  165276. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165277. static const UINT8 bits_dc_chrominance[17] =
  165278. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165279. static const UINT8 val_dc_chrominance[] =
  165280. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165281. static const UINT8 bits_ac_luminance[17] =
  165282. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165283. static const UINT8 val_ac_luminance[] =
  165284. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165285. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165286. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165287. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165288. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165289. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165290. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165291. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165292. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165293. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165294. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165295. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165296. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165297. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165298. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165299. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165300. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165301. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165302. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165303. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165304. 0xf9, 0xfa };
  165305. static const UINT8 bits_ac_chrominance[17] =
  165306. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165307. static const UINT8 val_ac_chrominance[] =
  165308. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165309. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165310. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165311. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165312. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165313. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165314. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165315. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165316. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165317. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165318. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165319. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165320. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165321. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165322. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165323. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165324. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165325. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165326. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165327. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165328. 0xf9, 0xfa };
  165329. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165330. bits_dc_luminance, val_dc_luminance);
  165331. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165332. bits_ac_luminance, val_ac_luminance);
  165333. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165334. bits_dc_chrominance, val_dc_chrominance);
  165335. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165336. bits_ac_chrominance, val_ac_chrominance);
  165337. }
  165338. /*
  165339. * Default parameter setup for compression.
  165340. *
  165341. * Applications that don't choose to use this routine must do their
  165342. * own setup of all these parameters. Alternately, you can call this
  165343. * to establish defaults and then alter parameters selectively. This
  165344. * is the recommended approach since, if we add any new parameters,
  165345. * your code will still work (they'll be set to reasonable defaults).
  165346. */
  165347. GLOBAL(void)
  165348. jpeg_set_defaults (j_compress_ptr cinfo)
  165349. {
  165350. int i;
  165351. /* Safety check to ensure start_compress not called yet. */
  165352. if (cinfo->global_state != CSTATE_START)
  165353. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165354. /* Allocate comp_info array large enough for maximum component count.
  165355. * Array is made permanent in case application wants to compress
  165356. * multiple images at same param settings.
  165357. */
  165358. if (cinfo->comp_info == NULL)
  165359. cinfo->comp_info = (jpeg_component_info *)
  165360. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165361. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165362. /* Initialize everything not dependent on the color space */
  165363. cinfo->data_precision = BITS_IN_JSAMPLE;
  165364. /* Set up two quantization tables using default quality of 75 */
  165365. jpeg_set_quality(cinfo, 75, TRUE);
  165366. /* Set up two Huffman tables */
  165367. std_huff_tables(cinfo);
  165368. /* Initialize default arithmetic coding conditioning */
  165369. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165370. cinfo->arith_dc_L[i] = 0;
  165371. cinfo->arith_dc_U[i] = 1;
  165372. cinfo->arith_ac_K[i] = 5;
  165373. }
  165374. /* Default is no multiple-scan output */
  165375. cinfo->scan_info = NULL;
  165376. cinfo->num_scans = 0;
  165377. /* Expect normal source image, not raw downsampled data */
  165378. cinfo->raw_data_in = FALSE;
  165379. /* Use Huffman coding, not arithmetic coding, by default */
  165380. cinfo->arith_code = FALSE;
  165381. /* By default, don't do extra passes to optimize entropy coding */
  165382. cinfo->optimize_coding = FALSE;
  165383. /* The standard Huffman tables are only valid for 8-bit data precision.
  165384. * If the precision is higher, force optimization on so that usable
  165385. * tables will be computed. This test can be removed if default tables
  165386. * are supplied that are valid for the desired precision.
  165387. */
  165388. if (cinfo->data_precision > 8)
  165389. cinfo->optimize_coding = TRUE;
  165390. /* By default, use the simpler non-cosited sampling alignment */
  165391. cinfo->CCIR601_sampling = FALSE;
  165392. /* No input smoothing */
  165393. cinfo->smoothing_factor = 0;
  165394. /* DCT algorithm preference */
  165395. cinfo->dct_method = JDCT_DEFAULT;
  165396. /* No restart markers */
  165397. cinfo->restart_interval = 0;
  165398. cinfo->restart_in_rows = 0;
  165399. /* Fill in default JFIF marker parameters. Note that whether the marker
  165400. * will actually be written is determined by jpeg_set_colorspace.
  165401. *
  165402. * By default, the library emits JFIF version code 1.01.
  165403. * An application that wants to emit JFIF 1.02 extension markers should set
  165404. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165405. * to 1.02, but there may still be some decoders in use that will complain
  165406. * about that; saying 1.01 should minimize compatibility problems.
  165407. */
  165408. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165409. cinfo->JFIF_minor_version = 1;
  165410. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165411. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165412. cinfo->Y_density = 1;
  165413. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165414. jpeg_default_colorspace(cinfo);
  165415. }
  165416. /*
  165417. * Select an appropriate JPEG colorspace for in_color_space.
  165418. */
  165419. GLOBAL(void)
  165420. jpeg_default_colorspace (j_compress_ptr cinfo)
  165421. {
  165422. switch (cinfo->in_color_space) {
  165423. case JCS_GRAYSCALE:
  165424. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165425. break;
  165426. case JCS_RGB:
  165427. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165428. break;
  165429. case JCS_YCbCr:
  165430. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165431. break;
  165432. case JCS_CMYK:
  165433. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165434. break;
  165435. case JCS_YCCK:
  165436. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165437. break;
  165438. case JCS_UNKNOWN:
  165439. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165440. break;
  165441. default:
  165442. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165443. }
  165444. }
  165445. /*
  165446. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165447. */
  165448. GLOBAL(void)
  165449. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165450. {
  165451. jpeg_component_info * compptr;
  165452. int ci;
  165453. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165454. (compptr = &cinfo->comp_info[index], \
  165455. compptr->component_id = (id), \
  165456. compptr->h_samp_factor = (hsamp), \
  165457. compptr->v_samp_factor = (vsamp), \
  165458. compptr->quant_tbl_no = (quant), \
  165459. compptr->dc_tbl_no = (dctbl), \
  165460. compptr->ac_tbl_no = (actbl) )
  165461. /* Safety check to ensure start_compress not called yet. */
  165462. if (cinfo->global_state != CSTATE_START)
  165463. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165464. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165465. * tables 1 for chrominance components.
  165466. */
  165467. cinfo->jpeg_color_space = colorspace;
  165468. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165469. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165470. switch (colorspace) {
  165471. case JCS_GRAYSCALE:
  165472. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165473. cinfo->num_components = 1;
  165474. /* JFIF specifies component ID 1 */
  165475. SET_COMP(0, 1, 1,1, 0, 0,0);
  165476. break;
  165477. case JCS_RGB:
  165478. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165479. cinfo->num_components = 3;
  165480. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165481. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165482. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165483. break;
  165484. case JCS_YCbCr:
  165485. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165486. cinfo->num_components = 3;
  165487. /* JFIF specifies component IDs 1,2,3 */
  165488. /* We default to 2x2 subsamples of chrominance */
  165489. SET_COMP(0, 1, 2,2, 0, 0,0);
  165490. SET_COMP(1, 2, 1,1, 1, 1,1);
  165491. SET_COMP(2, 3, 1,1, 1, 1,1);
  165492. break;
  165493. case JCS_CMYK:
  165494. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165495. cinfo->num_components = 4;
  165496. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165497. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165498. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165499. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165500. break;
  165501. case JCS_YCCK:
  165502. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165503. cinfo->num_components = 4;
  165504. SET_COMP(0, 1, 2,2, 0, 0,0);
  165505. SET_COMP(1, 2, 1,1, 1, 1,1);
  165506. SET_COMP(2, 3, 1,1, 1, 1,1);
  165507. SET_COMP(3, 4, 2,2, 0, 0,0);
  165508. break;
  165509. case JCS_UNKNOWN:
  165510. cinfo->num_components = cinfo->input_components;
  165511. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165512. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165513. MAX_COMPONENTS);
  165514. for (ci = 0; ci < cinfo->num_components; ci++) {
  165515. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165516. }
  165517. break;
  165518. default:
  165519. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165520. }
  165521. }
  165522. #ifdef C_PROGRESSIVE_SUPPORTED
  165523. LOCAL(jpeg_scan_info *)
  165524. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165525. int Ss, int Se, int Ah, int Al)
  165526. /* Support routine: generate one scan for specified component */
  165527. {
  165528. scanptr->comps_in_scan = 1;
  165529. scanptr->component_index[0] = ci;
  165530. scanptr->Ss = Ss;
  165531. scanptr->Se = Se;
  165532. scanptr->Ah = Ah;
  165533. scanptr->Al = Al;
  165534. scanptr++;
  165535. return scanptr;
  165536. }
  165537. LOCAL(jpeg_scan_info *)
  165538. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165539. int Ss, int Se, int Ah, int Al)
  165540. /* Support routine: generate one scan for each component */
  165541. {
  165542. int ci;
  165543. for (ci = 0; ci < ncomps; ci++) {
  165544. scanptr->comps_in_scan = 1;
  165545. scanptr->component_index[0] = ci;
  165546. scanptr->Ss = Ss;
  165547. scanptr->Se = Se;
  165548. scanptr->Ah = Ah;
  165549. scanptr->Al = Al;
  165550. scanptr++;
  165551. }
  165552. return scanptr;
  165553. }
  165554. LOCAL(jpeg_scan_info *)
  165555. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165556. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165557. {
  165558. int ci;
  165559. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165560. /* Single interleaved DC scan */
  165561. scanptr->comps_in_scan = ncomps;
  165562. for (ci = 0; ci < ncomps; ci++)
  165563. scanptr->component_index[ci] = ci;
  165564. scanptr->Ss = scanptr->Se = 0;
  165565. scanptr->Ah = Ah;
  165566. scanptr->Al = Al;
  165567. scanptr++;
  165568. } else {
  165569. /* Noninterleaved DC scan for each component */
  165570. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165571. }
  165572. return scanptr;
  165573. }
  165574. /*
  165575. * Create a recommended progressive-JPEG script.
  165576. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165577. */
  165578. GLOBAL(void)
  165579. jpeg_simple_progression (j_compress_ptr cinfo)
  165580. {
  165581. int ncomps = cinfo->num_components;
  165582. int nscans;
  165583. jpeg_scan_info * scanptr;
  165584. /* Safety check to ensure start_compress not called yet. */
  165585. if (cinfo->global_state != CSTATE_START)
  165586. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165587. /* Figure space needed for script. Calculation must match code below! */
  165588. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165589. /* Custom script for YCbCr color images. */
  165590. nscans = 10;
  165591. } else {
  165592. /* All-purpose script for other color spaces. */
  165593. if (ncomps > MAX_COMPS_IN_SCAN)
  165594. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165595. else
  165596. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165597. }
  165598. /* Allocate space for script.
  165599. * We need to put it in the permanent pool in case the application performs
  165600. * multiple compressions without changing the settings. To avoid a memory
  165601. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165602. * object, we try to re-use previously allocated space, and we allocate
  165603. * enough space to handle YCbCr even if initially asked for grayscale.
  165604. */
  165605. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165606. cinfo->script_space_size = MAX(nscans, 10);
  165607. cinfo->script_space = (jpeg_scan_info *)
  165608. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165609. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165610. }
  165611. scanptr = cinfo->script_space;
  165612. cinfo->scan_info = scanptr;
  165613. cinfo->num_scans = nscans;
  165614. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165615. /* Custom script for YCbCr color images. */
  165616. /* Initial DC scan */
  165617. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165618. /* Initial AC scan: get some luma data out in a hurry */
  165619. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165620. /* Chroma data is too small to be worth expending many scans on */
  165621. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165622. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165623. /* Complete spectral selection for luma AC */
  165624. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165625. /* Refine next bit of luma AC */
  165626. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165627. /* Finish DC successive approximation */
  165628. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165629. /* Finish AC successive approximation */
  165630. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165631. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165632. /* Luma bottom bit comes last since it's usually largest scan */
  165633. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165634. } else {
  165635. /* All-purpose script for other color spaces. */
  165636. /* Successive approximation first pass */
  165637. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165638. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165639. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165640. /* Successive approximation second pass */
  165641. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165642. /* Successive approximation final pass */
  165643. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165644. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165645. }
  165646. }
  165647. #endif /* C_PROGRESSIVE_SUPPORTED */
  165648. /*** End of inlined file: jcparam.c ***/
  165649. /*** Start of inlined file: jcphuff.c ***/
  165650. #define JPEG_INTERNALS
  165651. #ifdef C_PROGRESSIVE_SUPPORTED
  165652. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165653. typedef struct {
  165654. struct jpeg_entropy_encoder pub; /* public fields */
  165655. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165656. boolean gather_statistics;
  165657. /* Bit-level coding status.
  165658. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165659. */
  165660. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165661. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165662. INT32 put_buffer; /* current bit-accumulation buffer */
  165663. int put_bits; /* # of bits now in it */
  165664. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165665. /* Coding status for DC components */
  165666. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165667. /* Coding status for AC components */
  165668. int ac_tbl_no; /* the table number of the single component */
  165669. unsigned int EOBRUN; /* run length of EOBs */
  165670. unsigned int BE; /* # of buffered correction bits before MCU */
  165671. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165672. /* packing correction bits tightly would save some space but cost time... */
  165673. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165674. int next_restart_num; /* next restart number to write (0-7) */
  165675. /* Pointers to derived tables (these workspaces have image lifespan).
  165676. * Since any one scan codes only DC or only AC, we only need one set
  165677. * of tables, not one for DC and one for AC.
  165678. */
  165679. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165680. /* Statistics tables for optimization; again, one set is enough */
  165681. long * count_ptrs[NUM_HUFF_TBLS];
  165682. } phuff_entropy_encoder;
  165683. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165684. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165685. * buffer can hold. Larger sizes may slightly improve compression, but
  165686. * 1000 is already well into the realm of overkill.
  165687. * The minimum safe size is 64 bits.
  165688. */
  165689. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165690. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165691. * We assume that int right shift is unsigned if INT32 right shift is,
  165692. * which should be safe.
  165693. */
  165694. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165695. #define ISHIFT_TEMPS int ishift_temp;
  165696. #define IRIGHT_SHIFT(x,shft) \
  165697. ((ishift_temp = (x)) < 0 ? \
  165698. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165699. (ishift_temp >> (shft)))
  165700. #else
  165701. #define ISHIFT_TEMPS
  165702. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165703. #endif
  165704. /* Forward declarations */
  165705. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165706. JBLOCKROW *MCU_data));
  165707. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165708. JBLOCKROW *MCU_data));
  165709. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165710. JBLOCKROW *MCU_data));
  165711. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165712. JBLOCKROW *MCU_data));
  165713. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165714. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165715. /*
  165716. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165717. */
  165718. METHODDEF(void)
  165719. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165720. {
  165721. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165722. boolean is_DC_band;
  165723. int ci, tbl;
  165724. jpeg_component_info * compptr;
  165725. entropy->cinfo = cinfo;
  165726. entropy->gather_statistics = gather_statistics;
  165727. is_DC_band = (cinfo->Ss == 0);
  165728. /* We assume jcmaster.c already validated the scan parameters. */
  165729. /* Select execution routines */
  165730. if (cinfo->Ah == 0) {
  165731. if (is_DC_band)
  165732. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165733. else
  165734. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165735. } else {
  165736. if (is_DC_band)
  165737. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165738. else {
  165739. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165740. /* AC refinement needs a correction bit buffer */
  165741. if (entropy->bit_buffer == NULL)
  165742. entropy->bit_buffer = (char *)
  165743. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165744. MAX_CORR_BITS * SIZEOF(char));
  165745. }
  165746. }
  165747. if (gather_statistics)
  165748. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165749. else
  165750. entropy->pub.finish_pass = finish_pass_phuff;
  165751. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165752. * for AC coefficients.
  165753. */
  165754. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165755. compptr = cinfo->cur_comp_info[ci];
  165756. /* Initialize DC predictions to 0 */
  165757. entropy->last_dc_val[ci] = 0;
  165758. /* Get table index */
  165759. if (is_DC_band) {
  165760. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165761. continue;
  165762. tbl = compptr->dc_tbl_no;
  165763. } else {
  165764. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165765. }
  165766. if (gather_statistics) {
  165767. /* Check for invalid table index */
  165768. /* (make_c_derived_tbl does this in the other path) */
  165769. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165770. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165771. /* Allocate and zero the statistics tables */
  165772. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165773. if (entropy->count_ptrs[tbl] == NULL)
  165774. entropy->count_ptrs[tbl] = (long *)
  165775. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165776. 257 * SIZEOF(long));
  165777. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165778. } else {
  165779. /* Compute derived values for Huffman table */
  165780. /* We may do this more than once for a table, but it's not expensive */
  165781. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165782. & entropy->derived_tbls[tbl]);
  165783. }
  165784. }
  165785. /* Initialize AC stuff */
  165786. entropy->EOBRUN = 0;
  165787. entropy->BE = 0;
  165788. /* Initialize bit buffer to empty */
  165789. entropy->put_buffer = 0;
  165790. entropy->put_bits = 0;
  165791. /* Initialize restart stuff */
  165792. entropy->restarts_to_go = cinfo->restart_interval;
  165793. entropy->next_restart_num = 0;
  165794. }
  165795. /* Outputting bytes to the file.
  165796. * NB: these must be called only when actually outputting,
  165797. * that is, entropy->gather_statistics == FALSE.
  165798. */
  165799. /* Emit a byte */
  165800. #define emit_byte(entropy,val) \
  165801. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165802. if (--(entropy)->free_in_buffer == 0) \
  165803. dump_buffer_p(entropy); }
  165804. LOCAL(void)
  165805. dump_buffer_p (phuff_entropy_ptr entropy)
  165806. /* Empty the output buffer; we do not support suspension in this module. */
  165807. {
  165808. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165809. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165810. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165811. /* After a successful buffer dump, must reset buffer pointers */
  165812. entropy->next_output_byte = dest->next_output_byte;
  165813. entropy->free_in_buffer = dest->free_in_buffer;
  165814. }
  165815. /* Outputting bits to the file */
  165816. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165817. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165818. * in one call, and we never retain more than 7 bits in put_buffer
  165819. * between calls, so 24 bits are sufficient.
  165820. */
  165821. INLINE
  165822. LOCAL(void)
  165823. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165824. /* Emit some bits, unless we are in gather mode */
  165825. {
  165826. /* This routine is heavily used, so it's worth coding tightly. */
  165827. register INT32 put_buffer = (INT32) code;
  165828. register int put_bits = entropy->put_bits;
  165829. /* if size is 0, caller used an invalid Huffman table entry */
  165830. if (size == 0)
  165831. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165832. if (entropy->gather_statistics)
  165833. return; /* do nothing if we're only getting stats */
  165834. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165835. put_bits += size; /* new number of bits in buffer */
  165836. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165837. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165838. while (put_bits >= 8) {
  165839. int c = (int) ((put_buffer >> 16) & 0xFF);
  165840. emit_byte(entropy, c);
  165841. if (c == 0xFF) { /* need to stuff a zero byte? */
  165842. emit_byte(entropy, 0);
  165843. }
  165844. put_buffer <<= 8;
  165845. put_bits -= 8;
  165846. }
  165847. entropy->put_buffer = put_buffer; /* update variables */
  165848. entropy->put_bits = put_bits;
  165849. }
  165850. LOCAL(void)
  165851. flush_bits_p (phuff_entropy_ptr entropy)
  165852. {
  165853. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165854. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165855. entropy->put_bits = 0;
  165856. }
  165857. /*
  165858. * Emit (or just count) a Huffman symbol.
  165859. */
  165860. INLINE
  165861. LOCAL(void)
  165862. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165863. {
  165864. if (entropy->gather_statistics)
  165865. entropy->count_ptrs[tbl_no][symbol]++;
  165866. else {
  165867. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165868. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165869. }
  165870. }
  165871. /*
  165872. * Emit bits from a correction bit buffer.
  165873. */
  165874. LOCAL(void)
  165875. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165876. unsigned int nbits)
  165877. {
  165878. if (entropy->gather_statistics)
  165879. return; /* no real work */
  165880. while (nbits > 0) {
  165881. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165882. bufstart++;
  165883. nbits--;
  165884. }
  165885. }
  165886. /*
  165887. * Emit any pending EOBRUN symbol.
  165888. */
  165889. LOCAL(void)
  165890. emit_eobrun (phuff_entropy_ptr entropy)
  165891. {
  165892. register int temp, nbits;
  165893. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165894. temp = entropy->EOBRUN;
  165895. nbits = 0;
  165896. while ((temp >>= 1))
  165897. nbits++;
  165898. /* safety check: shouldn't happen given limited correction-bit buffer */
  165899. if (nbits > 14)
  165900. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165901. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165902. if (nbits)
  165903. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165904. entropy->EOBRUN = 0;
  165905. /* Emit any buffered correction bits */
  165906. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165907. entropy->BE = 0;
  165908. }
  165909. }
  165910. /*
  165911. * Emit a restart marker & resynchronize predictions.
  165912. */
  165913. LOCAL(void)
  165914. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165915. {
  165916. int ci;
  165917. emit_eobrun(entropy);
  165918. if (! entropy->gather_statistics) {
  165919. flush_bits_p(entropy);
  165920. emit_byte(entropy, 0xFF);
  165921. emit_byte(entropy, JPEG_RST0 + restart_num);
  165922. }
  165923. if (entropy->cinfo->Ss == 0) {
  165924. /* Re-initialize DC predictions to 0 */
  165925. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165926. entropy->last_dc_val[ci] = 0;
  165927. } else {
  165928. /* Re-initialize all AC-related fields to 0 */
  165929. entropy->EOBRUN = 0;
  165930. entropy->BE = 0;
  165931. }
  165932. }
  165933. /*
  165934. * MCU encoding for DC initial scan (either spectral selection,
  165935. * or first pass of successive approximation).
  165936. */
  165937. METHODDEF(boolean)
  165938. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165939. {
  165940. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165941. register int temp, temp2;
  165942. register int nbits;
  165943. int blkn, ci;
  165944. int Al = cinfo->Al;
  165945. JBLOCKROW block;
  165946. jpeg_component_info * compptr;
  165947. ISHIFT_TEMPS
  165948. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165949. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165950. /* Emit restart marker if needed */
  165951. if (cinfo->restart_interval)
  165952. if (entropy->restarts_to_go == 0)
  165953. emit_restart_p(entropy, entropy->next_restart_num);
  165954. /* Encode the MCU data blocks */
  165955. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165956. block = MCU_data[blkn];
  165957. ci = cinfo->MCU_membership[blkn];
  165958. compptr = cinfo->cur_comp_info[ci];
  165959. /* Compute the DC value after the required point transform by Al.
  165960. * This is simply an arithmetic right shift.
  165961. */
  165962. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165963. /* DC differences are figured on the point-transformed values. */
  165964. temp = temp2 - entropy->last_dc_val[ci];
  165965. entropy->last_dc_val[ci] = temp2;
  165966. /* Encode the DC coefficient difference per section G.1.2.1 */
  165967. temp2 = temp;
  165968. if (temp < 0) {
  165969. temp = -temp; /* temp is abs value of input */
  165970. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165971. /* This code assumes we are on a two's complement machine */
  165972. temp2--;
  165973. }
  165974. /* Find the number of bits needed for the magnitude of the coefficient */
  165975. nbits = 0;
  165976. while (temp) {
  165977. nbits++;
  165978. temp >>= 1;
  165979. }
  165980. /* Check for out-of-range coefficient values.
  165981. * Since we're encoding a difference, the range limit is twice as much.
  165982. */
  165983. if (nbits > MAX_COEF_BITS+1)
  165984. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165985. /* Count/emit the Huffman-coded symbol for the number of bits */
  165986. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165987. /* Emit that number of bits of the value, if positive, */
  165988. /* or the complement of its magnitude, if negative. */
  165989. if (nbits) /* emit_bits rejects calls with size 0 */
  165990. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165991. }
  165992. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165993. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165994. /* Update restart-interval state too */
  165995. if (cinfo->restart_interval) {
  165996. if (entropy->restarts_to_go == 0) {
  165997. entropy->restarts_to_go = cinfo->restart_interval;
  165998. entropy->next_restart_num++;
  165999. entropy->next_restart_num &= 7;
  166000. }
  166001. entropy->restarts_to_go--;
  166002. }
  166003. return TRUE;
  166004. }
  166005. /*
  166006. * MCU encoding for AC initial scan (either spectral selection,
  166007. * or first pass of successive approximation).
  166008. */
  166009. METHODDEF(boolean)
  166010. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166011. {
  166012. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166013. register int temp, temp2;
  166014. register int nbits;
  166015. register int r, k;
  166016. int Se = cinfo->Se;
  166017. int Al = cinfo->Al;
  166018. JBLOCKROW block;
  166019. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166020. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166021. /* Emit restart marker if needed */
  166022. if (cinfo->restart_interval)
  166023. if (entropy->restarts_to_go == 0)
  166024. emit_restart_p(entropy, entropy->next_restart_num);
  166025. /* Encode the MCU data block */
  166026. block = MCU_data[0];
  166027. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166028. r = 0; /* r = run length of zeros */
  166029. for (k = cinfo->Ss; k <= Se; k++) {
  166030. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166031. r++;
  166032. continue;
  166033. }
  166034. /* We must apply the point transform by Al. For AC coefficients this
  166035. * is an integer division with rounding towards 0. To do this portably
  166036. * in C, we shift after obtaining the absolute value; so the code is
  166037. * interwoven with finding the abs value (temp) and output bits (temp2).
  166038. */
  166039. if (temp < 0) {
  166040. temp = -temp; /* temp is abs value of input */
  166041. temp >>= Al; /* apply the point transform */
  166042. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166043. temp2 = ~temp;
  166044. } else {
  166045. temp >>= Al; /* apply the point transform */
  166046. temp2 = temp;
  166047. }
  166048. /* Watch out for case that nonzero coef is zero after point transform */
  166049. if (temp == 0) {
  166050. r++;
  166051. continue;
  166052. }
  166053. /* Emit any pending EOBRUN */
  166054. if (entropy->EOBRUN > 0)
  166055. emit_eobrun(entropy);
  166056. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166057. while (r > 15) {
  166058. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166059. r -= 16;
  166060. }
  166061. /* Find the number of bits needed for the magnitude of the coefficient */
  166062. nbits = 1; /* there must be at least one 1 bit */
  166063. while ((temp >>= 1))
  166064. nbits++;
  166065. /* Check for out-of-range coefficient values */
  166066. if (nbits > MAX_COEF_BITS)
  166067. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166068. /* Count/emit Huffman symbol for run length / number of bits */
  166069. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166070. /* Emit that number of bits of the value, if positive, */
  166071. /* or the complement of its magnitude, if negative. */
  166072. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166073. r = 0; /* reset zero run length */
  166074. }
  166075. if (r > 0) { /* If there are trailing zeroes, */
  166076. entropy->EOBRUN++; /* count an EOB */
  166077. if (entropy->EOBRUN == 0x7FFF)
  166078. emit_eobrun(entropy); /* force it out to avoid overflow */
  166079. }
  166080. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166081. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166082. /* Update restart-interval state too */
  166083. if (cinfo->restart_interval) {
  166084. if (entropy->restarts_to_go == 0) {
  166085. entropy->restarts_to_go = cinfo->restart_interval;
  166086. entropy->next_restart_num++;
  166087. entropy->next_restart_num &= 7;
  166088. }
  166089. entropy->restarts_to_go--;
  166090. }
  166091. return TRUE;
  166092. }
  166093. /*
  166094. * MCU encoding for DC successive approximation refinement scan.
  166095. * Note: we assume such scans can be multi-component, although the spec
  166096. * is not very clear on the point.
  166097. */
  166098. METHODDEF(boolean)
  166099. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166100. {
  166101. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166102. register int temp;
  166103. int blkn;
  166104. int Al = cinfo->Al;
  166105. JBLOCKROW block;
  166106. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166107. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166108. /* Emit restart marker if needed */
  166109. if (cinfo->restart_interval)
  166110. if (entropy->restarts_to_go == 0)
  166111. emit_restart_p(entropy, entropy->next_restart_num);
  166112. /* Encode the MCU data blocks */
  166113. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166114. block = MCU_data[blkn];
  166115. /* We simply emit the Al'th bit of the DC coefficient value. */
  166116. temp = (*block)[0];
  166117. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166118. }
  166119. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166120. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166121. /* Update restart-interval state too */
  166122. if (cinfo->restart_interval) {
  166123. if (entropy->restarts_to_go == 0) {
  166124. entropy->restarts_to_go = cinfo->restart_interval;
  166125. entropy->next_restart_num++;
  166126. entropy->next_restart_num &= 7;
  166127. }
  166128. entropy->restarts_to_go--;
  166129. }
  166130. return TRUE;
  166131. }
  166132. /*
  166133. * MCU encoding for AC successive approximation refinement scan.
  166134. */
  166135. METHODDEF(boolean)
  166136. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166137. {
  166138. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166139. register int temp;
  166140. register int r, k;
  166141. int EOB;
  166142. char *BR_buffer;
  166143. unsigned int BR;
  166144. int Se = cinfo->Se;
  166145. int Al = cinfo->Al;
  166146. JBLOCKROW block;
  166147. int absvalues[DCTSIZE2];
  166148. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166149. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166150. /* Emit restart marker if needed */
  166151. if (cinfo->restart_interval)
  166152. if (entropy->restarts_to_go == 0)
  166153. emit_restart_p(entropy, entropy->next_restart_num);
  166154. /* Encode the MCU data block */
  166155. block = MCU_data[0];
  166156. /* It is convenient to make a pre-pass to determine the transformed
  166157. * coefficients' absolute values and the EOB position.
  166158. */
  166159. EOB = 0;
  166160. for (k = cinfo->Ss; k <= Se; k++) {
  166161. temp = (*block)[jpeg_natural_order[k]];
  166162. /* We must apply the point transform by Al. For AC coefficients this
  166163. * is an integer division with rounding towards 0. To do this portably
  166164. * in C, we shift after obtaining the absolute value.
  166165. */
  166166. if (temp < 0)
  166167. temp = -temp; /* temp is abs value of input */
  166168. temp >>= Al; /* apply the point transform */
  166169. absvalues[k] = temp; /* save abs value for main pass */
  166170. if (temp == 1)
  166171. EOB = k; /* EOB = index of last newly-nonzero coef */
  166172. }
  166173. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166174. r = 0; /* r = run length of zeros */
  166175. BR = 0; /* BR = count of buffered bits added now */
  166176. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166177. for (k = cinfo->Ss; k <= Se; k++) {
  166178. if ((temp = absvalues[k]) == 0) {
  166179. r++;
  166180. continue;
  166181. }
  166182. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166183. while (r > 15 && k <= EOB) {
  166184. /* emit any pending EOBRUN and the BE correction bits */
  166185. emit_eobrun(entropy);
  166186. /* Emit ZRL */
  166187. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166188. r -= 16;
  166189. /* Emit buffered correction bits that must be associated with ZRL */
  166190. emit_buffered_bits(entropy, BR_buffer, BR);
  166191. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166192. BR = 0;
  166193. }
  166194. /* If the coef was previously nonzero, it only needs a correction bit.
  166195. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166196. * that we also need to test r > 15. But if r > 15, we can only get here
  166197. * if k > EOB, which implies that this coefficient is not 1.
  166198. */
  166199. if (temp > 1) {
  166200. /* The correction bit is the next bit of the absolute value. */
  166201. BR_buffer[BR++] = (char) (temp & 1);
  166202. continue;
  166203. }
  166204. /* Emit any pending EOBRUN and the BE correction bits */
  166205. emit_eobrun(entropy);
  166206. /* Count/emit Huffman symbol for run length / number of bits */
  166207. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166208. /* Emit output bit for newly-nonzero coef */
  166209. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166210. emit_bits_p(entropy, (unsigned int) temp, 1);
  166211. /* Emit buffered correction bits that must be associated with this code */
  166212. emit_buffered_bits(entropy, BR_buffer, BR);
  166213. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166214. BR = 0;
  166215. r = 0; /* reset zero run length */
  166216. }
  166217. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166218. entropy->EOBRUN++; /* count an EOB */
  166219. entropy->BE += BR; /* concat my correction bits to older ones */
  166220. /* We force out the EOB if we risk either:
  166221. * 1. overflow of the EOB counter;
  166222. * 2. overflow of the correction bit buffer during the next MCU.
  166223. */
  166224. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166225. emit_eobrun(entropy);
  166226. }
  166227. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166228. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166229. /* Update restart-interval state too */
  166230. if (cinfo->restart_interval) {
  166231. if (entropy->restarts_to_go == 0) {
  166232. entropy->restarts_to_go = cinfo->restart_interval;
  166233. entropy->next_restart_num++;
  166234. entropy->next_restart_num &= 7;
  166235. }
  166236. entropy->restarts_to_go--;
  166237. }
  166238. return TRUE;
  166239. }
  166240. /*
  166241. * Finish up at the end of a Huffman-compressed progressive scan.
  166242. */
  166243. METHODDEF(void)
  166244. finish_pass_phuff (j_compress_ptr cinfo)
  166245. {
  166246. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166247. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166248. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166249. /* Flush out any buffered data */
  166250. emit_eobrun(entropy);
  166251. flush_bits_p(entropy);
  166252. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166253. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166254. }
  166255. /*
  166256. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166257. */
  166258. METHODDEF(void)
  166259. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166260. {
  166261. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166262. boolean is_DC_band;
  166263. int ci, tbl;
  166264. jpeg_component_info * compptr;
  166265. JHUFF_TBL **htblptr;
  166266. boolean did[NUM_HUFF_TBLS];
  166267. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166268. emit_eobrun(entropy);
  166269. is_DC_band = (cinfo->Ss == 0);
  166270. /* It's important not to apply jpeg_gen_optimal_table more than once
  166271. * per table, because it clobbers the input frequency counts!
  166272. */
  166273. MEMZERO(did, SIZEOF(did));
  166274. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166275. compptr = cinfo->cur_comp_info[ci];
  166276. if (is_DC_band) {
  166277. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166278. continue;
  166279. tbl = compptr->dc_tbl_no;
  166280. } else {
  166281. tbl = compptr->ac_tbl_no;
  166282. }
  166283. if (! did[tbl]) {
  166284. if (is_DC_band)
  166285. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166286. else
  166287. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166288. if (*htblptr == NULL)
  166289. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166290. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166291. did[tbl] = TRUE;
  166292. }
  166293. }
  166294. }
  166295. /*
  166296. * Module initialization routine for progressive Huffman entropy encoding.
  166297. */
  166298. GLOBAL(void)
  166299. jinit_phuff_encoder (j_compress_ptr cinfo)
  166300. {
  166301. phuff_entropy_ptr entropy;
  166302. int i;
  166303. entropy = (phuff_entropy_ptr)
  166304. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166305. SIZEOF(phuff_entropy_encoder));
  166306. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166307. entropy->pub.start_pass = start_pass_phuff;
  166308. /* Mark tables unallocated */
  166309. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166310. entropy->derived_tbls[i] = NULL;
  166311. entropy->count_ptrs[i] = NULL;
  166312. }
  166313. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166314. }
  166315. #endif /* C_PROGRESSIVE_SUPPORTED */
  166316. /*** End of inlined file: jcphuff.c ***/
  166317. /*** Start of inlined file: jcprepct.c ***/
  166318. #define JPEG_INTERNALS
  166319. /* At present, jcsample.c can request context rows only for smoothing.
  166320. * In the future, we might also need context rows for CCIR601 sampling
  166321. * or other more-complex downsampling procedures. The code to support
  166322. * context rows should be compiled only if needed.
  166323. */
  166324. #ifdef INPUT_SMOOTHING_SUPPORTED
  166325. #define CONTEXT_ROWS_SUPPORTED
  166326. #endif
  166327. /*
  166328. * For the simple (no-context-row) case, we just need to buffer one
  166329. * row group's worth of pixels for the downsampling step. At the bottom of
  166330. * the image, we pad to a full row group by replicating the last pixel row.
  166331. * The downsampler's last output row is then replicated if needed to pad
  166332. * out to a full iMCU row.
  166333. *
  166334. * When providing context rows, we must buffer three row groups' worth of
  166335. * pixels. Three row groups are physically allocated, but the row pointer
  166336. * arrays are made five row groups high, with the extra pointers above and
  166337. * below "wrapping around" to point to the last and first real row groups.
  166338. * This allows the downsampler to access the proper context rows.
  166339. * At the top and bottom of the image, we create dummy context rows by
  166340. * copying the first or last real pixel row. This copying could be avoided
  166341. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166342. * trouble on the compression side.
  166343. */
  166344. /* Private buffer controller object */
  166345. typedef struct {
  166346. struct jpeg_c_prep_controller pub; /* public fields */
  166347. /* Downsampling input buffer. This buffer holds color-converted data
  166348. * until we have enough to do a downsample step.
  166349. */
  166350. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166351. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166352. int next_buf_row; /* index of next row to store in color_buf */
  166353. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166354. int this_row_group; /* starting row index of group to process */
  166355. int next_buf_stop; /* downsample when we reach this index */
  166356. #endif
  166357. } my_prep_controller;
  166358. typedef my_prep_controller * my_prep_ptr;
  166359. /*
  166360. * Initialize for a processing pass.
  166361. */
  166362. METHODDEF(void)
  166363. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166364. {
  166365. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166366. if (pass_mode != JBUF_PASS_THRU)
  166367. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166368. /* Initialize total-height counter for detecting bottom of image */
  166369. prep->rows_to_go = cinfo->image_height;
  166370. /* Mark the conversion buffer empty */
  166371. prep->next_buf_row = 0;
  166372. #ifdef CONTEXT_ROWS_SUPPORTED
  166373. /* Preset additional state variables for context mode.
  166374. * These aren't used in non-context mode, so we needn't test which mode.
  166375. */
  166376. prep->this_row_group = 0;
  166377. /* Set next_buf_stop to stop after two row groups have been read in. */
  166378. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166379. #endif
  166380. }
  166381. /*
  166382. * Expand an image vertically from height input_rows to height output_rows,
  166383. * by duplicating the bottom row.
  166384. */
  166385. LOCAL(void)
  166386. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166387. int input_rows, int output_rows)
  166388. {
  166389. register int row;
  166390. for (row = input_rows; row < output_rows; row++) {
  166391. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166392. 1, num_cols);
  166393. }
  166394. }
  166395. /*
  166396. * Process some data in the simple no-context case.
  166397. *
  166398. * Preprocessor output data is counted in "row groups". A row group
  166399. * is defined to be v_samp_factor sample rows of each component.
  166400. * Downsampling will produce this much data from each max_v_samp_factor
  166401. * input rows.
  166402. */
  166403. METHODDEF(void)
  166404. pre_process_data (j_compress_ptr cinfo,
  166405. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166406. JDIMENSION in_rows_avail,
  166407. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166408. JDIMENSION out_row_groups_avail)
  166409. {
  166410. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166411. int numrows, ci;
  166412. JDIMENSION inrows;
  166413. jpeg_component_info * compptr;
  166414. while (*in_row_ctr < in_rows_avail &&
  166415. *out_row_group_ctr < out_row_groups_avail) {
  166416. /* Do color conversion to fill the conversion buffer. */
  166417. inrows = in_rows_avail - *in_row_ctr;
  166418. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166419. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166420. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166421. prep->color_buf,
  166422. (JDIMENSION) prep->next_buf_row,
  166423. numrows);
  166424. *in_row_ctr += numrows;
  166425. prep->next_buf_row += numrows;
  166426. prep->rows_to_go -= numrows;
  166427. /* If at bottom of image, pad to fill the conversion buffer. */
  166428. if (prep->rows_to_go == 0 &&
  166429. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166430. for (ci = 0; ci < cinfo->num_components; ci++) {
  166431. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166432. prep->next_buf_row, cinfo->max_v_samp_factor);
  166433. }
  166434. prep->next_buf_row = cinfo->max_v_samp_factor;
  166435. }
  166436. /* If we've filled the conversion buffer, empty it. */
  166437. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166438. (*cinfo->downsample->downsample) (cinfo,
  166439. prep->color_buf, (JDIMENSION) 0,
  166440. output_buf, *out_row_group_ctr);
  166441. prep->next_buf_row = 0;
  166442. (*out_row_group_ctr)++;
  166443. }
  166444. /* If at bottom of image, pad the output to a full iMCU height.
  166445. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166446. */
  166447. if (prep->rows_to_go == 0 &&
  166448. *out_row_group_ctr < out_row_groups_avail) {
  166449. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166450. ci++, compptr++) {
  166451. expand_bottom_edge(output_buf[ci],
  166452. compptr->width_in_blocks * DCTSIZE,
  166453. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166454. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166455. }
  166456. *out_row_group_ctr = out_row_groups_avail;
  166457. break; /* can exit outer loop without test */
  166458. }
  166459. }
  166460. }
  166461. #ifdef CONTEXT_ROWS_SUPPORTED
  166462. /*
  166463. * Process some data in the context case.
  166464. */
  166465. METHODDEF(void)
  166466. pre_process_context (j_compress_ptr cinfo,
  166467. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166468. JDIMENSION in_rows_avail,
  166469. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166470. JDIMENSION out_row_groups_avail)
  166471. {
  166472. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166473. int numrows, ci;
  166474. int buf_height = cinfo->max_v_samp_factor * 3;
  166475. JDIMENSION inrows;
  166476. while (*out_row_group_ctr < out_row_groups_avail) {
  166477. if (*in_row_ctr < in_rows_avail) {
  166478. /* Do color conversion to fill the conversion buffer. */
  166479. inrows = in_rows_avail - *in_row_ctr;
  166480. numrows = prep->next_buf_stop - prep->next_buf_row;
  166481. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166482. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166483. prep->color_buf,
  166484. (JDIMENSION) prep->next_buf_row,
  166485. numrows);
  166486. /* Pad at top of image, if first time through */
  166487. if (prep->rows_to_go == cinfo->image_height) {
  166488. for (ci = 0; ci < cinfo->num_components; ci++) {
  166489. int row;
  166490. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166491. jcopy_sample_rows(prep->color_buf[ci], 0,
  166492. prep->color_buf[ci], -row,
  166493. 1, cinfo->image_width);
  166494. }
  166495. }
  166496. }
  166497. *in_row_ctr += numrows;
  166498. prep->next_buf_row += numrows;
  166499. prep->rows_to_go -= numrows;
  166500. } else {
  166501. /* Return for more data, unless we are at the bottom of the image. */
  166502. if (prep->rows_to_go != 0)
  166503. break;
  166504. /* When at bottom of image, pad to fill the conversion buffer. */
  166505. if (prep->next_buf_row < prep->next_buf_stop) {
  166506. for (ci = 0; ci < cinfo->num_components; ci++) {
  166507. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166508. prep->next_buf_row, prep->next_buf_stop);
  166509. }
  166510. prep->next_buf_row = prep->next_buf_stop;
  166511. }
  166512. }
  166513. /* If we've gotten enough data, downsample a row group. */
  166514. if (prep->next_buf_row == prep->next_buf_stop) {
  166515. (*cinfo->downsample->downsample) (cinfo,
  166516. prep->color_buf,
  166517. (JDIMENSION) prep->this_row_group,
  166518. output_buf, *out_row_group_ctr);
  166519. (*out_row_group_ctr)++;
  166520. /* Advance pointers with wraparound as necessary. */
  166521. prep->this_row_group += cinfo->max_v_samp_factor;
  166522. if (prep->this_row_group >= buf_height)
  166523. prep->this_row_group = 0;
  166524. if (prep->next_buf_row >= buf_height)
  166525. prep->next_buf_row = 0;
  166526. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166527. }
  166528. }
  166529. }
  166530. /*
  166531. * Create the wrapped-around downsampling input buffer needed for context mode.
  166532. */
  166533. LOCAL(void)
  166534. create_context_buffer (j_compress_ptr cinfo)
  166535. {
  166536. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166537. int rgroup_height = cinfo->max_v_samp_factor;
  166538. int ci, i;
  166539. jpeg_component_info * compptr;
  166540. JSAMPARRAY true_buffer, fake_buffer;
  166541. /* Grab enough space for fake row pointers for all the components;
  166542. * we need five row groups' worth of pointers for each component.
  166543. */
  166544. fake_buffer = (JSAMPARRAY)
  166545. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166546. (cinfo->num_components * 5 * rgroup_height) *
  166547. SIZEOF(JSAMPROW));
  166548. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166549. ci++, compptr++) {
  166550. /* Allocate the actual buffer space (3 row groups) for this component.
  166551. * We make the buffer wide enough to allow the downsampler to edge-expand
  166552. * horizontally within the buffer, if it so chooses.
  166553. */
  166554. true_buffer = (*cinfo->mem->alloc_sarray)
  166555. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166556. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166557. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166558. (JDIMENSION) (3 * rgroup_height));
  166559. /* Copy true buffer row pointers into the middle of the fake row array */
  166560. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166561. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166562. /* Fill in the above and below wraparound pointers */
  166563. for (i = 0; i < rgroup_height; i++) {
  166564. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166565. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166566. }
  166567. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166568. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166569. }
  166570. }
  166571. #endif /* CONTEXT_ROWS_SUPPORTED */
  166572. /*
  166573. * Initialize preprocessing controller.
  166574. */
  166575. GLOBAL(void)
  166576. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166577. {
  166578. my_prep_ptr prep;
  166579. int ci;
  166580. jpeg_component_info * compptr;
  166581. if (need_full_buffer) /* safety check */
  166582. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166583. prep = (my_prep_ptr)
  166584. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166585. SIZEOF(my_prep_controller));
  166586. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166587. prep->pub.start_pass = start_pass_prep;
  166588. /* Allocate the color conversion buffer.
  166589. * We make the buffer wide enough to allow the downsampler to edge-expand
  166590. * horizontally within the buffer, if it so chooses.
  166591. */
  166592. if (cinfo->downsample->need_context_rows) {
  166593. /* Set up to provide context rows */
  166594. #ifdef CONTEXT_ROWS_SUPPORTED
  166595. prep->pub.pre_process_data = pre_process_context;
  166596. create_context_buffer(cinfo);
  166597. #else
  166598. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166599. #endif
  166600. } else {
  166601. /* No context, just make it tall enough for one row group */
  166602. prep->pub.pre_process_data = pre_process_data;
  166603. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166604. ci++, compptr++) {
  166605. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166606. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166607. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166608. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166609. (JDIMENSION) cinfo->max_v_samp_factor);
  166610. }
  166611. }
  166612. }
  166613. /*** End of inlined file: jcprepct.c ***/
  166614. /*** Start of inlined file: jcsample.c ***/
  166615. #define JPEG_INTERNALS
  166616. /* Pointer to routine to downsample a single component */
  166617. typedef JMETHOD(void, downsample1_ptr,
  166618. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166619. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166620. /* Private subobject */
  166621. typedef struct {
  166622. struct jpeg_downsampler pub; /* public fields */
  166623. /* Downsampling method pointers, one per component */
  166624. downsample1_ptr methods[MAX_COMPONENTS];
  166625. } my_downsampler;
  166626. typedef my_downsampler * my_downsample_ptr;
  166627. /*
  166628. * Initialize for a downsampling pass.
  166629. */
  166630. METHODDEF(void)
  166631. start_pass_downsample (j_compress_ptr)
  166632. {
  166633. /* no work for now */
  166634. }
  166635. /*
  166636. * Expand a component horizontally from width input_cols to width output_cols,
  166637. * by duplicating the rightmost samples.
  166638. */
  166639. LOCAL(void)
  166640. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166641. JDIMENSION input_cols, JDIMENSION output_cols)
  166642. {
  166643. register JSAMPROW ptr;
  166644. register JSAMPLE pixval;
  166645. register int count;
  166646. int row;
  166647. int numcols = (int) (output_cols - input_cols);
  166648. if (numcols > 0) {
  166649. for (row = 0; row < num_rows; row++) {
  166650. ptr = image_data[row] + input_cols;
  166651. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166652. for (count = numcols; count > 0; count--)
  166653. *ptr++ = pixval;
  166654. }
  166655. }
  166656. }
  166657. /*
  166658. * Do downsampling for a whole row group (all components).
  166659. *
  166660. * In this version we simply downsample each component independently.
  166661. */
  166662. METHODDEF(void)
  166663. sep_downsample (j_compress_ptr cinfo,
  166664. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166665. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166666. {
  166667. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166668. int ci;
  166669. jpeg_component_info * compptr;
  166670. JSAMPARRAY in_ptr, out_ptr;
  166671. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166672. ci++, compptr++) {
  166673. in_ptr = input_buf[ci] + in_row_index;
  166674. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166675. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166676. }
  166677. }
  166678. /*
  166679. * Downsample pixel values of a single component.
  166680. * One row group is processed per call.
  166681. * This version handles arbitrary integral sampling ratios, without smoothing.
  166682. * Note that this version is not actually used for customary sampling ratios.
  166683. */
  166684. METHODDEF(void)
  166685. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166686. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166687. {
  166688. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166689. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166690. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166691. JSAMPROW inptr, outptr;
  166692. INT32 outvalue;
  166693. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166694. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166695. numpix = h_expand * v_expand;
  166696. numpix2 = numpix/2;
  166697. /* Expand input data enough to let all the output samples be generated
  166698. * by the standard loop. Special-casing padded output would be more
  166699. * efficient.
  166700. */
  166701. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166702. cinfo->image_width, output_cols * h_expand);
  166703. inrow = 0;
  166704. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166705. outptr = output_data[outrow];
  166706. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166707. outcol++, outcol_h += h_expand) {
  166708. outvalue = 0;
  166709. for (v = 0; v < v_expand; v++) {
  166710. inptr = input_data[inrow+v] + outcol_h;
  166711. for (h = 0; h < h_expand; h++) {
  166712. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166713. }
  166714. }
  166715. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166716. }
  166717. inrow += v_expand;
  166718. }
  166719. }
  166720. /*
  166721. * Downsample pixel values of a single component.
  166722. * This version handles the special case of a full-size component,
  166723. * without smoothing.
  166724. */
  166725. METHODDEF(void)
  166726. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166727. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166728. {
  166729. /* Copy the data */
  166730. jcopy_sample_rows(input_data, 0, output_data, 0,
  166731. cinfo->max_v_samp_factor, cinfo->image_width);
  166732. /* Edge-expand */
  166733. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166734. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166735. }
  166736. /*
  166737. * Downsample pixel values of a single component.
  166738. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166739. * without smoothing.
  166740. *
  166741. * A note about the "bias" calculations: when rounding fractional values to
  166742. * integer, we do not want to always round 0.5 up to the next integer.
  166743. * If we did that, we'd introduce a noticeable bias towards larger values.
  166744. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166745. * alternate pixel locations (a simple ordered dither pattern).
  166746. */
  166747. METHODDEF(void)
  166748. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166749. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166750. {
  166751. int outrow;
  166752. JDIMENSION outcol;
  166753. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166754. register JSAMPROW inptr, outptr;
  166755. register int bias;
  166756. /* Expand input data enough to let all the output samples be generated
  166757. * by the standard loop. Special-casing padded output would be more
  166758. * efficient.
  166759. */
  166760. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166761. cinfo->image_width, output_cols * 2);
  166762. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166763. outptr = output_data[outrow];
  166764. inptr = input_data[outrow];
  166765. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166766. for (outcol = 0; outcol < output_cols; outcol++) {
  166767. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166768. + bias) >> 1);
  166769. bias ^= 1; /* 0=>1, 1=>0 */
  166770. inptr += 2;
  166771. }
  166772. }
  166773. }
  166774. /*
  166775. * Downsample pixel values of a single component.
  166776. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166777. * without smoothing.
  166778. */
  166779. METHODDEF(void)
  166780. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166781. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166782. {
  166783. int inrow, outrow;
  166784. JDIMENSION outcol;
  166785. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166786. register JSAMPROW inptr0, inptr1, outptr;
  166787. register int bias;
  166788. /* Expand input data enough to let all the output samples be generated
  166789. * by the standard loop. Special-casing padded output would be more
  166790. * efficient.
  166791. */
  166792. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166793. cinfo->image_width, output_cols * 2);
  166794. inrow = 0;
  166795. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166796. outptr = output_data[outrow];
  166797. inptr0 = input_data[inrow];
  166798. inptr1 = input_data[inrow+1];
  166799. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166800. for (outcol = 0; outcol < output_cols; outcol++) {
  166801. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166802. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166803. + bias) >> 2);
  166804. bias ^= 3; /* 1=>2, 2=>1 */
  166805. inptr0 += 2; inptr1 += 2;
  166806. }
  166807. inrow += 2;
  166808. }
  166809. }
  166810. #ifdef INPUT_SMOOTHING_SUPPORTED
  166811. /*
  166812. * Downsample pixel values of a single component.
  166813. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166814. * with smoothing. One row of context is required.
  166815. */
  166816. METHODDEF(void)
  166817. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166818. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166819. {
  166820. int inrow, outrow;
  166821. JDIMENSION colctr;
  166822. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166823. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166824. INT32 membersum, neighsum, memberscale, neighscale;
  166825. /* Expand input data enough to let all the output samples be generated
  166826. * by the standard loop. Special-casing padded output would be more
  166827. * efficient.
  166828. */
  166829. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166830. cinfo->image_width, output_cols * 2);
  166831. /* We don't bother to form the individual "smoothed" input pixel values;
  166832. * we can directly compute the output which is the average of the four
  166833. * smoothed values. Each of the four member pixels contributes a fraction
  166834. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166835. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166836. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166837. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166838. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166839. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166840. * factors are scaled by 2^16 = 65536.
  166841. * Also recall that SF = smoothing_factor / 1024.
  166842. */
  166843. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166844. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166845. inrow = 0;
  166846. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166847. outptr = output_data[outrow];
  166848. inptr0 = input_data[inrow];
  166849. inptr1 = input_data[inrow+1];
  166850. above_ptr = input_data[inrow-1];
  166851. below_ptr = input_data[inrow+2];
  166852. /* Special case for first column: pretend column -1 is same as column 0 */
  166853. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166854. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166855. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166856. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166857. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166858. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166859. neighsum += neighsum;
  166860. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166861. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166862. membersum = membersum * memberscale + neighsum * neighscale;
  166863. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166864. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166865. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166866. /* sum of pixels directly mapped to this output element */
  166867. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166868. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166869. /* sum of edge-neighbor pixels */
  166870. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166871. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166872. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166873. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166874. /* The edge-neighbors count twice as much as corner-neighbors */
  166875. neighsum += neighsum;
  166876. /* Add in the corner-neighbors */
  166877. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166878. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166879. /* form final output scaled up by 2^16 */
  166880. membersum = membersum * memberscale + neighsum * neighscale;
  166881. /* round, descale and output it */
  166882. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166883. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166884. }
  166885. /* Special case for last column */
  166886. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166887. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166888. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166889. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166890. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166891. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166892. neighsum += neighsum;
  166893. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166894. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166895. membersum = membersum * memberscale + neighsum * neighscale;
  166896. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166897. inrow += 2;
  166898. }
  166899. }
  166900. /*
  166901. * Downsample pixel values of a single component.
  166902. * This version handles the special case of a full-size component,
  166903. * with smoothing. One row of context is required.
  166904. */
  166905. METHODDEF(void)
  166906. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166907. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166908. {
  166909. int outrow;
  166910. JDIMENSION colctr;
  166911. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166912. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166913. INT32 membersum, neighsum, memberscale, neighscale;
  166914. int colsum, lastcolsum, nextcolsum;
  166915. /* Expand input data enough to let all the output samples be generated
  166916. * by the standard loop. Special-casing padded output would be more
  166917. * efficient.
  166918. */
  166919. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166920. cinfo->image_width, output_cols);
  166921. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166922. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166923. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166924. * Also recall that SF = smoothing_factor / 1024.
  166925. */
  166926. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166927. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166928. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166929. outptr = output_data[outrow];
  166930. inptr = input_data[outrow];
  166931. above_ptr = input_data[outrow-1];
  166932. below_ptr = input_data[outrow+1];
  166933. /* Special case for first column */
  166934. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166935. GETJSAMPLE(*inptr);
  166936. membersum = GETJSAMPLE(*inptr++);
  166937. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166938. GETJSAMPLE(*inptr);
  166939. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166940. membersum = membersum * memberscale + neighsum * neighscale;
  166941. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166942. lastcolsum = colsum; colsum = nextcolsum;
  166943. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166944. membersum = GETJSAMPLE(*inptr++);
  166945. above_ptr++; below_ptr++;
  166946. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166947. GETJSAMPLE(*inptr);
  166948. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166949. membersum = membersum * memberscale + neighsum * neighscale;
  166950. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166951. lastcolsum = colsum; colsum = nextcolsum;
  166952. }
  166953. /* Special case for last column */
  166954. membersum = GETJSAMPLE(*inptr);
  166955. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166956. membersum = membersum * memberscale + neighsum * neighscale;
  166957. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166958. }
  166959. }
  166960. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166961. /*
  166962. * Module initialization routine for downsampling.
  166963. * Note that we must select a routine for each component.
  166964. */
  166965. GLOBAL(void)
  166966. jinit_downsampler (j_compress_ptr cinfo)
  166967. {
  166968. my_downsample_ptr downsample;
  166969. int ci;
  166970. jpeg_component_info * compptr;
  166971. boolean smoothok = TRUE;
  166972. downsample = (my_downsample_ptr)
  166973. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166974. SIZEOF(my_downsampler));
  166975. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166976. downsample->pub.start_pass = start_pass_downsample;
  166977. downsample->pub.downsample = sep_downsample;
  166978. downsample->pub.need_context_rows = FALSE;
  166979. if (cinfo->CCIR601_sampling)
  166980. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166981. /* Verify we can handle the sampling factors, and set up method pointers */
  166982. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166983. ci++, compptr++) {
  166984. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166985. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166986. #ifdef INPUT_SMOOTHING_SUPPORTED
  166987. if (cinfo->smoothing_factor) {
  166988. downsample->methods[ci] = fullsize_smooth_downsample;
  166989. downsample->pub.need_context_rows = TRUE;
  166990. } else
  166991. #endif
  166992. downsample->methods[ci] = fullsize_downsample;
  166993. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166994. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166995. smoothok = FALSE;
  166996. downsample->methods[ci] = h2v1_downsample;
  166997. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166998. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166999. #ifdef INPUT_SMOOTHING_SUPPORTED
  167000. if (cinfo->smoothing_factor) {
  167001. downsample->methods[ci] = h2v2_smooth_downsample;
  167002. downsample->pub.need_context_rows = TRUE;
  167003. } else
  167004. #endif
  167005. downsample->methods[ci] = h2v2_downsample;
  167006. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167007. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167008. smoothok = FALSE;
  167009. downsample->methods[ci] = int_downsample;
  167010. } else
  167011. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167012. }
  167013. #ifdef INPUT_SMOOTHING_SUPPORTED
  167014. if (cinfo->smoothing_factor && !smoothok)
  167015. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167016. #endif
  167017. }
  167018. /*** End of inlined file: jcsample.c ***/
  167019. /*** Start of inlined file: jctrans.c ***/
  167020. #define JPEG_INTERNALS
  167021. /* Forward declarations */
  167022. LOCAL(void) transencode_master_selection
  167023. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167024. LOCAL(void) transencode_coef_controller
  167025. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167026. /*
  167027. * Compression initialization for writing raw-coefficient data.
  167028. * Before calling this, all parameters and a data destination must be set up.
  167029. * Call jpeg_finish_compress() to actually write the data.
  167030. *
  167031. * The number of passed virtual arrays must match cinfo->num_components.
  167032. * Note that the virtual arrays need not be filled or even realized at
  167033. * the time write_coefficients is called; indeed, if the virtual arrays
  167034. * were requested from this compression object's memory manager, they
  167035. * typically will be realized during this routine and filled afterwards.
  167036. */
  167037. GLOBAL(void)
  167038. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167039. {
  167040. if (cinfo->global_state != CSTATE_START)
  167041. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167042. /* Mark all tables to be written */
  167043. jpeg_suppress_tables(cinfo, FALSE);
  167044. /* (Re)initialize error mgr and destination modules */
  167045. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167046. (*cinfo->dest->init_destination) (cinfo);
  167047. /* Perform master selection of active modules */
  167048. transencode_master_selection(cinfo, coef_arrays);
  167049. /* Wait for jpeg_finish_compress() call */
  167050. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167051. cinfo->global_state = CSTATE_WRCOEFS;
  167052. }
  167053. /*
  167054. * Initialize the compression object with default parameters,
  167055. * then copy from the source object all parameters needed for lossless
  167056. * transcoding. Parameters that can be varied without loss (such as
  167057. * scan script and Huffman optimization) are left in their default states.
  167058. */
  167059. GLOBAL(void)
  167060. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167061. j_compress_ptr dstinfo)
  167062. {
  167063. JQUANT_TBL ** qtblptr;
  167064. jpeg_component_info *incomp, *outcomp;
  167065. JQUANT_TBL *c_quant, *slot_quant;
  167066. int tblno, ci, coefi;
  167067. /* Safety check to ensure start_compress not called yet. */
  167068. if (dstinfo->global_state != CSTATE_START)
  167069. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167070. /* Copy fundamental image dimensions */
  167071. dstinfo->image_width = srcinfo->image_width;
  167072. dstinfo->image_height = srcinfo->image_height;
  167073. dstinfo->input_components = srcinfo->num_components;
  167074. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167075. /* Initialize all parameters to default values */
  167076. jpeg_set_defaults(dstinfo);
  167077. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167078. * Fix it to get the right header markers for the image colorspace.
  167079. */
  167080. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167081. dstinfo->data_precision = srcinfo->data_precision;
  167082. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167083. /* Copy the source's quantization tables. */
  167084. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167085. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167086. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167087. if (*qtblptr == NULL)
  167088. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167089. MEMCOPY((*qtblptr)->quantval,
  167090. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167091. SIZEOF((*qtblptr)->quantval));
  167092. (*qtblptr)->sent_table = FALSE;
  167093. }
  167094. }
  167095. /* Copy the source's per-component info.
  167096. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167097. */
  167098. dstinfo->num_components = srcinfo->num_components;
  167099. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167100. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167101. MAX_COMPONENTS);
  167102. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167103. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167104. outcomp->component_id = incomp->component_id;
  167105. outcomp->h_samp_factor = incomp->h_samp_factor;
  167106. outcomp->v_samp_factor = incomp->v_samp_factor;
  167107. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167108. /* Make sure saved quantization table for component matches the qtable
  167109. * slot. If not, the input file re-used this qtable slot.
  167110. * IJG encoder currently cannot duplicate this.
  167111. */
  167112. tblno = outcomp->quant_tbl_no;
  167113. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167114. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167115. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167116. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167117. c_quant = incomp->quant_table;
  167118. if (c_quant != NULL) {
  167119. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167120. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167121. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167122. }
  167123. }
  167124. /* Note: we do not copy the source's Huffman table assignments;
  167125. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167126. */
  167127. }
  167128. /* Also copy JFIF version and resolution information, if available.
  167129. * Strictly speaking this isn't "critical" info, but it's nearly
  167130. * always appropriate to copy it if available. In particular,
  167131. * if the application chooses to copy JFIF 1.02 extension markers from
  167132. * the source file, we need to copy the version to make sure we don't
  167133. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167134. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167135. */
  167136. if (srcinfo->saw_JFIF_marker) {
  167137. if (srcinfo->JFIF_major_version == 1) {
  167138. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167139. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167140. }
  167141. dstinfo->density_unit = srcinfo->density_unit;
  167142. dstinfo->X_density = srcinfo->X_density;
  167143. dstinfo->Y_density = srcinfo->Y_density;
  167144. }
  167145. }
  167146. /*
  167147. * Master selection of compression modules for transcoding.
  167148. * This substitutes for jcinit.c's initialization of the full compressor.
  167149. */
  167150. LOCAL(void)
  167151. transencode_master_selection (j_compress_ptr cinfo,
  167152. jvirt_barray_ptr * coef_arrays)
  167153. {
  167154. /* Although we don't actually use input_components for transcoding,
  167155. * jcmaster.c's initial_setup will complain if input_components is 0.
  167156. */
  167157. cinfo->input_components = 1;
  167158. /* Initialize master control (includes parameter checking/processing) */
  167159. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167160. /* Entropy encoding: either Huffman or arithmetic coding. */
  167161. if (cinfo->arith_code) {
  167162. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167163. } else {
  167164. if (cinfo->progressive_mode) {
  167165. #ifdef C_PROGRESSIVE_SUPPORTED
  167166. jinit_phuff_encoder(cinfo);
  167167. #else
  167168. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167169. #endif
  167170. } else
  167171. jinit_huff_encoder(cinfo);
  167172. }
  167173. /* We need a special coefficient buffer controller. */
  167174. transencode_coef_controller(cinfo, coef_arrays);
  167175. jinit_marker_writer(cinfo);
  167176. /* We can now tell the memory manager to allocate virtual arrays. */
  167177. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167178. /* Write the datastream header (SOI, JFIF) immediately.
  167179. * Frame and scan headers are postponed till later.
  167180. * This lets application insert special markers after the SOI.
  167181. */
  167182. (*cinfo->marker->write_file_header) (cinfo);
  167183. }
  167184. /*
  167185. * The rest of this file is a special implementation of the coefficient
  167186. * buffer controller. This is similar to jccoefct.c, but it handles only
  167187. * output from presupplied virtual arrays. Furthermore, we generate any
  167188. * dummy padding blocks on-the-fly rather than expecting them to be present
  167189. * in the arrays.
  167190. */
  167191. /* Private buffer controller object */
  167192. typedef struct {
  167193. struct jpeg_c_coef_controller pub; /* public fields */
  167194. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167195. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167196. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167197. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167198. /* Virtual block array for each component. */
  167199. jvirt_barray_ptr * whole_image;
  167200. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167201. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167202. } my_coef_controller2;
  167203. typedef my_coef_controller2 * my_coef_ptr2;
  167204. LOCAL(void)
  167205. start_iMCU_row2 (j_compress_ptr cinfo)
  167206. /* Reset within-iMCU-row counters for a new row */
  167207. {
  167208. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167209. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167210. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167211. * But at the bottom of the image, process only what's left.
  167212. */
  167213. if (cinfo->comps_in_scan > 1) {
  167214. coef->MCU_rows_per_iMCU_row = 1;
  167215. } else {
  167216. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167217. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167218. else
  167219. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167220. }
  167221. coef->mcu_ctr = 0;
  167222. coef->MCU_vert_offset = 0;
  167223. }
  167224. /*
  167225. * Initialize for a processing pass.
  167226. */
  167227. METHODDEF(void)
  167228. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167229. {
  167230. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167231. if (pass_mode != JBUF_CRANK_DEST)
  167232. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167233. coef->iMCU_row_num = 0;
  167234. start_iMCU_row2(cinfo);
  167235. }
  167236. /*
  167237. * Process some data.
  167238. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167239. * per call, ie, v_samp_factor block rows for each component in the scan.
  167240. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167241. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167242. *
  167243. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167244. */
  167245. METHODDEF(boolean)
  167246. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167247. {
  167248. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167249. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167250. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167251. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167252. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167253. JDIMENSION start_col;
  167254. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167255. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167256. JBLOCKROW buffer_ptr;
  167257. jpeg_component_info *compptr;
  167258. /* Align the virtual buffers for the components used in this scan. */
  167259. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167260. compptr = cinfo->cur_comp_info[ci];
  167261. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167262. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167263. coef->iMCU_row_num * compptr->v_samp_factor,
  167264. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167265. }
  167266. /* Loop to process one whole iMCU row */
  167267. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167268. yoffset++) {
  167269. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167270. MCU_col_num++) {
  167271. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167272. blkn = 0; /* index of current DCT block within MCU */
  167273. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167274. compptr = cinfo->cur_comp_info[ci];
  167275. start_col = MCU_col_num * compptr->MCU_width;
  167276. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167277. : compptr->last_col_width;
  167278. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167279. if (coef->iMCU_row_num < last_iMCU_row ||
  167280. yindex+yoffset < compptr->last_row_height) {
  167281. /* Fill in pointers to real blocks in this row */
  167282. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167283. for (xindex = 0; xindex < blockcnt; xindex++)
  167284. MCU_buffer[blkn++] = buffer_ptr++;
  167285. } else {
  167286. /* At bottom of image, need a whole row of dummy blocks */
  167287. xindex = 0;
  167288. }
  167289. /* Fill in any dummy blocks needed in this row.
  167290. * Dummy blocks are filled in the same way as in jccoefct.c:
  167291. * all zeroes in the AC entries, DC entries equal to previous
  167292. * block's DC value. The init routine has already zeroed the
  167293. * AC entries, so we need only set the DC entries correctly.
  167294. */
  167295. for (; xindex < compptr->MCU_width; xindex++) {
  167296. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167297. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167298. blkn++;
  167299. }
  167300. }
  167301. }
  167302. /* Try to write the MCU. */
  167303. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167304. /* Suspension forced; update state counters and exit */
  167305. coef->MCU_vert_offset = yoffset;
  167306. coef->mcu_ctr = MCU_col_num;
  167307. return FALSE;
  167308. }
  167309. }
  167310. /* Completed an MCU row, but perhaps not an iMCU row */
  167311. coef->mcu_ctr = 0;
  167312. }
  167313. /* Completed the iMCU row, advance counters for next one */
  167314. coef->iMCU_row_num++;
  167315. start_iMCU_row2(cinfo);
  167316. return TRUE;
  167317. }
  167318. /*
  167319. * Initialize coefficient buffer controller.
  167320. *
  167321. * Each passed coefficient array must be the right size for that
  167322. * coefficient: width_in_blocks wide and height_in_blocks high,
  167323. * with unitheight at least v_samp_factor.
  167324. */
  167325. LOCAL(void)
  167326. transencode_coef_controller (j_compress_ptr cinfo,
  167327. jvirt_barray_ptr * coef_arrays)
  167328. {
  167329. my_coef_ptr2 coef;
  167330. JBLOCKROW buffer;
  167331. int i;
  167332. coef = (my_coef_ptr2)
  167333. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167334. SIZEOF(my_coef_controller2));
  167335. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167336. coef->pub.start_pass = start_pass_coef2;
  167337. coef->pub.compress_data = compress_output2;
  167338. /* Save pointer to virtual arrays */
  167339. coef->whole_image = coef_arrays;
  167340. /* Allocate and pre-zero space for dummy DCT blocks. */
  167341. buffer = (JBLOCKROW)
  167342. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167343. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167344. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167345. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167346. coef->dummy_buffer[i] = buffer + i;
  167347. }
  167348. }
  167349. /*** End of inlined file: jctrans.c ***/
  167350. /*** Start of inlined file: jdapistd.c ***/
  167351. #define JPEG_INTERNALS
  167352. /* Forward declarations */
  167353. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167354. /*
  167355. * Decompression initialization.
  167356. * jpeg_read_header must be completed before calling this.
  167357. *
  167358. * If a multipass operating mode was selected, this will do all but the
  167359. * last pass, and thus may take a great deal of time.
  167360. *
  167361. * Returns FALSE if suspended. The return value need be inspected only if
  167362. * a suspending data source is used.
  167363. */
  167364. GLOBAL(boolean)
  167365. jpeg_start_decompress (j_decompress_ptr cinfo)
  167366. {
  167367. if (cinfo->global_state == DSTATE_READY) {
  167368. /* First call: initialize master control, select active modules */
  167369. jinit_master_decompress(cinfo);
  167370. if (cinfo->buffered_image) {
  167371. /* No more work here; expecting jpeg_start_output next */
  167372. cinfo->global_state = DSTATE_BUFIMAGE;
  167373. return TRUE;
  167374. }
  167375. cinfo->global_state = DSTATE_PRELOAD;
  167376. }
  167377. if (cinfo->global_state == DSTATE_PRELOAD) {
  167378. /* If file has multiple scans, absorb them all into the coef buffer */
  167379. if (cinfo->inputctl->has_multiple_scans) {
  167380. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167381. for (;;) {
  167382. int retcode;
  167383. /* Call progress monitor hook if present */
  167384. if (cinfo->progress != NULL)
  167385. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167386. /* Absorb some more input */
  167387. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167388. if (retcode == JPEG_SUSPENDED)
  167389. return FALSE;
  167390. if (retcode == JPEG_REACHED_EOI)
  167391. break;
  167392. /* Advance progress counter if appropriate */
  167393. if (cinfo->progress != NULL &&
  167394. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167395. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167396. /* jdmaster underestimated number of scans; ratchet up one scan */
  167397. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167398. }
  167399. }
  167400. }
  167401. #else
  167402. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167403. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167404. }
  167405. cinfo->output_scan_number = cinfo->input_scan_number;
  167406. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167407. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167408. /* Perform any dummy output passes, and set up for the final pass */
  167409. return output_pass_setup(cinfo);
  167410. }
  167411. /*
  167412. * Set up for an output pass, and perform any dummy pass(es) needed.
  167413. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167414. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167415. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167416. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167417. */
  167418. LOCAL(boolean)
  167419. output_pass_setup (j_decompress_ptr cinfo)
  167420. {
  167421. if (cinfo->global_state != DSTATE_PRESCAN) {
  167422. /* First call: do pass setup */
  167423. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167424. cinfo->output_scanline = 0;
  167425. cinfo->global_state = DSTATE_PRESCAN;
  167426. }
  167427. /* Loop over any required dummy passes */
  167428. while (cinfo->master->is_dummy_pass) {
  167429. #ifdef QUANT_2PASS_SUPPORTED
  167430. /* Crank through the dummy pass */
  167431. while (cinfo->output_scanline < cinfo->output_height) {
  167432. JDIMENSION last_scanline;
  167433. /* Call progress monitor hook if present */
  167434. if (cinfo->progress != NULL) {
  167435. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167436. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167437. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167438. }
  167439. /* Process some data */
  167440. last_scanline = cinfo->output_scanline;
  167441. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167442. &cinfo->output_scanline, (JDIMENSION) 0);
  167443. if (cinfo->output_scanline == last_scanline)
  167444. return FALSE; /* No progress made, must suspend */
  167445. }
  167446. /* Finish up dummy pass, and set up for another one */
  167447. (*cinfo->master->finish_output_pass) (cinfo);
  167448. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167449. cinfo->output_scanline = 0;
  167450. #else
  167451. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167452. #endif /* QUANT_2PASS_SUPPORTED */
  167453. }
  167454. /* Ready for application to drive output pass through
  167455. * jpeg_read_scanlines or jpeg_read_raw_data.
  167456. */
  167457. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167458. return TRUE;
  167459. }
  167460. /*
  167461. * Read some scanlines of data from the JPEG decompressor.
  167462. *
  167463. * The return value will be the number of lines actually read.
  167464. * This may be less than the number requested in several cases,
  167465. * including bottom of image, data source suspension, and operating
  167466. * modes that emit multiple scanlines at a time.
  167467. *
  167468. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167469. * this likely signals an application programmer error. However,
  167470. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167471. */
  167472. GLOBAL(JDIMENSION)
  167473. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167474. JDIMENSION max_lines)
  167475. {
  167476. JDIMENSION row_ctr;
  167477. if (cinfo->global_state != DSTATE_SCANNING)
  167478. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167479. if (cinfo->output_scanline >= cinfo->output_height) {
  167480. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167481. return 0;
  167482. }
  167483. /* Call progress monitor hook if present */
  167484. if (cinfo->progress != NULL) {
  167485. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167486. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167487. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167488. }
  167489. /* Process some data */
  167490. row_ctr = 0;
  167491. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167492. cinfo->output_scanline += row_ctr;
  167493. return row_ctr;
  167494. }
  167495. /*
  167496. * Alternate entry point to read raw data.
  167497. * Processes exactly one iMCU row per call, unless suspended.
  167498. */
  167499. GLOBAL(JDIMENSION)
  167500. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167501. JDIMENSION max_lines)
  167502. {
  167503. JDIMENSION lines_per_iMCU_row;
  167504. if (cinfo->global_state != DSTATE_RAW_OK)
  167505. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167506. if (cinfo->output_scanline >= cinfo->output_height) {
  167507. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167508. return 0;
  167509. }
  167510. /* Call progress monitor hook if present */
  167511. if (cinfo->progress != NULL) {
  167512. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167513. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167514. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167515. }
  167516. /* Verify that at least one iMCU row can be returned. */
  167517. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167518. if (max_lines < lines_per_iMCU_row)
  167519. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167520. /* Decompress directly into user's buffer. */
  167521. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167522. return 0; /* suspension forced, can do nothing more */
  167523. /* OK, we processed one iMCU row. */
  167524. cinfo->output_scanline += lines_per_iMCU_row;
  167525. return lines_per_iMCU_row;
  167526. }
  167527. /* Additional entry points for buffered-image mode. */
  167528. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167529. /*
  167530. * Initialize for an output pass in buffered-image mode.
  167531. */
  167532. GLOBAL(boolean)
  167533. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167534. {
  167535. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167536. cinfo->global_state != DSTATE_PRESCAN)
  167537. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167538. /* Limit scan number to valid range */
  167539. if (scan_number <= 0)
  167540. scan_number = 1;
  167541. if (cinfo->inputctl->eoi_reached &&
  167542. scan_number > cinfo->input_scan_number)
  167543. scan_number = cinfo->input_scan_number;
  167544. cinfo->output_scan_number = scan_number;
  167545. /* Perform any dummy output passes, and set up for the real pass */
  167546. return output_pass_setup(cinfo);
  167547. }
  167548. /*
  167549. * Finish up after an output pass in buffered-image mode.
  167550. *
  167551. * Returns FALSE if suspended. The return value need be inspected only if
  167552. * a suspending data source is used.
  167553. */
  167554. GLOBAL(boolean)
  167555. jpeg_finish_output (j_decompress_ptr cinfo)
  167556. {
  167557. if ((cinfo->global_state == DSTATE_SCANNING ||
  167558. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167559. /* Terminate this pass. */
  167560. /* We do not require the whole pass to have been completed. */
  167561. (*cinfo->master->finish_output_pass) (cinfo);
  167562. cinfo->global_state = DSTATE_BUFPOST;
  167563. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167564. /* BUFPOST = repeat call after a suspension, anything else is error */
  167565. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167566. }
  167567. /* Read markers looking for SOS or EOI */
  167568. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167569. ! cinfo->inputctl->eoi_reached) {
  167570. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167571. return FALSE; /* Suspend, come back later */
  167572. }
  167573. cinfo->global_state = DSTATE_BUFIMAGE;
  167574. return TRUE;
  167575. }
  167576. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167577. /*** End of inlined file: jdapistd.c ***/
  167578. /*** Start of inlined file: jdapimin.c ***/
  167579. #define JPEG_INTERNALS
  167580. /*
  167581. * Initialization of a JPEG decompression object.
  167582. * The error manager must already be set up (in case memory manager fails).
  167583. */
  167584. GLOBAL(void)
  167585. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167586. {
  167587. int i;
  167588. /* Guard against version mismatches between library and caller. */
  167589. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167590. if (version != JPEG_LIB_VERSION)
  167591. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167592. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167593. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167594. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167595. /* For debugging purposes, we zero the whole master structure.
  167596. * But the application has already set the err pointer, and may have set
  167597. * client_data, so we have to save and restore those fields.
  167598. * Note: if application hasn't set client_data, tools like Purify may
  167599. * complain here.
  167600. */
  167601. {
  167602. struct jpeg_error_mgr * err = cinfo->err;
  167603. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167604. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167605. cinfo->err = err;
  167606. cinfo->client_data = client_data;
  167607. }
  167608. cinfo->is_decompressor = TRUE;
  167609. /* Initialize a memory manager instance for this object */
  167610. jinit_memory_mgr((j_common_ptr) cinfo);
  167611. /* Zero out pointers to permanent structures. */
  167612. cinfo->progress = NULL;
  167613. cinfo->src = NULL;
  167614. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167615. cinfo->quant_tbl_ptrs[i] = NULL;
  167616. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167617. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167618. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167619. }
  167620. /* Initialize marker processor so application can override methods
  167621. * for COM, APPn markers before calling jpeg_read_header.
  167622. */
  167623. cinfo->marker_list = NULL;
  167624. jinit_marker_reader(cinfo);
  167625. /* And initialize the overall input controller. */
  167626. jinit_input_controller(cinfo);
  167627. /* OK, I'm ready */
  167628. cinfo->global_state = DSTATE_START;
  167629. }
  167630. /*
  167631. * Destruction of a JPEG decompression object
  167632. */
  167633. GLOBAL(void)
  167634. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167635. {
  167636. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167637. }
  167638. /*
  167639. * Abort processing of a JPEG decompression operation,
  167640. * but don't destroy the object itself.
  167641. */
  167642. GLOBAL(void)
  167643. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167644. {
  167645. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167646. }
  167647. /*
  167648. * Set default decompression parameters.
  167649. */
  167650. LOCAL(void)
  167651. default_decompress_parms (j_decompress_ptr cinfo)
  167652. {
  167653. /* Guess the input colorspace, and set output colorspace accordingly. */
  167654. /* (Wish JPEG committee had provided a real way to specify this...) */
  167655. /* Note application may override our guesses. */
  167656. switch (cinfo->num_components) {
  167657. case 1:
  167658. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167659. cinfo->out_color_space = JCS_GRAYSCALE;
  167660. break;
  167661. case 3:
  167662. if (cinfo->saw_JFIF_marker) {
  167663. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167664. } else if (cinfo->saw_Adobe_marker) {
  167665. switch (cinfo->Adobe_transform) {
  167666. case 0:
  167667. cinfo->jpeg_color_space = JCS_RGB;
  167668. break;
  167669. case 1:
  167670. cinfo->jpeg_color_space = JCS_YCbCr;
  167671. break;
  167672. default:
  167673. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167674. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167675. break;
  167676. }
  167677. } else {
  167678. /* Saw no special markers, try to guess from the component IDs */
  167679. int cid0 = cinfo->comp_info[0].component_id;
  167680. int cid1 = cinfo->comp_info[1].component_id;
  167681. int cid2 = cinfo->comp_info[2].component_id;
  167682. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167683. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167684. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167685. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167686. else {
  167687. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167688. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167689. }
  167690. }
  167691. /* Always guess RGB is proper output colorspace. */
  167692. cinfo->out_color_space = JCS_RGB;
  167693. break;
  167694. case 4:
  167695. if (cinfo->saw_Adobe_marker) {
  167696. switch (cinfo->Adobe_transform) {
  167697. case 0:
  167698. cinfo->jpeg_color_space = JCS_CMYK;
  167699. break;
  167700. case 2:
  167701. cinfo->jpeg_color_space = JCS_YCCK;
  167702. break;
  167703. default:
  167704. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167705. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167706. break;
  167707. }
  167708. } else {
  167709. /* No special markers, assume straight CMYK. */
  167710. cinfo->jpeg_color_space = JCS_CMYK;
  167711. }
  167712. cinfo->out_color_space = JCS_CMYK;
  167713. break;
  167714. default:
  167715. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167716. cinfo->out_color_space = JCS_UNKNOWN;
  167717. break;
  167718. }
  167719. /* Set defaults for other decompression parameters. */
  167720. cinfo->scale_num = 1; /* 1:1 scaling */
  167721. cinfo->scale_denom = 1;
  167722. cinfo->output_gamma = 1.0;
  167723. cinfo->buffered_image = FALSE;
  167724. cinfo->raw_data_out = FALSE;
  167725. cinfo->dct_method = JDCT_DEFAULT;
  167726. cinfo->do_fancy_upsampling = TRUE;
  167727. cinfo->do_block_smoothing = TRUE;
  167728. cinfo->quantize_colors = FALSE;
  167729. /* We set these in case application only sets quantize_colors. */
  167730. cinfo->dither_mode = JDITHER_FS;
  167731. #ifdef QUANT_2PASS_SUPPORTED
  167732. cinfo->two_pass_quantize = TRUE;
  167733. #else
  167734. cinfo->two_pass_quantize = FALSE;
  167735. #endif
  167736. cinfo->desired_number_of_colors = 256;
  167737. cinfo->colormap = NULL;
  167738. /* Initialize for no mode change in buffered-image mode. */
  167739. cinfo->enable_1pass_quant = FALSE;
  167740. cinfo->enable_external_quant = FALSE;
  167741. cinfo->enable_2pass_quant = FALSE;
  167742. }
  167743. /*
  167744. * Decompression startup: read start of JPEG datastream to see what's there.
  167745. * Need only initialize JPEG object and supply a data source before calling.
  167746. *
  167747. * This routine will read as far as the first SOS marker (ie, actual start of
  167748. * compressed data), and will save all tables and parameters in the JPEG
  167749. * object. It will also initialize the decompression parameters to default
  167750. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167751. * adjust the decompression parameters and then call jpeg_start_decompress.
  167752. * (Or, if the application only wanted to determine the image parameters,
  167753. * the data need not be decompressed. In that case, call jpeg_abort or
  167754. * jpeg_destroy to release any temporary space.)
  167755. * If an abbreviated (tables only) datastream is presented, the routine will
  167756. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167757. * re-use the JPEG object to read the abbreviated image datastream(s).
  167758. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167759. * The JPEG_SUSPENDED return code only occurs if the data source module
  167760. * requests suspension of the decompressor. In this case the application
  167761. * should load more source data and then re-call jpeg_read_header to resume
  167762. * processing.
  167763. * If a non-suspending data source is used and require_image is TRUE, then the
  167764. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167765. *
  167766. * This routine is now just a front end to jpeg_consume_input, with some
  167767. * extra error checking.
  167768. */
  167769. GLOBAL(int)
  167770. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167771. {
  167772. int retcode;
  167773. if (cinfo->global_state != DSTATE_START &&
  167774. cinfo->global_state != DSTATE_INHEADER)
  167775. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167776. retcode = jpeg_consume_input(cinfo);
  167777. switch (retcode) {
  167778. case JPEG_REACHED_SOS:
  167779. retcode = JPEG_HEADER_OK;
  167780. break;
  167781. case JPEG_REACHED_EOI:
  167782. if (require_image) /* Complain if application wanted an image */
  167783. ERREXIT(cinfo, JERR_NO_IMAGE);
  167784. /* Reset to start state; it would be safer to require the application to
  167785. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167786. * A side effect is to free any temporary memory (there shouldn't be any).
  167787. */
  167788. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167789. retcode = JPEG_HEADER_TABLES_ONLY;
  167790. break;
  167791. case JPEG_SUSPENDED:
  167792. /* no work */
  167793. break;
  167794. }
  167795. return retcode;
  167796. }
  167797. /*
  167798. * Consume data in advance of what the decompressor requires.
  167799. * This can be called at any time once the decompressor object has
  167800. * been created and a data source has been set up.
  167801. *
  167802. * This routine is essentially a state machine that handles a couple
  167803. * of critical state-transition actions, namely initial setup and
  167804. * transition from header scanning to ready-for-start_decompress.
  167805. * All the actual input is done via the input controller's consume_input
  167806. * method.
  167807. */
  167808. GLOBAL(int)
  167809. jpeg_consume_input (j_decompress_ptr cinfo)
  167810. {
  167811. int retcode = JPEG_SUSPENDED;
  167812. /* NB: every possible DSTATE value should be listed in this switch */
  167813. switch (cinfo->global_state) {
  167814. case DSTATE_START:
  167815. /* Start-of-datastream actions: reset appropriate modules */
  167816. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167817. /* Initialize application's data source module */
  167818. (*cinfo->src->init_source) (cinfo);
  167819. cinfo->global_state = DSTATE_INHEADER;
  167820. /*FALLTHROUGH*/
  167821. case DSTATE_INHEADER:
  167822. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167823. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167824. /* Set up default parameters based on header data */
  167825. default_decompress_parms(cinfo);
  167826. /* Set global state: ready for start_decompress */
  167827. cinfo->global_state = DSTATE_READY;
  167828. }
  167829. break;
  167830. case DSTATE_READY:
  167831. /* Can't advance past first SOS until start_decompress is called */
  167832. retcode = JPEG_REACHED_SOS;
  167833. break;
  167834. case DSTATE_PRELOAD:
  167835. case DSTATE_PRESCAN:
  167836. case DSTATE_SCANNING:
  167837. case DSTATE_RAW_OK:
  167838. case DSTATE_BUFIMAGE:
  167839. case DSTATE_BUFPOST:
  167840. case DSTATE_STOPPING:
  167841. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167842. break;
  167843. default:
  167844. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167845. }
  167846. return retcode;
  167847. }
  167848. /*
  167849. * Have we finished reading the input file?
  167850. */
  167851. GLOBAL(boolean)
  167852. jpeg_input_complete (j_decompress_ptr cinfo)
  167853. {
  167854. /* Check for valid jpeg object */
  167855. if (cinfo->global_state < DSTATE_START ||
  167856. cinfo->global_state > DSTATE_STOPPING)
  167857. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167858. return cinfo->inputctl->eoi_reached;
  167859. }
  167860. /*
  167861. * Is there more than one scan?
  167862. */
  167863. GLOBAL(boolean)
  167864. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167865. {
  167866. /* Only valid after jpeg_read_header completes */
  167867. if (cinfo->global_state < DSTATE_READY ||
  167868. cinfo->global_state > DSTATE_STOPPING)
  167869. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167870. return cinfo->inputctl->has_multiple_scans;
  167871. }
  167872. /*
  167873. * Finish JPEG decompression.
  167874. *
  167875. * This will normally just verify the file trailer and release temp storage.
  167876. *
  167877. * Returns FALSE if suspended. The return value need be inspected only if
  167878. * a suspending data source is used.
  167879. */
  167880. GLOBAL(boolean)
  167881. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167882. {
  167883. if ((cinfo->global_state == DSTATE_SCANNING ||
  167884. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167885. /* Terminate final pass of non-buffered mode */
  167886. if (cinfo->output_scanline < cinfo->output_height)
  167887. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167888. (*cinfo->master->finish_output_pass) (cinfo);
  167889. cinfo->global_state = DSTATE_STOPPING;
  167890. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167891. /* Finishing after a buffered-image operation */
  167892. cinfo->global_state = DSTATE_STOPPING;
  167893. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167894. /* STOPPING = repeat call after a suspension, anything else is error */
  167895. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167896. }
  167897. /* Read until EOI */
  167898. while (! cinfo->inputctl->eoi_reached) {
  167899. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167900. return FALSE; /* Suspend, come back later */
  167901. }
  167902. /* Do final cleanup */
  167903. (*cinfo->src->term_source) (cinfo);
  167904. /* We can use jpeg_abort to release memory and reset global_state */
  167905. jpeg_abort((j_common_ptr) cinfo);
  167906. return TRUE;
  167907. }
  167908. /*** End of inlined file: jdapimin.c ***/
  167909. /*** Start of inlined file: jdatasrc.c ***/
  167910. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167911. /*** Start of inlined file: jerror.h ***/
  167912. /*
  167913. * To define the enum list of message codes, include this file without
  167914. * defining macro JMESSAGE. To create a message string table, include it
  167915. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167916. */
  167917. #ifndef JMESSAGE
  167918. #ifndef JERROR_H
  167919. /* First time through, define the enum list */
  167920. #define JMAKE_ENUM_LIST
  167921. #else
  167922. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167923. #define JMESSAGE(code,string)
  167924. #endif /* JERROR_H */
  167925. #endif /* JMESSAGE */
  167926. #ifdef JMAKE_ENUM_LIST
  167927. typedef enum {
  167928. #define JMESSAGE(code,string) code ,
  167929. #endif /* JMAKE_ENUM_LIST */
  167930. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167931. /* For maintenance convenience, list is alphabetical by message code name */
  167932. JMESSAGE(JERR_ARITH_NOTIMPL,
  167933. "Sorry, there are legal restrictions on arithmetic coding")
  167934. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167935. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167936. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167937. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167938. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167939. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167940. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167941. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167942. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167943. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167944. JMESSAGE(JERR_BAD_LIB_VERSION,
  167945. "Wrong JPEG library version: library is %d, caller expects %d")
  167946. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167947. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167948. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167949. JMESSAGE(JERR_BAD_PROGRESSION,
  167950. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167951. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167952. "Invalid progressive parameters at scan script entry %d")
  167953. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167954. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167955. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167956. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167957. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167958. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167959. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167960. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167961. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167962. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167963. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167964. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167965. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167966. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167967. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167968. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167969. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167970. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167971. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167972. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167973. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167974. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167975. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167976. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167977. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167978. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167979. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167980. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167981. "Cannot transcode due to multiple use of quantization table %d")
  167982. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167983. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167984. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167985. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167986. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167987. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167988. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167989. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167990. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167991. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167992. JMESSAGE(JERR_QUANT_COMPONENTS,
  167993. "Cannot quantize more than %d color components")
  167994. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167995. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167996. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167997. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167998. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167999. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168000. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168001. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168002. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168003. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168004. JMESSAGE(JERR_TFILE_WRITE,
  168005. "Write failed on temporary file --- out of disk space?")
  168006. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168007. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168008. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168009. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168010. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168011. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168012. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168013. JMESSAGE(JMSG_VERSION, JVERSION)
  168014. JMESSAGE(JTRC_16BIT_TABLES,
  168015. "Caution: quantization tables are too coarse for baseline JPEG")
  168016. JMESSAGE(JTRC_ADOBE,
  168017. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168018. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168019. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168020. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168021. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168022. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168023. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168024. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168025. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168026. JMESSAGE(JTRC_EOI, "End Of Image")
  168027. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168028. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168029. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168030. "Warning: thumbnail image size does not match data length %u")
  168031. JMESSAGE(JTRC_JFIF_EXTENSION,
  168032. "JFIF extension marker: type 0x%02x, length %u")
  168033. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168034. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168035. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168036. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168037. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168038. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168039. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168040. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168041. JMESSAGE(JTRC_RST, "RST%d")
  168042. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168043. "Smoothing not supported with nonstandard sampling ratios")
  168044. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168045. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168046. JMESSAGE(JTRC_SOI, "Start of Image")
  168047. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168048. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168049. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168050. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168051. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168052. JMESSAGE(JTRC_THUMB_JPEG,
  168053. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168054. JMESSAGE(JTRC_THUMB_PALETTE,
  168055. "JFIF extension marker: palette thumbnail image, length %u")
  168056. JMESSAGE(JTRC_THUMB_RGB,
  168057. "JFIF extension marker: RGB thumbnail image, length %u")
  168058. JMESSAGE(JTRC_UNKNOWN_IDS,
  168059. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168060. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168061. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168062. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168063. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168064. "Inconsistent progression sequence for component %d coefficient %d")
  168065. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168066. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168067. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168068. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168069. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168070. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168071. JMESSAGE(JWRN_MUST_RESYNC,
  168072. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168073. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168074. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168075. #ifdef JMAKE_ENUM_LIST
  168076. JMSG_LASTMSGCODE
  168077. } J_MESSAGE_CODE;
  168078. #undef JMAKE_ENUM_LIST
  168079. #endif /* JMAKE_ENUM_LIST */
  168080. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168081. #undef JMESSAGE
  168082. #ifndef JERROR_H
  168083. #define JERROR_H
  168084. /* Macros to simplify using the error and trace message stuff */
  168085. /* The first parameter is either type of cinfo pointer */
  168086. /* Fatal errors (print message and exit) */
  168087. #define ERREXIT(cinfo,code) \
  168088. ((cinfo)->err->msg_code = (code), \
  168089. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168090. #define ERREXIT1(cinfo,code,p1) \
  168091. ((cinfo)->err->msg_code = (code), \
  168092. (cinfo)->err->msg_parm.i[0] = (p1), \
  168093. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168094. #define ERREXIT2(cinfo,code,p1,p2) \
  168095. ((cinfo)->err->msg_code = (code), \
  168096. (cinfo)->err->msg_parm.i[0] = (p1), \
  168097. (cinfo)->err->msg_parm.i[1] = (p2), \
  168098. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168099. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168100. ((cinfo)->err->msg_code = (code), \
  168101. (cinfo)->err->msg_parm.i[0] = (p1), \
  168102. (cinfo)->err->msg_parm.i[1] = (p2), \
  168103. (cinfo)->err->msg_parm.i[2] = (p3), \
  168104. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168105. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168106. ((cinfo)->err->msg_code = (code), \
  168107. (cinfo)->err->msg_parm.i[0] = (p1), \
  168108. (cinfo)->err->msg_parm.i[1] = (p2), \
  168109. (cinfo)->err->msg_parm.i[2] = (p3), \
  168110. (cinfo)->err->msg_parm.i[3] = (p4), \
  168111. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168112. #define ERREXITS(cinfo,code,str) \
  168113. ((cinfo)->err->msg_code = (code), \
  168114. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168115. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168116. #define MAKESTMT(stuff) do { stuff } while (0)
  168117. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168118. #define WARNMS(cinfo,code) \
  168119. ((cinfo)->err->msg_code = (code), \
  168120. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168121. #define WARNMS1(cinfo,code,p1) \
  168122. ((cinfo)->err->msg_code = (code), \
  168123. (cinfo)->err->msg_parm.i[0] = (p1), \
  168124. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168125. #define WARNMS2(cinfo,code,p1,p2) \
  168126. ((cinfo)->err->msg_code = (code), \
  168127. (cinfo)->err->msg_parm.i[0] = (p1), \
  168128. (cinfo)->err->msg_parm.i[1] = (p2), \
  168129. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168130. /* Informational/debugging messages */
  168131. #define TRACEMS(cinfo,lvl,code) \
  168132. ((cinfo)->err->msg_code = (code), \
  168133. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168134. #define TRACEMS1(cinfo,lvl,code,p1) \
  168135. ((cinfo)->err->msg_code = (code), \
  168136. (cinfo)->err->msg_parm.i[0] = (p1), \
  168137. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168138. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168139. ((cinfo)->err->msg_code = (code), \
  168140. (cinfo)->err->msg_parm.i[0] = (p1), \
  168141. (cinfo)->err->msg_parm.i[1] = (p2), \
  168142. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168143. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168144. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168145. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168146. (cinfo)->err->msg_code = (code); \
  168147. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168148. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168149. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168150. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168151. (cinfo)->err->msg_code = (code); \
  168152. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168153. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168154. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168155. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168156. _mp[4] = (p5); \
  168157. (cinfo)->err->msg_code = (code); \
  168158. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168159. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168160. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168161. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168162. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168163. (cinfo)->err->msg_code = (code); \
  168164. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168165. #define TRACEMSS(cinfo,lvl,code,str) \
  168166. ((cinfo)->err->msg_code = (code), \
  168167. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168168. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168169. #endif /* JERROR_H */
  168170. /*** End of inlined file: jerror.h ***/
  168171. /* Expanded data source object for stdio input */
  168172. typedef struct {
  168173. struct jpeg_source_mgr pub; /* public fields */
  168174. FILE * infile; /* source stream */
  168175. JOCTET * buffer; /* start of buffer */
  168176. boolean start_of_file; /* have we gotten any data yet? */
  168177. } my_source_mgr;
  168178. typedef my_source_mgr * my_src_ptr;
  168179. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168180. /*
  168181. * Initialize source --- called by jpeg_read_header
  168182. * before any data is actually read.
  168183. */
  168184. METHODDEF(void)
  168185. init_source (j_decompress_ptr cinfo)
  168186. {
  168187. my_src_ptr src = (my_src_ptr) cinfo->src;
  168188. /* We reset the empty-input-file flag for each image,
  168189. * but we don't clear the input buffer.
  168190. * This is correct behavior for reading a series of images from one source.
  168191. */
  168192. src->start_of_file = TRUE;
  168193. }
  168194. /*
  168195. * Fill the input buffer --- called whenever buffer is emptied.
  168196. *
  168197. * In typical applications, this should read fresh data into the buffer
  168198. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168199. * reset the pointer & count to the start of the buffer, and return TRUE
  168200. * indicating that the buffer has been reloaded. It is not necessary to
  168201. * fill the buffer entirely, only to obtain at least one more byte.
  168202. *
  168203. * There is no such thing as an EOF return. If the end of the file has been
  168204. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168205. * the buffer. In most cases, generating a warning message and inserting a
  168206. * fake EOI marker is the best course of action --- this will allow the
  168207. * decompressor to output however much of the image is there. However,
  168208. * the resulting error message is misleading if the real problem is an empty
  168209. * input file, so we handle that case specially.
  168210. *
  168211. * In applications that need to be able to suspend compression due to input
  168212. * not being available yet, a FALSE return indicates that no more data can be
  168213. * obtained right now, but more may be forthcoming later. In this situation,
  168214. * the decompressor will return to its caller (with an indication of the
  168215. * number of scanlines it has read, if any). The application should resume
  168216. * decompression after it has loaded more data into the input buffer. Note
  168217. * that there are substantial restrictions on the use of suspension --- see
  168218. * the documentation.
  168219. *
  168220. * When suspending, the decompressor will back up to a convenient restart point
  168221. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168222. * indicate where the restart point will be if the current call returns FALSE.
  168223. * Data beyond this point must be rescanned after resumption, so move it to
  168224. * the front of the buffer rather than discarding it.
  168225. */
  168226. METHODDEF(boolean)
  168227. fill_input_buffer (j_decompress_ptr cinfo)
  168228. {
  168229. my_src_ptr src = (my_src_ptr) cinfo->src;
  168230. size_t nbytes;
  168231. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168232. if (nbytes <= 0) {
  168233. if (src->start_of_file) /* Treat empty input file as fatal error */
  168234. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168235. WARNMS(cinfo, JWRN_JPEG_EOF);
  168236. /* Insert a fake EOI marker */
  168237. src->buffer[0] = (JOCTET) 0xFF;
  168238. src->buffer[1] = (JOCTET) JPEG_EOI;
  168239. nbytes = 2;
  168240. }
  168241. src->pub.next_input_byte = src->buffer;
  168242. src->pub.bytes_in_buffer = nbytes;
  168243. src->start_of_file = FALSE;
  168244. return TRUE;
  168245. }
  168246. /*
  168247. * Skip data --- used to skip over a potentially large amount of
  168248. * uninteresting data (such as an APPn marker).
  168249. *
  168250. * Writers of suspendable-input applications must note that skip_input_data
  168251. * is not granted the right to give a suspension return. If the skip extends
  168252. * beyond the data currently in the buffer, the buffer can be marked empty so
  168253. * that the next read will cause a fill_input_buffer call that can suspend.
  168254. * Arranging for additional bytes to be discarded before reloading the input
  168255. * buffer is the application writer's problem.
  168256. */
  168257. METHODDEF(void)
  168258. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168259. {
  168260. my_src_ptr src = (my_src_ptr) cinfo->src;
  168261. /* Just a dumb implementation for now. Could use fseek() except
  168262. * it doesn't work on pipes. Not clear that being smart is worth
  168263. * any trouble anyway --- large skips are infrequent.
  168264. */
  168265. if (num_bytes > 0) {
  168266. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168267. num_bytes -= (long) src->pub.bytes_in_buffer;
  168268. (void) fill_input_buffer(cinfo);
  168269. /* note we assume that fill_input_buffer will never return FALSE,
  168270. * so suspension need not be handled.
  168271. */
  168272. }
  168273. src->pub.next_input_byte += (size_t) num_bytes;
  168274. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168275. }
  168276. }
  168277. /*
  168278. * An additional method that can be provided by data source modules is the
  168279. * resync_to_restart method for error recovery in the presence of RST markers.
  168280. * For the moment, this source module just uses the default resync method
  168281. * provided by the JPEG library. That method assumes that no backtracking
  168282. * is possible.
  168283. */
  168284. /*
  168285. * Terminate source --- called by jpeg_finish_decompress
  168286. * after all data has been read. Often a no-op.
  168287. *
  168288. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168289. * application must deal with any cleanup that should happen even
  168290. * for error exit.
  168291. */
  168292. METHODDEF(void)
  168293. term_source (j_decompress_ptr)
  168294. {
  168295. /* no work necessary here */
  168296. }
  168297. /*
  168298. * Prepare for input from a stdio stream.
  168299. * The caller must have already opened the stream, and is responsible
  168300. * for closing it after finishing decompression.
  168301. */
  168302. GLOBAL(void)
  168303. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168304. {
  168305. my_src_ptr src;
  168306. /* The source object and input buffer are made permanent so that a series
  168307. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168308. * only before the first one. (If we discarded the buffer at the end of
  168309. * one image, we'd likely lose the start of the next one.)
  168310. * This makes it unsafe to use this manager and a different source
  168311. * manager serially with the same JPEG object. Caveat programmer.
  168312. */
  168313. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168314. cinfo->src = (struct jpeg_source_mgr *)
  168315. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168316. SIZEOF(my_source_mgr));
  168317. src = (my_src_ptr) cinfo->src;
  168318. src->buffer = (JOCTET *)
  168319. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168320. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168321. }
  168322. src = (my_src_ptr) cinfo->src;
  168323. src->pub.init_source = init_source;
  168324. src->pub.fill_input_buffer = fill_input_buffer;
  168325. src->pub.skip_input_data = skip_input_data;
  168326. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168327. src->pub.term_source = term_source;
  168328. src->infile = infile;
  168329. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168330. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168331. }
  168332. /*** End of inlined file: jdatasrc.c ***/
  168333. /*** Start of inlined file: jdcoefct.c ***/
  168334. #define JPEG_INTERNALS
  168335. /* Block smoothing is only applicable for progressive JPEG, so: */
  168336. #ifndef D_PROGRESSIVE_SUPPORTED
  168337. #undef BLOCK_SMOOTHING_SUPPORTED
  168338. #endif
  168339. /* Private buffer controller object */
  168340. typedef struct {
  168341. struct jpeg_d_coef_controller pub; /* public fields */
  168342. /* These variables keep track of the current location of the input side. */
  168343. /* cinfo->input_iMCU_row is also used for this. */
  168344. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168345. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168346. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168347. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168348. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168349. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168350. * and let the entropy decoder write into that workspace each time.
  168351. * (On 80x86, the workspace is FAR even though it's not really very big;
  168352. * this is to keep the module interfaces unchanged when a large coefficient
  168353. * buffer is necessary.)
  168354. * In multi-pass modes, this array points to the current MCU's blocks
  168355. * within the virtual arrays; it is used only by the input side.
  168356. */
  168357. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168358. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168359. /* In multi-pass modes, we need a virtual block array for each component. */
  168360. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168361. #endif
  168362. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168363. /* When doing block smoothing, we latch coefficient Al values here */
  168364. int * coef_bits_latch;
  168365. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168366. #endif
  168367. } my_coef_controller3;
  168368. typedef my_coef_controller3 * my_coef_ptr3;
  168369. /* Forward declarations */
  168370. METHODDEF(int) decompress_onepass
  168371. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168372. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168373. METHODDEF(int) decompress_data
  168374. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168375. #endif
  168376. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168377. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168378. METHODDEF(int) decompress_smooth_data
  168379. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168380. #endif
  168381. LOCAL(void)
  168382. start_iMCU_row3 (j_decompress_ptr cinfo)
  168383. /* Reset within-iMCU-row counters for a new row (input side) */
  168384. {
  168385. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168386. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168387. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168388. * But at the bottom of the image, process only what's left.
  168389. */
  168390. if (cinfo->comps_in_scan > 1) {
  168391. coef->MCU_rows_per_iMCU_row = 1;
  168392. } else {
  168393. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168394. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168395. else
  168396. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168397. }
  168398. coef->MCU_ctr = 0;
  168399. coef->MCU_vert_offset = 0;
  168400. }
  168401. /*
  168402. * Initialize for an input processing pass.
  168403. */
  168404. METHODDEF(void)
  168405. start_input_pass (j_decompress_ptr cinfo)
  168406. {
  168407. cinfo->input_iMCU_row = 0;
  168408. start_iMCU_row3(cinfo);
  168409. }
  168410. /*
  168411. * Initialize for an output processing pass.
  168412. */
  168413. METHODDEF(void)
  168414. start_output_pass (j_decompress_ptr cinfo)
  168415. {
  168416. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168417. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168418. /* If multipass, check to see whether to use block smoothing on this pass */
  168419. if (coef->pub.coef_arrays != NULL) {
  168420. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168421. coef->pub.decompress_data = decompress_smooth_data;
  168422. else
  168423. coef->pub.decompress_data = decompress_data;
  168424. }
  168425. #endif
  168426. cinfo->output_iMCU_row = 0;
  168427. }
  168428. /*
  168429. * Decompress and return some data in the single-pass case.
  168430. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168431. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168432. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168433. *
  168434. * NB: output_buf contains a plane for each component in image,
  168435. * which we index according to the component's SOF position.
  168436. */
  168437. METHODDEF(int)
  168438. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168439. {
  168440. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168441. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168442. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168443. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168444. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168445. JSAMPARRAY output_ptr;
  168446. JDIMENSION start_col, output_col;
  168447. jpeg_component_info *compptr;
  168448. inverse_DCT_method_ptr inverse_DCT;
  168449. /* Loop to process as much as one whole iMCU row */
  168450. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168451. yoffset++) {
  168452. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168453. MCU_col_num++) {
  168454. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168455. jzero_far((void FAR *) coef->MCU_buffer[0],
  168456. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168457. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168458. /* Suspension forced; update state counters and exit */
  168459. coef->MCU_vert_offset = yoffset;
  168460. coef->MCU_ctr = MCU_col_num;
  168461. return JPEG_SUSPENDED;
  168462. }
  168463. /* Determine where data should go in output_buf and do the IDCT thing.
  168464. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168465. * incremented past them!). Note the inner loop relies on having
  168466. * allocated the MCU_buffer[] blocks sequentially.
  168467. */
  168468. blkn = 0; /* index of current DCT block within MCU */
  168469. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168470. compptr = cinfo->cur_comp_info[ci];
  168471. /* Don't bother to IDCT an uninteresting component. */
  168472. if (! compptr->component_needed) {
  168473. blkn += compptr->MCU_blocks;
  168474. continue;
  168475. }
  168476. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168477. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168478. : compptr->last_col_width;
  168479. output_ptr = output_buf[compptr->component_index] +
  168480. yoffset * compptr->DCT_scaled_size;
  168481. start_col = MCU_col_num * compptr->MCU_sample_width;
  168482. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168483. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168484. yoffset+yindex < compptr->last_row_height) {
  168485. output_col = start_col;
  168486. for (xindex = 0; xindex < useful_width; xindex++) {
  168487. (*inverse_DCT) (cinfo, compptr,
  168488. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168489. output_ptr, output_col);
  168490. output_col += compptr->DCT_scaled_size;
  168491. }
  168492. }
  168493. blkn += compptr->MCU_width;
  168494. output_ptr += compptr->DCT_scaled_size;
  168495. }
  168496. }
  168497. }
  168498. /* Completed an MCU row, but perhaps not an iMCU row */
  168499. coef->MCU_ctr = 0;
  168500. }
  168501. /* Completed the iMCU row, advance counters for next one */
  168502. cinfo->output_iMCU_row++;
  168503. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168504. start_iMCU_row3(cinfo);
  168505. return JPEG_ROW_COMPLETED;
  168506. }
  168507. /* Completed the scan */
  168508. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168509. return JPEG_SCAN_COMPLETED;
  168510. }
  168511. /*
  168512. * Dummy consume-input routine for single-pass operation.
  168513. */
  168514. METHODDEF(int)
  168515. dummy_consume_data (j_decompress_ptr)
  168516. {
  168517. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168518. }
  168519. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168520. /*
  168521. * Consume input data and store it in the full-image coefficient buffer.
  168522. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168523. * ie, v_samp_factor block rows for each component in the scan.
  168524. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168525. */
  168526. METHODDEF(int)
  168527. consume_data (j_decompress_ptr cinfo)
  168528. {
  168529. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168530. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168531. int blkn, ci, xindex, yindex, yoffset;
  168532. JDIMENSION start_col;
  168533. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168534. JBLOCKROW buffer_ptr;
  168535. jpeg_component_info *compptr;
  168536. /* Align the virtual buffers for the components used in this scan. */
  168537. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168538. compptr = cinfo->cur_comp_info[ci];
  168539. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168540. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168541. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168542. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168543. /* Note: entropy decoder expects buffer to be zeroed,
  168544. * but this is handled automatically by the memory manager
  168545. * because we requested a pre-zeroed array.
  168546. */
  168547. }
  168548. /* Loop to process one whole iMCU row */
  168549. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168550. yoffset++) {
  168551. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168552. MCU_col_num++) {
  168553. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168554. blkn = 0; /* index of current DCT block within MCU */
  168555. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168556. compptr = cinfo->cur_comp_info[ci];
  168557. start_col = MCU_col_num * compptr->MCU_width;
  168558. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168559. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168560. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168561. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168562. }
  168563. }
  168564. }
  168565. /* Try to fetch the MCU. */
  168566. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168567. /* Suspension forced; update state counters and exit */
  168568. coef->MCU_vert_offset = yoffset;
  168569. coef->MCU_ctr = MCU_col_num;
  168570. return JPEG_SUSPENDED;
  168571. }
  168572. }
  168573. /* Completed an MCU row, but perhaps not an iMCU row */
  168574. coef->MCU_ctr = 0;
  168575. }
  168576. /* Completed the iMCU row, advance counters for next one */
  168577. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168578. start_iMCU_row3(cinfo);
  168579. return JPEG_ROW_COMPLETED;
  168580. }
  168581. /* Completed the scan */
  168582. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168583. return JPEG_SCAN_COMPLETED;
  168584. }
  168585. /*
  168586. * Decompress and return some data in the multi-pass case.
  168587. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168588. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168589. *
  168590. * NB: output_buf contains a plane for each component in image.
  168591. */
  168592. METHODDEF(int)
  168593. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168594. {
  168595. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168596. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168597. JDIMENSION block_num;
  168598. int ci, block_row, block_rows;
  168599. JBLOCKARRAY buffer;
  168600. JBLOCKROW buffer_ptr;
  168601. JSAMPARRAY output_ptr;
  168602. JDIMENSION output_col;
  168603. jpeg_component_info *compptr;
  168604. inverse_DCT_method_ptr inverse_DCT;
  168605. /* Force some input to be done if we are getting ahead of the input. */
  168606. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168607. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168608. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168609. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168610. return JPEG_SUSPENDED;
  168611. }
  168612. /* OK, output from the virtual arrays. */
  168613. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168614. ci++, compptr++) {
  168615. /* Don't bother to IDCT an uninteresting component. */
  168616. if (! compptr->component_needed)
  168617. continue;
  168618. /* Align the virtual buffer for this component. */
  168619. buffer = (*cinfo->mem->access_virt_barray)
  168620. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168621. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168622. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168623. /* Count non-dummy DCT block rows in this iMCU row. */
  168624. if (cinfo->output_iMCU_row < last_iMCU_row)
  168625. block_rows = compptr->v_samp_factor;
  168626. else {
  168627. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168628. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168629. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168630. }
  168631. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168632. output_ptr = output_buf[ci];
  168633. /* Loop over all DCT blocks to be processed. */
  168634. for (block_row = 0; block_row < block_rows; block_row++) {
  168635. buffer_ptr = buffer[block_row];
  168636. output_col = 0;
  168637. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168638. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168639. output_ptr, output_col);
  168640. buffer_ptr++;
  168641. output_col += compptr->DCT_scaled_size;
  168642. }
  168643. output_ptr += compptr->DCT_scaled_size;
  168644. }
  168645. }
  168646. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168647. return JPEG_ROW_COMPLETED;
  168648. return JPEG_SCAN_COMPLETED;
  168649. }
  168650. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168651. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168652. /*
  168653. * This code applies interblock smoothing as described by section K.8
  168654. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168655. * the DC values of a DCT block and its 8 neighboring blocks.
  168656. * We apply smoothing only for progressive JPEG decoding, and only if
  168657. * the coefficients it can estimate are not yet known to full precision.
  168658. */
  168659. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168660. #define Q01_POS 1
  168661. #define Q10_POS 8
  168662. #define Q20_POS 16
  168663. #define Q11_POS 9
  168664. #define Q02_POS 2
  168665. /*
  168666. * Determine whether block smoothing is applicable and safe.
  168667. * We also latch the current states of the coef_bits[] entries for the
  168668. * AC coefficients; otherwise, if the input side of the decompressor
  168669. * advances into a new scan, we might think the coefficients are known
  168670. * more accurately than they really are.
  168671. */
  168672. LOCAL(boolean)
  168673. smoothing_ok (j_decompress_ptr cinfo)
  168674. {
  168675. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168676. boolean smoothing_useful = FALSE;
  168677. int ci, coefi;
  168678. jpeg_component_info *compptr;
  168679. JQUANT_TBL * qtable;
  168680. int * coef_bits;
  168681. int * coef_bits_latch;
  168682. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168683. return FALSE;
  168684. /* Allocate latch area if not already done */
  168685. if (coef->coef_bits_latch == NULL)
  168686. coef->coef_bits_latch = (int *)
  168687. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168688. cinfo->num_components *
  168689. (SAVED_COEFS * SIZEOF(int)));
  168690. coef_bits_latch = coef->coef_bits_latch;
  168691. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168692. ci++, compptr++) {
  168693. /* All components' quantization values must already be latched. */
  168694. if ((qtable = compptr->quant_table) == NULL)
  168695. return FALSE;
  168696. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168697. if (qtable->quantval[0] == 0 ||
  168698. qtable->quantval[Q01_POS] == 0 ||
  168699. qtable->quantval[Q10_POS] == 0 ||
  168700. qtable->quantval[Q20_POS] == 0 ||
  168701. qtable->quantval[Q11_POS] == 0 ||
  168702. qtable->quantval[Q02_POS] == 0)
  168703. return FALSE;
  168704. /* DC values must be at least partly known for all components. */
  168705. coef_bits = cinfo->coef_bits[ci];
  168706. if (coef_bits[0] < 0)
  168707. return FALSE;
  168708. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168709. for (coefi = 1; coefi <= 5; coefi++) {
  168710. coef_bits_latch[coefi] = coef_bits[coefi];
  168711. if (coef_bits[coefi] != 0)
  168712. smoothing_useful = TRUE;
  168713. }
  168714. coef_bits_latch += SAVED_COEFS;
  168715. }
  168716. return smoothing_useful;
  168717. }
  168718. /*
  168719. * Variant of decompress_data for use when doing block smoothing.
  168720. */
  168721. METHODDEF(int)
  168722. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168723. {
  168724. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168725. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168726. JDIMENSION block_num, last_block_column;
  168727. int ci, block_row, block_rows, access_rows;
  168728. JBLOCKARRAY buffer;
  168729. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168730. JSAMPARRAY output_ptr;
  168731. JDIMENSION output_col;
  168732. jpeg_component_info *compptr;
  168733. inverse_DCT_method_ptr inverse_DCT;
  168734. boolean first_row, last_row;
  168735. JBLOCK workspace;
  168736. int *coef_bits;
  168737. JQUANT_TBL *quanttbl;
  168738. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168739. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168740. int Al, pred;
  168741. /* Force some input to be done if we are getting ahead of the input. */
  168742. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168743. ! cinfo->inputctl->eoi_reached) {
  168744. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168745. /* If input is working on current scan, we ordinarily want it to
  168746. * have completed the current row. But if input scan is DC,
  168747. * we want it to keep one row ahead so that next block row's DC
  168748. * values are up to date.
  168749. */
  168750. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168751. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168752. break;
  168753. }
  168754. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168755. return JPEG_SUSPENDED;
  168756. }
  168757. /* OK, output from the virtual arrays. */
  168758. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168759. ci++, compptr++) {
  168760. /* Don't bother to IDCT an uninteresting component. */
  168761. if (! compptr->component_needed)
  168762. continue;
  168763. /* Count non-dummy DCT block rows in this iMCU row. */
  168764. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168765. block_rows = compptr->v_samp_factor;
  168766. access_rows = block_rows * 2; /* this and next iMCU row */
  168767. last_row = FALSE;
  168768. } else {
  168769. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168770. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168771. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168772. access_rows = block_rows; /* this iMCU row only */
  168773. last_row = TRUE;
  168774. }
  168775. /* Align the virtual buffer for this component. */
  168776. if (cinfo->output_iMCU_row > 0) {
  168777. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168778. buffer = (*cinfo->mem->access_virt_barray)
  168779. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168780. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168781. (JDIMENSION) access_rows, FALSE);
  168782. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168783. first_row = FALSE;
  168784. } else {
  168785. buffer = (*cinfo->mem->access_virt_barray)
  168786. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168787. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168788. first_row = TRUE;
  168789. }
  168790. /* Fetch component-dependent info */
  168791. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168792. quanttbl = compptr->quant_table;
  168793. Q00 = quanttbl->quantval[0];
  168794. Q01 = quanttbl->quantval[Q01_POS];
  168795. Q10 = quanttbl->quantval[Q10_POS];
  168796. Q20 = quanttbl->quantval[Q20_POS];
  168797. Q11 = quanttbl->quantval[Q11_POS];
  168798. Q02 = quanttbl->quantval[Q02_POS];
  168799. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168800. output_ptr = output_buf[ci];
  168801. /* Loop over all DCT blocks to be processed. */
  168802. for (block_row = 0; block_row < block_rows; block_row++) {
  168803. buffer_ptr = buffer[block_row];
  168804. if (first_row && block_row == 0)
  168805. prev_block_row = buffer_ptr;
  168806. else
  168807. prev_block_row = buffer[block_row-1];
  168808. if (last_row && block_row == block_rows-1)
  168809. next_block_row = buffer_ptr;
  168810. else
  168811. next_block_row = buffer[block_row+1];
  168812. /* We fetch the surrounding DC values using a sliding-register approach.
  168813. * Initialize all nine here so as to do the right thing on narrow pics.
  168814. */
  168815. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168816. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168817. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168818. output_col = 0;
  168819. last_block_column = compptr->width_in_blocks - 1;
  168820. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168821. /* Fetch current DCT block into workspace so we can modify it. */
  168822. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168823. /* Update DC values */
  168824. if (block_num < last_block_column) {
  168825. DC3 = (int) prev_block_row[1][0];
  168826. DC6 = (int) buffer_ptr[1][0];
  168827. DC9 = (int) next_block_row[1][0];
  168828. }
  168829. /* Compute coefficient estimates per K.8.
  168830. * An estimate is applied only if coefficient is still zero,
  168831. * and is not known to be fully accurate.
  168832. */
  168833. /* AC01 */
  168834. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168835. num = 36 * Q00 * (DC4 - DC6);
  168836. if (num >= 0) {
  168837. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168838. if (Al > 0 && pred >= (1<<Al))
  168839. pred = (1<<Al)-1;
  168840. } else {
  168841. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168842. if (Al > 0 && pred >= (1<<Al))
  168843. pred = (1<<Al)-1;
  168844. pred = -pred;
  168845. }
  168846. workspace[1] = (JCOEF) pred;
  168847. }
  168848. /* AC10 */
  168849. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168850. num = 36 * Q00 * (DC2 - DC8);
  168851. if (num >= 0) {
  168852. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168853. if (Al > 0 && pred >= (1<<Al))
  168854. pred = (1<<Al)-1;
  168855. } else {
  168856. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168857. if (Al > 0 && pred >= (1<<Al))
  168858. pred = (1<<Al)-1;
  168859. pred = -pred;
  168860. }
  168861. workspace[8] = (JCOEF) pred;
  168862. }
  168863. /* AC20 */
  168864. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168865. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168866. if (num >= 0) {
  168867. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168868. if (Al > 0 && pred >= (1<<Al))
  168869. pred = (1<<Al)-1;
  168870. } else {
  168871. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168872. if (Al > 0 && pred >= (1<<Al))
  168873. pred = (1<<Al)-1;
  168874. pred = -pred;
  168875. }
  168876. workspace[16] = (JCOEF) pred;
  168877. }
  168878. /* AC11 */
  168879. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168880. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168881. if (num >= 0) {
  168882. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168883. if (Al > 0 && pred >= (1<<Al))
  168884. pred = (1<<Al)-1;
  168885. } else {
  168886. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168887. if (Al > 0 && pred >= (1<<Al))
  168888. pred = (1<<Al)-1;
  168889. pred = -pred;
  168890. }
  168891. workspace[9] = (JCOEF) pred;
  168892. }
  168893. /* AC02 */
  168894. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168895. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168896. if (num >= 0) {
  168897. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168898. if (Al > 0 && pred >= (1<<Al))
  168899. pred = (1<<Al)-1;
  168900. } else {
  168901. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168902. if (Al > 0 && pred >= (1<<Al))
  168903. pred = (1<<Al)-1;
  168904. pred = -pred;
  168905. }
  168906. workspace[2] = (JCOEF) pred;
  168907. }
  168908. /* OK, do the IDCT */
  168909. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168910. output_ptr, output_col);
  168911. /* Advance for next column */
  168912. DC1 = DC2; DC2 = DC3;
  168913. DC4 = DC5; DC5 = DC6;
  168914. DC7 = DC8; DC8 = DC9;
  168915. buffer_ptr++, prev_block_row++, next_block_row++;
  168916. output_col += compptr->DCT_scaled_size;
  168917. }
  168918. output_ptr += compptr->DCT_scaled_size;
  168919. }
  168920. }
  168921. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168922. return JPEG_ROW_COMPLETED;
  168923. return JPEG_SCAN_COMPLETED;
  168924. }
  168925. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168926. /*
  168927. * Initialize coefficient buffer controller.
  168928. */
  168929. GLOBAL(void)
  168930. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168931. {
  168932. my_coef_ptr3 coef;
  168933. coef = (my_coef_ptr3)
  168934. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168935. SIZEOF(my_coef_controller3));
  168936. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168937. coef->pub.start_input_pass = start_input_pass;
  168938. coef->pub.start_output_pass = start_output_pass;
  168939. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168940. coef->coef_bits_latch = NULL;
  168941. #endif
  168942. /* Create the coefficient buffer. */
  168943. if (need_full_buffer) {
  168944. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168945. /* Allocate a full-image virtual array for each component, */
  168946. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168947. /* Note we ask for a pre-zeroed array. */
  168948. int ci, access_rows;
  168949. jpeg_component_info *compptr;
  168950. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168951. ci++, compptr++) {
  168952. access_rows = compptr->v_samp_factor;
  168953. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168954. /* If block smoothing could be used, need a bigger window */
  168955. if (cinfo->progressive_mode)
  168956. access_rows *= 3;
  168957. #endif
  168958. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168959. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168960. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168961. (long) compptr->h_samp_factor),
  168962. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168963. (long) compptr->v_samp_factor),
  168964. (JDIMENSION) access_rows);
  168965. }
  168966. coef->pub.consume_data = consume_data;
  168967. coef->pub.decompress_data = decompress_data;
  168968. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168969. #else
  168970. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168971. #endif
  168972. } else {
  168973. /* We only need a single-MCU buffer. */
  168974. JBLOCKROW buffer;
  168975. int i;
  168976. buffer = (JBLOCKROW)
  168977. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168978. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168979. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168980. coef->MCU_buffer[i] = buffer + i;
  168981. }
  168982. coef->pub.consume_data = dummy_consume_data;
  168983. coef->pub.decompress_data = decompress_onepass;
  168984. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168985. }
  168986. }
  168987. /*** End of inlined file: jdcoefct.c ***/
  168988. #undef FIX
  168989. /*** Start of inlined file: jdcolor.c ***/
  168990. #define JPEG_INTERNALS
  168991. /* Private subobject */
  168992. typedef struct {
  168993. struct jpeg_color_deconverter pub; /* public fields */
  168994. /* Private state for YCC->RGB conversion */
  168995. int * Cr_r_tab; /* => table for Cr to R conversion */
  168996. int * Cb_b_tab; /* => table for Cb to B conversion */
  168997. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168998. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168999. } my_color_deconverter2;
  169000. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169001. /**************** YCbCr -> RGB conversion: most common case **************/
  169002. /*
  169003. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169004. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169005. * The conversion equations to be implemented are therefore
  169006. * R = Y + 1.40200 * Cr
  169007. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169008. * B = Y + 1.77200 * Cb
  169009. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169010. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169011. *
  169012. * To avoid floating-point arithmetic, we represent the fractional constants
  169013. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169014. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169015. * Notice that Y, being an integral input, does not contribute any fraction
  169016. * so it need not participate in the rounding.
  169017. *
  169018. * For even more speed, we avoid doing any multiplications in the inner loop
  169019. * by precalculating the constants times Cb and Cr for all possible values.
  169020. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169021. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169022. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169023. * colorspace anyway.
  169024. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169025. * values for the G calculation are left scaled up, since we must add them
  169026. * together before rounding.
  169027. */
  169028. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169029. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169030. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169031. /*
  169032. * Initialize tables for YCC->RGB colorspace conversion.
  169033. */
  169034. LOCAL(void)
  169035. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169036. {
  169037. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169038. int i;
  169039. INT32 x;
  169040. SHIFT_TEMPS
  169041. cconvert->Cr_r_tab = (int *)
  169042. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169043. (MAXJSAMPLE+1) * SIZEOF(int));
  169044. cconvert->Cb_b_tab = (int *)
  169045. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169046. (MAXJSAMPLE+1) * SIZEOF(int));
  169047. cconvert->Cr_g_tab = (INT32 *)
  169048. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169049. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169050. cconvert->Cb_g_tab = (INT32 *)
  169051. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169052. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169053. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169054. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169055. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169056. /* Cr=>R value is nearest int to 1.40200 * x */
  169057. cconvert->Cr_r_tab[i] = (int)
  169058. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169059. /* Cb=>B value is nearest int to 1.77200 * x */
  169060. cconvert->Cb_b_tab[i] = (int)
  169061. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169062. /* Cr=>G value is scaled-up -0.71414 * x */
  169063. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169064. /* Cb=>G value is scaled-up -0.34414 * x */
  169065. /* We also add in ONE_HALF so that need not do it in inner loop */
  169066. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169067. }
  169068. }
  169069. /*
  169070. * Convert some rows of samples to the output colorspace.
  169071. *
  169072. * Note that we change from noninterleaved, one-plane-per-component format
  169073. * to interleaved-pixel format. The output buffer is therefore three times
  169074. * as wide as the input buffer.
  169075. * A starting row offset is provided only for the input buffer. The caller
  169076. * can easily adjust the passed output_buf value to accommodate any row
  169077. * offset required on that side.
  169078. */
  169079. METHODDEF(void)
  169080. ycc_rgb_convert (j_decompress_ptr cinfo,
  169081. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169082. JSAMPARRAY output_buf, int num_rows)
  169083. {
  169084. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169085. register int y, cb, cr;
  169086. register JSAMPROW outptr;
  169087. register JSAMPROW inptr0, inptr1, inptr2;
  169088. register JDIMENSION col;
  169089. JDIMENSION num_cols = cinfo->output_width;
  169090. /* copy these pointers into registers if possible */
  169091. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169092. register int * Crrtab = cconvert->Cr_r_tab;
  169093. register int * Cbbtab = cconvert->Cb_b_tab;
  169094. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169095. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169096. SHIFT_TEMPS
  169097. while (--num_rows >= 0) {
  169098. inptr0 = input_buf[0][input_row];
  169099. inptr1 = input_buf[1][input_row];
  169100. inptr2 = input_buf[2][input_row];
  169101. input_row++;
  169102. outptr = *output_buf++;
  169103. for (col = 0; col < num_cols; col++) {
  169104. y = GETJSAMPLE(inptr0[col]);
  169105. cb = GETJSAMPLE(inptr1[col]);
  169106. cr = GETJSAMPLE(inptr2[col]);
  169107. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169108. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169109. outptr[RGB_GREEN] = range_limit[y +
  169110. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169111. SCALEBITS))];
  169112. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169113. outptr += RGB_PIXELSIZE;
  169114. }
  169115. }
  169116. }
  169117. /**************** Cases other than YCbCr -> RGB **************/
  169118. /*
  169119. * Color conversion for no colorspace change: just copy the data,
  169120. * converting from separate-planes to interleaved representation.
  169121. */
  169122. METHODDEF(void)
  169123. null_convert2 (j_decompress_ptr cinfo,
  169124. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169125. JSAMPARRAY output_buf, int num_rows)
  169126. {
  169127. register JSAMPROW inptr, outptr;
  169128. register JDIMENSION count;
  169129. register int num_components = cinfo->num_components;
  169130. JDIMENSION num_cols = cinfo->output_width;
  169131. int ci;
  169132. while (--num_rows >= 0) {
  169133. for (ci = 0; ci < num_components; ci++) {
  169134. inptr = input_buf[ci][input_row];
  169135. outptr = output_buf[0] + ci;
  169136. for (count = num_cols; count > 0; count--) {
  169137. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169138. outptr += num_components;
  169139. }
  169140. }
  169141. input_row++;
  169142. output_buf++;
  169143. }
  169144. }
  169145. /*
  169146. * Color conversion for grayscale: just copy the data.
  169147. * This also works for YCbCr -> grayscale conversion, in which
  169148. * we just copy the Y (luminance) component and ignore chrominance.
  169149. */
  169150. METHODDEF(void)
  169151. grayscale_convert2 (j_decompress_ptr cinfo,
  169152. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169153. JSAMPARRAY output_buf, int num_rows)
  169154. {
  169155. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169156. num_rows, cinfo->output_width);
  169157. }
  169158. /*
  169159. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169160. * This is provided to support applications that don't want to cope
  169161. * with grayscale as a separate case.
  169162. */
  169163. METHODDEF(void)
  169164. gray_rgb_convert (j_decompress_ptr cinfo,
  169165. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169166. JSAMPARRAY output_buf, int num_rows)
  169167. {
  169168. register JSAMPROW inptr, outptr;
  169169. register JDIMENSION col;
  169170. JDIMENSION num_cols = cinfo->output_width;
  169171. while (--num_rows >= 0) {
  169172. inptr = input_buf[0][input_row++];
  169173. outptr = *output_buf++;
  169174. for (col = 0; col < num_cols; col++) {
  169175. /* We can dispense with GETJSAMPLE() here */
  169176. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169177. outptr += RGB_PIXELSIZE;
  169178. }
  169179. }
  169180. }
  169181. /*
  169182. * Adobe-style YCCK->CMYK conversion.
  169183. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169184. * conversion as above, while passing K (black) unchanged.
  169185. * We assume build_ycc_rgb_table has been called.
  169186. */
  169187. METHODDEF(void)
  169188. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169189. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169190. JSAMPARRAY output_buf, int num_rows)
  169191. {
  169192. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169193. register int y, cb, cr;
  169194. register JSAMPROW outptr;
  169195. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169196. register JDIMENSION col;
  169197. JDIMENSION num_cols = cinfo->output_width;
  169198. /* copy these pointers into registers if possible */
  169199. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169200. register int * Crrtab = cconvert->Cr_r_tab;
  169201. register int * Cbbtab = cconvert->Cb_b_tab;
  169202. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169203. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169204. SHIFT_TEMPS
  169205. while (--num_rows >= 0) {
  169206. inptr0 = input_buf[0][input_row];
  169207. inptr1 = input_buf[1][input_row];
  169208. inptr2 = input_buf[2][input_row];
  169209. inptr3 = input_buf[3][input_row];
  169210. input_row++;
  169211. outptr = *output_buf++;
  169212. for (col = 0; col < num_cols; col++) {
  169213. y = GETJSAMPLE(inptr0[col]);
  169214. cb = GETJSAMPLE(inptr1[col]);
  169215. cr = GETJSAMPLE(inptr2[col]);
  169216. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169217. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169218. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169219. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169220. SCALEBITS)))];
  169221. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169222. /* K passes through unchanged */
  169223. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169224. outptr += 4;
  169225. }
  169226. }
  169227. }
  169228. /*
  169229. * Empty method for start_pass.
  169230. */
  169231. METHODDEF(void)
  169232. start_pass_dcolor (j_decompress_ptr)
  169233. {
  169234. /* no work needed */
  169235. }
  169236. /*
  169237. * Module initialization routine for output colorspace conversion.
  169238. */
  169239. GLOBAL(void)
  169240. jinit_color_deconverter (j_decompress_ptr cinfo)
  169241. {
  169242. my_cconvert_ptr2 cconvert;
  169243. int ci;
  169244. cconvert = (my_cconvert_ptr2)
  169245. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169246. SIZEOF(my_color_deconverter2));
  169247. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169248. cconvert->pub.start_pass = start_pass_dcolor;
  169249. /* Make sure num_components agrees with jpeg_color_space */
  169250. switch (cinfo->jpeg_color_space) {
  169251. case JCS_GRAYSCALE:
  169252. if (cinfo->num_components != 1)
  169253. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169254. break;
  169255. case JCS_RGB:
  169256. case JCS_YCbCr:
  169257. if (cinfo->num_components != 3)
  169258. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169259. break;
  169260. case JCS_CMYK:
  169261. case JCS_YCCK:
  169262. if (cinfo->num_components != 4)
  169263. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169264. break;
  169265. default: /* JCS_UNKNOWN can be anything */
  169266. if (cinfo->num_components < 1)
  169267. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169268. break;
  169269. }
  169270. /* Set out_color_components and conversion method based on requested space.
  169271. * Also clear the component_needed flags for any unused components,
  169272. * so that earlier pipeline stages can avoid useless computation.
  169273. */
  169274. switch (cinfo->out_color_space) {
  169275. case JCS_GRAYSCALE:
  169276. cinfo->out_color_components = 1;
  169277. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169278. cinfo->jpeg_color_space == JCS_YCbCr) {
  169279. cconvert->pub.color_convert = grayscale_convert2;
  169280. /* For color->grayscale conversion, only the Y (0) component is needed */
  169281. for (ci = 1; ci < cinfo->num_components; ci++)
  169282. cinfo->comp_info[ci].component_needed = FALSE;
  169283. } else
  169284. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169285. break;
  169286. case JCS_RGB:
  169287. cinfo->out_color_components = RGB_PIXELSIZE;
  169288. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169289. cconvert->pub.color_convert = ycc_rgb_convert;
  169290. build_ycc_rgb_table(cinfo);
  169291. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169292. cconvert->pub.color_convert = gray_rgb_convert;
  169293. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169294. cconvert->pub.color_convert = null_convert2;
  169295. } else
  169296. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169297. break;
  169298. case JCS_CMYK:
  169299. cinfo->out_color_components = 4;
  169300. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169301. cconvert->pub.color_convert = ycck_cmyk_convert;
  169302. build_ycc_rgb_table(cinfo);
  169303. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169304. cconvert->pub.color_convert = null_convert2;
  169305. } else
  169306. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169307. break;
  169308. default:
  169309. /* Permit null conversion to same output space */
  169310. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169311. cinfo->out_color_components = cinfo->num_components;
  169312. cconvert->pub.color_convert = null_convert2;
  169313. } else /* unsupported non-null conversion */
  169314. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169315. break;
  169316. }
  169317. if (cinfo->quantize_colors)
  169318. cinfo->output_components = 1; /* single colormapped output component */
  169319. else
  169320. cinfo->output_components = cinfo->out_color_components;
  169321. }
  169322. /*** End of inlined file: jdcolor.c ***/
  169323. #undef FIX
  169324. /*** Start of inlined file: jddctmgr.c ***/
  169325. #define JPEG_INTERNALS
  169326. /*
  169327. * The decompressor input side (jdinput.c) saves away the appropriate
  169328. * quantization table for each component at the start of the first scan
  169329. * involving that component. (This is necessary in order to correctly
  169330. * decode files that reuse Q-table slots.)
  169331. * When we are ready to make an output pass, the saved Q-table is converted
  169332. * to a multiplier table that will actually be used by the IDCT routine.
  169333. * The multiplier table contents are IDCT-method-dependent. To support
  169334. * application changes in IDCT method between scans, we can remake the
  169335. * multiplier tables if necessary.
  169336. * In buffered-image mode, the first output pass may occur before any data
  169337. * has been seen for some components, and thus before their Q-tables have
  169338. * been saved away. To handle this case, multiplier tables are preset
  169339. * to zeroes; the result of the IDCT will be a neutral gray level.
  169340. */
  169341. /* Private subobject for this module */
  169342. typedef struct {
  169343. struct jpeg_inverse_dct pub; /* public fields */
  169344. /* This array contains the IDCT method code that each multiplier table
  169345. * is currently set up for, or -1 if it's not yet set up.
  169346. * The actual multiplier tables are pointed to by dct_table in the
  169347. * per-component comp_info structures.
  169348. */
  169349. int cur_method[MAX_COMPONENTS];
  169350. } my_idct_controller;
  169351. typedef my_idct_controller * my_idct_ptr;
  169352. /* Allocated multiplier tables: big enough for any supported variant */
  169353. typedef union {
  169354. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169355. #ifdef DCT_IFAST_SUPPORTED
  169356. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169357. #endif
  169358. #ifdef DCT_FLOAT_SUPPORTED
  169359. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169360. #endif
  169361. } multiplier_table;
  169362. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169363. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169364. */
  169365. #ifdef DCT_ISLOW_SUPPORTED
  169366. #define PROVIDE_ISLOW_TABLES
  169367. #else
  169368. #ifdef IDCT_SCALING_SUPPORTED
  169369. #define PROVIDE_ISLOW_TABLES
  169370. #endif
  169371. #endif
  169372. /*
  169373. * Prepare for an output pass.
  169374. * Here we select the proper IDCT routine for each component and build
  169375. * a matching multiplier table.
  169376. */
  169377. METHODDEF(void)
  169378. start_pass (j_decompress_ptr cinfo)
  169379. {
  169380. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169381. int ci, i;
  169382. jpeg_component_info *compptr;
  169383. int method = 0;
  169384. inverse_DCT_method_ptr method_ptr = NULL;
  169385. JQUANT_TBL * qtbl;
  169386. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169387. ci++, compptr++) {
  169388. /* Select the proper IDCT routine for this component's scaling */
  169389. switch (compptr->DCT_scaled_size) {
  169390. #ifdef IDCT_SCALING_SUPPORTED
  169391. case 1:
  169392. method_ptr = jpeg_idct_1x1;
  169393. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169394. break;
  169395. case 2:
  169396. method_ptr = jpeg_idct_2x2;
  169397. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169398. break;
  169399. case 4:
  169400. method_ptr = jpeg_idct_4x4;
  169401. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169402. break;
  169403. #endif
  169404. case DCTSIZE:
  169405. switch (cinfo->dct_method) {
  169406. #ifdef DCT_ISLOW_SUPPORTED
  169407. case JDCT_ISLOW:
  169408. method_ptr = jpeg_idct_islow;
  169409. method = JDCT_ISLOW;
  169410. break;
  169411. #endif
  169412. #ifdef DCT_IFAST_SUPPORTED
  169413. case JDCT_IFAST:
  169414. method_ptr = jpeg_idct_ifast;
  169415. method = JDCT_IFAST;
  169416. break;
  169417. #endif
  169418. #ifdef DCT_FLOAT_SUPPORTED
  169419. case JDCT_FLOAT:
  169420. method_ptr = jpeg_idct_float;
  169421. method = JDCT_FLOAT;
  169422. break;
  169423. #endif
  169424. default:
  169425. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169426. break;
  169427. }
  169428. break;
  169429. default:
  169430. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169431. break;
  169432. }
  169433. idct->pub.inverse_DCT[ci] = method_ptr;
  169434. /* Create multiplier table from quant table.
  169435. * However, we can skip this if the component is uninteresting
  169436. * or if we already built the table. Also, if no quant table
  169437. * has yet been saved for the component, we leave the
  169438. * multiplier table all-zero; we'll be reading zeroes from the
  169439. * coefficient controller's buffer anyway.
  169440. */
  169441. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169442. continue;
  169443. qtbl = compptr->quant_table;
  169444. if (qtbl == NULL) /* happens if no data yet for component */
  169445. continue;
  169446. idct->cur_method[ci] = method;
  169447. switch (method) {
  169448. #ifdef PROVIDE_ISLOW_TABLES
  169449. case JDCT_ISLOW:
  169450. {
  169451. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169452. * coefficients, but are stored as ints to ensure access efficiency.
  169453. */
  169454. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169455. for (i = 0; i < DCTSIZE2; i++) {
  169456. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169457. }
  169458. }
  169459. break;
  169460. #endif
  169461. #ifdef DCT_IFAST_SUPPORTED
  169462. case JDCT_IFAST:
  169463. {
  169464. /* For AA&N IDCT method, multipliers are equal to quantization
  169465. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169466. * scalefactor[0] = 1
  169467. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169468. * For integer operation, the multiplier table is to be scaled by
  169469. * IFAST_SCALE_BITS.
  169470. */
  169471. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169472. #define CONST_BITS 14
  169473. static const INT16 aanscales[DCTSIZE2] = {
  169474. /* precomputed values scaled up by 14 bits */
  169475. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169476. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169477. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169478. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169479. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169480. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169481. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169482. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169483. };
  169484. SHIFT_TEMPS
  169485. for (i = 0; i < DCTSIZE2; i++) {
  169486. ifmtbl[i] = (IFAST_MULT_TYPE)
  169487. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169488. (INT32) aanscales[i]),
  169489. CONST_BITS-IFAST_SCALE_BITS);
  169490. }
  169491. }
  169492. break;
  169493. #endif
  169494. #ifdef DCT_FLOAT_SUPPORTED
  169495. case JDCT_FLOAT:
  169496. {
  169497. /* For float AA&N IDCT method, multipliers are equal to quantization
  169498. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169499. * scalefactor[0] = 1
  169500. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169501. */
  169502. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169503. int row, col;
  169504. static const double aanscalefactor[DCTSIZE] = {
  169505. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169506. 1.0, 0.785694958, 0.541196100, 0.275899379
  169507. };
  169508. i = 0;
  169509. for (row = 0; row < DCTSIZE; row++) {
  169510. for (col = 0; col < DCTSIZE; col++) {
  169511. fmtbl[i] = (FLOAT_MULT_TYPE)
  169512. ((double) qtbl->quantval[i] *
  169513. aanscalefactor[row] * aanscalefactor[col]);
  169514. i++;
  169515. }
  169516. }
  169517. }
  169518. break;
  169519. #endif
  169520. default:
  169521. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169522. break;
  169523. }
  169524. }
  169525. }
  169526. /*
  169527. * Initialize IDCT manager.
  169528. */
  169529. GLOBAL(void)
  169530. jinit_inverse_dct (j_decompress_ptr cinfo)
  169531. {
  169532. my_idct_ptr idct;
  169533. int ci;
  169534. jpeg_component_info *compptr;
  169535. idct = (my_idct_ptr)
  169536. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169537. SIZEOF(my_idct_controller));
  169538. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169539. idct->pub.start_pass = start_pass;
  169540. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169541. ci++, compptr++) {
  169542. /* Allocate and pre-zero a multiplier table for each component */
  169543. compptr->dct_table =
  169544. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169545. SIZEOF(multiplier_table));
  169546. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169547. /* Mark multiplier table not yet set up for any method */
  169548. idct->cur_method[ci] = -1;
  169549. }
  169550. }
  169551. /*** End of inlined file: jddctmgr.c ***/
  169552. #undef CONST_BITS
  169553. #undef ASSIGN_STATE
  169554. /*** Start of inlined file: jdhuff.c ***/
  169555. #define JPEG_INTERNALS
  169556. /*** Start of inlined file: jdhuff.h ***/
  169557. /* Short forms of external names for systems with brain-damaged linkers. */
  169558. #ifndef __jdhuff_h__
  169559. #define __jdhuff_h__
  169560. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169561. #define jpeg_make_d_derived_tbl jMkDDerived
  169562. #define jpeg_fill_bit_buffer jFilBitBuf
  169563. #define jpeg_huff_decode jHufDecode
  169564. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169565. /* Derived data constructed for each Huffman table */
  169566. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169567. typedef struct {
  169568. /* Basic tables: (element [0] of each array is unused) */
  169569. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169570. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169571. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169572. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169573. * the smallest code of length k; so given a code of length k, the
  169574. * corresponding symbol is huffval[code + valoffset[k]]
  169575. */
  169576. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169577. JHUFF_TBL *pub;
  169578. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169579. * the input data stream. If the next Huffman code is no more
  169580. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169581. * the corresponding symbol directly from these tables.
  169582. */
  169583. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169584. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169585. } d_derived_tbl;
  169586. /* Expand a Huffman table definition into the derived format */
  169587. EXTERN(void) jpeg_make_d_derived_tbl
  169588. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169589. d_derived_tbl ** pdtbl));
  169590. /*
  169591. * Fetching the next N bits from the input stream is a time-critical operation
  169592. * for the Huffman decoders. We implement it with a combination of inline
  169593. * macros and out-of-line subroutines. Note that N (the number of bits
  169594. * demanded at one time) never exceeds 15 for JPEG use.
  169595. *
  169596. * We read source bytes into get_buffer and dole out bits as needed.
  169597. * If get_buffer already contains enough bits, they are fetched in-line
  169598. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169599. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169600. * as full as possible (not just to the number of bits needed; this
  169601. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169602. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169603. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169604. * at least the requested number of bits --- dummy zeroes are inserted if
  169605. * necessary.
  169606. */
  169607. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169608. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169609. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169610. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169611. * appropriately should be a win. Unfortunately we can't define the size
  169612. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169613. * because not all machines measure sizeof in 8-bit bytes.
  169614. */
  169615. typedef struct { /* Bitreading state saved across MCUs */
  169616. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169617. int bits_left; /* # of unused bits in it */
  169618. } bitread_perm_state;
  169619. typedef struct { /* Bitreading working state within an MCU */
  169620. /* Current data source location */
  169621. /* We need a copy, rather than munging the original, in case of suspension */
  169622. const JOCTET * next_input_byte; /* => next byte to read from source */
  169623. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169624. /* Bit input buffer --- note these values are kept in register variables,
  169625. * not in this struct, inside the inner loops.
  169626. */
  169627. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169628. int bits_left; /* # of unused bits in it */
  169629. /* Pointer needed by jpeg_fill_bit_buffer. */
  169630. j_decompress_ptr cinfo; /* back link to decompress master record */
  169631. } bitread_working_state;
  169632. /* Macros to declare and load/save bitread local variables. */
  169633. #define BITREAD_STATE_VARS \
  169634. register bit_buf_type get_buffer; \
  169635. register int bits_left; \
  169636. bitread_working_state br_state
  169637. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169638. br_state.cinfo = cinfop; \
  169639. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169640. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169641. get_buffer = permstate.get_buffer; \
  169642. bits_left = permstate.bits_left;
  169643. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169644. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169645. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169646. permstate.get_buffer = get_buffer; \
  169647. permstate.bits_left = bits_left
  169648. /*
  169649. * These macros provide the in-line portion of bit fetching.
  169650. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169651. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169652. * The variables get_buffer and bits_left are assumed to be locals,
  169653. * but the state struct might not be (jpeg_huff_decode needs this).
  169654. * CHECK_BIT_BUFFER(state,n,action);
  169655. * Ensure there are N bits in get_buffer; if suspend, take action.
  169656. * val = GET_BITS(n);
  169657. * Fetch next N bits.
  169658. * val = PEEK_BITS(n);
  169659. * Fetch next N bits without removing them from the buffer.
  169660. * DROP_BITS(n);
  169661. * Discard next N bits.
  169662. * The value N should be a simple variable, not an expression, because it
  169663. * is evaluated multiple times.
  169664. */
  169665. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169666. { if (bits_left < (nbits)) { \
  169667. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169668. { action; } \
  169669. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169670. #define GET_BITS(nbits) \
  169671. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169672. #define PEEK_BITS(nbits) \
  169673. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169674. #define DROP_BITS(nbits) \
  169675. (bits_left -= (nbits))
  169676. /* Load up the bit buffer to a depth of at least nbits */
  169677. EXTERN(boolean) jpeg_fill_bit_buffer
  169678. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169679. register int bits_left, int nbits));
  169680. /*
  169681. * Code for extracting next Huffman-coded symbol from input bit stream.
  169682. * Again, this is time-critical and we make the main paths be macros.
  169683. *
  169684. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169685. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169686. * or fewer bits long. The few overlength codes are handled with a loop,
  169687. * which need not be inline code.
  169688. *
  169689. * Notes about the HUFF_DECODE macro:
  169690. * 1. Near the end of the data segment, we may fail to get enough bits
  169691. * for a lookahead. In that case, we do it the hard way.
  169692. * 2. If the lookahead table contains no entry, the next code must be
  169693. * more than HUFF_LOOKAHEAD bits long.
  169694. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169695. */
  169696. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169697. { register int nb, look; \
  169698. if (bits_left < HUFF_LOOKAHEAD) { \
  169699. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169700. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169701. if (bits_left < HUFF_LOOKAHEAD) { \
  169702. nb = 1; goto slowlabel; \
  169703. } \
  169704. } \
  169705. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169706. if ((nb = htbl->look_nbits[look]) != 0) { \
  169707. DROP_BITS(nb); \
  169708. result = htbl->look_sym[look]; \
  169709. } else { \
  169710. nb = HUFF_LOOKAHEAD+1; \
  169711. slowlabel: \
  169712. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169713. { failaction; } \
  169714. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169715. } \
  169716. }
  169717. /* Out-of-line case for Huffman code fetching */
  169718. EXTERN(int) jpeg_huff_decode
  169719. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169720. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169721. #endif
  169722. /*** End of inlined file: jdhuff.h ***/
  169723. /* Declarations shared with jdphuff.c */
  169724. /*
  169725. * Expanded entropy decoder object for Huffman decoding.
  169726. *
  169727. * The savable_state subrecord contains fields that change within an MCU,
  169728. * but must not be updated permanently until we complete the MCU.
  169729. */
  169730. typedef struct {
  169731. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169732. } savable_state2;
  169733. /* This macro is to work around compilers with missing or broken
  169734. * structure assignment. You'll need to fix this code if you have
  169735. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169736. */
  169737. #ifndef NO_STRUCT_ASSIGN
  169738. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169739. #else
  169740. #if MAX_COMPS_IN_SCAN == 4
  169741. #define ASSIGN_STATE(dest,src) \
  169742. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169743. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169744. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169745. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169746. #endif
  169747. #endif
  169748. typedef struct {
  169749. struct jpeg_entropy_decoder pub; /* public fields */
  169750. /* These fields are loaded into local variables at start of each MCU.
  169751. * In case of suspension, we exit WITHOUT updating them.
  169752. */
  169753. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169754. savable_state2 saved; /* Other state at start of MCU */
  169755. /* These fields are NOT loaded into local working state. */
  169756. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169757. /* Pointers to derived tables (these workspaces have image lifespan) */
  169758. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169759. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169760. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169761. /* Pointers to derived tables to be used for each block within an MCU */
  169762. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169763. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169764. /* Whether we care about the DC and AC coefficient values for each block */
  169765. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169766. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169767. } huff_entropy_decoder2;
  169768. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169769. /*
  169770. * Initialize for a Huffman-compressed scan.
  169771. */
  169772. METHODDEF(void)
  169773. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169774. {
  169775. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169776. int ci, blkn, dctbl, actbl;
  169777. jpeg_component_info * compptr;
  169778. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169779. * This ought to be an error condition, but we make it a warning because
  169780. * there are some baseline files out there with all zeroes in these bytes.
  169781. */
  169782. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169783. cinfo->Ah != 0 || cinfo->Al != 0)
  169784. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169785. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169786. compptr = cinfo->cur_comp_info[ci];
  169787. dctbl = compptr->dc_tbl_no;
  169788. actbl = compptr->ac_tbl_no;
  169789. /* Compute derived values for Huffman tables */
  169790. /* We may do this more than once for a table, but it's not expensive */
  169791. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169792. & entropy->dc_derived_tbls[dctbl]);
  169793. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169794. & entropy->ac_derived_tbls[actbl]);
  169795. /* Initialize DC predictions to 0 */
  169796. entropy->saved.last_dc_val[ci] = 0;
  169797. }
  169798. /* Precalculate decoding info for each block in an MCU of this scan */
  169799. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169800. ci = cinfo->MCU_membership[blkn];
  169801. compptr = cinfo->cur_comp_info[ci];
  169802. /* Precalculate which table to use for each block */
  169803. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169804. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169805. /* Decide whether we really care about the coefficient values */
  169806. if (compptr->component_needed) {
  169807. entropy->dc_needed[blkn] = TRUE;
  169808. /* we don't need the ACs if producing a 1/8th-size image */
  169809. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169810. } else {
  169811. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169812. }
  169813. }
  169814. /* Initialize bitread state variables */
  169815. entropy->bitstate.bits_left = 0;
  169816. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169817. entropy->pub.insufficient_data = FALSE;
  169818. /* Initialize restart counter */
  169819. entropy->restarts_to_go = cinfo->restart_interval;
  169820. }
  169821. /*
  169822. * Compute the derived values for a Huffman table.
  169823. * This routine also performs some validation checks on the table.
  169824. *
  169825. * Note this is also used by jdphuff.c.
  169826. */
  169827. GLOBAL(void)
  169828. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169829. d_derived_tbl ** pdtbl)
  169830. {
  169831. JHUFF_TBL *htbl;
  169832. d_derived_tbl *dtbl;
  169833. int p, i, l, si, numsymbols;
  169834. int lookbits, ctr;
  169835. char huffsize[257];
  169836. unsigned int huffcode[257];
  169837. unsigned int code;
  169838. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169839. * paralleling the order of the symbols themselves in htbl->huffval[].
  169840. */
  169841. /* Find the input Huffman table */
  169842. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169843. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169844. htbl =
  169845. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169846. if (htbl == NULL)
  169847. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169848. /* Allocate a workspace if we haven't already done so. */
  169849. if (*pdtbl == NULL)
  169850. *pdtbl = (d_derived_tbl *)
  169851. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169852. SIZEOF(d_derived_tbl));
  169853. dtbl = *pdtbl;
  169854. dtbl->pub = htbl; /* fill in back link */
  169855. /* Figure C.1: make table of Huffman code length for each symbol */
  169856. p = 0;
  169857. for (l = 1; l <= 16; l++) {
  169858. i = (int) htbl->bits[l];
  169859. if (i < 0 || p + i > 256) /* protect against table overrun */
  169860. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169861. while (i--)
  169862. huffsize[p++] = (char) l;
  169863. }
  169864. huffsize[p] = 0;
  169865. numsymbols = p;
  169866. /* Figure C.2: generate the codes themselves */
  169867. /* We also validate that the counts represent a legal Huffman code tree. */
  169868. code = 0;
  169869. si = huffsize[0];
  169870. p = 0;
  169871. while (huffsize[p]) {
  169872. while (((int) huffsize[p]) == si) {
  169873. huffcode[p++] = code;
  169874. code++;
  169875. }
  169876. /* code is now 1 more than the last code used for codelength si; but
  169877. * it must still fit in si bits, since no code is allowed to be all ones.
  169878. */
  169879. if (((INT32) code) >= (((INT32) 1) << si))
  169880. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169881. code <<= 1;
  169882. si++;
  169883. }
  169884. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169885. p = 0;
  169886. for (l = 1; l <= 16; l++) {
  169887. if (htbl->bits[l]) {
  169888. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169889. * minus the minimum code of length l
  169890. */
  169891. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169892. p += htbl->bits[l];
  169893. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169894. } else {
  169895. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169896. }
  169897. }
  169898. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169899. /* Compute lookahead tables to speed up decoding.
  169900. * First we set all the table entries to 0, indicating "too long";
  169901. * then we iterate through the Huffman codes that are short enough and
  169902. * fill in all the entries that correspond to bit sequences starting
  169903. * with that code.
  169904. */
  169905. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169906. p = 0;
  169907. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169908. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169909. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169910. /* Generate left-justified code followed by all possible bit sequences */
  169911. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169912. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169913. dtbl->look_nbits[lookbits] = l;
  169914. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169915. lookbits++;
  169916. }
  169917. }
  169918. }
  169919. /* Validate symbols as being reasonable.
  169920. * For AC tables, we make no check, but accept all byte values 0..255.
  169921. * For DC tables, we require the symbols to be in range 0..15.
  169922. * (Tighter bounds could be applied depending on the data depth and mode,
  169923. * but this is sufficient to ensure safe decoding.)
  169924. */
  169925. if (isDC) {
  169926. for (i = 0; i < numsymbols; i++) {
  169927. int sym = htbl->huffval[i];
  169928. if (sym < 0 || sym > 15)
  169929. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169930. }
  169931. }
  169932. }
  169933. /*
  169934. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169935. * See jdhuff.h for info about usage.
  169936. * Note: current values of get_buffer and bits_left are passed as parameters,
  169937. * but are returned in the corresponding fields of the state struct.
  169938. *
  169939. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169940. * of get_buffer to be used. (On machines with wider words, an even larger
  169941. * buffer could be used.) However, on some machines 32-bit shifts are
  169942. * quite slow and take time proportional to the number of places shifted.
  169943. * (This is true with most PC compilers, for instance.) In this case it may
  169944. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169945. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169946. */
  169947. #ifdef SLOW_SHIFT_32
  169948. #define MIN_GET_BITS 15 /* minimum allowable value */
  169949. #else
  169950. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169951. #endif
  169952. GLOBAL(boolean)
  169953. jpeg_fill_bit_buffer (bitread_working_state * state,
  169954. register bit_buf_type get_buffer, register int bits_left,
  169955. int nbits)
  169956. /* Load up the bit buffer to a depth of at least nbits */
  169957. {
  169958. /* Copy heavily used state fields into locals (hopefully registers) */
  169959. register const JOCTET * next_input_byte = state->next_input_byte;
  169960. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169961. j_decompress_ptr cinfo = state->cinfo;
  169962. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169963. /* (It is assumed that no request will be for more than that many bits.) */
  169964. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169965. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169966. while (bits_left < MIN_GET_BITS) {
  169967. register int c;
  169968. /* Attempt to read a byte */
  169969. if (bytes_in_buffer == 0) {
  169970. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169971. return FALSE;
  169972. next_input_byte = cinfo->src->next_input_byte;
  169973. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169974. }
  169975. bytes_in_buffer--;
  169976. c = GETJOCTET(*next_input_byte++);
  169977. /* If it's 0xFF, check and discard stuffed zero byte */
  169978. if (c == 0xFF) {
  169979. /* Loop here to discard any padding FF's on terminating marker,
  169980. * so that we can save a valid unread_marker value. NOTE: we will
  169981. * accept multiple FF's followed by a 0 as meaning a single FF data
  169982. * byte. This data pattern is not valid according to the standard.
  169983. */
  169984. do {
  169985. if (bytes_in_buffer == 0) {
  169986. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169987. return FALSE;
  169988. next_input_byte = cinfo->src->next_input_byte;
  169989. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169990. }
  169991. bytes_in_buffer--;
  169992. c = GETJOCTET(*next_input_byte++);
  169993. } while (c == 0xFF);
  169994. if (c == 0) {
  169995. /* Found FF/00, which represents an FF data byte */
  169996. c = 0xFF;
  169997. } else {
  169998. /* Oops, it's actually a marker indicating end of compressed data.
  169999. * Save the marker code for later use.
  170000. * Fine point: it might appear that we should save the marker into
  170001. * bitread working state, not straight into permanent state. But
  170002. * once we have hit a marker, we cannot need to suspend within the
  170003. * current MCU, because we will read no more bytes from the data
  170004. * source. So it is OK to update permanent state right away.
  170005. */
  170006. cinfo->unread_marker = c;
  170007. /* See if we need to insert some fake zero bits. */
  170008. goto no_more_bytes;
  170009. }
  170010. }
  170011. /* OK, load c into get_buffer */
  170012. get_buffer = (get_buffer << 8) | c;
  170013. bits_left += 8;
  170014. } /* end while */
  170015. } else {
  170016. no_more_bytes:
  170017. /* We get here if we've read the marker that terminates the compressed
  170018. * data segment. There should be enough bits in the buffer register
  170019. * to satisfy the request; if so, no problem.
  170020. */
  170021. if (nbits > bits_left) {
  170022. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170023. * the data stream, so that we can produce some kind of image.
  170024. * We use a nonvolatile flag to ensure that only one warning message
  170025. * appears per data segment.
  170026. */
  170027. if (! cinfo->entropy->insufficient_data) {
  170028. WARNMS(cinfo, JWRN_HIT_MARKER);
  170029. cinfo->entropy->insufficient_data = TRUE;
  170030. }
  170031. /* Fill the buffer with zero bits */
  170032. get_buffer <<= MIN_GET_BITS - bits_left;
  170033. bits_left = MIN_GET_BITS;
  170034. }
  170035. }
  170036. /* Unload the local registers */
  170037. state->next_input_byte = next_input_byte;
  170038. state->bytes_in_buffer = bytes_in_buffer;
  170039. state->get_buffer = get_buffer;
  170040. state->bits_left = bits_left;
  170041. return TRUE;
  170042. }
  170043. /*
  170044. * Out-of-line code for Huffman code decoding.
  170045. * See jdhuff.h for info about usage.
  170046. */
  170047. GLOBAL(int)
  170048. jpeg_huff_decode (bitread_working_state * state,
  170049. register bit_buf_type get_buffer, register int bits_left,
  170050. d_derived_tbl * htbl, int min_bits)
  170051. {
  170052. register int l = min_bits;
  170053. register INT32 code;
  170054. /* HUFF_DECODE has determined that the code is at least min_bits */
  170055. /* bits long, so fetch that many bits in one swoop. */
  170056. CHECK_BIT_BUFFER(*state, l, return -1);
  170057. code = GET_BITS(l);
  170058. /* Collect the rest of the Huffman code one bit at a time. */
  170059. /* This is per Figure F.16 in the JPEG spec. */
  170060. while (code > htbl->maxcode[l]) {
  170061. code <<= 1;
  170062. CHECK_BIT_BUFFER(*state, 1, return -1);
  170063. code |= GET_BITS(1);
  170064. l++;
  170065. }
  170066. /* Unload the local registers */
  170067. state->get_buffer = get_buffer;
  170068. state->bits_left = bits_left;
  170069. /* With garbage input we may reach the sentinel value l = 17. */
  170070. if (l > 16) {
  170071. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170072. return 0; /* fake a zero as the safest result */
  170073. }
  170074. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170075. }
  170076. /*
  170077. * Check for a restart marker & resynchronize decoder.
  170078. * Returns FALSE if must suspend.
  170079. */
  170080. LOCAL(boolean)
  170081. process_restart (j_decompress_ptr cinfo)
  170082. {
  170083. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170084. int ci;
  170085. /* Throw away any unused bits remaining in bit buffer; */
  170086. /* include any full bytes in next_marker's count of discarded bytes */
  170087. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170088. entropy->bitstate.bits_left = 0;
  170089. /* Advance past the RSTn marker */
  170090. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170091. return FALSE;
  170092. /* Re-initialize DC predictions to 0 */
  170093. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170094. entropy->saved.last_dc_val[ci] = 0;
  170095. /* Reset restart counter */
  170096. entropy->restarts_to_go = cinfo->restart_interval;
  170097. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170098. * against a marker. In that case we will end up treating the next data
  170099. * segment as empty, and we can avoid producing bogus output pixels by
  170100. * leaving the flag set.
  170101. */
  170102. if (cinfo->unread_marker == 0)
  170103. entropy->pub.insufficient_data = FALSE;
  170104. return TRUE;
  170105. }
  170106. /*
  170107. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170108. * The coefficients are reordered from zigzag order into natural array order,
  170109. * but are not dequantized.
  170110. *
  170111. * The i'th block of the MCU is stored into the block pointed to by
  170112. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170113. * (Wholesale zeroing is usually a little faster than retail...)
  170114. *
  170115. * Returns FALSE if data source requested suspension. In that case no
  170116. * changes have been made to permanent state. (Exception: some output
  170117. * coefficients may already have been assigned. This is harmless for
  170118. * this module, since we'll just re-assign them on the next call.)
  170119. */
  170120. METHODDEF(boolean)
  170121. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170122. {
  170123. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170124. int blkn;
  170125. BITREAD_STATE_VARS;
  170126. savable_state2 state;
  170127. /* Process restart marker if needed; may have to suspend */
  170128. if (cinfo->restart_interval) {
  170129. if (entropy->restarts_to_go == 0)
  170130. if (! process_restart(cinfo))
  170131. return FALSE;
  170132. }
  170133. /* If we've run out of data, just leave the MCU set to zeroes.
  170134. * This way, we return uniform gray for the remainder of the segment.
  170135. */
  170136. if (! entropy->pub.insufficient_data) {
  170137. /* Load up working state */
  170138. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170139. ASSIGN_STATE(state, entropy->saved);
  170140. /* Outer loop handles each block in the MCU */
  170141. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170142. JBLOCKROW block = MCU_data[blkn];
  170143. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170144. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170145. register int s, k, r;
  170146. /* Decode a single block's worth of coefficients */
  170147. /* Section F.2.2.1: decode the DC coefficient difference */
  170148. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170149. if (s) {
  170150. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170151. r = GET_BITS(s);
  170152. s = HUFF_EXTEND(r, s);
  170153. }
  170154. if (entropy->dc_needed[blkn]) {
  170155. /* Convert DC difference to actual value, update last_dc_val */
  170156. int ci = cinfo->MCU_membership[blkn];
  170157. s += state.last_dc_val[ci];
  170158. state.last_dc_val[ci] = s;
  170159. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170160. (*block)[0] = (JCOEF) s;
  170161. }
  170162. if (entropy->ac_needed[blkn]) {
  170163. /* Section F.2.2.2: decode the AC coefficients */
  170164. /* Since zeroes are skipped, output area must be cleared beforehand */
  170165. for (k = 1; k < DCTSIZE2; k++) {
  170166. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170167. r = s >> 4;
  170168. s &= 15;
  170169. if (s) {
  170170. k += r;
  170171. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170172. r = GET_BITS(s);
  170173. s = HUFF_EXTEND(r, s);
  170174. /* Output coefficient in natural (dezigzagged) order.
  170175. * Note: the extra entries in jpeg_natural_order[] will save us
  170176. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170177. */
  170178. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170179. } else {
  170180. if (r != 15)
  170181. break;
  170182. k += 15;
  170183. }
  170184. }
  170185. } else {
  170186. /* Section F.2.2.2: decode the AC coefficients */
  170187. /* In this path we just discard the values */
  170188. for (k = 1; k < DCTSIZE2; k++) {
  170189. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170190. r = s >> 4;
  170191. s &= 15;
  170192. if (s) {
  170193. k += r;
  170194. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170195. DROP_BITS(s);
  170196. } else {
  170197. if (r != 15)
  170198. break;
  170199. k += 15;
  170200. }
  170201. }
  170202. }
  170203. }
  170204. /* Completed MCU, so update state */
  170205. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170206. ASSIGN_STATE(entropy->saved, state);
  170207. }
  170208. /* Account for restart interval (no-op if not using restarts) */
  170209. entropy->restarts_to_go--;
  170210. return TRUE;
  170211. }
  170212. /*
  170213. * Module initialization routine for Huffman entropy decoding.
  170214. */
  170215. GLOBAL(void)
  170216. jinit_huff_decoder (j_decompress_ptr cinfo)
  170217. {
  170218. huff_entropy_ptr2 entropy;
  170219. int i;
  170220. entropy = (huff_entropy_ptr2)
  170221. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170222. SIZEOF(huff_entropy_decoder2));
  170223. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170224. entropy->pub.start_pass = start_pass_huff_decoder;
  170225. entropy->pub.decode_mcu = decode_mcu;
  170226. /* Mark tables unallocated */
  170227. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170228. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170229. }
  170230. }
  170231. /*** End of inlined file: jdhuff.c ***/
  170232. /*** Start of inlined file: jdinput.c ***/
  170233. #define JPEG_INTERNALS
  170234. /* Private state */
  170235. typedef struct {
  170236. struct jpeg_input_controller pub; /* public fields */
  170237. boolean inheaders; /* TRUE until first SOS is reached */
  170238. } my_input_controller;
  170239. typedef my_input_controller * my_inputctl_ptr;
  170240. /* Forward declarations */
  170241. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170242. /*
  170243. * Routines to calculate various quantities related to the size of the image.
  170244. */
  170245. LOCAL(void)
  170246. initial_setup2 (j_decompress_ptr cinfo)
  170247. /* Called once, when first SOS marker is reached */
  170248. {
  170249. int ci;
  170250. jpeg_component_info *compptr;
  170251. /* Make sure image isn't bigger than I can handle */
  170252. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170253. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170254. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170255. /* For now, precision must match compiled-in value... */
  170256. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170257. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170258. /* Check that number of components won't exceed internal array sizes */
  170259. if (cinfo->num_components > MAX_COMPONENTS)
  170260. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170261. MAX_COMPONENTS);
  170262. /* Compute maximum sampling factors; check factor validity */
  170263. cinfo->max_h_samp_factor = 1;
  170264. cinfo->max_v_samp_factor = 1;
  170265. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170266. ci++, compptr++) {
  170267. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170268. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170269. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170270. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170271. compptr->h_samp_factor);
  170272. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170273. compptr->v_samp_factor);
  170274. }
  170275. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170276. * In the full decompressor, this will be overridden by jdmaster.c;
  170277. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170278. */
  170279. cinfo->min_DCT_scaled_size = DCTSIZE;
  170280. /* Compute dimensions of components */
  170281. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170282. ci++, compptr++) {
  170283. compptr->DCT_scaled_size = DCTSIZE;
  170284. /* Size in DCT blocks */
  170285. compptr->width_in_blocks = (JDIMENSION)
  170286. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170287. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170288. compptr->height_in_blocks = (JDIMENSION)
  170289. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170290. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170291. /* downsampled_width and downsampled_height will also be overridden by
  170292. * jdmaster.c if we are doing full decompression. The transcoder library
  170293. * doesn't use these values, but the calling application might.
  170294. */
  170295. /* Size in samples */
  170296. compptr->downsampled_width = (JDIMENSION)
  170297. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170298. (long) cinfo->max_h_samp_factor);
  170299. compptr->downsampled_height = (JDIMENSION)
  170300. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170301. (long) cinfo->max_v_samp_factor);
  170302. /* Mark component needed, until color conversion says otherwise */
  170303. compptr->component_needed = TRUE;
  170304. /* Mark no quantization table yet saved for component */
  170305. compptr->quant_table = NULL;
  170306. }
  170307. /* Compute number of fully interleaved MCU rows. */
  170308. cinfo->total_iMCU_rows = (JDIMENSION)
  170309. jdiv_round_up((long) cinfo->image_height,
  170310. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170311. /* Decide whether file contains multiple scans */
  170312. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170313. cinfo->inputctl->has_multiple_scans = TRUE;
  170314. else
  170315. cinfo->inputctl->has_multiple_scans = FALSE;
  170316. }
  170317. LOCAL(void)
  170318. per_scan_setup2 (j_decompress_ptr cinfo)
  170319. /* Do computations that are needed before processing a JPEG scan */
  170320. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170321. {
  170322. int ci, mcublks, tmp;
  170323. jpeg_component_info *compptr;
  170324. if (cinfo->comps_in_scan == 1) {
  170325. /* Noninterleaved (single-component) scan */
  170326. compptr = cinfo->cur_comp_info[0];
  170327. /* Overall image size in MCUs */
  170328. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170329. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170330. /* For noninterleaved scan, always one block per MCU */
  170331. compptr->MCU_width = 1;
  170332. compptr->MCU_height = 1;
  170333. compptr->MCU_blocks = 1;
  170334. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170335. compptr->last_col_width = 1;
  170336. /* For noninterleaved scans, it is convenient to define last_row_height
  170337. * as the number of block rows present in the last iMCU row.
  170338. */
  170339. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170340. if (tmp == 0) tmp = compptr->v_samp_factor;
  170341. compptr->last_row_height = tmp;
  170342. /* Prepare array describing MCU composition */
  170343. cinfo->blocks_in_MCU = 1;
  170344. cinfo->MCU_membership[0] = 0;
  170345. } else {
  170346. /* Interleaved (multi-component) scan */
  170347. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170348. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170349. MAX_COMPS_IN_SCAN);
  170350. /* Overall image size in MCUs */
  170351. cinfo->MCUs_per_row = (JDIMENSION)
  170352. jdiv_round_up((long) cinfo->image_width,
  170353. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170354. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170355. jdiv_round_up((long) cinfo->image_height,
  170356. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170357. cinfo->blocks_in_MCU = 0;
  170358. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170359. compptr = cinfo->cur_comp_info[ci];
  170360. /* Sampling factors give # of blocks of component in each MCU */
  170361. compptr->MCU_width = compptr->h_samp_factor;
  170362. compptr->MCU_height = compptr->v_samp_factor;
  170363. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170364. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170365. /* Figure number of non-dummy blocks in last MCU column & row */
  170366. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170367. if (tmp == 0) tmp = compptr->MCU_width;
  170368. compptr->last_col_width = tmp;
  170369. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170370. if (tmp == 0) tmp = compptr->MCU_height;
  170371. compptr->last_row_height = tmp;
  170372. /* Prepare array describing MCU composition */
  170373. mcublks = compptr->MCU_blocks;
  170374. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170375. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170376. while (mcublks-- > 0) {
  170377. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170378. }
  170379. }
  170380. }
  170381. }
  170382. /*
  170383. * Save away a copy of the Q-table referenced by each component present
  170384. * in the current scan, unless already saved during a prior scan.
  170385. *
  170386. * In a multiple-scan JPEG file, the encoder could assign different components
  170387. * the same Q-table slot number, but change table definitions between scans
  170388. * so that each component uses a different Q-table. (The IJG encoder is not
  170389. * currently capable of doing this, but other encoders might.) Since we want
  170390. * to be able to dequantize all the components at the end of the file, this
  170391. * means that we have to save away the table actually used for each component.
  170392. * We do this by copying the table at the start of the first scan containing
  170393. * the component.
  170394. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170395. * slot between scans of a component using that slot. If the encoder does so
  170396. * anyway, this decoder will simply use the Q-table values that were current
  170397. * at the start of the first scan for the component.
  170398. *
  170399. * The decompressor output side looks only at the saved quant tables,
  170400. * not at the current Q-table slots.
  170401. */
  170402. LOCAL(void)
  170403. latch_quant_tables (j_decompress_ptr cinfo)
  170404. {
  170405. int ci, qtblno;
  170406. jpeg_component_info *compptr;
  170407. JQUANT_TBL * qtbl;
  170408. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170409. compptr = cinfo->cur_comp_info[ci];
  170410. /* No work if we already saved Q-table for this component */
  170411. if (compptr->quant_table != NULL)
  170412. continue;
  170413. /* Make sure specified quantization table is present */
  170414. qtblno = compptr->quant_tbl_no;
  170415. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170416. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170417. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170418. /* OK, save away the quantization table */
  170419. qtbl = (JQUANT_TBL *)
  170420. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170421. SIZEOF(JQUANT_TBL));
  170422. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170423. compptr->quant_table = qtbl;
  170424. }
  170425. }
  170426. /*
  170427. * Initialize the input modules to read a scan of compressed data.
  170428. * The first call to this is done by jdmaster.c after initializing
  170429. * the entire decompressor (during jpeg_start_decompress).
  170430. * Subsequent calls come from consume_markers, below.
  170431. */
  170432. METHODDEF(void)
  170433. start_input_pass2 (j_decompress_ptr cinfo)
  170434. {
  170435. per_scan_setup2(cinfo);
  170436. latch_quant_tables(cinfo);
  170437. (*cinfo->entropy->start_pass) (cinfo);
  170438. (*cinfo->coef->start_input_pass) (cinfo);
  170439. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170440. }
  170441. /*
  170442. * Finish up after inputting a compressed-data scan.
  170443. * This is called by the coefficient controller after it's read all
  170444. * the expected data of the scan.
  170445. */
  170446. METHODDEF(void)
  170447. finish_input_pass (j_decompress_ptr cinfo)
  170448. {
  170449. cinfo->inputctl->consume_input = consume_markers;
  170450. }
  170451. /*
  170452. * Read JPEG markers before, between, or after compressed-data scans.
  170453. * Change state as necessary when a new scan is reached.
  170454. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170455. *
  170456. * The consume_input method pointer points either here or to the
  170457. * coefficient controller's consume_data routine, depending on whether
  170458. * we are reading a compressed data segment or inter-segment markers.
  170459. */
  170460. METHODDEF(int)
  170461. consume_markers (j_decompress_ptr cinfo)
  170462. {
  170463. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170464. int val;
  170465. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170466. return JPEG_REACHED_EOI;
  170467. val = (*cinfo->marker->read_markers) (cinfo);
  170468. switch (val) {
  170469. case JPEG_REACHED_SOS: /* Found SOS */
  170470. if (inputctl->inheaders) { /* 1st SOS */
  170471. initial_setup2(cinfo);
  170472. inputctl->inheaders = FALSE;
  170473. /* Note: start_input_pass must be called by jdmaster.c
  170474. * before any more input can be consumed. jdapimin.c is
  170475. * responsible for enforcing this sequencing.
  170476. */
  170477. } else { /* 2nd or later SOS marker */
  170478. if (! inputctl->pub.has_multiple_scans)
  170479. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170480. start_input_pass2(cinfo);
  170481. }
  170482. break;
  170483. case JPEG_REACHED_EOI: /* Found EOI */
  170484. inputctl->pub.eoi_reached = TRUE;
  170485. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170486. if (cinfo->marker->saw_SOF)
  170487. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170488. } else {
  170489. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170490. * if user set output_scan_number larger than number of scans.
  170491. */
  170492. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170493. cinfo->output_scan_number = cinfo->input_scan_number;
  170494. }
  170495. break;
  170496. case JPEG_SUSPENDED:
  170497. break;
  170498. }
  170499. return val;
  170500. }
  170501. /*
  170502. * Reset state to begin a fresh datastream.
  170503. */
  170504. METHODDEF(void)
  170505. reset_input_controller (j_decompress_ptr cinfo)
  170506. {
  170507. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170508. inputctl->pub.consume_input = consume_markers;
  170509. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170510. inputctl->pub.eoi_reached = FALSE;
  170511. inputctl->inheaders = TRUE;
  170512. /* Reset other modules */
  170513. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170514. (*cinfo->marker->reset_marker_reader) (cinfo);
  170515. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170516. cinfo->coef_bits = NULL;
  170517. }
  170518. /*
  170519. * Initialize the input controller module.
  170520. * This is called only once, when the decompression object is created.
  170521. */
  170522. GLOBAL(void)
  170523. jinit_input_controller (j_decompress_ptr cinfo)
  170524. {
  170525. my_inputctl_ptr inputctl;
  170526. /* Create subobject in permanent pool */
  170527. inputctl = (my_inputctl_ptr)
  170528. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170529. SIZEOF(my_input_controller));
  170530. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170531. /* Initialize method pointers */
  170532. inputctl->pub.consume_input = consume_markers;
  170533. inputctl->pub.reset_input_controller = reset_input_controller;
  170534. inputctl->pub.start_input_pass = start_input_pass2;
  170535. inputctl->pub.finish_input_pass = finish_input_pass;
  170536. /* Initialize state: can't use reset_input_controller since we don't
  170537. * want to try to reset other modules yet.
  170538. */
  170539. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170540. inputctl->pub.eoi_reached = FALSE;
  170541. inputctl->inheaders = TRUE;
  170542. }
  170543. /*** End of inlined file: jdinput.c ***/
  170544. /*** Start of inlined file: jdmainct.c ***/
  170545. #define JPEG_INTERNALS
  170546. /*
  170547. * In the current system design, the main buffer need never be a full-image
  170548. * buffer; any full-height buffers will be found inside the coefficient or
  170549. * postprocessing controllers. Nonetheless, the main controller is not
  170550. * trivial. Its responsibility is to provide context rows for upsampling/
  170551. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170552. *
  170553. * Postprocessor input data is counted in "row groups". A row group
  170554. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170555. * sample rows of each component. (We require DCT_scaled_size values to be
  170556. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170557. * values will likely be powers of two, so we actually have the stronger
  170558. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170559. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170560. * row group (times any additional scale factor that the upsampler is
  170561. * applying).
  170562. *
  170563. * The coefficient controller will deliver data to us one iMCU row at a time;
  170564. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170565. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170566. * to one row of MCUs when the image is fully interleaved.) Note that the
  170567. * number of sample rows varies across components, but the number of row
  170568. * groups does not. Some garbage sample rows may be included in the last iMCU
  170569. * row at the bottom of the image.
  170570. *
  170571. * Depending on the vertical scaling algorithm used, the upsampler may need
  170572. * access to the sample row(s) above and below its current input row group.
  170573. * The upsampler is required to set need_context_rows TRUE at global selection
  170574. * time if so. When need_context_rows is FALSE, this controller can simply
  170575. * obtain one iMCU row at a time from the coefficient controller and dole it
  170576. * out as row groups to the postprocessor.
  170577. *
  170578. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170579. * passed to postprocessing contains at least one row group's worth of samples
  170580. * above and below the row group(s) being processed. Note that the context
  170581. * rows "above" the first passed row group appear at negative row offsets in
  170582. * the passed buffer. At the top and bottom of the image, the required
  170583. * context rows are manufactured by duplicating the first or last real sample
  170584. * row; this avoids having special cases in the upsampling inner loops.
  170585. *
  170586. * The amount of context is fixed at one row group just because that's a
  170587. * convenient number for this controller to work with. The existing
  170588. * upsamplers really only need one sample row of context. An upsampler
  170589. * supporting arbitrary output rescaling might wish for more than one row
  170590. * group of context when shrinking the image; tough, we don't handle that.
  170591. * (This is justified by the assumption that downsizing will be handled mostly
  170592. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170593. * the upsample step needn't be much less than one.)
  170594. *
  170595. * To provide the desired context, we have to retain the last two row groups
  170596. * of one iMCU row while reading in the next iMCU row. (The last row group
  170597. * can't be processed until we have another row group for its below-context,
  170598. * and so we have to save the next-to-last group too for its above-context.)
  170599. * We could do this most simply by copying data around in our buffer, but
  170600. * that'd be very slow. We can avoid copying any data by creating a rather
  170601. * strange pointer structure. Here's how it works. We allocate a workspace
  170602. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170603. * of row groups per iMCU row). We create two sets of redundant pointers to
  170604. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170605. * pointer lists look like this:
  170606. * M+1 M-1
  170607. * master pointer --> 0 master pointer --> 0
  170608. * 1 1
  170609. * ... ...
  170610. * M-3 M-3
  170611. * M-2 M
  170612. * M-1 M+1
  170613. * M M-2
  170614. * M+1 M-1
  170615. * 0 0
  170616. * We read alternate iMCU rows using each master pointer; thus the last two
  170617. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170618. * The pointer lists are set up so that the required context rows appear to
  170619. * be adjacent to the proper places when we pass the pointer lists to the
  170620. * upsampler.
  170621. *
  170622. * The above pictures describe the normal state of the pointer lists.
  170623. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170624. * the first or last sample row as necessary (this is cheaper than copying
  170625. * sample rows around).
  170626. *
  170627. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170628. * situation each iMCU row provides only one row group so the buffering logic
  170629. * must be different (eg, we must read two iMCU rows before we can emit the
  170630. * first row group). For now, we simply do not support providing context
  170631. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170632. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170633. * want it quick and dirty, so a context-free upsampler is sufficient.
  170634. */
  170635. /* Private buffer controller object */
  170636. typedef struct {
  170637. struct jpeg_d_main_controller pub; /* public fields */
  170638. /* Pointer to allocated workspace (M or M+2 row groups). */
  170639. JSAMPARRAY buffer[MAX_COMPONENTS];
  170640. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170641. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170642. /* Remaining fields are only used in the context case. */
  170643. /* These are the master pointers to the funny-order pointer lists. */
  170644. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170645. int whichptr; /* indicates which pointer set is now in use */
  170646. int context_state; /* process_data state machine status */
  170647. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170648. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170649. } my_main_controller4;
  170650. typedef my_main_controller4 * my_main_ptr4;
  170651. /* context_state values: */
  170652. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170653. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170654. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170655. /* Forward declarations */
  170656. METHODDEF(void) process_data_simple_main2
  170657. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170658. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170659. METHODDEF(void) process_data_context_main
  170660. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170661. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170662. #ifdef QUANT_2PASS_SUPPORTED
  170663. METHODDEF(void) process_data_crank_post
  170664. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170665. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170666. #endif
  170667. LOCAL(void)
  170668. alloc_funny_pointers (j_decompress_ptr cinfo)
  170669. /* Allocate space for the funny pointer lists.
  170670. * This is done only once, not once per pass.
  170671. */
  170672. {
  170673. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170674. int ci, rgroup;
  170675. int M = cinfo->min_DCT_scaled_size;
  170676. jpeg_component_info *compptr;
  170677. JSAMPARRAY xbuf;
  170678. /* Get top-level space for component array pointers.
  170679. * We alloc both arrays with one call to save a few cycles.
  170680. */
  170681. main_->xbuffer[0] = (JSAMPIMAGE)
  170682. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170683. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170684. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170685. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170686. ci++, compptr++) {
  170687. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170688. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170689. /* Get space for pointer lists --- M+4 row groups in each list.
  170690. * We alloc both pointer lists with one call to save a few cycles.
  170691. */
  170692. xbuf = (JSAMPARRAY)
  170693. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170694. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170695. xbuf += rgroup; /* want one row group at negative offsets */
  170696. main_->xbuffer[0][ci] = xbuf;
  170697. xbuf += rgroup * (M + 4);
  170698. main_->xbuffer[1][ci] = xbuf;
  170699. }
  170700. }
  170701. LOCAL(void)
  170702. make_funny_pointers (j_decompress_ptr cinfo)
  170703. /* Create the funny pointer lists discussed in the comments above.
  170704. * The actual workspace is already allocated (in main->buffer),
  170705. * and the space for the pointer lists is allocated too.
  170706. * This routine just fills in the curiously ordered lists.
  170707. * This will be repeated at the beginning of each pass.
  170708. */
  170709. {
  170710. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170711. int ci, i, rgroup;
  170712. int M = cinfo->min_DCT_scaled_size;
  170713. jpeg_component_info *compptr;
  170714. JSAMPARRAY buf, xbuf0, xbuf1;
  170715. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170716. ci++, compptr++) {
  170717. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170718. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170719. xbuf0 = main_->xbuffer[0][ci];
  170720. xbuf1 = main_->xbuffer[1][ci];
  170721. /* First copy the workspace pointers as-is */
  170722. buf = main_->buffer[ci];
  170723. for (i = 0; i < rgroup * (M + 2); i++) {
  170724. xbuf0[i] = xbuf1[i] = buf[i];
  170725. }
  170726. /* In the second list, put the last four row groups in swapped order */
  170727. for (i = 0; i < rgroup * 2; i++) {
  170728. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170729. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170730. }
  170731. /* The wraparound pointers at top and bottom will be filled later
  170732. * (see set_wraparound_pointers, below). Initially we want the "above"
  170733. * pointers to duplicate the first actual data line. This only needs
  170734. * to happen in xbuffer[0].
  170735. */
  170736. for (i = 0; i < rgroup; i++) {
  170737. xbuf0[i - rgroup] = xbuf0[0];
  170738. }
  170739. }
  170740. }
  170741. LOCAL(void)
  170742. set_wraparound_pointers (j_decompress_ptr cinfo)
  170743. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170744. * This changes the pointer list state from top-of-image to the normal state.
  170745. */
  170746. {
  170747. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170748. int ci, i, rgroup;
  170749. int M = cinfo->min_DCT_scaled_size;
  170750. jpeg_component_info *compptr;
  170751. JSAMPARRAY xbuf0, xbuf1;
  170752. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170753. ci++, compptr++) {
  170754. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170755. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170756. xbuf0 = main_->xbuffer[0][ci];
  170757. xbuf1 = main_->xbuffer[1][ci];
  170758. for (i = 0; i < rgroup; i++) {
  170759. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170760. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170761. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170762. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170763. }
  170764. }
  170765. }
  170766. LOCAL(void)
  170767. set_bottom_pointers (j_decompress_ptr cinfo)
  170768. /* Change the pointer lists to duplicate the last sample row at the bottom
  170769. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170770. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170771. */
  170772. {
  170773. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170774. int ci, i, rgroup, iMCUheight, rows_left;
  170775. jpeg_component_info *compptr;
  170776. JSAMPARRAY xbuf;
  170777. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170778. ci++, compptr++) {
  170779. /* Count sample rows in one iMCU row and in one row group */
  170780. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170781. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170782. /* Count nondummy sample rows remaining for this component */
  170783. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170784. if (rows_left == 0) rows_left = iMCUheight;
  170785. /* Count nondummy row groups. Should get same answer for each component,
  170786. * so we need only do it once.
  170787. */
  170788. if (ci == 0) {
  170789. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170790. }
  170791. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170792. * last partial rowgroup and ensures at least one full rowgroup of context.
  170793. */
  170794. xbuf = main_->xbuffer[main_->whichptr][ci];
  170795. for (i = 0; i < rgroup * 2; i++) {
  170796. xbuf[rows_left + i] = xbuf[rows_left-1];
  170797. }
  170798. }
  170799. }
  170800. /*
  170801. * Initialize for a processing pass.
  170802. */
  170803. METHODDEF(void)
  170804. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170805. {
  170806. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170807. switch (pass_mode) {
  170808. case JBUF_PASS_THRU:
  170809. if (cinfo->upsample->need_context_rows) {
  170810. main_->pub.process_data = process_data_context_main;
  170811. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170812. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170813. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170814. main_->iMCU_row_ctr = 0;
  170815. } else {
  170816. /* Simple case with no context needed */
  170817. main_->pub.process_data = process_data_simple_main2;
  170818. }
  170819. main_->buffer_full = FALSE; /* Mark buffer empty */
  170820. main_->rowgroup_ctr = 0;
  170821. break;
  170822. #ifdef QUANT_2PASS_SUPPORTED
  170823. case JBUF_CRANK_DEST:
  170824. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170825. main_->pub.process_data = process_data_crank_post;
  170826. break;
  170827. #endif
  170828. default:
  170829. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170830. break;
  170831. }
  170832. }
  170833. /*
  170834. * Process some data.
  170835. * This handles the simple case where no context is required.
  170836. */
  170837. METHODDEF(void)
  170838. process_data_simple_main2 (j_decompress_ptr cinfo,
  170839. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170840. JDIMENSION out_rows_avail)
  170841. {
  170842. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170843. JDIMENSION rowgroups_avail;
  170844. /* Read input data if we haven't filled the main buffer yet */
  170845. if (! main_->buffer_full) {
  170846. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170847. return; /* suspension forced, can do nothing more */
  170848. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170849. }
  170850. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170851. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170852. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170853. * to the postprocessor. The postprocessor has to check for bottom
  170854. * of image anyway (at row resolution), so no point in us doing it too.
  170855. */
  170856. /* Feed the postprocessor */
  170857. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170858. &main_->rowgroup_ctr, rowgroups_avail,
  170859. output_buf, out_row_ctr, out_rows_avail);
  170860. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170861. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170862. main_->buffer_full = FALSE;
  170863. main_->rowgroup_ctr = 0;
  170864. }
  170865. }
  170866. /*
  170867. * Process some data.
  170868. * This handles the case where context rows must be provided.
  170869. */
  170870. METHODDEF(void)
  170871. process_data_context_main (j_decompress_ptr cinfo,
  170872. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170873. JDIMENSION out_rows_avail)
  170874. {
  170875. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170876. /* Read input data if we haven't filled the main buffer yet */
  170877. if (! main_->buffer_full) {
  170878. if (! (*cinfo->coef->decompress_data) (cinfo,
  170879. main_->xbuffer[main_->whichptr]))
  170880. return; /* suspension forced, can do nothing more */
  170881. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170882. main_->iMCU_row_ctr++; /* count rows received */
  170883. }
  170884. /* Postprocessor typically will not swallow all the input data it is handed
  170885. * in one call (due to filling the output buffer first). Must be prepared
  170886. * to exit and restart. This switch lets us keep track of how far we got.
  170887. * Note that each case falls through to the next on successful completion.
  170888. */
  170889. switch (main_->context_state) {
  170890. case CTX_POSTPONED_ROW:
  170891. /* Call postprocessor using previously set pointers for postponed row */
  170892. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170893. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170894. output_buf, out_row_ctr, out_rows_avail);
  170895. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170896. return; /* Need to suspend */
  170897. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170898. if (*out_row_ctr >= out_rows_avail)
  170899. return; /* Postprocessor exactly filled output buf */
  170900. /*FALLTHROUGH*/
  170901. case CTX_PREPARE_FOR_IMCU:
  170902. /* Prepare to process first M-1 row groups of this iMCU row */
  170903. main_->rowgroup_ctr = 0;
  170904. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170905. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170906. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170907. */
  170908. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170909. set_bottom_pointers(cinfo);
  170910. main_->context_state = CTX_PROCESS_IMCU;
  170911. /*FALLTHROUGH*/
  170912. case CTX_PROCESS_IMCU:
  170913. /* Call postprocessor using previously set pointers */
  170914. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170915. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170916. output_buf, out_row_ctr, out_rows_avail);
  170917. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170918. return; /* Need to suspend */
  170919. /* After the first iMCU, change wraparound pointers to normal state */
  170920. if (main_->iMCU_row_ctr == 1)
  170921. set_wraparound_pointers(cinfo);
  170922. /* Prepare to load new iMCU row using other xbuffer list */
  170923. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170924. main_->buffer_full = FALSE;
  170925. /* Still need to process last row group of this iMCU row, */
  170926. /* which is saved at index M+1 of the other xbuffer */
  170927. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170928. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170929. main_->context_state = CTX_POSTPONED_ROW;
  170930. }
  170931. }
  170932. /*
  170933. * Process some data.
  170934. * Final pass of two-pass quantization: just call the postprocessor.
  170935. * Source data will be the postprocessor controller's internal buffer.
  170936. */
  170937. #ifdef QUANT_2PASS_SUPPORTED
  170938. METHODDEF(void)
  170939. process_data_crank_post (j_decompress_ptr cinfo,
  170940. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170941. JDIMENSION out_rows_avail)
  170942. {
  170943. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170944. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170945. output_buf, out_row_ctr, out_rows_avail);
  170946. }
  170947. #endif /* QUANT_2PASS_SUPPORTED */
  170948. /*
  170949. * Initialize main buffer controller.
  170950. */
  170951. GLOBAL(void)
  170952. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170953. {
  170954. my_main_ptr4 main_;
  170955. int ci, rgroup, ngroups;
  170956. jpeg_component_info *compptr;
  170957. main_ = (my_main_ptr4)
  170958. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170959. SIZEOF(my_main_controller4));
  170960. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170961. main_->pub.start_pass = start_pass_main2;
  170962. if (need_full_buffer) /* shouldn't happen */
  170963. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170964. /* Allocate the workspace.
  170965. * ngroups is the number of row groups we need.
  170966. */
  170967. if (cinfo->upsample->need_context_rows) {
  170968. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170969. ERREXIT(cinfo, JERR_NOTIMPL);
  170970. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170971. ngroups = cinfo->min_DCT_scaled_size + 2;
  170972. } else {
  170973. ngroups = cinfo->min_DCT_scaled_size;
  170974. }
  170975. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170976. ci++, compptr++) {
  170977. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170978. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170979. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170980. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170981. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170982. (JDIMENSION) (rgroup * ngroups));
  170983. }
  170984. }
  170985. /*** End of inlined file: jdmainct.c ***/
  170986. /*** Start of inlined file: jdmarker.c ***/
  170987. #define JPEG_INTERNALS
  170988. /* Private state */
  170989. typedef struct {
  170990. struct jpeg_marker_reader pub; /* public fields */
  170991. /* Application-overridable marker processing methods */
  170992. jpeg_marker_parser_method process_COM;
  170993. jpeg_marker_parser_method process_APPn[16];
  170994. /* Limit on marker data length to save for each marker type */
  170995. unsigned int length_limit_COM;
  170996. unsigned int length_limit_APPn[16];
  170997. /* Status of COM/APPn marker saving */
  170998. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170999. unsigned int bytes_read; /* data bytes read so far in marker */
  171000. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171001. } my_marker_reader;
  171002. typedef my_marker_reader * my_marker_ptr2;
  171003. /*
  171004. * Macros for fetching data from the data source module.
  171005. *
  171006. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171007. * the current restart point; we update them only when we have reached a
  171008. * suitable place to restart if a suspension occurs.
  171009. */
  171010. /* Declare and initialize local copies of input pointer/count */
  171011. #define INPUT_VARS(cinfo) \
  171012. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171013. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171014. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171015. /* Unload the local copies --- do this only at a restart boundary */
  171016. #define INPUT_SYNC(cinfo) \
  171017. ( datasrc->next_input_byte = next_input_byte, \
  171018. datasrc->bytes_in_buffer = bytes_in_buffer )
  171019. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171020. #define INPUT_RELOAD(cinfo) \
  171021. ( next_input_byte = datasrc->next_input_byte, \
  171022. bytes_in_buffer = datasrc->bytes_in_buffer )
  171023. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171024. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171025. * but we must reload the local copies after a successful fill.
  171026. */
  171027. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171028. if (bytes_in_buffer == 0) { \
  171029. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171030. { action; } \
  171031. INPUT_RELOAD(cinfo); \
  171032. }
  171033. /* Read a byte into variable V.
  171034. * If must suspend, take the specified action (typically "return FALSE").
  171035. */
  171036. #define INPUT_BYTE(cinfo,V,action) \
  171037. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171038. bytes_in_buffer--; \
  171039. V = GETJOCTET(*next_input_byte++); )
  171040. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171041. * V should be declared unsigned int or perhaps INT32.
  171042. */
  171043. #define INPUT_2BYTES(cinfo,V,action) \
  171044. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171045. bytes_in_buffer--; \
  171046. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171047. MAKE_BYTE_AVAIL(cinfo,action); \
  171048. bytes_in_buffer--; \
  171049. V += GETJOCTET(*next_input_byte++); )
  171050. /*
  171051. * Routines to process JPEG markers.
  171052. *
  171053. * Entry condition: JPEG marker itself has been read and its code saved
  171054. * in cinfo->unread_marker; input restart point is just after the marker.
  171055. *
  171056. * Exit: if return TRUE, have read and processed any parameters, and have
  171057. * updated the restart point to point after the parameters.
  171058. * If return FALSE, was forced to suspend before reaching end of
  171059. * marker parameters; restart point has not been moved. Same routine
  171060. * will be called again after application supplies more input data.
  171061. *
  171062. * This approach to suspension assumes that all of a marker's parameters
  171063. * can fit into a single input bufferload. This should hold for "normal"
  171064. * markers. Some COM/APPn markers might have large parameter segments
  171065. * that might not fit. If we are simply dropping such a marker, we use
  171066. * skip_input_data to get past it, and thereby put the problem on the
  171067. * source manager's shoulders. If we are saving the marker's contents
  171068. * into memory, we use a slightly different convention: when forced to
  171069. * suspend, the marker processor updates the restart point to the end of
  171070. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171071. * On resumption, cinfo->unread_marker still contains the marker code,
  171072. * but the data source will point to the next chunk of marker data.
  171073. * The marker processor must retain internal state to deal with this.
  171074. *
  171075. * Note that we don't bother to avoid duplicate trace messages if a
  171076. * suspension occurs within marker parameters. Other side effects
  171077. * require more care.
  171078. */
  171079. LOCAL(boolean)
  171080. get_soi (j_decompress_ptr cinfo)
  171081. /* Process an SOI marker */
  171082. {
  171083. int i;
  171084. TRACEMS(cinfo, 1, JTRC_SOI);
  171085. if (cinfo->marker->saw_SOI)
  171086. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171087. /* Reset all parameters that are defined to be reset by SOI */
  171088. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171089. cinfo->arith_dc_L[i] = 0;
  171090. cinfo->arith_dc_U[i] = 1;
  171091. cinfo->arith_ac_K[i] = 5;
  171092. }
  171093. cinfo->restart_interval = 0;
  171094. /* Set initial assumptions for colorspace etc */
  171095. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171096. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171097. cinfo->saw_JFIF_marker = FALSE;
  171098. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171099. cinfo->JFIF_minor_version = 1;
  171100. cinfo->density_unit = 0;
  171101. cinfo->X_density = 1;
  171102. cinfo->Y_density = 1;
  171103. cinfo->saw_Adobe_marker = FALSE;
  171104. cinfo->Adobe_transform = 0;
  171105. cinfo->marker->saw_SOI = TRUE;
  171106. return TRUE;
  171107. }
  171108. LOCAL(boolean)
  171109. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171110. /* Process a SOFn marker */
  171111. {
  171112. INT32 length;
  171113. int c, ci;
  171114. jpeg_component_info * compptr;
  171115. INPUT_VARS(cinfo);
  171116. cinfo->progressive_mode = is_prog;
  171117. cinfo->arith_code = is_arith;
  171118. INPUT_2BYTES(cinfo, length, return FALSE);
  171119. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171120. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171121. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171122. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171123. length -= 8;
  171124. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171125. (int) cinfo->image_width, (int) cinfo->image_height,
  171126. cinfo->num_components);
  171127. if (cinfo->marker->saw_SOF)
  171128. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171129. /* We don't support files in which the image height is initially specified */
  171130. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171131. /* might as well have a general sanity check. */
  171132. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171133. || cinfo->num_components <= 0)
  171134. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171135. if (length != (cinfo->num_components * 3))
  171136. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171137. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171138. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171139. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171140. cinfo->num_components * SIZEOF(jpeg_component_info));
  171141. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171142. ci++, compptr++) {
  171143. compptr->component_index = ci;
  171144. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171145. INPUT_BYTE(cinfo, c, return FALSE);
  171146. compptr->h_samp_factor = (c >> 4) & 15;
  171147. compptr->v_samp_factor = (c ) & 15;
  171148. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171149. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171150. compptr->component_id, compptr->h_samp_factor,
  171151. compptr->v_samp_factor, compptr->quant_tbl_no);
  171152. }
  171153. cinfo->marker->saw_SOF = TRUE;
  171154. INPUT_SYNC(cinfo);
  171155. return TRUE;
  171156. }
  171157. LOCAL(boolean)
  171158. get_sos (j_decompress_ptr cinfo)
  171159. /* Process a SOS marker */
  171160. {
  171161. INT32 length;
  171162. int i, ci, n, c, cc;
  171163. jpeg_component_info * compptr;
  171164. INPUT_VARS(cinfo);
  171165. if (! cinfo->marker->saw_SOF)
  171166. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171167. INPUT_2BYTES(cinfo, length, return FALSE);
  171168. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171169. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171170. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171171. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171172. cinfo->comps_in_scan = n;
  171173. /* Collect the component-spec parameters */
  171174. for (i = 0; i < n; i++) {
  171175. INPUT_BYTE(cinfo, cc, return FALSE);
  171176. INPUT_BYTE(cinfo, c, return FALSE);
  171177. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171178. ci++, compptr++) {
  171179. if (cc == compptr->component_id)
  171180. goto id_found;
  171181. }
  171182. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171183. id_found:
  171184. cinfo->cur_comp_info[i] = compptr;
  171185. compptr->dc_tbl_no = (c >> 4) & 15;
  171186. compptr->ac_tbl_no = (c ) & 15;
  171187. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171188. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171189. }
  171190. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171191. INPUT_BYTE(cinfo, c, return FALSE);
  171192. cinfo->Ss = c;
  171193. INPUT_BYTE(cinfo, c, return FALSE);
  171194. cinfo->Se = c;
  171195. INPUT_BYTE(cinfo, c, return FALSE);
  171196. cinfo->Ah = (c >> 4) & 15;
  171197. cinfo->Al = (c ) & 15;
  171198. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171199. cinfo->Ah, cinfo->Al);
  171200. /* Prepare to scan data & restart markers */
  171201. cinfo->marker->next_restart_num = 0;
  171202. /* Count another SOS marker */
  171203. cinfo->input_scan_number++;
  171204. INPUT_SYNC(cinfo);
  171205. return TRUE;
  171206. }
  171207. #ifdef D_ARITH_CODING_SUPPORTED
  171208. LOCAL(boolean)
  171209. get_dac (j_decompress_ptr cinfo)
  171210. /* Process a DAC marker */
  171211. {
  171212. INT32 length;
  171213. int index, val;
  171214. INPUT_VARS(cinfo);
  171215. INPUT_2BYTES(cinfo, length, return FALSE);
  171216. length -= 2;
  171217. while (length > 0) {
  171218. INPUT_BYTE(cinfo, index, return FALSE);
  171219. INPUT_BYTE(cinfo, val, return FALSE);
  171220. length -= 2;
  171221. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171222. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171223. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171224. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171225. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171226. } else { /* define DC table */
  171227. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171228. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171229. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171230. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171231. }
  171232. }
  171233. if (length != 0)
  171234. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171235. INPUT_SYNC(cinfo);
  171236. return TRUE;
  171237. }
  171238. #else /* ! D_ARITH_CODING_SUPPORTED */
  171239. #define get_dac(cinfo) skip_variable(cinfo)
  171240. #endif /* D_ARITH_CODING_SUPPORTED */
  171241. LOCAL(boolean)
  171242. get_dht (j_decompress_ptr cinfo)
  171243. /* Process a DHT marker */
  171244. {
  171245. INT32 length;
  171246. UINT8 bits[17];
  171247. UINT8 huffval[256];
  171248. int i, index, count;
  171249. JHUFF_TBL **htblptr;
  171250. INPUT_VARS(cinfo);
  171251. INPUT_2BYTES(cinfo, length, return FALSE);
  171252. length -= 2;
  171253. while (length > 16) {
  171254. INPUT_BYTE(cinfo, index, return FALSE);
  171255. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171256. bits[0] = 0;
  171257. count = 0;
  171258. for (i = 1; i <= 16; i++) {
  171259. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171260. count += bits[i];
  171261. }
  171262. length -= 1 + 16;
  171263. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171264. bits[1], bits[2], bits[3], bits[4],
  171265. bits[5], bits[6], bits[7], bits[8]);
  171266. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171267. bits[9], bits[10], bits[11], bits[12],
  171268. bits[13], bits[14], bits[15], bits[16]);
  171269. /* Here we just do minimal validation of the counts to avoid walking
  171270. * off the end of our table space. jdhuff.c will check more carefully.
  171271. */
  171272. if (count > 256 || ((INT32) count) > length)
  171273. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171274. for (i = 0; i < count; i++)
  171275. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171276. length -= count;
  171277. if (index & 0x10) { /* AC table definition */
  171278. index -= 0x10;
  171279. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171280. } else { /* DC table definition */
  171281. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171282. }
  171283. if (index < 0 || index >= NUM_HUFF_TBLS)
  171284. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171285. if (*htblptr == NULL)
  171286. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171287. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171288. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171289. }
  171290. if (length != 0)
  171291. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171292. INPUT_SYNC(cinfo);
  171293. return TRUE;
  171294. }
  171295. LOCAL(boolean)
  171296. get_dqt (j_decompress_ptr cinfo)
  171297. /* Process a DQT marker */
  171298. {
  171299. INT32 length;
  171300. int n, i, prec;
  171301. unsigned int tmp;
  171302. JQUANT_TBL *quant_ptr;
  171303. INPUT_VARS(cinfo);
  171304. INPUT_2BYTES(cinfo, length, return FALSE);
  171305. length -= 2;
  171306. while (length > 0) {
  171307. INPUT_BYTE(cinfo, n, return FALSE);
  171308. prec = n >> 4;
  171309. n &= 0x0F;
  171310. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171311. if (n >= NUM_QUANT_TBLS)
  171312. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171313. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171314. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171315. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171316. for (i = 0; i < DCTSIZE2; i++) {
  171317. if (prec)
  171318. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171319. else
  171320. INPUT_BYTE(cinfo, tmp, return FALSE);
  171321. /* We convert the zigzag-order table to natural array order. */
  171322. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171323. }
  171324. if (cinfo->err->trace_level >= 2) {
  171325. for (i = 0; i < DCTSIZE2; i += 8) {
  171326. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171327. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171328. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171329. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171330. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171331. }
  171332. }
  171333. length -= DCTSIZE2+1;
  171334. if (prec) length -= DCTSIZE2;
  171335. }
  171336. if (length != 0)
  171337. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171338. INPUT_SYNC(cinfo);
  171339. return TRUE;
  171340. }
  171341. LOCAL(boolean)
  171342. get_dri (j_decompress_ptr cinfo)
  171343. /* Process a DRI marker */
  171344. {
  171345. INT32 length;
  171346. unsigned int tmp;
  171347. INPUT_VARS(cinfo);
  171348. INPUT_2BYTES(cinfo, length, return FALSE);
  171349. if (length != 4)
  171350. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171351. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171352. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171353. cinfo->restart_interval = tmp;
  171354. INPUT_SYNC(cinfo);
  171355. return TRUE;
  171356. }
  171357. /*
  171358. * Routines for processing APPn and COM markers.
  171359. * These are either saved in memory or discarded, per application request.
  171360. * APP0 and APP14 are specially checked to see if they are
  171361. * JFIF and Adobe markers, respectively.
  171362. */
  171363. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171364. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171365. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171366. LOCAL(void)
  171367. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171368. unsigned int datalen, INT32 remaining)
  171369. /* Examine first few bytes from an APP0.
  171370. * Take appropriate action if it is a JFIF marker.
  171371. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171372. */
  171373. {
  171374. INT32 totallen = (INT32) datalen + remaining;
  171375. if (datalen >= APP0_DATA_LEN &&
  171376. GETJOCTET(data[0]) == 0x4A &&
  171377. GETJOCTET(data[1]) == 0x46 &&
  171378. GETJOCTET(data[2]) == 0x49 &&
  171379. GETJOCTET(data[3]) == 0x46 &&
  171380. GETJOCTET(data[4]) == 0) {
  171381. /* Found JFIF APP0 marker: save info */
  171382. cinfo->saw_JFIF_marker = TRUE;
  171383. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171384. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171385. cinfo->density_unit = GETJOCTET(data[7]);
  171386. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171387. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171388. /* Check version.
  171389. * Major version must be 1, anything else signals an incompatible change.
  171390. * (We used to treat this as an error, but now it's a nonfatal warning,
  171391. * because some bozo at Hijaak couldn't read the spec.)
  171392. * Minor version should be 0..2, but process anyway if newer.
  171393. */
  171394. if (cinfo->JFIF_major_version != 1)
  171395. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171396. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171397. /* Generate trace messages */
  171398. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171399. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171400. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171401. /* Validate thumbnail dimensions and issue appropriate messages */
  171402. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171403. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171404. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171405. totallen -= APP0_DATA_LEN;
  171406. if (totallen !=
  171407. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171408. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171409. } else if (datalen >= 6 &&
  171410. GETJOCTET(data[0]) == 0x4A &&
  171411. GETJOCTET(data[1]) == 0x46 &&
  171412. GETJOCTET(data[2]) == 0x58 &&
  171413. GETJOCTET(data[3]) == 0x58 &&
  171414. GETJOCTET(data[4]) == 0) {
  171415. /* Found JFIF "JFXX" extension APP0 marker */
  171416. /* The library doesn't actually do anything with these,
  171417. * but we try to produce a helpful trace message.
  171418. */
  171419. switch (GETJOCTET(data[5])) {
  171420. case 0x10:
  171421. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171422. break;
  171423. case 0x11:
  171424. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171425. break;
  171426. case 0x13:
  171427. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171428. break;
  171429. default:
  171430. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171431. GETJOCTET(data[5]), (int) totallen);
  171432. break;
  171433. }
  171434. } else {
  171435. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171436. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171437. }
  171438. }
  171439. LOCAL(void)
  171440. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171441. unsigned int datalen, INT32 remaining)
  171442. /* Examine first few bytes from an APP14.
  171443. * Take appropriate action if it is an Adobe marker.
  171444. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171445. */
  171446. {
  171447. unsigned int version, flags0, flags1, transform;
  171448. if (datalen >= APP14_DATA_LEN &&
  171449. GETJOCTET(data[0]) == 0x41 &&
  171450. GETJOCTET(data[1]) == 0x64 &&
  171451. GETJOCTET(data[2]) == 0x6F &&
  171452. GETJOCTET(data[3]) == 0x62 &&
  171453. GETJOCTET(data[4]) == 0x65) {
  171454. /* Found Adobe APP14 marker */
  171455. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171456. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171457. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171458. transform = GETJOCTET(data[11]);
  171459. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171460. cinfo->saw_Adobe_marker = TRUE;
  171461. cinfo->Adobe_transform = (UINT8) transform;
  171462. } else {
  171463. /* Start of APP14 does not match "Adobe", or too short */
  171464. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171465. }
  171466. }
  171467. METHODDEF(boolean)
  171468. get_interesting_appn (j_decompress_ptr cinfo)
  171469. /* Process an APP0 or APP14 marker without saving it */
  171470. {
  171471. INT32 length;
  171472. JOCTET b[APPN_DATA_LEN];
  171473. unsigned int i, numtoread;
  171474. INPUT_VARS(cinfo);
  171475. INPUT_2BYTES(cinfo, length, return FALSE);
  171476. length -= 2;
  171477. /* get the interesting part of the marker data */
  171478. if (length >= APPN_DATA_LEN)
  171479. numtoread = APPN_DATA_LEN;
  171480. else if (length > 0)
  171481. numtoread = (unsigned int) length;
  171482. else
  171483. numtoread = 0;
  171484. for (i = 0; i < numtoread; i++)
  171485. INPUT_BYTE(cinfo, b[i], return FALSE);
  171486. length -= numtoread;
  171487. /* process it */
  171488. switch (cinfo->unread_marker) {
  171489. case M_APP0:
  171490. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171491. break;
  171492. case M_APP14:
  171493. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171494. break;
  171495. default:
  171496. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171497. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171498. break;
  171499. }
  171500. /* skip any remaining data -- could be lots */
  171501. INPUT_SYNC(cinfo);
  171502. if (length > 0)
  171503. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171504. return TRUE;
  171505. }
  171506. #ifdef SAVE_MARKERS_SUPPORTED
  171507. METHODDEF(boolean)
  171508. save_marker (j_decompress_ptr cinfo)
  171509. /* Save an APPn or COM marker into the marker list */
  171510. {
  171511. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171512. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171513. unsigned int bytes_read, data_length;
  171514. JOCTET FAR * data;
  171515. INT32 length = 0;
  171516. INPUT_VARS(cinfo);
  171517. if (cur_marker == NULL) {
  171518. /* begin reading a marker */
  171519. INPUT_2BYTES(cinfo, length, return FALSE);
  171520. length -= 2;
  171521. if (length >= 0) { /* watch out for bogus length word */
  171522. /* figure out how much we want to save */
  171523. unsigned int limit;
  171524. if (cinfo->unread_marker == (int) M_COM)
  171525. limit = marker->length_limit_COM;
  171526. else
  171527. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171528. if ((unsigned int) length < limit)
  171529. limit = (unsigned int) length;
  171530. /* allocate and initialize the marker item */
  171531. cur_marker = (jpeg_saved_marker_ptr)
  171532. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171533. SIZEOF(struct jpeg_marker_struct) + limit);
  171534. cur_marker->next = NULL;
  171535. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171536. cur_marker->original_length = (unsigned int) length;
  171537. cur_marker->data_length = limit;
  171538. /* data area is just beyond the jpeg_marker_struct */
  171539. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171540. marker->cur_marker = cur_marker;
  171541. marker->bytes_read = 0;
  171542. bytes_read = 0;
  171543. data_length = limit;
  171544. } else {
  171545. /* deal with bogus length word */
  171546. bytes_read = data_length = 0;
  171547. data = NULL;
  171548. }
  171549. } else {
  171550. /* resume reading a marker */
  171551. bytes_read = marker->bytes_read;
  171552. data_length = cur_marker->data_length;
  171553. data = cur_marker->data + bytes_read;
  171554. }
  171555. while (bytes_read < data_length) {
  171556. INPUT_SYNC(cinfo); /* move the restart point to here */
  171557. marker->bytes_read = bytes_read;
  171558. /* If there's not at least one byte in buffer, suspend */
  171559. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171560. /* Copy bytes with reasonable rapidity */
  171561. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171562. *data++ = *next_input_byte++;
  171563. bytes_in_buffer--;
  171564. bytes_read++;
  171565. }
  171566. }
  171567. /* Done reading what we want to read */
  171568. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171569. /* Add new marker to end of list */
  171570. if (cinfo->marker_list == NULL) {
  171571. cinfo->marker_list = cur_marker;
  171572. } else {
  171573. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171574. while (prev->next != NULL)
  171575. prev = prev->next;
  171576. prev->next = cur_marker;
  171577. }
  171578. /* Reset pointer & calc remaining data length */
  171579. data = cur_marker->data;
  171580. length = cur_marker->original_length - data_length;
  171581. }
  171582. /* Reset to initial state for next marker */
  171583. marker->cur_marker = NULL;
  171584. /* Process the marker if interesting; else just make a generic trace msg */
  171585. switch (cinfo->unread_marker) {
  171586. case M_APP0:
  171587. examine_app0(cinfo, data, data_length, length);
  171588. break;
  171589. case M_APP14:
  171590. examine_app14(cinfo, data, data_length, length);
  171591. break;
  171592. default:
  171593. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171594. (int) (data_length + length));
  171595. break;
  171596. }
  171597. /* skip any remaining data -- could be lots */
  171598. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171599. if (length > 0)
  171600. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171601. return TRUE;
  171602. }
  171603. #endif /* SAVE_MARKERS_SUPPORTED */
  171604. METHODDEF(boolean)
  171605. skip_variable (j_decompress_ptr cinfo)
  171606. /* Skip over an unknown or uninteresting variable-length marker */
  171607. {
  171608. INT32 length;
  171609. INPUT_VARS(cinfo);
  171610. INPUT_2BYTES(cinfo, length, return FALSE);
  171611. length -= 2;
  171612. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171613. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171614. if (length > 0)
  171615. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171616. return TRUE;
  171617. }
  171618. /*
  171619. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171620. * Returns FALSE if had to suspend before reaching a marker;
  171621. * in that case cinfo->unread_marker is unchanged.
  171622. *
  171623. * Note that the result might not be a valid marker code,
  171624. * but it will never be 0 or FF.
  171625. */
  171626. LOCAL(boolean)
  171627. next_marker (j_decompress_ptr cinfo)
  171628. {
  171629. int c;
  171630. INPUT_VARS(cinfo);
  171631. for (;;) {
  171632. INPUT_BYTE(cinfo, c, return FALSE);
  171633. /* Skip any non-FF bytes.
  171634. * This may look a bit inefficient, but it will not occur in a valid file.
  171635. * We sync after each discarded byte so that a suspending data source
  171636. * can discard the byte from its buffer.
  171637. */
  171638. while (c != 0xFF) {
  171639. cinfo->marker->discarded_bytes++;
  171640. INPUT_SYNC(cinfo);
  171641. INPUT_BYTE(cinfo, c, return FALSE);
  171642. }
  171643. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171644. * pad bytes, so don't count them in discarded_bytes. We assume there
  171645. * will not be so many consecutive FF bytes as to overflow a suspending
  171646. * data source's input buffer.
  171647. */
  171648. do {
  171649. INPUT_BYTE(cinfo, c, return FALSE);
  171650. } while (c == 0xFF);
  171651. if (c != 0)
  171652. break; /* found a valid marker, exit loop */
  171653. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171654. * Discard it and loop back to try again.
  171655. */
  171656. cinfo->marker->discarded_bytes += 2;
  171657. INPUT_SYNC(cinfo);
  171658. }
  171659. if (cinfo->marker->discarded_bytes != 0) {
  171660. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171661. cinfo->marker->discarded_bytes = 0;
  171662. }
  171663. cinfo->unread_marker = c;
  171664. INPUT_SYNC(cinfo);
  171665. return TRUE;
  171666. }
  171667. LOCAL(boolean)
  171668. first_marker (j_decompress_ptr cinfo)
  171669. /* Like next_marker, but used to obtain the initial SOI marker. */
  171670. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171671. * we might well scan an entire input file before realizing it ain't JPEG.
  171672. * If an application wants to process non-JFIF files, it must seek to the
  171673. * SOI before calling the JPEG library.
  171674. */
  171675. {
  171676. int c, c2;
  171677. INPUT_VARS(cinfo);
  171678. INPUT_BYTE(cinfo, c, return FALSE);
  171679. INPUT_BYTE(cinfo, c2, return FALSE);
  171680. if (c != 0xFF || c2 != (int) M_SOI)
  171681. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171682. cinfo->unread_marker = c2;
  171683. INPUT_SYNC(cinfo);
  171684. return TRUE;
  171685. }
  171686. /*
  171687. * Read markers until SOS or EOI.
  171688. *
  171689. * Returns same codes as are defined for jpeg_consume_input:
  171690. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171691. */
  171692. METHODDEF(int)
  171693. read_markers (j_decompress_ptr cinfo)
  171694. {
  171695. /* Outer loop repeats once for each marker. */
  171696. for (;;) {
  171697. /* Collect the marker proper, unless we already did. */
  171698. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171699. if (cinfo->unread_marker == 0) {
  171700. if (! cinfo->marker->saw_SOI) {
  171701. if (! first_marker(cinfo))
  171702. return JPEG_SUSPENDED;
  171703. } else {
  171704. if (! next_marker(cinfo))
  171705. return JPEG_SUSPENDED;
  171706. }
  171707. }
  171708. /* At this point cinfo->unread_marker contains the marker code and the
  171709. * input point is just past the marker proper, but before any parameters.
  171710. * A suspension will cause us to return with this state still true.
  171711. */
  171712. switch (cinfo->unread_marker) {
  171713. case M_SOI:
  171714. if (! get_soi(cinfo))
  171715. return JPEG_SUSPENDED;
  171716. break;
  171717. case M_SOF0: /* Baseline */
  171718. case M_SOF1: /* Extended sequential, Huffman */
  171719. if (! get_sof(cinfo, FALSE, FALSE))
  171720. return JPEG_SUSPENDED;
  171721. break;
  171722. case M_SOF2: /* Progressive, Huffman */
  171723. if (! get_sof(cinfo, TRUE, FALSE))
  171724. return JPEG_SUSPENDED;
  171725. break;
  171726. case M_SOF9: /* Extended sequential, arithmetic */
  171727. if (! get_sof(cinfo, FALSE, TRUE))
  171728. return JPEG_SUSPENDED;
  171729. break;
  171730. case M_SOF10: /* Progressive, arithmetic */
  171731. if (! get_sof(cinfo, TRUE, TRUE))
  171732. return JPEG_SUSPENDED;
  171733. break;
  171734. /* Currently unsupported SOFn types */
  171735. case M_SOF3: /* Lossless, Huffman */
  171736. case M_SOF5: /* Differential sequential, Huffman */
  171737. case M_SOF6: /* Differential progressive, Huffman */
  171738. case M_SOF7: /* Differential lossless, Huffman */
  171739. case M_JPG: /* Reserved for JPEG extensions */
  171740. case M_SOF11: /* Lossless, arithmetic */
  171741. case M_SOF13: /* Differential sequential, arithmetic */
  171742. case M_SOF14: /* Differential progressive, arithmetic */
  171743. case M_SOF15: /* Differential lossless, arithmetic */
  171744. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171745. break;
  171746. case M_SOS:
  171747. if (! get_sos(cinfo))
  171748. return JPEG_SUSPENDED;
  171749. cinfo->unread_marker = 0; /* processed the marker */
  171750. return JPEG_REACHED_SOS;
  171751. case M_EOI:
  171752. TRACEMS(cinfo, 1, JTRC_EOI);
  171753. cinfo->unread_marker = 0; /* processed the marker */
  171754. return JPEG_REACHED_EOI;
  171755. case M_DAC:
  171756. if (! get_dac(cinfo))
  171757. return JPEG_SUSPENDED;
  171758. break;
  171759. case M_DHT:
  171760. if (! get_dht(cinfo))
  171761. return JPEG_SUSPENDED;
  171762. break;
  171763. case M_DQT:
  171764. if (! get_dqt(cinfo))
  171765. return JPEG_SUSPENDED;
  171766. break;
  171767. case M_DRI:
  171768. if (! get_dri(cinfo))
  171769. return JPEG_SUSPENDED;
  171770. break;
  171771. case M_APP0:
  171772. case M_APP1:
  171773. case M_APP2:
  171774. case M_APP3:
  171775. case M_APP4:
  171776. case M_APP5:
  171777. case M_APP6:
  171778. case M_APP7:
  171779. case M_APP8:
  171780. case M_APP9:
  171781. case M_APP10:
  171782. case M_APP11:
  171783. case M_APP12:
  171784. case M_APP13:
  171785. case M_APP14:
  171786. case M_APP15:
  171787. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171788. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171789. return JPEG_SUSPENDED;
  171790. break;
  171791. case M_COM:
  171792. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171793. return JPEG_SUSPENDED;
  171794. break;
  171795. case M_RST0: /* these are all parameterless */
  171796. case M_RST1:
  171797. case M_RST2:
  171798. case M_RST3:
  171799. case M_RST4:
  171800. case M_RST5:
  171801. case M_RST6:
  171802. case M_RST7:
  171803. case M_TEM:
  171804. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171805. break;
  171806. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171807. if (! skip_variable(cinfo))
  171808. return JPEG_SUSPENDED;
  171809. break;
  171810. default: /* must be DHP, EXP, JPGn, or RESn */
  171811. /* For now, we treat the reserved markers as fatal errors since they are
  171812. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171813. * Once the JPEG 3 version-number marker is well defined, this code
  171814. * ought to change!
  171815. */
  171816. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171817. break;
  171818. }
  171819. /* Successfully processed marker, so reset state variable */
  171820. cinfo->unread_marker = 0;
  171821. } /* end loop */
  171822. }
  171823. /*
  171824. * Read a restart marker, which is expected to appear next in the datastream;
  171825. * if the marker is not there, take appropriate recovery action.
  171826. * Returns FALSE if suspension is required.
  171827. *
  171828. * This is called by the entropy decoder after it has read an appropriate
  171829. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171830. * has already read a marker from the data source. Under normal conditions
  171831. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171832. * it holds a marker which the decoder will be unable to read past.
  171833. */
  171834. METHODDEF(boolean)
  171835. read_restart_marker (j_decompress_ptr cinfo)
  171836. {
  171837. /* Obtain a marker unless we already did. */
  171838. /* Note that next_marker will complain if it skips any data. */
  171839. if (cinfo->unread_marker == 0) {
  171840. if (! next_marker(cinfo))
  171841. return FALSE;
  171842. }
  171843. if (cinfo->unread_marker ==
  171844. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171845. /* Normal case --- swallow the marker and let entropy decoder continue */
  171846. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171847. cinfo->unread_marker = 0;
  171848. } else {
  171849. /* Uh-oh, the restart markers have been messed up. */
  171850. /* Let the data source manager determine how to resync. */
  171851. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171852. cinfo->marker->next_restart_num))
  171853. return FALSE;
  171854. }
  171855. /* Update next-restart state */
  171856. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171857. return TRUE;
  171858. }
  171859. /*
  171860. * This is the default resync_to_restart method for data source managers
  171861. * to use if they don't have any better approach. Some data source managers
  171862. * may be able to back up, or may have additional knowledge about the data
  171863. * which permits a more intelligent recovery strategy; such managers would
  171864. * presumably supply their own resync method.
  171865. *
  171866. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171867. * the restart marker it was expecting. (This code is *not* used unless
  171868. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171869. * the marker code actually found (might be anything, except 0 or FF).
  171870. * The desired restart marker number (0..7) is passed as a parameter.
  171871. * This routine is supposed to apply whatever error recovery strategy seems
  171872. * appropriate in order to position the input stream to the next data segment.
  171873. * Note that cinfo->unread_marker is treated as a marker appearing before
  171874. * the current data-source input point; usually it should be reset to zero
  171875. * before returning.
  171876. * Returns FALSE if suspension is required.
  171877. *
  171878. * This implementation is substantially constrained by wanting to treat the
  171879. * input as a data stream; this means we can't back up. Therefore, we have
  171880. * only the following actions to work with:
  171881. * 1. Simply discard the marker and let the entropy decoder resume at next
  171882. * byte of file.
  171883. * 2. Read forward until we find another marker, discarding intervening
  171884. * data. (In theory we could look ahead within the current bufferload,
  171885. * without having to discard data if we don't find the desired marker.
  171886. * This idea is not implemented here, in part because it makes behavior
  171887. * dependent on buffer size and chance buffer-boundary positions.)
  171888. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171889. * This will cause the entropy decoder to process an empty data segment,
  171890. * inserting dummy zeroes, and then we will reprocess the marker.
  171891. *
  171892. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171893. * appropriate if the found marker is a future restart marker (indicating
  171894. * that we have missed the desired restart marker, probably because it got
  171895. * corrupted).
  171896. * We apply #2 or #3 if the found marker is a restart marker no more than
  171897. * two counts behind or ahead of the expected one. We also apply #2 if the
  171898. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171899. * If the found marker is a restart marker more than 2 counts away, we do #1
  171900. * (too much risk that the marker is erroneous; with luck we will be able to
  171901. * resync at some future point).
  171902. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171903. * overrunning the end of a scan. An implementation limited to single-scan
  171904. * files might find it better to apply #2 for markers other than EOI, since
  171905. * any other marker would have to be bogus data in that case.
  171906. */
  171907. GLOBAL(boolean)
  171908. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171909. {
  171910. int marker = cinfo->unread_marker;
  171911. int action = 1;
  171912. /* Always put up a warning. */
  171913. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171914. /* Outer loop handles repeated decision after scanning forward. */
  171915. for (;;) {
  171916. if (marker < (int) M_SOF0)
  171917. action = 2; /* invalid marker */
  171918. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171919. action = 3; /* valid non-restart marker */
  171920. else {
  171921. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171922. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171923. action = 3; /* one of the next two expected restarts */
  171924. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171925. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171926. action = 2; /* a prior restart, so advance */
  171927. else
  171928. action = 1; /* desired restart or too far away */
  171929. }
  171930. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171931. switch (action) {
  171932. case 1:
  171933. /* Discard marker and let entropy decoder resume processing. */
  171934. cinfo->unread_marker = 0;
  171935. return TRUE;
  171936. case 2:
  171937. /* Scan to the next marker, and repeat the decision loop. */
  171938. if (! next_marker(cinfo))
  171939. return FALSE;
  171940. marker = cinfo->unread_marker;
  171941. break;
  171942. case 3:
  171943. /* Return without advancing past this marker. */
  171944. /* Entropy decoder will be forced to process an empty segment. */
  171945. return TRUE;
  171946. }
  171947. } /* end loop */
  171948. }
  171949. /*
  171950. * Reset marker processing state to begin a fresh datastream.
  171951. */
  171952. METHODDEF(void)
  171953. reset_marker_reader (j_decompress_ptr cinfo)
  171954. {
  171955. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171956. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171957. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171958. cinfo->unread_marker = 0; /* no pending marker */
  171959. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171960. marker->pub.saw_SOF = FALSE;
  171961. marker->pub.discarded_bytes = 0;
  171962. marker->cur_marker = NULL;
  171963. }
  171964. /*
  171965. * Initialize the marker reader module.
  171966. * This is called only once, when the decompression object is created.
  171967. */
  171968. GLOBAL(void)
  171969. jinit_marker_reader (j_decompress_ptr cinfo)
  171970. {
  171971. my_marker_ptr2 marker;
  171972. int i;
  171973. /* Create subobject in permanent pool */
  171974. marker = (my_marker_ptr2)
  171975. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171976. SIZEOF(my_marker_reader));
  171977. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171978. /* Initialize public method pointers */
  171979. marker->pub.reset_marker_reader = reset_marker_reader;
  171980. marker->pub.read_markers = read_markers;
  171981. marker->pub.read_restart_marker = read_restart_marker;
  171982. /* Initialize COM/APPn processing.
  171983. * By default, we examine and then discard APP0 and APP14,
  171984. * but simply discard COM and all other APPn.
  171985. */
  171986. marker->process_COM = skip_variable;
  171987. marker->length_limit_COM = 0;
  171988. for (i = 0; i < 16; i++) {
  171989. marker->process_APPn[i] = skip_variable;
  171990. marker->length_limit_APPn[i] = 0;
  171991. }
  171992. marker->process_APPn[0] = get_interesting_appn;
  171993. marker->process_APPn[14] = get_interesting_appn;
  171994. /* Reset marker processing state */
  171995. reset_marker_reader(cinfo);
  171996. }
  171997. /*
  171998. * Control saving of COM and APPn markers into marker_list.
  171999. */
  172000. #ifdef SAVE_MARKERS_SUPPORTED
  172001. GLOBAL(void)
  172002. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172003. unsigned int length_limit)
  172004. {
  172005. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172006. long maxlength;
  172007. jpeg_marker_parser_method processor;
  172008. /* Length limit mustn't be larger than what we can allocate
  172009. * (should only be a concern in a 16-bit environment).
  172010. */
  172011. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172012. if (((long) length_limit) > maxlength)
  172013. length_limit = (unsigned int) maxlength;
  172014. /* Choose processor routine to use.
  172015. * APP0/APP14 have special requirements.
  172016. */
  172017. if (length_limit) {
  172018. processor = save_marker;
  172019. /* If saving APP0/APP14, save at least enough for our internal use. */
  172020. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172021. length_limit = APP0_DATA_LEN;
  172022. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172023. length_limit = APP14_DATA_LEN;
  172024. } else {
  172025. processor = skip_variable;
  172026. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172027. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172028. processor = get_interesting_appn;
  172029. }
  172030. if (marker_code == (int) M_COM) {
  172031. marker->process_COM = processor;
  172032. marker->length_limit_COM = length_limit;
  172033. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172034. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172035. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172036. } else
  172037. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172038. }
  172039. #endif /* SAVE_MARKERS_SUPPORTED */
  172040. /*
  172041. * Install a special processing method for COM or APPn markers.
  172042. */
  172043. GLOBAL(void)
  172044. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172045. jpeg_marker_parser_method routine)
  172046. {
  172047. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172048. if (marker_code == (int) M_COM)
  172049. marker->process_COM = routine;
  172050. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172051. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172052. else
  172053. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172054. }
  172055. /*** End of inlined file: jdmarker.c ***/
  172056. /*** Start of inlined file: jdmaster.c ***/
  172057. #define JPEG_INTERNALS
  172058. /* Private state */
  172059. typedef struct {
  172060. struct jpeg_decomp_master pub; /* public fields */
  172061. int pass_number; /* # of passes completed */
  172062. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172063. /* Saved references to initialized quantizer modules,
  172064. * in case we need to switch modes.
  172065. */
  172066. struct jpeg_color_quantizer * quantizer_1pass;
  172067. struct jpeg_color_quantizer * quantizer_2pass;
  172068. } my_decomp_master;
  172069. typedef my_decomp_master * my_master_ptr6;
  172070. /*
  172071. * Determine whether merged upsample/color conversion should be used.
  172072. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172073. */
  172074. LOCAL(boolean)
  172075. use_merged_upsample (j_decompress_ptr cinfo)
  172076. {
  172077. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172078. /* Merging is the equivalent of plain box-filter upsampling */
  172079. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172080. return FALSE;
  172081. /* jdmerge.c only supports YCC=>RGB color conversion */
  172082. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172083. cinfo->out_color_space != JCS_RGB ||
  172084. cinfo->out_color_components != RGB_PIXELSIZE)
  172085. return FALSE;
  172086. /* and it only handles 2h1v or 2h2v sampling ratios */
  172087. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172088. cinfo->comp_info[1].h_samp_factor != 1 ||
  172089. cinfo->comp_info[2].h_samp_factor != 1 ||
  172090. cinfo->comp_info[0].v_samp_factor > 2 ||
  172091. cinfo->comp_info[1].v_samp_factor != 1 ||
  172092. cinfo->comp_info[2].v_samp_factor != 1)
  172093. return FALSE;
  172094. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172095. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172096. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172097. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172098. return FALSE;
  172099. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172100. return TRUE; /* by golly, it'll work... */
  172101. #else
  172102. return FALSE;
  172103. #endif
  172104. }
  172105. /*
  172106. * Compute output image dimensions and related values.
  172107. * NOTE: this is exported for possible use by application.
  172108. * Hence it mustn't do anything that can't be done twice.
  172109. * Also note that it may be called before the master module is initialized!
  172110. */
  172111. GLOBAL(void)
  172112. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172113. /* Do computations that are needed before master selection phase */
  172114. {
  172115. #ifdef IDCT_SCALING_SUPPORTED
  172116. int ci;
  172117. jpeg_component_info *compptr;
  172118. #endif
  172119. /* Prevent application from calling me at wrong times */
  172120. if (cinfo->global_state != DSTATE_READY)
  172121. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172122. #ifdef IDCT_SCALING_SUPPORTED
  172123. /* Compute actual output image dimensions and DCT scaling choices. */
  172124. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172125. /* Provide 1/8 scaling */
  172126. cinfo->output_width = (JDIMENSION)
  172127. jdiv_round_up((long) cinfo->image_width, 8L);
  172128. cinfo->output_height = (JDIMENSION)
  172129. jdiv_round_up((long) cinfo->image_height, 8L);
  172130. cinfo->min_DCT_scaled_size = 1;
  172131. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172132. /* Provide 1/4 scaling */
  172133. cinfo->output_width = (JDIMENSION)
  172134. jdiv_round_up((long) cinfo->image_width, 4L);
  172135. cinfo->output_height = (JDIMENSION)
  172136. jdiv_round_up((long) cinfo->image_height, 4L);
  172137. cinfo->min_DCT_scaled_size = 2;
  172138. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172139. /* Provide 1/2 scaling */
  172140. cinfo->output_width = (JDIMENSION)
  172141. jdiv_round_up((long) cinfo->image_width, 2L);
  172142. cinfo->output_height = (JDIMENSION)
  172143. jdiv_round_up((long) cinfo->image_height, 2L);
  172144. cinfo->min_DCT_scaled_size = 4;
  172145. } else {
  172146. /* Provide 1/1 scaling */
  172147. cinfo->output_width = cinfo->image_width;
  172148. cinfo->output_height = cinfo->image_height;
  172149. cinfo->min_DCT_scaled_size = DCTSIZE;
  172150. }
  172151. /* In selecting the actual DCT scaling for each component, we try to
  172152. * scale up the chroma components via IDCT scaling rather than upsampling.
  172153. * This saves time if the upsampler gets to use 1:1 scaling.
  172154. * Note this code assumes that the supported DCT scalings are powers of 2.
  172155. */
  172156. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172157. ci++, compptr++) {
  172158. int ssize = cinfo->min_DCT_scaled_size;
  172159. while (ssize < DCTSIZE &&
  172160. (compptr->h_samp_factor * ssize * 2 <=
  172161. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172162. (compptr->v_samp_factor * ssize * 2 <=
  172163. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172164. ssize = ssize * 2;
  172165. }
  172166. compptr->DCT_scaled_size = ssize;
  172167. }
  172168. /* Recompute downsampled dimensions of components;
  172169. * application needs to know these if using raw downsampled data.
  172170. */
  172171. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172172. ci++, compptr++) {
  172173. /* Size in samples, after IDCT scaling */
  172174. compptr->downsampled_width = (JDIMENSION)
  172175. jdiv_round_up((long) cinfo->image_width *
  172176. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172177. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172178. compptr->downsampled_height = (JDIMENSION)
  172179. jdiv_round_up((long) cinfo->image_height *
  172180. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172181. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172182. }
  172183. #else /* !IDCT_SCALING_SUPPORTED */
  172184. /* Hardwire it to "no scaling" */
  172185. cinfo->output_width = cinfo->image_width;
  172186. cinfo->output_height = cinfo->image_height;
  172187. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172188. * and has computed unscaled downsampled_width and downsampled_height.
  172189. */
  172190. #endif /* IDCT_SCALING_SUPPORTED */
  172191. /* Report number of components in selected colorspace. */
  172192. /* Probably this should be in the color conversion module... */
  172193. switch (cinfo->out_color_space) {
  172194. case JCS_GRAYSCALE:
  172195. cinfo->out_color_components = 1;
  172196. break;
  172197. case JCS_RGB:
  172198. #if RGB_PIXELSIZE != 3
  172199. cinfo->out_color_components = RGB_PIXELSIZE;
  172200. break;
  172201. #endif /* else share code with YCbCr */
  172202. case JCS_YCbCr:
  172203. cinfo->out_color_components = 3;
  172204. break;
  172205. case JCS_CMYK:
  172206. case JCS_YCCK:
  172207. cinfo->out_color_components = 4;
  172208. break;
  172209. default: /* else must be same colorspace as in file */
  172210. cinfo->out_color_components = cinfo->num_components;
  172211. break;
  172212. }
  172213. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172214. cinfo->out_color_components);
  172215. /* See if upsampler will want to emit more than one row at a time */
  172216. if (use_merged_upsample(cinfo))
  172217. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172218. else
  172219. cinfo->rec_outbuf_height = 1;
  172220. }
  172221. /*
  172222. * Several decompression processes need to range-limit values to the range
  172223. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172224. * due to noise introduced by quantization, roundoff error, etc. These
  172225. * processes are inner loops and need to be as fast as possible. On most
  172226. * machines, particularly CPUs with pipelines or instruction prefetch,
  172227. * a (subscript-check-less) C table lookup
  172228. * x = sample_range_limit[x];
  172229. * is faster than explicit tests
  172230. * if (x < 0) x = 0;
  172231. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172232. * These processes all use a common table prepared by the routine below.
  172233. *
  172234. * For most steps we can mathematically guarantee that the initial value
  172235. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172236. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172237. * limiting step (just after the IDCT), a wildly out-of-range value is
  172238. * possible if the input data is corrupt. To avoid any chance of indexing
  172239. * off the end of memory and getting a bad-pointer trap, we perform the
  172240. * post-IDCT limiting thus:
  172241. * x = range_limit[x & MASK];
  172242. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172243. * samples. Under normal circumstances this is more than enough range and
  172244. * a correct output will be generated; with bogus input data the mask will
  172245. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172246. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172247. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172248. * So the post-IDCT limiting table ends up looking like this:
  172249. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172250. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172251. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172252. * 0,1,...,CENTERJSAMPLE-1
  172253. * Negative inputs select values from the upper half of the table after
  172254. * masking.
  172255. *
  172256. * We can save some space by overlapping the start of the post-IDCT table
  172257. * with the simpler range limiting table. The post-IDCT table begins at
  172258. * sample_range_limit + CENTERJSAMPLE.
  172259. *
  172260. * Note that the table is allocated in near data space on PCs; it's small
  172261. * enough and used often enough to justify this.
  172262. */
  172263. LOCAL(void)
  172264. prepare_range_limit_table (j_decompress_ptr cinfo)
  172265. /* Allocate and fill in the sample_range_limit table */
  172266. {
  172267. JSAMPLE * table;
  172268. int i;
  172269. table = (JSAMPLE *)
  172270. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172271. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172272. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172273. cinfo->sample_range_limit = table;
  172274. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172275. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172276. /* Main part of "simple" table: limit[x] = x */
  172277. for (i = 0; i <= MAXJSAMPLE; i++)
  172278. table[i] = (JSAMPLE) i;
  172279. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172280. /* End of simple table, rest of first half of post-IDCT table */
  172281. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172282. table[i] = MAXJSAMPLE;
  172283. /* Second half of post-IDCT table */
  172284. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172285. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172286. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172287. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172288. }
  172289. /*
  172290. * Master selection of decompression modules.
  172291. * This is done once at jpeg_start_decompress time. We determine
  172292. * which modules will be used and give them appropriate initialization calls.
  172293. * We also initialize the decompressor input side to begin consuming data.
  172294. *
  172295. * Since jpeg_read_header has finished, we know what is in the SOF
  172296. * and (first) SOS markers. We also have all the application parameter
  172297. * settings.
  172298. */
  172299. LOCAL(void)
  172300. master_selection (j_decompress_ptr cinfo)
  172301. {
  172302. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172303. boolean use_c_buffer;
  172304. long samplesperrow;
  172305. JDIMENSION jd_samplesperrow;
  172306. /* Initialize dimensions and other stuff */
  172307. jpeg_calc_output_dimensions(cinfo);
  172308. prepare_range_limit_table(cinfo);
  172309. /* Width of an output scanline must be representable as JDIMENSION. */
  172310. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172311. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172312. if ((long) jd_samplesperrow != samplesperrow)
  172313. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172314. /* Initialize my private state */
  172315. master->pass_number = 0;
  172316. master->using_merged_upsample = use_merged_upsample(cinfo);
  172317. /* Color quantizer selection */
  172318. master->quantizer_1pass = NULL;
  172319. master->quantizer_2pass = NULL;
  172320. /* No mode changes if not using buffered-image mode. */
  172321. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172322. cinfo->enable_1pass_quant = FALSE;
  172323. cinfo->enable_external_quant = FALSE;
  172324. cinfo->enable_2pass_quant = FALSE;
  172325. }
  172326. if (cinfo->quantize_colors) {
  172327. if (cinfo->raw_data_out)
  172328. ERREXIT(cinfo, JERR_NOTIMPL);
  172329. /* 2-pass quantizer only works in 3-component color space. */
  172330. if (cinfo->out_color_components != 3) {
  172331. cinfo->enable_1pass_quant = TRUE;
  172332. cinfo->enable_external_quant = FALSE;
  172333. cinfo->enable_2pass_quant = FALSE;
  172334. cinfo->colormap = NULL;
  172335. } else if (cinfo->colormap != NULL) {
  172336. cinfo->enable_external_quant = TRUE;
  172337. } else if (cinfo->two_pass_quantize) {
  172338. cinfo->enable_2pass_quant = TRUE;
  172339. } else {
  172340. cinfo->enable_1pass_quant = TRUE;
  172341. }
  172342. if (cinfo->enable_1pass_quant) {
  172343. #ifdef QUANT_1PASS_SUPPORTED
  172344. jinit_1pass_quantizer(cinfo);
  172345. master->quantizer_1pass = cinfo->cquantize;
  172346. #else
  172347. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172348. #endif
  172349. }
  172350. /* We use the 2-pass code to map to external colormaps. */
  172351. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172352. #ifdef QUANT_2PASS_SUPPORTED
  172353. jinit_2pass_quantizer(cinfo);
  172354. master->quantizer_2pass = cinfo->cquantize;
  172355. #else
  172356. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172357. #endif
  172358. }
  172359. /* If both quantizers are initialized, the 2-pass one is left active;
  172360. * this is necessary for starting with quantization to an external map.
  172361. */
  172362. }
  172363. /* Post-processing: in particular, color conversion first */
  172364. if (! cinfo->raw_data_out) {
  172365. if (master->using_merged_upsample) {
  172366. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172367. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172368. #else
  172369. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172370. #endif
  172371. } else {
  172372. jinit_color_deconverter(cinfo);
  172373. jinit_upsampler(cinfo);
  172374. }
  172375. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172376. }
  172377. /* Inverse DCT */
  172378. jinit_inverse_dct(cinfo);
  172379. /* Entropy decoding: either Huffman or arithmetic coding. */
  172380. if (cinfo->arith_code) {
  172381. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172382. } else {
  172383. if (cinfo->progressive_mode) {
  172384. #ifdef D_PROGRESSIVE_SUPPORTED
  172385. jinit_phuff_decoder(cinfo);
  172386. #else
  172387. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172388. #endif
  172389. } else
  172390. jinit_huff_decoder(cinfo);
  172391. }
  172392. /* Initialize principal buffer controllers. */
  172393. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172394. jinit_d_coef_controller(cinfo, use_c_buffer);
  172395. if (! cinfo->raw_data_out)
  172396. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172397. /* We can now tell the memory manager to allocate virtual arrays. */
  172398. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172399. /* Initialize input side of decompressor to consume first scan. */
  172400. (*cinfo->inputctl->start_input_pass) (cinfo);
  172401. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172402. /* If jpeg_start_decompress will read the whole file, initialize
  172403. * progress monitoring appropriately. The input step is counted
  172404. * as one pass.
  172405. */
  172406. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172407. cinfo->inputctl->has_multiple_scans) {
  172408. int nscans;
  172409. /* Estimate number of scans to set pass_limit. */
  172410. if (cinfo->progressive_mode) {
  172411. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172412. nscans = 2 + 3 * cinfo->num_components;
  172413. } else {
  172414. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172415. nscans = cinfo->num_components;
  172416. }
  172417. cinfo->progress->pass_counter = 0L;
  172418. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172419. cinfo->progress->completed_passes = 0;
  172420. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172421. /* Count the input pass as done */
  172422. master->pass_number++;
  172423. }
  172424. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172425. }
  172426. /*
  172427. * Per-pass setup.
  172428. * This is called at the beginning of each output pass. We determine which
  172429. * modules will be active during this pass and give them appropriate
  172430. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172431. * is a "real" output pass or a dummy pass for color quantization.
  172432. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172433. */
  172434. METHODDEF(void)
  172435. prepare_for_output_pass (j_decompress_ptr cinfo)
  172436. {
  172437. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172438. if (master->pub.is_dummy_pass) {
  172439. #ifdef QUANT_2PASS_SUPPORTED
  172440. /* Final pass of 2-pass quantization */
  172441. master->pub.is_dummy_pass = FALSE;
  172442. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172443. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172444. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172445. #else
  172446. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172447. #endif /* QUANT_2PASS_SUPPORTED */
  172448. } else {
  172449. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172450. /* Select new quantization method */
  172451. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172452. cinfo->cquantize = master->quantizer_2pass;
  172453. master->pub.is_dummy_pass = TRUE;
  172454. } else if (cinfo->enable_1pass_quant) {
  172455. cinfo->cquantize = master->quantizer_1pass;
  172456. } else {
  172457. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172458. }
  172459. }
  172460. (*cinfo->idct->start_pass) (cinfo);
  172461. (*cinfo->coef->start_output_pass) (cinfo);
  172462. if (! cinfo->raw_data_out) {
  172463. if (! master->using_merged_upsample)
  172464. (*cinfo->cconvert->start_pass) (cinfo);
  172465. (*cinfo->upsample->start_pass) (cinfo);
  172466. if (cinfo->quantize_colors)
  172467. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172468. (*cinfo->post->start_pass) (cinfo,
  172469. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172470. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172471. }
  172472. }
  172473. /* Set up progress monitor's pass info if present */
  172474. if (cinfo->progress != NULL) {
  172475. cinfo->progress->completed_passes = master->pass_number;
  172476. cinfo->progress->total_passes = master->pass_number +
  172477. (master->pub.is_dummy_pass ? 2 : 1);
  172478. /* In buffered-image mode, we assume one more output pass if EOI not
  172479. * yet reached, but no more passes if EOI has been reached.
  172480. */
  172481. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172482. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172483. }
  172484. }
  172485. }
  172486. /*
  172487. * Finish up at end of an output pass.
  172488. */
  172489. METHODDEF(void)
  172490. finish_output_pass (j_decompress_ptr cinfo)
  172491. {
  172492. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172493. if (cinfo->quantize_colors)
  172494. (*cinfo->cquantize->finish_pass) (cinfo);
  172495. master->pass_number++;
  172496. }
  172497. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172498. /*
  172499. * Switch to a new external colormap between output passes.
  172500. */
  172501. GLOBAL(void)
  172502. jpeg_new_colormap (j_decompress_ptr cinfo)
  172503. {
  172504. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172505. /* Prevent application from calling me at wrong times */
  172506. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172507. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172508. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172509. cinfo->colormap != NULL) {
  172510. /* Select 2-pass quantizer for external colormap use */
  172511. cinfo->cquantize = master->quantizer_2pass;
  172512. /* Notify quantizer of colormap change */
  172513. (*cinfo->cquantize->new_color_map) (cinfo);
  172514. master->pub.is_dummy_pass = FALSE; /* just in case */
  172515. } else
  172516. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172517. }
  172518. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172519. /*
  172520. * Initialize master decompression control and select active modules.
  172521. * This is performed at the start of jpeg_start_decompress.
  172522. */
  172523. GLOBAL(void)
  172524. jinit_master_decompress (j_decompress_ptr cinfo)
  172525. {
  172526. my_master_ptr6 master;
  172527. master = (my_master_ptr6)
  172528. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172529. SIZEOF(my_decomp_master));
  172530. cinfo->master = (struct jpeg_decomp_master *) master;
  172531. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172532. master->pub.finish_output_pass = finish_output_pass;
  172533. master->pub.is_dummy_pass = FALSE;
  172534. master_selection(cinfo);
  172535. }
  172536. /*** End of inlined file: jdmaster.c ***/
  172537. #undef FIX
  172538. /*** Start of inlined file: jdmerge.c ***/
  172539. #define JPEG_INTERNALS
  172540. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172541. /* Private subobject */
  172542. typedef struct {
  172543. struct jpeg_upsampler pub; /* public fields */
  172544. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172545. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172546. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172547. JSAMPARRAY output_buf));
  172548. /* Private state for YCC->RGB conversion */
  172549. int * Cr_r_tab; /* => table for Cr to R conversion */
  172550. int * Cb_b_tab; /* => table for Cb to B conversion */
  172551. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172552. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172553. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172554. * We need a "spare" row buffer to hold the second output row if the
  172555. * application provides just a one-row buffer; we also use the spare
  172556. * to discard the dummy last row if the image height is odd.
  172557. */
  172558. JSAMPROW spare_row;
  172559. boolean spare_full; /* T if spare buffer is occupied */
  172560. JDIMENSION out_row_width; /* samples per output row */
  172561. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172562. } my_upsampler;
  172563. typedef my_upsampler * my_upsample_ptr;
  172564. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172565. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172566. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172567. /*
  172568. * Initialize tables for YCC->RGB colorspace conversion.
  172569. * This is taken directly from jdcolor.c; see that file for more info.
  172570. */
  172571. LOCAL(void)
  172572. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172573. {
  172574. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172575. int i;
  172576. INT32 x;
  172577. SHIFT_TEMPS
  172578. upsample->Cr_r_tab = (int *)
  172579. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172580. (MAXJSAMPLE+1) * SIZEOF(int));
  172581. upsample->Cb_b_tab = (int *)
  172582. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172583. (MAXJSAMPLE+1) * SIZEOF(int));
  172584. upsample->Cr_g_tab = (INT32 *)
  172585. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172586. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172587. upsample->Cb_g_tab = (INT32 *)
  172588. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172589. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172590. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172591. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172592. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172593. /* Cr=>R value is nearest int to 1.40200 * x */
  172594. upsample->Cr_r_tab[i] = (int)
  172595. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172596. /* Cb=>B value is nearest int to 1.77200 * x */
  172597. upsample->Cb_b_tab[i] = (int)
  172598. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172599. /* Cr=>G value is scaled-up -0.71414 * x */
  172600. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172601. /* Cb=>G value is scaled-up -0.34414 * x */
  172602. /* We also add in ONE_HALF so that need not do it in inner loop */
  172603. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172604. }
  172605. }
  172606. /*
  172607. * Initialize for an upsampling pass.
  172608. */
  172609. METHODDEF(void)
  172610. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172611. {
  172612. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172613. /* Mark the spare buffer empty */
  172614. upsample->spare_full = FALSE;
  172615. /* Initialize total-height counter for detecting bottom of image */
  172616. upsample->rows_to_go = cinfo->output_height;
  172617. }
  172618. /*
  172619. * Control routine to do upsampling (and color conversion).
  172620. *
  172621. * The control routine just handles the row buffering considerations.
  172622. */
  172623. METHODDEF(void)
  172624. merged_2v_upsample (j_decompress_ptr cinfo,
  172625. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172626. JDIMENSION,
  172627. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172628. JDIMENSION out_rows_avail)
  172629. /* 2:1 vertical sampling case: may need a spare row. */
  172630. {
  172631. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172632. JSAMPROW work_ptrs[2];
  172633. JDIMENSION num_rows; /* number of rows returned to caller */
  172634. if (upsample->spare_full) {
  172635. /* If we have a spare row saved from a previous cycle, just return it. */
  172636. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172637. 1, upsample->out_row_width);
  172638. num_rows = 1;
  172639. upsample->spare_full = FALSE;
  172640. } else {
  172641. /* Figure number of rows to return to caller. */
  172642. num_rows = 2;
  172643. /* Not more than the distance to the end of the image. */
  172644. if (num_rows > upsample->rows_to_go)
  172645. num_rows = upsample->rows_to_go;
  172646. /* And not more than what the client can accept: */
  172647. out_rows_avail -= *out_row_ctr;
  172648. if (num_rows > out_rows_avail)
  172649. num_rows = out_rows_avail;
  172650. /* Create output pointer array for upsampler. */
  172651. work_ptrs[0] = output_buf[*out_row_ctr];
  172652. if (num_rows > 1) {
  172653. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172654. } else {
  172655. work_ptrs[1] = upsample->spare_row;
  172656. upsample->spare_full = TRUE;
  172657. }
  172658. /* Now do the upsampling. */
  172659. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172660. }
  172661. /* Adjust counts */
  172662. *out_row_ctr += num_rows;
  172663. upsample->rows_to_go -= num_rows;
  172664. /* When the buffer is emptied, declare this input row group consumed */
  172665. if (! upsample->spare_full)
  172666. (*in_row_group_ctr)++;
  172667. }
  172668. METHODDEF(void)
  172669. merged_1v_upsample (j_decompress_ptr cinfo,
  172670. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172671. JDIMENSION,
  172672. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172673. JDIMENSION)
  172674. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172675. {
  172676. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172677. /* Just do the upsampling. */
  172678. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172679. output_buf + *out_row_ctr);
  172680. /* Adjust counts */
  172681. (*out_row_ctr)++;
  172682. (*in_row_group_ctr)++;
  172683. }
  172684. /*
  172685. * These are the routines invoked by the control routines to do
  172686. * the actual upsampling/conversion. One row group is processed per call.
  172687. *
  172688. * Note: since we may be writing directly into application-supplied buffers,
  172689. * we have to be honest about the output width; we can't assume the buffer
  172690. * has been rounded up to an even width.
  172691. */
  172692. /*
  172693. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172694. */
  172695. METHODDEF(void)
  172696. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172697. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172698. JSAMPARRAY output_buf)
  172699. {
  172700. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172701. register int y, cred, cgreen, cblue;
  172702. int cb, cr;
  172703. register JSAMPROW outptr;
  172704. JSAMPROW inptr0, inptr1, inptr2;
  172705. JDIMENSION col;
  172706. /* copy these pointers into registers if possible */
  172707. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172708. int * Crrtab = upsample->Cr_r_tab;
  172709. int * Cbbtab = upsample->Cb_b_tab;
  172710. INT32 * Crgtab = upsample->Cr_g_tab;
  172711. INT32 * Cbgtab = upsample->Cb_g_tab;
  172712. SHIFT_TEMPS
  172713. inptr0 = input_buf[0][in_row_group_ctr];
  172714. inptr1 = input_buf[1][in_row_group_ctr];
  172715. inptr2 = input_buf[2][in_row_group_ctr];
  172716. outptr = output_buf[0];
  172717. /* Loop for each pair of output pixels */
  172718. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172719. /* Do the chroma part of the calculation */
  172720. cb = GETJSAMPLE(*inptr1++);
  172721. cr = GETJSAMPLE(*inptr2++);
  172722. cred = Crrtab[cr];
  172723. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172724. cblue = Cbbtab[cb];
  172725. /* Fetch 2 Y values and emit 2 pixels */
  172726. y = GETJSAMPLE(*inptr0++);
  172727. outptr[RGB_RED] = range_limit[y + cred];
  172728. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172729. outptr[RGB_BLUE] = range_limit[y + cblue];
  172730. outptr += RGB_PIXELSIZE;
  172731. y = GETJSAMPLE(*inptr0++);
  172732. outptr[RGB_RED] = range_limit[y + cred];
  172733. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172734. outptr[RGB_BLUE] = range_limit[y + cblue];
  172735. outptr += RGB_PIXELSIZE;
  172736. }
  172737. /* If image width is odd, do the last output column separately */
  172738. if (cinfo->output_width & 1) {
  172739. cb = GETJSAMPLE(*inptr1);
  172740. cr = GETJSAMPLE(*inptr2);
  172741. cred = Crrtab[cr];
  172742. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172743. cblue = Cbbtab[cb];
  172744. y = GETJSAMPLE(*inptr0);
  172745. outptr[RGB_RED] = range_limit[y + cred];
  172746. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172747. outptr[RGB_BLUE] = range_limit[y + cblue];
  172748. }
  172749. }
  172750. /*
  172751. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172752. */
  172753. METHODDEF(void)
  172754. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172755. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172756. JSAMPARRAY output_buf)
  172757. {
  172758. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172759. register int y, cred, cgreen, cblue;
  172760. int cb, cr;
  172761. register JSAMPROW outptr0, outptr1;
  172762. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172763. JDIMENSION col;
  172764. /* copy these pointers into registers if possible */
  172765. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172766. int * Crrtab = upsample->Cr_r_tab;
  172767. int * Cbbtab = upsample->Cb_b_tab;
  172768. INT32 * Crgtab = upsample->Cr_g_tab;
  172769. INT32 * Cbgtab = upsample->Cb_g_tab;
  172770. SHIFT_TEMPS
  172771. inptr00 = input_buf[0][in_row_group_ctr*2];
  172772. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172773. inptr1 = input_buf[1][in_row_group_ctr];
  172774. inptr2 = input_buf[2][in_row_group_ctr];
  172775. outptr0 = output_buf[0];
  172776. outptr1 = output_buf[1];
  172777. /* Loop for each group of output pixels */
  172778. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172779. /* Do the chroma part of the calculation */
  172780. cb = GETJSAMPLE(*inptr1++);
  172781. cr = GETJSAMPLE(*inptr2++);
  172782. cred = Crrtab[cr];
  172783. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172784. cblue = Cbbtab[cb];
  172785. /* Fetch 4 Y values and emit 4 pixels */
  172786. y = GETJSAMPLE(*inptr00++);
  172787. outptr0[RGB_RED] = range_limit[y + cred];
  172788. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172789. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172790. outptr0 += RGB_PIXELSIZE;
  172791. y = GETJSAMPLE(*inptr00++);
  172792. outptr0[RGB_RED] = range_limit[y + cred];
  172793. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172794. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172795. outptr0 += RGB_PIXELSIZE;
  172796. y = GETJSAMPLE(*inptr01++);
  172797. outptr1[RGB_RED] = range_limit[y + cred];
  172798. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172799. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172800. outptr1 += RGB_PIXELSIZE;
  172801. y = GETJSAMPLE(*inptr01++);
  172802. outptr1[RGB_RED] = range_limit[y + cred];
  172803. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172804. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172805. outptr1 += RGB_PIXELSIZE;
  172806. }
  172807. /* If image width is odd, do the last output column separately */
  172808. if (cinfo->output_width & 1) {
  172809. cb = GETJSAMPLE(*inptr1);
  172810. cr = GETJSAMPLE(*inptr2);
  172811. cred = Crrtab[cr];
  172812. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172813. cblue = Cbbtab[cb];
  172814. y = GETJSAMPLE(*inptr00);
  172815. outptr0[RGB_RED] = range_limit[y + cred];
  172816. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172817. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172818. y = GETJSAMPLE(*inptr01);
  172819. outptr1[RGB_RED] = range_limit[y + cred];
  172820. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172821. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172822. }
  172823. }
  172824. /*
  172825. * Module initialization routine for merged upsampling/color conversion.
  172826. *
  172827. * NB: this is called under the conditions determined by use_merged_upsample()
  172828. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172829. * of this module; no safety checks are made here.
  172830. */
  172831. GLOBAL(void)
  172832. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172833. {
  172834. my_upsample_ptr upsample;
  172835. upsample = (my_upsample_ptr)
  172836. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172837. SIZEOF(my_upsampler));
  172838. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172839. upsample->pub.start_pass = start_pass_merged_upsample;
  172840. upsample->pub.need_context_rows = FALSE;
  172841. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172842. if (cinfo->max_v_samp_factor == 2) {
  172843. upsample->pub.upsample = merged_2v_upsample;
  172844. upsample->upmethod = h2v2_merged_upsample;
  172845. /* Allocate a spare row buffer */
  172846. upsample->spare_row = (JSAMPROW)
  172847. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172848. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172849. } else {
  172850. upsample->pub.upsample = merged_1v_upsample;
  172851. upsample->upmethod = h2v1_merged_upsample;
  172852. /* No spare row needed */
  172853. upsample->spare_row = NULL;
  172854. }
  172855. build_ycc_rgb_table2(cinfo);
  172856. }
  172857. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172858. /*** End of inlined file: jdmerge.c ***/
  172859. #undef ASSIGN_STATE
  172860. /*** Start of inlined file: jdphuff.c ***/
  172861. #define JPEG_INTERNALS
  172862. #ifdef D_PROGRESSIVE_SUPPORTED
  172863. /*
  172864. * Expanded entropy decoder object for progressive Huffman decoding.
  172865. *
  172866. * The savable_state subrecord contains fields that change within an MCU,
  172867. * but must not be updated permanently until we complete the MCU.
  172868. */
  172869. typedef struct {
  172870. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172871. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172872. } savable_state3;
  172873. /* This macro is to work around compilers with missing or broken
  172874. * structure assignment. You'll need to fix this code if you have
  172875. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172876. */
  172877. #ifndef NO_STRUCT_ASSIGN
  172878. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172879. #else
  172880. #if MAX_COMPS_IN_SCAN == 4
  172881. #define ASSIGN_STATE(dest,src) \
  172882. ((dest).EOBRUN = (src).EOBRUN, \
  172883. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172884. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172885. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172886. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172887. #endif
  172888. #endif
  172889. typedef struct {
  172890. struct jpeg_entropy_decoder pub; /* public fields */
  172891. /* These fields are loaded into local variables at start of each MCU.
  172892. * In case of suspension, we exit WITHOUT updating them.
  172893. */
  172894. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172895. savable_state3 saved; /* Other state at start of MCU */
  172896. /* These fields are NOT loaded into local working state. */
  172897. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172898. /* Pointers to derived tables (these workspaces have image lifespan) */
  172899. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172900. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172901. } phuff_entropy_decoder;
  172902. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172903. /* Forward declarations */
  172904. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172905. JBLOCKROW *MCU_data));
  172906. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172907. JBLOCKROW *MCU_data));
  172908. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172909. JBLOCKROW *MCU_data));
  172910. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172911. JBLOCKROW *MCU_data));
  172912. /*
  172913. * Initialize for a Huffman-compressed scan.
  172914. */
  172915. METHODDEF(void)
  172916. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172917. {
  172918. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172919. boolean is_DC_band, bad;
  172920. int ci, coefi, tbl;
  172921. int *coef_bit_ptr;
  172922. jpeg_component_info * compptr;
  172923. is_DC_band = (cinfo->Ss == 0);
  172924. /* Validate scan parameters */
  172925. bad = FALSE;
  172926. if (is_DC_band) {
  172927. if (cinfo->Se != 0)
  172928. bad = TRUE;
  172929. } else {
  172930. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172931. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172932. bad = TRUE;
  172933. /* AC scans may have only one component */
  172934. if (cinfo->comps_in_scan != 1)
  172935. bad = TRUE;
  172936. }
  172937. if (cinfo->Ah != 0) {
  172938. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172939. if (cinfo->Al != cinfo->Ah-1)
  172940. bad = TRUE;
  172941. }
  172942. if (cinfo->Al > 13) /* need not check for < 0 */
  172943. bad = TRUE;
  172944. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172945. * but the spec doesn't say so, and we try to be liberal about what we
  172946. * accept. Note: large Al values could result in out-of-range DC
  172947. * coefficients during early scans, leading to bizarre displays due to
  172948. * overflows in the IDCT math. But we won't crash.
  172949. */
  172950. if (bad)
  172951. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172952. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172953. /* Update progression status, and verify that scan order is legal.
  172954. * Note that inter-scan inconsistencies are treated as warnings
  172955. * not fatal errors ... not clear if this is right way to behave.
  172956. */
  172957. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172958. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172959. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172960. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172961. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172962. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172963. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172964. if (cinfo->Ah != expected)
  172965. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172966. coef_bit_ptr[coefi] = cinfo->Al;
  172967. }
  172968. }
  172969. /* Select MCU decoding routine */
  172970. if (cinfo->Ah == 0) {
  172971. if (is_DC_band)
  172972. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172973. else
  172974. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172975. } else {
  172976. if (is_DC_band)
  172977. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172978. else
  172979. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172980. }
  172981. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172982. compptr = cinfo->cur_comp_info[ci];
  172983. /* Make sure requested tables are present, and compute derived tables.
  172984. * We may build same derived table more than once, but it's not expensive.
  172985. */
  172986. if (is_DC_band) {
  172987. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172988. tbl = compptr->dc_tbl_no;
  172989. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172990. & entropy->derived_tbls[tbl]);
  172991. }
  172992. } else {
  172993. tbl = compptr->ac_tbl_no;
  172994. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172995. & entropy->derived_tbls[tbl]);
  172996. /* remember the single active table */
  172997. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172998. }
  172999. /* Initialize DC predictions to 0 */
  173000. entropy->saved.last_dc_val[ci] = 0;
  173001. }
  173002. /* Initialize bitread state variables */
  173003. entropy->bitstate.bits_left = 0;
  173004. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173005. entropy->pub.insufficient_data = FALSE;
  173006. /* Initialize private state variables */
  173007. entropy->saved.EOBRUN = 0;
  173008. /* Initialize restart counter */
  173009. entropy->restarts_to_go = cinfo->restart_interval;
  173010. }
  173011. /*
  173012. * Check for a restart marker & resynchronize decoder.
  173013. * Returns FALSE if must suspend.
  173014. */
  173015. LOCAL(boolean)
  173016. process_restartp (j_decompress_ptr cinfo)
  173017. {
  173018. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173019. int ci;
  173020. /* Throw away any unused bits remaining in bit buffer; */
  173021. /* include any full bytes in next_marker's count of discarded bytes */
  173022. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173023. entropy->bitstate.bits_left = 0;
  173024. /* Advance past the RSTn marker */
  173025. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173026. return FALSE;
  173027. /* Re-initialize DC predictions to 0 */
  173028. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173029. entropy->saved.last_dc_val[ci] = 0;
  173030. /* Re-init EOB run count, too */
  173031. entropy->saved.EOBRUN = 0;
  173032. /* Reset restart counter */
  173033. entropy->restarts_to_go = cinfo->restart_interval;
  173034. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173035. * against a marker. In that case we will end up treating the next data
  173036. * segment as empty, and we can avoid producing bogus output pixels by
  173037. * leaving the flag set.
  173038. */
  173039. if (cinfo->unread_marker == 0)
  173040. entropy->pub.insufficient_data = FALSE;
  173041. return TRUE;
  173042. }
  173043. /*
  173044. * Huffman MCU decoding.
  173045. * Each of these routines decodes and returns one MCU's worth of
  173046. * Huffman-compressed coefficients.
  173047. * The coefficients are reordered from zigzag order into natural array order,
  173048. * but are not dequantized.
  173049. *
  173050. * The i'th block of the MCU is stored into the block pointed to by
  173051. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173052. *
  173053. * We return FALSE if data source requested suspension. In that case no
  173054. * changes have been made to permanent state. (Exception: some output
  173055. * coefficients may already have been assigned. This is harmless for
  173056. * spectral selection, since we'll just re-assign them on the next call.
  173057. * Successive approximation AC refinement has to be more careful, however.)
  173058. */
  173059. /*
  173060. * MCU decoding for DC initial scan (either spectral selection,
  173061. * or first pass of successive approximation).
  173062. */
  173063. METHODDEF(boolean)
  173064. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173065. {
  173066. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173067. int Al = cinfo->Al;
  173068. register int s, r;
  173069. int blkn, ci;
  173070. JBLOCKROW block;
  173071. BITREAD_STATE_VARS;
  173072. savable_state3 state;
  173073. d_derived_tbl * tbl;
  173074. jpeg_component_info * compptr;
  173075. /* Process restart marker if needed; may have to suspend */
  173076. if (cinfo->restart_interval) {
  173077. if (entropy->restarts_to_go == 0)
  173078. if (! process_restartp(cinfo))
  173079. return FALSE;
  173080. }
  173081. /* If we've run out of data, just leave the MCU set to zeroes.
  173082. * This way, we return uniform gray for the remainder of the segment.
  173083. */
  173084. if (! entropy->pub.insufficient_data) {
  173085. /* Load up working state */
  173086. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173087. ASSIGN_STATE(state, entropy->saved);
  173088. /* Outer loop handles each block in the MCU */
  173089. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173090. block = MCU_data[blkn];
  173091. ci = cinfo->MCU_membership[blkn];
  173092. compptr = cinfo->cur_comp_info[ci];
  173093. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173094. /* Decode a single block's worth of coefficients */
  173095. /* Section F.2.2.1: decode the DC coefficient difference */
  173096. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173097. if (s) {
  173098. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173099. r = GET_BITS(s);
  173100. s = HUFF_EXTEND(r, s);
  173101. }
  173102. /* Convert DC difference to actual value, update last_dc_val */
  173103. s += state.last_dc_val[ci];
  173104. state.last_dc_val[ci] = s;
  173105. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173106. (*block)[0] = (JCOEF) (s << Al);
  173107. }
  173108. /* Completed MCU, so update state */
  173109. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173110. ASSIGN_STATE(entropy->saved, state);
  173111. }
  173112. /* Account for restart interval (no-op if not using restarts) */
  173113. entropy->restarts_to_go--;
  173114. return TRUE;
  173115. }
  173116. /*
  173117. * MCU decoding for AC initial scan (either spectral selection,
  173118. * or first pass of successive approximation).
  173119. */
  173120. METHODDEF(boolean)
  173121. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173122. {
  173123. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173124. int Se = cinfo->Se;
  173125. int Al = cinfo->Al;
  173126. register int s, k, r;
  173127. unsigned int EOBRUN;
  173128. JBLOCKROW block;
  173129. BITREAD_STATE_VARS;
  173130. d_derived_tbl * tbl;
  173131. /* Process restart marker if needed; may have to suspend */
  173132. if (cinfo->restart_interval) {
  173133. if (entropy->restarts_to_go == 0)
  173134. if (! process_restartp(cinfo))
  173135. return FALSE;
  173136. }
  173137. /* If we've run out of data, just leave the MCU set to zeroes.
  173138. * This way, we return uniform gray for the remainder of the segment.
  173139. */
  173140. if (! entropy->pub.insufficient_data) {
  173141. /* Load up working state.
  173142. * We can avoid loading/saving bitread state if in an EOB run.
  173143. */
  173144. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173145. /* There is always only one block per MCU */
  173146. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173147. EOBRUN--; /* ...process it now (we do nothing) */
  173148. else {
  173149. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173150. block = MCU_data[0];
  173151. tbl = entropy->ac_derived_tbl;
  173152. for (k = cinfo->Ss; k <= Se; k++) {
  173153. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173154. r = s >> 4;
  173155. s &= 15;
  173156. if (s) {
  173157. k += r;
  173158. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173159. r = GET_BITS(s);
  173160. s = HUFF_EXTEND(r, s);
  173161. /* Scale and output coefficient in natural (dezigzagged) order */
  173162. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173163. } else {
  173164. if (r == 15) { /* ZRL */
  173165. k += 15; /* skip 15 zeroes in band */
  173166. } else { /* EOBr, run length is 2^r + appended bits */
  173167. EOBRUN = 1 << r;
  173168. if (r) { /* EOBr, r > 0 */
  173169. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173170. r = GET_BITS(r);
  173171. EOBRUN += r;
  173172. }
  173173. EOBRUN--; /* this band is processed at this moment */
  173174. break; /* force end-of-band */
  173175. }
  173176. }
  173177. }
  173178. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173179. }
  173180. /* Completed MCU, so update state */
  173181. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173182. }
  173183. /* Account for restart interval (no-op if not using restarts) */
  173184. entropy->restarts_to_go--;
  173185. return TRUE;
  173186. }
  173187. /*
  173188. * MCU decoding for DC successive approximation refinement scan.
  173189. * Note: we assume such scans can be multi-component, although the spec
  173190. * is not very clear on the point.
  173191. */
  173192. METHODDEF(boolean)
  173193. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173194. {
  173195. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173196. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173197. int blkn;
  173198. JBLOCKROW block;
  173199. BITREAD_STATE_VARS;
  173200. /* Process restart marker if needed; may have to suspend */
  173201. if (cinfo->restart_interval) {
  173202. if (entropy->restarts_to_go == 0)
  173203. if (! process_restartp(cinfo))
  173204. return FALSE;
  173205. }
  173206. /* Not worth the cycles to check insufficient_data here,
  173207. * since we will not change the data anyway if we read zeroes.
  173208. */
  173209. /* Load up working state */
  173210. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173211. /* Outer loop handles each block in the MCU */
  173212. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173213. block = MCU_data[blkn];
  173214. /* Encoded data is simply the next bit of the two's-complement DC value */
  173215. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173216. if (GET_BITS(1))
  173217. (*block)[0] |= p1;
  173218. /* Note: since we use |=, repeating the assignment later is safe */
  173219. }
  173220. /* Completed MCU, so update state */
  173221. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173222. /* Account for restart interval (no-op if not using restarts) */
  173223. entropy->restarts_to_go--;
  173224. return TRUE;
  173225. }
  173226. /*
  173227. * MCU decoding for AC successive approximation refinement scan.
  173228. */
  173229. METHODDEF(boolean)
  173230. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173231. {
  173232. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173233. int Se = cinfo->Se;
  173234. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173235. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173236. register int s, k, r;
  173237. unsigned int EOBRUN;
  173238. JBLOCKROW block;
  173239. JCOEFPTR thiscoef;
  173240. BITREAD_STATE_VARS;
  173241. d_derived_tbl * tbl;
  173242. int num_newnz;
  173243. int newnz_pos[DCTSIZE2];
  173244. /* Process restart marker if needed; may have to suspend */
  173245. if (cinfo->restart_interval) {
  173246. if (entropy->restarts_to_go == 0)
  173247. if (! process_restartp(cinfo))
  173248. return FALSE;
  173249. }
  173250. /* If we've run out of data, don't modify the MCU.
  173251. */
  173252. if (! entropy->pub.insufficient_data) {
  173253. /* Load up working state */
  173254. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173255. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173256. /* There is always only one block per MCU */
  173257. block = MCU_data[0];
  173258. tbl = entropy->ac_derived_tbl;
  173259. /* If we are forced to suspend, we must undo the assignments to any newly
  173260. * nonzero coefficients in the block, because otherwise we'd get confused
  173261. * next time about which coefficients were already nonzero.
  173262. * But we need not undo addition of bits to already-nonzero coefficients;
  173263. * instead, we can test the current bit to see if we already did it.
  173264. */
  173265. num_newnz = 0;
  173266. /* initialize coefficient loop counter to start of band */
  173267. k = cinfo->Ss;
  173268. if (EOBRUN == 0) {
  173269. for (; k <= Se; k++) {
  173270. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173271. r = s >> 4;
  173272. s &= 15;
  173273. if (s) {
  173274. if (s != 1) /* size of new coef should always be 1 */
  173275. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173276. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173277. if (GET_BITS(1))
  173278. s = p1; /* newly nonzero coef is positive */
  173279. else
  173280. s = m1; /* newly nonzero coef is negative */
  173281. } else {
  173282. if (r != 15) {
  173283. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173284. if (r) {
  173285. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173286. r = GET_BITS(r);
  173287. EOBRUN += r;
  173288. }
  173289. break; /* rest of block is handled by EOB logic */
  173290. }
  173291. /* note s = 0 for processing ZRL */
  173292. }
  173293. /* Advance over already-nonzero coefs and r still-zero coefs,
  173294. * appending correction bits to the nonzeroes. A correction bit is 1
  173295. * if the absolute value of the coefficient must be increased.
  173296. */
  173297. do {
  173298. thiscoef = *block + jpeg_natural_order[k];
  173299. if (*thiscoef != 0) {
  173300. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173301. if (GET_BITS(1)) {
  173302. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173303. if (*thiscoef >= 0)
  173304. *thiscoef += p1;
  173305. else
  173306. *thiscoef += m1;
  173307. }
  173308. }
  173309. } else {
  173310. if (--r < 0)
  173311. break; /* reached target zero coefficient */
  173312. }
  173313. k++;
  173314. } while (k <= Se);
  173315. if (s) {
  173316. int pos = jpeg_natural_order[k];
  173317. /* Output newly nonzero coefficient */
  173318. (*block)[pos] = (JCOEF) s;
  173319. /* Remember its position in case we have to suspend */
  173320. newnz_pos[num_newnz++] = pos;
  173321. }
  173322. }
  173323. }
  173324. if (EOBRUN > 0) {
  173325. /* Scan any remaining coefficient positions after the end-of-band
  173326. * (the last newly nonzero coefficient, if any). Append a correction
  173327. * bit to each already-nonzero coefficient. A correction bit is 1
  173328. * if the absolute value of the coefficient must be increased.
  173329. */
  173330. for (; k <= Se; k++) {
  173331. thiscoef = *block + jpeg_natural_order[k];
  173332. if (*thiscoef != 0) {
  173333. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173334. if (GET_BITS(1)) {
  173335. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173336. if (*thiscoef >= 0)
  173337. *thiscoef += p1;
  173338. else
  173339. *thiscoef += m1;
  173340. }
  173341. }
  173342. }
  173343. }
  173344. /* Count one block completed in EOB run */
  173345. EOBRUN--;
  173346. }
  173347. /* Completed MCU, so update state */
  173348. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173349. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173350. }
  173351. /* Account for restart interval (no-op if not using restarts) */
  173352. entropy->restarts_to_go--;
  173353. return TRUE;
  173354. undoit:
  173355. /* Re-zero any output coefficients that we made newly nonzero */
  173356. while (num_newnz > 0)
  173357. (*block)[newnz_pos[--num_newnz]] = 0;
  173358. return FALSE;
  173359. }
  173360. /*
  173361. * Module initialization routine for progressive Huffman entropy decoding.
  173362. */
  173363. GLOBAL(void)
  173364. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173365. {
  173366. phuff_entropy_ptr2 entropy;
  173367. int *coef_bit_ptr;
  173368. int ci, i;
  173369. entropy = (phuff_entropy_ptr2)
  173370. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173371. SIZEOF(phuff_entropy_decoder));
  173372. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173373. entropy->pub.start_pass = start_pass_phuff_decoder;
  173374. /* Mark derived tables unallocated */
  173375. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173376. entropy->derived_tbls[i] = NULL;
  173377. }
  173378. /* Create progression status table */
  173379. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173380. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173381. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173382. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173383. for (ci = 0; ci < cinfo->num_components; ci++)
  173384. for (i = 0; i < DCTSIZE2; i++)
  173385. *coef_bit_ptr++ = -1;
  173386. }
  173387. #endif /* D_PROGRESSIVE_SUPPORTED */
  173388. /*** End of inlined file: jdphuff.c ***/
  173389. /*** Start of inlined file: jdpostct.c ***/
  173390. #define JPEG_INTERNALS
  173391. /* Private buffer controller object */
  173392. typedef struct {
  173393. struct jpeg_d_post_controller pub; /* public fields */
  173394. /* Color quantization source buffer: this holds output data from
  173395. * the upsample/color conversion step to be passed to the quantizer.
  173396. * For two-pass color quantization, we need a full-image buffer;
  173397. * for one-pass operation, a strip buffer is sufficient.
  173398. */
  173399. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173400. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173401. JDIMENSION strip_height; /* buffer size in rows */
  173402. /* for two-pass mode only: */
  173403. JDIMENSION starting_row; /* row # of first row in current strip */
  173404. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173405. } my_post_controller;
  173406. typedef my_post_controller * my_post_ptr;
  173407. /* Forward declarations */
  173408. METHODDEF(void) post_process_1pass
  173409. JPP((j_decompress_ptr cinfo,
  173410. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173411. JDIMENSION in_row_groups_avail,
  173412. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173413. JDIMENSION out_rows_avail));
  173414. #ifdef QUANT_2PASS_SUPPORTED
  173415. METHODDEF(void) post_process_prepass
  173416. JPP((j_decompress_ptr cinfo,
  173417. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173418. JDIMENSION in_row_groups_avail,
  173419. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173420. JDIMENSION out_rows_avail));
  173421. METHODDEF(void) post_process_2pass
  173422. JPP((j_decompress_ptr cinfo,
  173423. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173424. JDIMENSION in_row_groups_avail,
  173425. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173426. JDIMENSION out_rows_avail));
  173427. #endif
  173428. /*
  173429. * Initialize for a processing pass.
  173430. */
  173431. METHODDEF(void)
  173432. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173433. {
  173434. my_post_ptr post = (my_post_ptr) cinfo->post;
  173435. switch (pass_mode) {
  173436. case JBUF_PASS_THRU:
  173437. if (cinfo->quantize_colors) {
  173438. /* Single-pass processing with color quantization. */
  173439. post->pub.post_process_data = post_process_1pass;
  173440. /* We could be doing buffered-image output before starting a 2-pass
  173441. * color quantization; in that case, jinit_d_post_controller did not
  173442. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173443. */
  173444. if (post->buffer == NULL) {
  173445. post->buffer = (*cinfo->mem->access_virt_sarray)
  173446. ((j_common_ptr) cinfo, post->whole_image,
  173447. (JDIMENSION) 0, post->strip_height, TRUE);
  173448. }
  173449. } else {
  173450. /* For single-pass processing without color quantization,
  173451. * I have no work to do; just call the upsampler directly.
  173452. */
  173453. post->pub.post_process_data = cinfo->upsample->upsample;
  173454. }
  173455. break;
  173456. #ifdef QUANT_2PASS_SUPPORTED
  173457. case JBUF_SAVE_AND_PASS:
  173458. /* First pass of 2-pass quantization */
  173459. if (post->whole_image == NULL)
  173460. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173461. post->pub.post_process_data = post_process_prepass;
  173462. break;
  173463. case JBUF_CRANK_DEST:
  173464. /* Second pass of 2-pass quantization */
  173465. if (post->whole_image == NULL)
  173466. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173467. post->pub.post_process_data = post_process_2pass;
  173468. break;
  173469. #endif /* QUANT_2PASS_SUPPORTED */
  173470. default:
  173471. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173472. break;
  173473. }
  173474. post->starting_row = post->next_row = 0;
  173475. }
  173476. /*
  173477. * Process some data in the one-pass (strip buffer) case.
  173478. * This is used for color precision reduction as well as one-pass quantization.
  173479. */
  173480. METHODDEF(void)
  173481. post_process_1pass (j_decompress_ptr cinfo,
  173482. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173483. JDIMENSION in_row_groups_avail,
  173484. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173485. JDIMENSION out_rows_avail)
  173486. {
  173487. my_post_ptr post = (my_post_ptr) cinfo->post;
  173488. JDIMENSION num_rows, max_rows;
  173489. /* Fill the buffer, but not more than what we can dump out in one go. */
  173490. /* Note we rely on the upsampler to detect bottom of image. */
  173491. max_rows = out_rows_avail - *out_row_ctr;
  173492. if (max_rows > post->strip_height)
  173493. max_rows = post->strip_height;
  173494. num_rows = 0;
  173495. (*cinfo->upsample->upsample) (cinfo,
  173496. input_buf, in_row_group_ctr, in_row_groups_avail,
  173497. post->buffer, &num_rows, max_rows);
  173498. /* Quantize and emit data. */
  173499. (*cinfo->cquantize->color_quantize) (cinfo,
  173500. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173501. *out_row_ctr += num_rows;
  173502. }
  173503. #ifdef QUANT_2PASS_SUPPORTED
  173504. /*
  173505. * Process some data in the first pass of 2-pass quantization.
  173506. */
  173507. METHODDEF(void)
  173508. post_process_prepass (j_decompress_ptr cinfo,
  173509. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173510. JDIMENSION in_row_groups_avail,
  173511. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173512. JDIMENSION)
  173513. {
  173514. my_post_ptr post = (my_post_ptr) cinfo->post;
  173515. JDIMENSION old_next_row, num_rows;
  173516. /* Reposition virtual buffer if at start of strip. */
  173517. if (post->next_row == 0) {
  173518. post->buffer = (*cinfo->mem->access_virt_sarray)
  173519. ((j_common_ptr) cinfo, post->whole_image,
  173520. post->starting_row, post->strip_height, TRUE);
  173521. }
  173522. /* Upsample some data (up to a strip height's worth). */
  173523. old_next_row = post->next_row;
  173524. (*cinfo->upsample->upsample) (cinfo,
  173525. input_buf, in_row_group_ctr, in_row_groups_avail,
  173526. post->buffer, &post->next_row, post->strip_height);
  173527. /* Allow quantizer to scan new data. No data is emitted, */
  173528. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173529. if (post->next_row > old_next_row) {
  173530. num_rows = post->next_row - old_next_row;
  173531. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173532. (JSAMPARRAY) NULL, (int) num_rows);
  173533. *out_row_ctr += num_rows;
  173534. }
  173535. /* Advance if we filled the strip. */
  173536. if (post->next_row >= post->strip_height) {
  173537. post->starting_row += post->strip_height;
  173538. post->next_row = 0;
  173539. }
  173540. }
  173541. /*
  173542. * Process some data in the second pass of 2-pass quantization.
  173543. */
  173544. METHODDEF(void)
  173545. post_process_2pass (j_decompress_ptr cinfo,
  173546. JSAMPIMAGE, JDIMENSION *,
  173547. JDIMENSION,
  173548. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173549. JDIMENSION out_rows_avail)
  173550. {
  173551. my_post_ptr post = (my_post_ptr) cinfo->post;
  173552. JDIMENSION num_rows, max_rows;
  173553. /* Reposition virtual buffer if at start of strip. */
  173554. if (post->next_row == 0) {
  173555. post->buffer = (*cinfo->mem->access_virt_sarray)
  173556. ((j_common_ptr) cinfo, post->whole_image,
  173557. post->starting_row, post->strip_height, FALSE);
  173558. }
  173559. /* Determine number of rows to emit. */
  173560. num_rows = post->strip_height - post->next_row; /* available in strip */
  173561. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173562. if (num_rows > max_rows)
  173563. num_rows = max_rows;
  173564. /* We have to check bottom of image here, can't depend on upsampler. */
  173565. max_rows = cinfo->output_height - post->starting_row;
  173566. if (num_rows > max_rows)
  173567. num_rows = max_rows;
  173568. /* Quantize and emit data. */
  173569. (*cinfo->cquantize->color_quantize) (cinfo,
  173570. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173571. (int) num_rows);
  173572. *out_row_ctr += num_rows;
  173573. /* Advance if we filled the strip. */
  173574. post->next_row += num_rows;
  173575. if (post->next_row >= post->strip_height) {
  173576. post->starting_row += post->strip_height;
  173577. post->next_row = 0;
  173578. }
  173579. }
  173580. #endif /* QUANT_2PASS_SUPPORTED */
  173581. /*
  173582. * Initialize postprocessing controller.
  173583. */
  173584. GLOBAL(void)
  173585. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173586. {
  173587. my_post_ptr post;
  173588. post = (my_post_ptr)
  173589. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173590. SIZEOF(my_post_controller));
  173591. cinfo->post = (struct jpeg_d_post_controller *) post;
  173592. post->pub.start_pass = start_pass_dpost;
  173593. post->whole_image = NULL; /* flag for no virtual arrays */
  173594. post->buffer = NULL; /* flag for no strip buffer */
  173595. /* Create the quantization buffer, if needed */
  173596. if (cinfo->quantize_colors) {
  173597. /* The buffer strip height is max_v_samp_factor, which is typically
  173598. * an efficient number of rows for upsampling to return.
  173599. * (In the presence of output rescaling, we might want to be smarter?)
  173600. */
  173601. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173602. if (need_full_buffer) {
  173603. /* Two-pass color quantization: need full-image storage. */
  173604. /* We round up the number of rows to a multiple of the strip height. */
  173605. #ifdef QUANT_2PASS_SUPPORTED
  173606. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173607. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173608. cinfo->output_width * cinfo->out_color_components,
  173609. (JDIMENSION) jround_up((long) cinfo->output_height,
  173610. (long) post->strip_height),
  173611. post->strip_height);
  173612. #else
  173613. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173614. #endif /* QUANT_2PASS_SUPPORTED */
  173615. } else {
  173616. /* One-pass color quantization: just make a strip buffer. */
  173617. post->buffer = (*cinfo->mem->alloc_sarray)
  173618. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173619. cinfo->output_width * cinfo->out_color_components,
  173620. post->strip_height);
  173621. }
  173622. }
  173623. }
  173624. /*** End of inlined file: jdpostct.c ***/
  173625. #undef FIX
  173626. /*** Start of inlined file: jdsample.c ***/
  173627. #define JPEG_INTERNALS
  173628. /* Pointer to routine to upsample a single component */
  173629. typedef JMETHOD(void, upsample1_ptr,
  173630. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173631. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173632. /* Private subobject */
  173633. typedef struct {
  173634. struct jpeg_upsampler pub; /* public fields */
  173635. /* Color conversion buffer. When using separate upsampling and color
  173636. * conversion steps, this buffer holds one upsampled row group until it
  173637. * has been color converted and output.
  173638. * Note: we do not allocate any storage for component(s) which are full-size,
  173639. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173640. * simply set to point to the input data array, thereby avoiding copying.
  173641. */
  173642. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173643. /* Per-component upsampling method pointers */
  173644. upsample1_ptr methods[MAX_COMPONENTS];
  173645. int next_row_out; /* counts rows emitted from color_buf */
  173646. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173647. /* Height of an input row group for each component. */
  173648. int rowgroup_height[MAX_COMPONENTS];
  173649. /* These arrays save pixel expansion factors so that int_expand need not
  173650. * recompute them each time. They are unused for other upsampling methods.
  173651. */
  173652. UINT8 h_expand[MAX_COMPONENTS];
  173653. UINT8 v_expand[MAX_COMPONENTS];
  173654. } my_upsampler2;
  173655. typedef my_upsampler2 * my_upsample_ptr2;
  173656. /*
  173657. * Initialize for an upsampling pass.
  173658. */
  173659. METHODDEF(void)
  173660. start_pass_upsample (j_decompress_ptr cinfo)
  173661. {
  173662. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173663. /* Mark the conversion buffer empty */
  173664. upsample->next_row_out = cinfo->max_v_samp_factor;
  173665. /* Initialize total-height counter for detecting bottom of image */
  173666. upsample->rows_to_go = cinfo->output_height;
  173667. }
  173668. /*
  173669. * Control routine to do upsampling (and color conversion).
  173670. *
  173671. * In this version we upsample each component independently.
  173672. * We upsample one row group into the conversion buffer, then apply
  173673. * color conversion a row at a time.
  173674. */
  173675. METHODDEF(void)
  173676. sep_upsample (j_decompress_ptr cinfo,
  173677. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173678. JDIMENSION,
  173679. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173680. JDIMENSION out_rows_avail)
  173681. {
  173682. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173683. int ci;
  173684. jpeg_component_info * compptr;
  173685. JDIMENSION num_rows;
  173686. /* Fill the conversion buffer, if it's empty */
  173687. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173688. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173689. ci++, compptr++) {
  173690. /* Invoke per-component upsample method. Notice we pass a POINTER
  173691. * to color_buf[ci], so that fullsize_upsample can change it.
  173692. */
  173693. (*upsample->methods[ci]) (cinfo, compptr,
  173694. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173695. upsample->color_buf + ci);
  173696. }
  173697. upsample->next_row_out = 0;
  173698. }
  173699. /* Color-convert and emit rows */
  173700. /* How many we have in the buffer: */
  173701. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173702. /* Not more than the distance to the end of the image. Need this test
  173703. * in case the image height is not a multiple of max_v_samp_factor:
  173704. */
  173705. if (num_rows > upsample->rows_to_go)
  173706. num_rows = upsample->rows_to_go;
  173707. /* And not more than what the client can accept: */
  173708. out_rows_avail -= *out_row_ctr;
  173709. if (num_rows > out_rows_avail)
  173710. num_rows = out_rows_avail;
  173711. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173712. (JDIMENSION) upsample->next_row_out,
  173713. output_buf + *out_row_ctr,
  173714. (int) num_rows);
  173715. /* Adjust counts */
  173716. *out_row_ctr += num_rows;
  173717. upsample->rows_to_go -= num_rows;
  173718. upsample->next_row_out += num_rows;
  173719. /* When the buffer is emptied, declare this input row group consumed */
  173720. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173721. (*in_row_group_ctr)++;
  173722. }
  173723. /*
  173724. * These are the routines invoked by sep_upsample to upsample pixel values
  173725. * of a single component. One row group is processed per call.
  173726. */
  173727. /*
  173728. * For full-size components, we just make color_buf[ci] point at the
  173729. * input buffer, and thus avoid copying any data. Note that this is
  173730. * safe only because sep_upsample doesn't declare the input row group
  173731. * "consumed" until we are done color converting and emitting it.
  173732. */
  173733. METHODDEF(void)
  173734. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173735. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173736. {
  173737. *output_data_ptr = input_data;
  173738. }
  173739. /*
  173740. * This is a no-op version used for "uninteresting" components.
  173741. * These components will not be referenced by color conversion.
  173742. */
  173743. METHODDEF(void)
  173744. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173745. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173746. {
  173747. *output_data_ptr = NULL; /* safety check */
  173748. }
  173749. /*
  173750. * This version handles any integral sampling ratios.
  173751. * This is not used for typical JPEG files, so it need not be fast.
  173752. * Nor, for that matter, is it particularly accurate: the algorithm is
  173753. * simple replication of the input pixel onto the corresponding output
  173754. * pixels. The hi-falutin sampling literature refers to this as a
  173755. * "box filter". A box filter tends to introduce visible artifacts,
  173756. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173757. * you would be well advised to improve this code.
  173758. */
  173759. METHODDEF(void)
  173760. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173761. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173762. {
  173763. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173764. JSAMPARRAY output_data = *output_data_ptr;
  173765. register JSAMPROW inptr, outptr;
  173766. register JSAMPLE invalue;
  173767. register int h;
  173768. JSAMPROW outend;
  173769. int h_expand, v_expand;
  173770. int inrow, outrow;
  173771. h_expand = upsample->h_expand[compptr->component_index];
  173772. v_expand = upsample->v_expand[compptr->component_index];
  173773. inrow = outrow = 0;
  173774. while (outrow < cinfo->max_v_samp_factor) {
  173775. /* Generate one output row with proper horizontal expansion */
  173776. inptr = input_data[inrow];
  173777. outptr = output_data[outrow];
  173778. outend = outptr + cinfo->output_width;
  173779. while (outptr < outend) {
  173780. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173781. for (h = h_expand; h > 0; h--) {
  173782. *outptr++ = invalue;
  173783. }
  173784. }
  173785. /* Generate any additional output rows by duplicating the first one */
  173786. if (v_expand > 1) {
  173787. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173788. v_expand-1, cinfo->output_width);
  173789. }
  173790. inrow++;
  173791. outrow += v_expand;
  173792. }
  173793. }
  173794. /*
  173795. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173796. * It's still a box filter.
  173797. */
  173798. METHODDEF(void)
  173799. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173800. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173801. {
  173802. JSAMPARRAY output_data = *output_data_ptr;
  173803. register JSAMPROW inptr, outptr;
  173804. register JSAMPLE invalue;
  173805. JSAMPROW outend;
  173806. int inrow;
  173807. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173808. inptr = input_data[inrow];
  173809. outptr = output_data[inrow];
  173810. outend = outptr + cinfo->output_width;
  173811. while (outptr < outend) {
  173812. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173813. *outptr++ = invalue;
  173814. *outptr++ = invalue;
  173815. }
  173816. }
  173817. }
  173818. /*
  173819. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173820. * It's still a box filter.
  173821. */
  173822. METHODDEF(void)
  173823. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173824. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173825. {
  173826. JSAMPARRAY output_data = *output_data_ptr;
  173827. register JSAMPROW inptr, outptr;
  173828. register JSAMPLE invalue;
  173829. JSAMPROW outend;
  173830. int inrow, outrow;
  173831. inrow = outrow = 0;
  173832. while (outrow < cinfo->max_v_samp_factor) {
  173833. inptr = input_data[inrow];
  173834. outptr = output_data[outrow];
  173835. outend = outptr + cinfo->output_width;
  173836. while (outptr < outend) {
  173837. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173838. *outptr++ = invalue;
  173839. *outptr++ = invalue;
  173840. }
  173841. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173842. 1, cinfo->output_width);
  173843. inrow++;
  173844. outrow += 2;
  173845. }
  173846. }
  173847. /*
  173848. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173849. *
  173850. * The upsampling algorithm is linear interpolation between pixel centers,
  173851. * also known as a "triangle filter". This is a good compromise between
  173852. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173853. * of the way between input pixel centers.
  173854. *
  173855. * A note about the "bias" calculations: when rounding fractional values to
  173856. * integer, we do not want to always round 0.5 up to the next integer.
  173857. * If we did that, we'd introduce a noticeable bias towards larger values.
  173858. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173859. * alternate pixel locations (a simple ordered dither pattern).
  173860. */
  173861. METHODDEF(void)
  173862. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173863. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173864. {
  173865. JSAMPARRAY output_data = *output_data_ptr;
  173866. register JSAMPROW inptr, outptr;
  173867. register int invalue;
  173868. register JDIMENSION colctr;
  173869. int inrow;
  173870. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173871. inptr = input_data[inrow];
  173872. outptr = output_data[inrow];
  173873. /* Special case for first column */
  173874. invalue = GETJSAMPLE(*inptr++);
  173875. *outptr++ = (JSAMPLE) invalue;
  173876. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173877. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173878. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173879. invalue = GETJSAMPLE(*inptr++) * 3;
  173880. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173881. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173882. }
  173883. /* Special case for last column */
  173884. invalue = GETJSAMPLE(*inptr);
  173885. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173886. *outptr++ = (JSAMPLE) invalue;
  173887. }
  173888. }
  173889. /*
  173890. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173891. * Again a triangle filter; see comments for h2v1 case, above.
  173892. *
  173893. * It is OK for us to reference the adjacent input rows because we demanded
  173894. * context from the main buffer controller (see initialization code).
  173895. */
  173896. METHODDEF(void)
  173897. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173898. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173899. {
  173900. JSAMPARRAY output_data = *output_data_ptr;
  173901. register JSAMPROW inptr0, inptr1, outptr;
  173902. #if BITS_IN_JSAMPLE == 8
  173903. register int thiscolsum, lastcolsum, nextcolsum;
  173904. #else
  173905. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173906. #endif
  173907. register JDIMENSION colctr;
  173908. int inrow, outrow, v;
  173909. inrow = outrow = 0;
  173910. while (outrow < cinfo->max_v_samp_factor) {
  173911. for (v = 0; v < 2; v++) {
  173912. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173913. inptr0 = input_data[inrow];
  173914. if (v == 0) /* next nearest is row above */
  173915. inptr1 = input_data[inrow-1];
  173916. else /* next nearest is row below */
  173917. inptr1 = input_data[inrow+1];
  173918. outptr = output_data[outrow++];
  173919. /* Special case for first column */
  173920. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173921. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173922. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173923. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173924. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173925. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173926. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173927. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173928. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173929. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173930. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173931. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173932. }
  173933. /* Special case for last column */
  173934. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173935. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173936. }
  173937. inrow++;
  173938. }
  173939. }
  173940. /*
  173941. * Module initialization routine for upsampling.
  173942. */
  173943. GLOBAL(void)
  173944. jinit_upsampler (j_decompress_ptr cinfo)
  173945. {
  173946. my_upsample_ptr2 upsample;
  173947. int ci;
  173948. jpeg_component_info * compptr;
  173949. boolean need_buffer, do_fancy;
  173950. int h_in_group, v_in_group, h_out_group, v_out_group;
  173951. upsample = (my_upsample_ptr2)
  173952. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173953. SIZEOF(my_upsampler2));
  173954. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173955. upsample->pub.start_pass = start_pass_upsample;
  173956. upsample->pub.upsample = sep_upsample;
  173957. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173958. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173959. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173960. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173961. * so don't ask for it.
  173962. */
  173963. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173964. /* Verify we can handle the sampling factors, select per-component methods,
  173965. * and create storage as needed.
  173966. */
  173967. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173968. ci++, compptr++) {
  173969. /* Compute size of an "input group" after IDCT scaling. This many samples
  173970. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173971. */
  173972. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173973. cinfo->min_DCT_scaled_size;
  173974. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173975. cinfo->min_DCT_scaled_size;
  173976. h_out_group = cinfo->max_h_samp_factor;
  173977. v_out_group = cinfo->max_v_samp_factor;
  173978. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173979. need_buffer = TRUE;
  173980. if (! compptr->component_needed) {
  173981. /* Don't bother to upsample an uninteresting component. */
  173982. upsample->methods[ci] = noop_upsample;
  173983. need_buffer = FALSE;
  173984. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173985. /* Fullsize components can be processed without any work. */
  173986. upsample->methods[ci] = fullsize_upsample;
  173987. need_buffer = FALSE;
  173988. } else if (h_in_group * 2 == h_out_group &&
  173989. v_in_group == v_out_group) {
  173990. /* Special cases for 2h1v upsampling */
  173991. if (do_fancy && compptr->downsampled_width > 2)
  173992. upsample->methods[ci] = h2v1_fancy_upsample;
  173993. else
  173994. upsample->methods[ci] = h2v1_upsample;
  173995. } else if (h_in_group * 2 == h_out_group &&
  173996. v_in_group * 2 == v_out_group) {
  173997. /* Special cases for 2h2v upsampling */
  173998. if (do_fancy && compptr->downsampled_width > 2) {
  173999. upsample->methods[ci] = h2v2_fancy_upsample;
  174000. upsample->pub.need_context_rows = TRUE;
  174001. } else
  174002. upsample->methods[ci] = h2v2_upsample;
  174003. } else if ((h_out_group % h_in_group) == 0 &&
  174004. (v_out_group % v_in_group) == 0) {
  174005. /* Generic integral-factors upsampling method */
  174006. upsample->methods[ci] = int_upsample;
  174007. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174008. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174009. } else
  174010. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174011. if (need_buffer) {
  174012. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174013. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174014. (JDIMENSION) jround_up((long) cinfo->output_width,
  174015. (long) cinfo->max_h_samp_factor),
  174016. (JDIMENSION) cinfo->max_v_samp_factor);
  174017. }
  174018. }
  174019. }
  174020. /*** End of inlined file: jdsample.c ***/
  174021. /*** Start of inlined file: jdtrans.c ***/
  174022. #define JPEG_INTERNALS
  174023. /* Forward declarations */
  174024. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174025. /*
  174026. * Read the coefficient arrays from a JPEG file.
  174027. * jpeg_read_header must be completed before calling this.
  174028. *
  174029. * The entire image is read into a set of virtual coefficient-block arrays,
  174030. * one per component. The return value is a pointer to the array of
  174031. * virtual-array descriptors. These can be manipulated directly via the
  174032. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174033. * To release the memory occupied by the virtual arrays, call
  174034. * jpeg_finish_decompress() when done with the data.
  174035. *
  174036. * An alternative usage is to simply obtain access to the coefficient arrays
  174037. * during a buffered-image-mode decompression operation. This is allowed
  174038. * after any jpeg_finish_output() call. The arrays can be accessed until
  174039. * jpeg_finish_decompress() is called. (Note that any call to the library
  174040. * may reposition the arrays, so don't rely on access_virt_barray() results
  174041. * to stay valid across library calls.)
  174042. *
  174043. * Returns NULL if suspended. This case need be checked only if
  174044. * a suspending data source is used.
  174045. */
  174046. GLOBAL(jvirt_barray_ptr *)
  174047. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174048. {
  174049. if (cinfo->global_state == DSTATE_READY) {
  174050. /* First call: initialize active modules */
  174051. transdecode_master_selection(cinfo);
  174052. cinfo->global_state = DSTATE_RDCOEFS;
  174053. }
  174054. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174055. /* Absorb whole file into the coef buffer */
  174056. for (;;) {
  174057. int retcode;
  174058. /* Call progress monitor hook if present */
  174059. if (cinfo->progress != NULL)
  174060. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174061. /* Absorb some more input */
  174062. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174063. if (retcode == JPEG_SUSPENDED)
  174064. return NULL;
  174065. if (retcode == JPEG_REACHED_EOI)
  174066. break;
  174067. /* Advance progress counter if appropriate */
  174068. if (cinfo->progress != NULL &&
  174069. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174070. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174071. /* startup underestimated number of scans; ratchet up one scan */
  174072. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174073. }
  174074. }
  174075. }
  174076. /* Set state so that jpeg_finish_decompress does the right thing */
  174077. cinfo->global_state = DSTATE_STOPPING;
  174078. }
  174079. /* At this point we should be in state DSTATE_STOPPING if being used
  174080. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174081. * to the coefficients during a full buffered-image-mode decompression.
  174082. */
  174083. if ((cinfo->global_state == DSTATE_STOPPING ||
  174084. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174085. return cinfo->coef->coef_arrays;
  174086. }
  174087. /* Oops, improper usage */
  174088. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174089. return NULL; /* keep compiler happy */
  174090. }
  174091. /*
  174092. * Master selection of decompression modules for transcoding.
  174093. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174094. */
  174095. LOCAL(void)
  174096. transdecode_master_selection (j_decompress_ptr cinfo)
  174097. {
  174098. /* This is effectively a buffered-image operation. */
  174099. cinfo->buffered_image = TRUE;
  174100. /* Entropy decoding: either Huffman or arithmetic coding. */
  174101. if (cinfo->arith_code) {
  174102. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174103. } else {
  174104. if (cinfo->progressive_mode) {
  174105. #ifdef D_PROGRESSIVE_SUPPORTED
  174106. jinit_phuff_decoder(cinfo);
  174107. #else
  174108. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174109. #endif
  174110. } else
  174111. jinit_huff_decoder(cinfo);
  174112. }
  174113. /* Always get a full-image coefficient buffer. */
  174114. jinit_d_coef_controller(cinfo, TRUE);
  174115. /* We can now tell the memory manager to allocate virtual arrays. */
  174116. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174117. /* Initialize input side of decompressor to consume first scan. */
  174118. (*cinfo->inputctl->start_input_pass) (cinfo);
  174119. /* Initialize progress monitoring. */
  174120. if (cinfo->progress != NULL) {
  174121. int nscans;
  174122. /* Estimate number of scans to set pass_limit. */
  174123. if (cinfo->progressive_mode) {
  174124. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174125. nscans = 2 + 3 * cinfo->num_components;
  174126. } else if (cinfo->inputctl->has_multiple_scans) {
  174127. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174128. nscans = cinfo->num_components;
  174129. } else {
  174130. nscans = 1;
  174131. }
  174132. cinfo->progress->pass_counter = 0L;
  174133. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174134. cinfo->progress->completed_passes = 0;
  174135. cinfo->progress->total_passes = 1;
  174136. }
  174137. }
  174138. /*** End of inlined file: jdtrans.c ***/
  174139. /*** Start of inlined file: jfdctflt.c ***/
  174140. #define JPEG_INTERNALS
  174141. #ifdef DCT_FLOAT_SUPPORTED
  174142. /*
  174143. * This module is specialized to the case DCTSIZE = 8.
  174144. */
  174145. #if DCTSIZE != 8
  174146. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174147. #endif
  174148. /*
  174149. * Perform the forward DCT on one block of samples.
  174150. */
  174151. GLOBAL(void)
  174152. jpeg_fdct_float (FAST_FLOAT * data)
  174153. {
  174154. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174155. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174156. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174157. FAST_FLOAT *dataptr;
  174158. int ctr;
  174159. /* Pass 1: process rows. */
  174160. dataptr = data;
  174161. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174162. tmp0 = dataptr[0] + dataptr[7];
  174163. tmp7 = dataptr[0] - dataptr[7];
  174164. tmp1 = dataptr[1] + dataptr[6];
  174165. tmp6 = dataptr[1] - dataptr[6];
  174166. tmp2 = dataptr[2] + dataptr[5];
  174167. tmp5 = dataptr[2] - dataptr[5];
  174168. tmp3 = dataptr[3] + dataptr[4];
  174169. tmp4 = dataptr[3] - dataptr[4];
  174170. /* Even part */
  174171. tmp10 = tmp0 + tmp3; /* phase 2 */
  174172. tmp13 = tmp0 - tmp3;
  174173. tmp11 = tmp1 + tmp2;
  174174. tmp12 = tmp1 - tmp2;
  174175. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174176. dataptr[4] = tmp10 - tmp11;
  174177. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174178. dataptr[2] = tmp13 + z1; /* phase 5 */
  174179. dataptr[6] = tmp13 - z1;
  174180. /* Odd part */
  174181. tmp10 = tmp4 + tmp5; /* phase 2 */
  174182. tmp11 = tmp5 + tmp6;
  174183. tmp12 = tmp6 + tmp7;
  174184. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174185. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174186. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174187. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174188. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174189. z11 = tmp7 + z3; /* phase 5 */
  174190. z13 = tmp7 - z3;
  174191. dataptr[5] = z13 + z2; /* phase 6 */
  174192. dataptr[3] = z13 - z2;
  174193. dataptr[1] = z11 + z4;
  174194. dataptr[7] = z11 - z4;
  174195. dataptr += DCTSIZE; /* advance pointer to next row */
  174196. }
  174197. /* Pass 2: process columns. */
  174198. dataptr = data;
  174199. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174200. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174201. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174202. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174203. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174204. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174205. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174206. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174207. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174208. /* Even part */
  174209. tmp10 = tmp0 + tmp3; /* phase 2 */
  174210. tmp13 = tmp0 - tmp3;
  174211. tmp11 = tmp1 + tmp2;
  174212. tmp12 = tmp1 - tmp2;
  174213. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174214. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174215. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174216. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174217. dataptr[DCTSIZE*6] = tmp13 - z1;
  174218. /* Odd part */
  174219. tmp10 = tmp4 + tmp5; /* phase 2 */
  174220. tmp11 = tmp5 + tmp6;
  174221. tmp12 = tmp6 + tmp7;
  174222. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174223. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174224. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174225. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174226. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174227. z11 = tmp7 + z3; /* phase 5 */
  174228. z13 = tmp7 - z3;
  174229. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174230. dataptr[DCTSIZE*3] = z13 - z2;
  174231. dataptr[DCTSIZE*1] = z11 + z4;
  174232. dataptr[DCTSIZE*7] = z11 - z4;
  174233. dataptr++; /* advance pointer to next column */
  174234. }
  174235. }
  174236. #endif /* DCT_FLOAT_SUPPORTED */
  174237. /*** End of inlined file: jfdctflt.c ***/
  174238. /*** Start of inlined file: jfdctint.c ***/
  174239. #define JPEG_INTERNALS
  174240. #ifdef DCT_ISLOW_SUPPORTED
  174241. /*
  174242. * This module is specialized to the case DCTSIZE = 8.
  174243. */
  174244. #if DCTSIZE != 8
  174245. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174246. #endif
  174247. /*
  174248. * The poop on this scaling stuff is as follows:
  174249. *
  174250. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174251. * larger than the true DCT outputs. The final outputs are therefore
  174252. * a factor of N larger than desired; since N=8 this can be cured by
  174253. * a simple right shift at the end of the algorithm. The advantage of
  174254. * this arrangement is that we save two multiplications per 1-D DCT,
  174255. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174256. * In the IJG code, this factor of 8 is removed by the quantization step
  174257. * (in jcdctmgr.c), NOT in this module.
  174258. *
  174259. * We have to do addition and subtraction of the integer inputs, which
  174260. * is no problem, and multiplication by fractional constants, which is
  174261. * a problem to do in integer arithmetic. We multiply all the constants
  174262. * by CONST_SCALE and convert them to integer constants (thus retaining
  174263. * CONST_BITS bits of precision in the constants). After doing a
  174264. * multiplication we have to divide the product by CONST_SCALE, with proper
  174265. * rounding, to produce the correct output. This division can be done
  174266. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174267. * as long as possible so that partial sums can be added together with
  174268. * full fractional precision.
  174269. *
  174270. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174271. * they are represented to better-than-integral precision. These outputs
  174272. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174273. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174274. * array is INT32 anyway.)
  174275. *
  174276. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174277. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174278. * shows that the values given below are the most effective.
  174279. */
  174280. #if BITS_IN_JSAMPLE == 8
  174281. #define CONST_BITS 13
  174282. #define PASS1_BITS 2
  174283. #else
  174284. #define CONST_BITS 13
  174285. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174286. #endif
  174287. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174288. * causing a lot of useless floating-point operations at run time.
  174289. * To get around this we use the following pre-calculated constants.
  174290. * If you change CONST_BITS you may want to add appropriate values.
  174291. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174292. */
  174293. #if CONST_BITS == 13
  174294. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174295. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174296. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174297. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174298. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174299. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174300. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174301. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174302. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174303. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174304. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174305. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174306. #else
  174307. #define FIX_0_298631336 FIX(0.298631336)
  174308. #define FIX_0_390180644 FIX(0.390180644)
  174309. #define FIX_0_541196100 FIX(0.541196100)
  174310. #define FIX_0_765366865 FIX(0.765366865)
  174311. #define FIX_0_899976223 FIX(0.899976223)
  174312. #define FIX_1_175875602 FIX(1.175875602)
  174313. #define FIX_1_501321110 FIX(1.501321110)
  174314. #define FIX_1_847759065 FIX(1.847759065)
  174315. #define FIX_1_961570560 FIX(1.961570560)
  174316. #define FIX_2_053119869 FIX(2.053119869)
  174317. #define FIX_2_562915447 FIX(2.562915447)
  174318. #define FIX_3_072711026 FIX(3.072711026)
  174319. #endif
  174320. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174321. * For 8-bit samples with the recommended scaling, all the variable
  174322. * and constant values involved are no more than 16 bits wide, so a
  174323. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174324. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174325. */
  174326. #if BITS_IN_JSAMPLE == 8
  174327. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174328. #else
  174329. #define MULTIPLY(var,const) ((var) * (const))
  174330. #endif
  174331. /*
  174332. * Perform the forward DCT on one block of samples.
  174333. */
  174334. GLOBAL(void)
  174335. jpeg_fdct_islow (DCTELEM * data)
  174336. {
  174337. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174338. INT32 tmp10, tmp11, tmp12, tmp13;
  174339. INT32 z1, z2, z3, z4, z5;
  174340. DCTELEM *dataptr;
  174341. int ctr;
  174342. SHIFT_TEMPS
  174343. /* Pass 1: process rows. */
  174344. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174345. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174346. dataptr = data;
  174347. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174348. tmp0 = dataptr[0] + dataptr[7];
  174349. tmp7 = dataptr[0] - dataptr[7];
  174350. tmp1 = dataptr[1] + dataptr[6];
  174351. tmp6 = dataptr[1] - dataptr[6];
  174352. tmp2 = dataptr[2] + dataptr[5];
  174353. tmp5 = dataptr[2] - dataptr[5];
  174354. tmp3 = dataptr[3] + dataptr[4];
  174355. tmp4 = dataptr[3] - dataptr[4];
  174356. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174357. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174358. */
  174359. tmp10 = tmp0 + tmp3;
  174360. tmp13 = tmp0 - tmp3;
  174361. tmp11 = tmp1 + tmp2;
  174362. tmp12 = tmp1 - tmp2;
  174363. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174364. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174365. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174366. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174367. CONST_BITS-PASS1_BITS);
  174368. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174369. CONST_BITS-PASS1_BITS);
  174370. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174371. * cK represents cos(K*pi/16).
  174372. * i0..i3 in the paper are tmp4..tmp7 here.
  174373. */
  174374. z1 = tmp4 + tmp7;
  174375. z2 = tmp5 + tmp6;
  174376. z3 = tmp4 + tmp6;
  174377. z4 = tmp5 + tmp7;
  174378. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174379. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174380. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174381. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174382. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174383. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174384. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174385. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174386. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174387. z3 += z5;
  174388. z4 += z5;
  174389. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174390. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174391. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174392. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174393. dataptr += DCTSIZE; /* advance pointer to next row */
  174394. }
  174395. /* Pass 2: process columns.
  174396. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174397. * by an overall factor of 8.
  174398. */
  174399. dataptr = data;
  174400. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174401. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174402. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174403. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174404. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174405. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174406. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174407. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174408. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174409. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174410. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174411. */
  174412. tmp10 = tmp0 + tmp3;
  174413. tmp13 = tmp0 - tmp3;
  174414. tmp11 = tmp1 + tmp2;
  174415. tmp12 = tmp1 - tmp2;
  174416. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174417. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174418. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174419. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174420. CONST_BITS+PASS1_BITS);
  174421. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174422. CONST_BITS+PASS1_BITS);
  174423. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174424. * cK represents cos(K*pi/16).
  174425. * i0..i3 in the paper are tmp4..tmp7 here.
  174426. */
  174427. z1 = tmp4 + tmp7;
  174428. z2 = tmp5 + tmp6;
  174429. z3 = tmp4 + tmp6;
  174430. z4 = tmp5 + tmp7;
  174431. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174432. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174433. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174434. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174435. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174436. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174437. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174438. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174439. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174440. z3 += z5;
  174441. z4 += z5;
  174442. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174443. CONST_BITS+PASS1_BITS);
  174444. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174445. CONST_BITS+PASS1_BITS);
  174446. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174447. CONST_BITS+PASS1_BITS);
  174448. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174449. CONST_BITS+PASS1_BITS);
  174450. dataptr++; /* advance pointer to next column */
  174451. }
  174452. }
  174453. #endif /* DCT_ISLOW_SUPPORTED */
  174454. /*** End of inlined file: jfdctint.c ***/
  174455. #undef CONST_BITS
  174456. #undef MULTIPLY
  174457. #undef FIX_0_541196100
  174458. /*** Start of inlined file: jfdctfst.c ***/
  174459. #define JPEG_INTERNALS
  174460. #ifdef DCT_IFAST_SUPPORTED
  174461. /*
  174462. * This module is specialized to the case DCTSIZE = 8.
  174463. */
  174464. #if DCTSIZE != 8
  174465. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174466. #endif
  174467. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174468. * see jfdctint.c for more details. However, we choose to descale
  174469. * (right shift) multiplication products as soon as they are formed,
  174470. * rather than carrying additional fractional bits into subsequent additions.
  174471. * This compromises accuracy slightly, but it lets us save a few shifts.
  174472. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174473. * everywhere except in the multiplications proper; this saves a good deal
  174474. * of work on 16-bit-int machines.
  174475. *
  174476. * Again to save a few shifts, the intermediate results between pass 1 and
  174477. * pass 2 are not upscaled, but are represented only to integral precision.
  174478. *
  174479. * A final compromise is to represent the multiplicative constants to only
  174480. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174481. * machines, and may also reduce the cost of multiplication (since there
  174482. * are fewer one-bits in the constants).
  174483. */
  174484. #define CONST_BITS 8
  174485. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174486. * causing a lot of useless floating-point operations at run time.
  174487. * To get around this we use the following pre-calculated constants.
  174488. * If you change CONST_BITS you may want to add appropriate values.
  174489. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174490. */
  174491. #if CONST_BITS == 8
  174492. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174493. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174494. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174495. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174496. #else
  174497. #define FIX_0_382683433 FIX(0.382683433)
  174498. #define FIX_0_541196100 FIX(0.541196100)
  174499. #define FIX_0_707106781 FIX(0.707106781)
  174500. #define FIX_1_306562965 FIX(1.306562965)
  174501. #endif
  174502. /* We can gain a little more speed, with a further compromise in accuracy,
  174503. * by omitting the addition in a descaling shift. This yields an incorrectly
  174504. * rounded result half the time...
  174505. */
  174506. #ifndef USE_ACCURATE_ROUNDING
  174507. #undef DESCALE
  174508. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174509. #endif
  174510. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174511. * descale to yield a DCTELEM result.
  174512. */
  174513. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174514. /*
  174515. * Perform the forward DCT on one block of samples.
  174516. */
  174517. GLOBAL(void)
  174518. jpeg_fdct_ifast (DCTELEM * data)
  174519. {
  174520. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174521. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174522. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174523. DCTELEM *dataptr;
  174524. int ctr;
  174525. SHIFT_TEMPS
  174526. /* Pass 1: process rows. */
  174527. dataptr = data;
  174528. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174529. tmp0 = dataptr[0] + dataptr[7];
  174530. tmp7 = dataptr[0] - dataptr[7];
  174531. tmp1 = dataptr[1] + dataptr[6];
  174532. tmp6 = dataptr[1] - dataptr[6];
  174533. tmp2 = dataptr[2] + dataptr[5];
  174534. tmp5 = dataptr[2] - dataptr[5];
  174535. tmp3 = dataptr[3] + dataptr[4];
  174536. tmp4 = dataptr[3] - dataptr[4];
  174537. /* Even part */
  174538. tmp10 = tmp0 + tmp3; /* phase 2 */
  174539. tmp13 = tmp0 - tmp3;
  174540. tmp11 = tmp1 + tmp2;
  174541. tmp12 = tmp1 - tmp2;
  174542. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174543. dataptr[4] = tmp10 - tmp11;
  174544. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174545. dataptr[2] = tmp13 + z1; /* phase 5 */
  174546. dataptr[6] = tmp13 - z1;
  174547. /* Odd part */
  174548. tmp10 = tmp4 + tmp5; /* phase 2 */
  174549. tmp11 = tmp5 + tmp6;
  174550. tmp12 = tmp6 + tmp7;
  174551. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174552. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174553. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174554. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174555. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174556. z11 = tmp7 + z3; /* phase 5 */
  174557. z13 = tmp7 - z3;
  174558. dataptr[5] = z13 + z2; /* phase 6 */
  174559. dataptr[3] = z13 - z2;
  174560. dataptr[1] = z11 + z4;
  174561. dataptr[7] = z11 - z4;
  174562. dataptr += DCTSIZE; /* advance pointer to next row */
  174563. }
  174564. /* Pass 2: process columns. */
  174565. dataptr = data;
  174566. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174567. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174568. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174569. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174570. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174571. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174572. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174573. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174574. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174575. /* Even part */
  174576. tmp10 = tmp0 + tmp3; /* phase 2 */
  174577. tmp13 = tmp0 - tmp3;
  174578. tmp11 = tmp1 + tmp2;
  174579. tmp12 = tmp1 - tmp2;
  174580. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174581. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174582. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174583. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174584. dataptr[DCTSIZE*6] = tmp13 - z1;
  174585. /* Odd part */
  174586. tmp10 = tmp4 + tmp5; /* phase 2 */
  174587. tmp11 = tmp5 + tmp6;
  174588. tmp12 = tmp6 + tmp7;
  174589. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174590. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174591. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174592. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174593. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174594. z11 = tmp7 + z3; /* phase 5 */
  174595. z13 = tmp7 - z3;
  174596. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174597. dataptr[DCTSIZE*3] = z13 - z2;
  174598. dataptr[DCTSIZE*1] = z11 + z4;
  174599. dataptr[DCTSIZE*7] = z11 - z4;
  174600. dataptr++; /* advance pointer to next column */
  174601. }
  174602. }
  174603. #endif /* DCT_IFAST_SUPPORTED */
  174604. /*** End of inlined file: jfdctfst.c ***/
  174605. #undef FIX_0_541196100
  174606. /*** Start of inlined file: jidctflt.c ***/
  174607. #define JPEG_INTERNALS
  174608. #ifdef DCT_FLOAT_SUPPORTED
  174609. /*
  174610. * This module is specialized to the case DCTSIZE = 8.
  174611. */
  174612. #if DCTSIZE != 8
  174613. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174614. #endif
  174615. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174616. * entry; produce a float result.
  174617. */
  174618. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174619. /*
  174620. * Perform dequantization and inverse DCT on one block of coefficients.
  174621. */
  174622. GLOBAL(void)
  174623. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174624. JCOEFPTR coef_block,
  174625. JSAMPARRAY output_buf, JDIMENSION output_col)
  174626. {
  174627. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174628. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174629. FAST_FLOAT z5, z10, z11, z12, z13;
  174630. JCOEFPTR inptr;
  174631. FLOAT_MULT_TYPE * quantptr;
  174632. FAST_FLOAT * wsptr;
  174633. JSAMPROW outptr;
  174634. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174635. int ctr;
  174636. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174637. SHIFT_TEMPS
  174638. /* Pass 1: process columns from input, store into work array. */
  174639. inptr = coef_block;
  174640. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174641. wsptr = workspace;
  174642. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174643. /* Due to quantization, we will usually find that many of the input
  174644. * coefficients are zero, especially the AC terms. We can exploit this
  174645. * by short-circuiting the IDCT calculation for any column in which all
  174646. * the AC terms are zero. In that case each output is equal to the
  174647. * DC coefficient (with scale factor as needed).
  174648. * With typical images and quantization tables, half or more of the
  174649. * column DCT calculations can be simplified this way.
  174650. */
  174651. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174652. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174653. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174654. inptr[DCTSIZE*7] == 0) {
  174655. /* AC terms all zero */
  174656. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174657. wsptr[DCTSIZE*0] = dcval;
  174658. wsptr[DCTSIZE*1] = dcval;
  174659. wsptr[DCTSIZE*2] = dcval;
  174660. wsptr[DCTSIZE*3] = dcval;
  174661. wsptr[DCTSIZE*4] = dcval;
  174662. wsptr[DCTSIZE*5] = dcval;
  174663. wsptr[DCTSIZE*6] = dcval;
  174664. wsptr[DCTSIZE*7] = dcval;
  174665. inptr++; /* advance pointers to next column */
  174666. quantptr++;
  174667. wsptr++;
  174668. continue;
  174669. }
  174670. /* Even part */
  174671. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174672. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174673. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174674. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174675. tmp10 = tmp0 + tmp2; /* phase 3 */
  174676. tmp11 = tmp0 - tmp2;
  174677. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174678. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174679. tmp0 = tmp10 + tmp13; /* phase 2 */
  174680. tmp3 = tmp10 - tmp13;
  174681. tmp1 = tmp11 + tmp12;
  174682. tmp2 = tmp11 - tmp12;
  174683. /* Odd part */
  174684. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174685. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174686. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174687. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174688. z13 = tmp6 + tmp5; /* phase 6 */
  174689. z10 = tmp6 - tmp5;
  174690. z11 = tmp4 + tmp7;
  174691. z12 = tmp4 - tmp7;
  174692. tmp7 = z11 + z13; /* phase 5 */
  174693. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174694. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174695. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174696. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174697. tmp6 = tmp12 - tmp7; /* phase 2 */
  174698. tmp5 = tmp11 - tmp6;
  174699. tmp4 = tmp10 + tmp5;
  174700. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174701. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174702. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174703. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174704. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174705. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174706. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174707. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174708. inptr++; /* advance pointers to next column */
  174709. quantptr++;
  174710. wsptr++;
  174711. }
  174712. /* Pass 2: process rows from work array, store into output array. */
  174713. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174714. wsptr = workspace;
  174715. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174716. outptr = output_buf[ctr] + output_col;
  174717. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174718. * However, the column calculation has created many nonzero AC terms, so
  174719. * the simplification applies less often (typically 5% to 10% of the time).
  174720. * And testing floats for zero is relatively expensive, so we don't bother.
  174721. */
  174722. /* Even part */
  174723. tmp10 = wsptr[0] + wsptr[4];
  174724. tmp11 = wsptr[0] - wsptr[4];
  174725. tmp13 = wsptr[2] + wsptr[6];
  174726. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174727. tmp0 = tmp10 + tmp13;
  174728. tmp3 = tmp10 - tmp13;
  174729. tmp1 = tmp11 + tmp12;
  174730. tmp2 = tmp11 - tmp12;
  174731. /* Odd part */
  174732. z13 = wsptr[5] + wsptr[3];
  174733. z10 = wsptr[5] - wsptr[3];
  174734. z11 = wsptr[1] + wsptr[7];
  174735. z12 = wsptr[1] - wsptr[7];
  174736. tmp7 = z11 + z13;
  174737. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174738. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174739. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174740. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174741. tmp6 = tmp12 - tmp7;
  174742. tmp5 = tmp11 - tmp6;
  174743. tmp4 = tmp10 + tmp5;
  174744. /* Final output stage: scale down by a factor of 8 and range-limit */
  174745. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174746. & RANGE_MASK];
  174747. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174748. & RANGE_MASK];
  174749. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174750. & RANGE_MASK];
  174751. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174752. & RANGE_MASK];
  174753. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174754. & RANGE_MASK];
  174755. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174756. & RANGE_MASK];
  174757. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174758. & RANGE_MASK];
  174759. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174760. & RANGE_MASK];
  174761. wsptr += DCTSIZE; /* advance pointer to next row */
  174762. }
  174763. }
  174764. #endif /* DCT_FLOAT_SUPPORTED */
  174765. /*** End of inlined file: jidctflt.c ***/
  174766. #undef CONST_BITS
  174767. #undef FIX_1_847759065
  174768. #undef MULTIPLY
  174769. #undef DEQUANTIZE
  174770. #undef DESCALE
  174771. /*** Start of inlined file: jidctfst.c ***/
  174772. #define JPEG_INTERNALS
  174773. #ifdef DCT_IFAST_SUPPORTED
  174774. /*
  174775. * This module is specialized to the case DCTSIZE = 8.
  174776. */
  174777. #if DCTSIZE != 8
  174778. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174779. #endif
  174780. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174781. * see jidctint.c for more details. However, we choose to descale
  174782. * (right shift) multiplication products as soon as they are formed,
  174783. * rather than carrying additional fractional bits into subsequent additions.
  174784. * This compromises accuracy slightly, but it lets us save a few shifts.
  174785. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174786. * everywhere except in the multiplications proper; this saves a good deal
  174787. * of work on 16-bit-int machines.
  174788. *
  174789. * The dequantized coefficients are not integers because the AA&N scaling
  174790. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174791. * so that the first and second IDCT rounds have the same input scaling.
  174792. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174793. * avoid a descaling shift; this compromises accuracy rather drastically
  174794. * for small quantization table entries, but it saves a lot of shifts.
  174795. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174796. * so we use a much larger scaling factor to preserve accuracy.
  174797. *
  174798. * A final compromise is to represent the multiplicative constants to only
  174799. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174800. * machines, and may also reduce the cost of multiplication (since there
  174801. * are fewer one-bits in the constants).
  174802. */
  174803. #if BITS_IN_JSAMPLE == 8
  174804. #define CONST_BITS 8
  174805. #define PASS1_BITS 2
  174806. #else
  174807. #define CONST_BITS 8
  174808. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174809. #endif
  174810. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174811. * causing a lot of useless floating-point operations at run time.
  174812. * To get around this we use the following pre-calculated constants.
  174813. * If you change CONST_BITS you may want to add appropriate values.
  174814. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174815. */
  174816. #if CONST_BITS == 8
  174817. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174818. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174819. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174820. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174821. #else
  174822. #define FIX_1_082392200 FIX(1.082392200)
  174823. #define FIX_1_414213562 FIX(1.414213562)
  174824. #define FIX_1_847759065 FIX(1.847759065)
  174825. #define FIX_2_613125930 FIX(2.613125930)
  174826. #endif
  174827. /* We can gain a little more speed, with a further compromise in accuracy,
  174828. * by omitting the addition in a descaling shift. This yields an incorrectly
  174829. * rounded result half the time...
  174830. */
  174831. #ifndef USE_ACCURATE_ROUNDING
  174832. #undef DESCALE
  174833. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174834. #endif
  174835. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174836. * descale to yield a DCTELEM result.
  174837. */
  174838. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174839. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174840. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174841. * multiplication will do. For 12-bit data, the multiplier table is
  174842. * declared INT32, so a 32-bit multiply will be used.
  174843. */
  174844. #if BITS_IN_JSAMPLE == 8
  174845. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174846. #else
  174847. #define DEQUANTIZE(coef,quantval) \
  174848. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174849. #endif
  174850. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174851. * We assume that int right shift is unsigned if INT32 right shift is.
  174852. */
  174853. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174854. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174855. #if BITS_IN_JSAMPLE == 8
  174856. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174857. #else
  174858. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174859. #endif
  174860. #define IRIGHT_SHIFT(x,shft) \
  174861. ((ishift_temp = (x)) < 0 ? \
  174862. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174863. (ishift_temp >> (shft)))
  174864. #else
  174865. #define ISHIFT_TEMPS
  174866. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174867. #endif
  174868. #ifdef USE_ACCURATE_ROUNDING
  174869. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174870. #else
  174871. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174872. #endif
  174873. /*
  174874. * Perform dequantization and inverse DCT on one block of coefficients.
  174875. */
  174876. GLOBAL(void)
  174877. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174878. JCOEFPTR coef_block,
  174879. JSAMPARRAY output_buf, JDIMENSION output_col)
  174880. {
  174881. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174882. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174883. DCTELEM z5, z10, z11, z12, z13;
  174884. JCOEFPTR inptr;
  174885. IFAST_MULT_TYPE * quantptr;
  174886. int * wsptr;
  174887. JSAMPROW outptr;
  174888. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174889. int ctr;
  174890. int workspace[DCTSIZE2]; /* buffers data between passes */
  174891. SHIFT_TEMPS /* for DESCALE */
  174892. ISHIFT_TEMPS /* for IDESCALE */
  174893. /* Pass 1: process columns from input, store into work array. */
  174894. inptr = coef_block;
  174895. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174896. wsptr = workspace;
  174897. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174898. /* Due to quantization, we will usually find that many of the input
  174899. * coefficients are zero, especially the AC terms. We can exploit this
  174900. * by short-circuiting the IDCT calculation for any column in which all
  174901. * the AC terms are zero. In that case each output is equal to the
  174902. * DC coefficient (with scale factor as needed).
  174903. * With typical images and quantization tables, half or more of the
  174904. * column DCT calculations can be simplified this way.
  174905. */
  174906. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174907. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174908. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174909. inptr[DCTSIZE*7] == 0) {
  174910. /* AC terms all zero */
  174911. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174912. wsptr[DCTSIZE*0] = dcval;
  174913. wsptr[DCTSIZE*1] = dcval;
  174914. wsptr[DCTSIZE*2] = dcval;
  174915. wsptr[DCTSIZE*3] = dcval;
  174916. wsptr[DCTSIZE*4] = dcval;
  174917. wsptr[DCTSIZE*5] = dcval;
  174918. wsptr[DCTSIZE*6] = dcval;
  174919. wsptr[DCTSIZE*7] = dcval;
  174920. inptr++; /* advance pointers to next column */
  174921. quantptr++;
  174922. wsptr++;
  174923. continue;
  174924. }
  174925. /* Even part */
  174926. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174927. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174928. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174929. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174930. tmp10 = tmp0 + tmp2; /* phase 3 */
  174931. tmp11 = tmp0 - tmp2;
  174932. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174933. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174934. tmp0 = tmp10 + tmp13; /* phase 2 */
  174935. tmp3 = tmp10 - tmp13;
  174936. tmp1 = tmp11 + tmp12;
  174937. tmp2 = tmp11 - tmp12;
  174938. /* Odd part */
  174939. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174940. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174941. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174942. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174943. z13 = tmp6 + tmp5; /* phase 6 */
  174944. z10 = tmp6 - tmp5;
  174945. z11 = tmp4 + tmp7;
  174946. z12 = tmp4 - tmp7;
  174947. tmp7 = z11 + z13; /* phase 5 */
  174948. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174949. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174950. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174951. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174952. tmp6 = tmp12 - tmp7; /* phase 2 */
  174953. tmp5 = tmp11 - tmp6;
  174954. tmp4 = tmp10 + tmp5;
  174955. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174956. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174957. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174958. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174959. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174960. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174961. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174962. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174963. inptr++; /* advance pointers to next column */
  174964. quantptr++;
  174965. wsptr++;
  174966. }
  174967. /* Pass 2: process rows from work array, store into output array. */
  174968. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174969. /* and also undo the PASS1_BITS scaling. */
  174970. wsptr = workspace;
  174971. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174972. outptr = output_buf[ctr] + output_col;
  174973. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174974. * However, the column calculation has created many nonzero AC terms, so
  174975. * the simplification applies less often (typically 5% to 10% of the time).
  174976. * On machines with very fast multiplication, it's possible that the
  174977. * test takes more time than it's worth. In that case this section
  174978. * may be commented out.
  174979. */
  174980. #ifndef NO_ZERO_ROW_TEST
  174981. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174982. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174983. /* AC terms all zero */
  174984. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174985. & RANGE_MASK];
  174986. outptr[0] = dcval;
  174987. outptr[1] = dcval;
  174988. outptr[2] = dcval;
  174989. outptr[3] = dcval;
  174990. outptr[4] = dcval;
  174991. outptr[5] = dcval;
  174992. outptr[6] = dcval;
  174993. outptr[7] = dcval;
  174994. wsptr += DCTSIZE; /* advance pointer to next row */
  174995. continue;
  174996. }
  174997. #endif
  174998. /* Even part */
  174999. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175000. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175001. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175002. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175003. - tmp13;
  175004. tmp0 = tmp10 + tmp13;
  175005. tmp3 = tmp10 - tmp13;
  175006. tmp1 = tmp11 + tmp12;
  175007. tmp2 = tmp11 - tmp12;
  175008. /* Odd part */
  175009. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175010. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175011. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175012. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175013. tmp7 = z11 + z13; /* phase 5 */
  175014. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175015. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175016. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175017. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175018. tmp6 = tmp12 - tmp7; /* phase 2 */
  175019. tmp5 = tmp11 - tmp6;
  175020. tmp4 = tmp10 + tmp5;
  175021. /* Final output stage: scale down by a factor of 8 and range-limit */
  175022. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175023. & RANGE_MASK];
  175024. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175025. & RANGE_MASK];
  175026. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175027. & RANGE_MASK];
  175028. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175029. & RANGE_MASK];
  175030. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175031. & RANGE_MASK];
  175032. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175033. & RANGE_MASK];
  175034. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175035. & RANGE_MASK];
  175036. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175037. & RANGE_MASK];
  175038. wsptr += DCTSIZE; /* advance pointer to next row */
  175039. }
  175040. }
  175041. #endif /* DCT_IFAST_SUPPORTED */
  175042. /*** End of inlined file: jidctfst.c ***/
  175043. #undef CONST_BITS
  175044. #undef FIX_1_847759065
  175045. #undef MULTIPLY
  175046. #undef DEQUANTIZE
  175047. /*** Start of inlined file: jidctint.c ***/
  175048. #define JPEG_INTERNALS
  175049. #ifdef DCT_ISLOW_SUPPORTED
  175050. /*
  175051. * This module is specialized to the case DCTSIZE = 8.
  175052. */
  175053. #if DCTSIZE != 8
  175054. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175055. #endif
  175056. /*
  175057. * The poop on this scaling stuff is as follows:
  175058. *
  175059. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175060. * larger than the true IDCT outputs. The final outputs are therefore
  175061. * a factor of N larger than desired; since N=8 this can be cured by
  175062. * a simple right shift at the end of the algorithm. The advantage of
  175063. * this arrangement is that we save two multiplications per 1-D IDCT,
  175064. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175065. *
  175066. * We have to do addition and subtraction of the integer inputs, which
  175067. * is no problem, and multiplication by fractional constants, which is
  175068. * a problem to do in integer arithmetic. We multiply all the constants
  175069. * by CONST_SCALE and convert them to integer constants (thus retaining
  175070. * CONST_BITS bits of precision in the constants). After doing a
  175071. * multiplication we have to divide the product by CONST_SCALE, with proper
  175072. * rounding, to produce the correct output. This division can be done
  175073. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175074. * as long as possible so that partial sums can be added together with
  175075. * full fractional precision.
  175076. *
  175077. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175078. * they are represented to better-than-integral precision. These outputs
  175079. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175080. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175081. * intermediate INT32 array would be needed.)
  175082. *
  175083. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175084. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175085. * shows that the values given below are the most effective.
  175086. */
  175087. #if BITS_IN_JSAMPLE == 8
  175088. #define CONST_BITS 13
  175089. #define PASS1_BITS 2
  175090. #else
  175091. #define CONST_BITS 13
  175092. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175093. #endif
  175094. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175095. * causing a lot of useless floating-point operations at run time.
  175096. * To get around this we use the following pre-calculated constants.
  175097. * If you change CONST_BITS you may want to add appropriate values.
  175098. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175099. */
  175100. #if CONST_BITS == 13
  175101. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175102. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175103. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175104. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175105. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175106. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175107. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175108. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175109. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175110. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175111. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175112. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175113. #else
  175114. #define FIX_0_298631336 FIX(0.298631336)
  175115. #define FIX_0_390180644 FIX(0.390180644)
  175116. #define FIX_0_541196100 FIX(0.541196100)
  175117. #define FIX_0_765366865 FIX(0.765366865)
  175118. #define FIX_0_899976223 FIX(0.899976223)
  175119. #define FIX_1_175875602 FIX(1.175875602)
  175120. #define FIX_1_501321110 FIX(1.501321110)
  175121. #define FIX_1_847759065 FIX(1.847759065)
  175122. #define FIX_1_961570560 FIX(1.961570560)
  175123. #define FIX_2_053119869 FIX(2.053119869)
  175124. #define FIX_2_562915447 FIX(2.562915447)
  175125. #define FIX_3_072711026 FIX(3.072711026)
  175126. #endif
  175127. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175128. * For 8-bit samples with the recommended scaling, all the variable
  175129. * and constant values involved are no more than 16 bits wide, so a
  175130. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175131. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175132. */
  175133. #if BITS_IN_JSAMPLE == 8
  175134. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175135. #else
  175136. #define MULTIPLY(var,const) ((var) * (const))
  175137. #endif
  175138. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175139. * entry; produce an int result. In this module, both inputs and result
  175140. * are 16 bits or less, so either int or short multiply will work.
  175141. */
  175142. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175143. /*
  175144. * Perform dequantization and inverse DCT on one block of coefficients.
  175145. */
  175146. GLOBAL(void)
  175147. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175148. JCOEFPTR coef_block,
  175149. JSAMPARRAY output_buf, JDIMENSION output_col)
  175150. {
  175151. INT32 tmp0, tmp1, tmp2, tmp3;
  175152. INT32 tmp10, tmp11, tmp12, tmp13;
  175153. INT32 z1, z2, z3, z4, z5;
  175154. JCOEFPTR inptr;
  175155. ISLOW_MULT_TYPE * quantptr;
  175156. int * wsptr;
  175157. JSAMPROW outptr;
  175158. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175159. int ctr;
  175160. int workspace[DCTSIZE2]; /* buffers data between passes */
  175161. SHIFT_TEMPS
  175162. /* Pass 1: process columns from input, store into work array. */
  175163. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175164. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175165. inptr = coef_block;
  175166. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175167. wsptr = workspace;
  175168. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175169. /* Due to quantization, we will usually find that many of the input
  175170. * coefficients are zero, especially the AC terms. We can exploit this
  175171. * by short-circuiting the IDCT calculation for any column in which all
  175172. * the AC terms are zero. In that case each output is equal to the
  175173. * DC coefficient (with scale factor as needed).
  175174. * With typical images and quantization tables, half or more of the
  175175. * column DCT calculations can be simplified this way.
  175176. */
  175177. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175178. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175179. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175180. inptr[DCTSIZE*7] == 0) {
  175181. /* AC terms all zero */
  175182. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175183. wsptr[DCTSIZE*0] = dcval;
  175184. wsptr[DCTSIZE*1] = dcval;
  175185. wsptr[DCTSIZE*2] = dcval;
  175186. wsptr[DCTSIZE*3] = dcval;
  175187. wsptr[DCTSIZE*4] = dcval;
  175188. wsptr[DCTSIZE*5] = dcval;
  175189. wsptr[DCTSIZE*6] = dcval;
  175190. wsptr[DCTSIZE*7] = dcval;
  175191. inptr++; /* advance pointers to next column */
  175192. quantptr++;
  175193. wsptr++;
  175194. continue;
  175195. }
  175196. /* Even part: reverse the even part of the forward DCT. */
  175197. /* The rotator is sqrt(2)*c(-6). */
  175198. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175199. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175200. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175201. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175202. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175203. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175204. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175205. tmp0 = (z2 + z3) << CONST_BITS;
  175206. tmp1 = (z2 - z3) << CONST_BITS;
  175207. tmp10 = tmp0 + tmp3;
  175208. tmp13 = tmp0 - tmp3;
  175209. tmp11 = tmp1 + tmp2;
  175210. tmp12 = tmp1 - tmp2;
  175211. /* Odd part per figure 8; the matrix is unitary and hence its
  175212. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175213. */
  175214. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175215. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175216. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175217. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175218. z1 = tmp0 + tmp3;
  175219. z2 = tmp1 + tmp2;
  175220. z3 = tmp0 + tmp2;
  175221. z4 = tmp1 + tmp3;
  175222. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175223. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175224. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175225. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175226. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175227. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175228. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175229. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175230. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175231. z3 += z5;
  175232. z4 += z5;
  175233. tmp0 += z1 + z3;
  175234. tmp1 += z2 + z4;
  175235. tmp2 += z2 + z3;
  175236. tmp3 += z1 + z4;
  175237. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175238. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175239. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175240. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175241. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175242. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175243. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175244. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175245. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175246. inptr++; /* advance pointers to next column */
  175247. quantptr++;
  175248. wsptr++;
  175249. }
  175250. /* Pass 2: process rows from work array, store into output array. */
  175251. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175252. /* and also undo the PASS1_BITS scaling. */
  175253. wsptr = workspace;
  175254. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175255. outptr = output_buf[ctr] + output_col;
  175256. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175257. * However, the column calculation has created many nonzero AC terms, so
  175258. * the simplification applies less often (typically 5% to 10% of the time).
  175259. * On machines with very fast multiplication, it's possible that the
  175260. * test takes more time than it's worth. In that case this section
  175261. * may be commented out.
  175262. */
  175263. #ifndef NO_ZERO_ROW_TEST
  175264. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175265. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175266. /* AC terms all zero */
  175267. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175268. & RANGE_MASK];
  175269. outptr[0] = dcval;
  175270. outptr[1] = dcval;
  175271. outptr[2] = dcval;
  175272. outptr[3] = dcval;
  175273. outptr[4] = dcval;
  175274. outptr[5] = dcval;
  175275. outptr[6] = dcval;
  175276. outptr[7] = dcval;
  175277. wsptr += DCTSIZE; /* advance pointer to next row */
  175278. continue;
  175279. }
  175280. #endif
  175281. /* Even part: reverse the even part of the forward DCT. */
  175282. /* The rotator is sqrt(2)*c(-6). */
  175283. z2 = (INT32) wsptr[2];
  175284. z3 = (INT32) wsptr[6];
  175285. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175286. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175287. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175288. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175289. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175290. tmp10 = tmp0 + tmp3;
  175291. tmp13 = tmp0 - tmp3;
  175292. tmp11 = tmp1 + tmp2;
  175293. tmp12 = tmp1 - tmp2;
  175294. /* Odd part per figure 8; the matrix is unitary and hence its
  175295. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175296. */
  175297. tmp0 = (INT32) wsptr[7];
  175298. tmp1 = (INT32) wsptr[5];
  175299. tmp2 = (INT32) wsptr[3];
  175300. tmp3 = (INT32) wsptr[1];
  175301. z1 = tmp0 + tmp3;
  175302. z2 = tmp1 + tmp2;
  175303. z3 = tmp0 + tmp2;
  175304. z4 = tmp1 + tmp3;
  175305. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175306. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175307. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175308. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175309. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175310. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175311. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175312. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175313. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175314. z3 += z5;
  175315. z4 += z5;
  175316. tmp0 += z1 + z3;
  175317. tmp1 += z2 + z4;
  175318. tmp2 += z2 + z3;
  175319. tmp3 += z1 + z4;
  175320. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175321. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175322. CONST_BITS+PASS1_BITS+3)
  175323. & RANGE_MASK];
  175324. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175325. CONST_BITS+PASS1_BITS+3)
  175326. & RANGE_MASK];
  175327. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175328. CONST_BITS+PASS1_BITS+3)
  175329. & RANGE_MASK];
  175330. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175331. CONST_BITS+PASS1_BITS+3)
  175332. & RANGE_MASK];
  175333. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175334. CONST_BITS+PASS1_BITS+3)
  175335. & RANGE_MASK];
  175336. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175337. CONST_BITS+PASS1_BITS+3)
  175338. & RANGE_MASK];
  175339. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175340. CONST_BITS+PASS1_BITS+3)
  175341. & RANGE_MASK];
  175342. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175343. CONST_BITS+PASS1_BITS+3)
  175344. & RANGE_MASK];
  175345. wsptr += DCTSIZE; /* advance pointer to next row */
  175346. }
  175347. }
  175348. #endif /* DCT_ISLOW_SUPPORTED */
  175349. /*** End of inlined file: jidctint.c ***/
  175350. /*** Start of inlined file: jidctred.c ***/
  175351. #define JPEG_INTERNALS
  175352. #ifdef IDCT_SCALING_SUPPORTED
  175353. /*
  175354. * This module is specialized to the case DCTSIZE = 8.
  175355. */
  175356. #if DCTSIZE != 8
  175357. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175358. #endif
  175359. /* Scaling is the same as in jidctint.c. */
  175360. #if BITS_IN_JSAMPLE == 8
  175361. #define CONST_BITS 13
  175362. #define PASS1_BITS 2
  175363. #else
  175364. #define CONST_BITS 13
  175365. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175366. #endif
  175367. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175368. * causing a lot of useless floating-point operations at run time.
  175369. * To get around this we use the following pre-calculated constants.
  175370. * If you change CONST_BITS you may want to add appropriate values.
  175371. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175372. */
  175373. #if CONST_BITS == 13
  175374. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175375. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175376. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175377. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175378. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175379. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175380. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175381. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175382. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175383. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175384. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175385. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175386. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175387. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175388. #else
  175389. #define FIX_0_211164243 FIX(0.211164243)
  175390. #define FIX_0_509795579 FIX(0.509795579)
  175391. #define FIX_0_601344887 FIX(0.601344887)
  175392. #define FIX_0_720959822 FIX(0.720959822)
  175393. #define FIX_0_765366865 FIX(0.765366865)
  175394. #define FIX_0_850430095 FIX(0.850430095)
  175395. #define FIX_0_899976223 FIX(0.899976223)
  175396. #define FIX_1_061594337 FIX(1.061594337)
  175397. #define FIX_1_272758580 FIX(1.272758580)
  175398. #define FIX_1_451774981 FIX(1.451774981)
  175399. #define FIX_1_847759065 FIX(1.847759065)
  175400. #define FIX_2_172734803 FIX(2.172734803)
  175401. #define FIX_2_562915447 FIX(2.562915447)
  175402. #define FIX_3_624509785 FIX(3.624509785)
  175403. #endif
  175404. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175405. * For 8-bit samples with the recommended scaling, all the variable
  175406. * and constant values involved are no more than 16 bits wide, so a
  175407. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175408. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175409. */
  175410. #if BITS_IN_JSAMPLE == 8
  175411. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175412. #else
  175413. #define MULTIPLY(var,const) ((var) * (const))
  175414. #endif
  175415. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175416. * entry; produce an int result. In this module, both inputs and result
  175417. * are 16 bits or less, so either int or short multiply will work.
  175418. */
  175419. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175420. /*
  175421. * Perform dequantization and inverse DCT on one block of coefficients,
  175422. * producing a reduced-size 4x4 output block.
  175423. */
  175424. GLOBAL(void)
  175425. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175426. JCOEFPTR coef_block,
  175427. JSAMPARRAY output_buf, JDIMENSION output_col)
  175428. {
  175429. INT32 tmp0, tmp2, tmp10, tmp12;
  175430. INT32 z1, z2, z3, z4;
  175431. JCOEFPTR inptr;
  175432. ISLOW_MULT_TYPE * quantptr;
  175433. int * wsptr;
  175434. JSAMPROW outptr;
  175435. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175436. int ctr;
  175437. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175438. SHIFT_TEMPS
  175439. /* Pass 1: process columns from input, store into work array. */
  175440. inptr = coef_block;
  175441. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175442. wsptr = workspace;
  175443. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175444. /* Don't bother to process column 4, because second pass won't use it */
  175445. if (ctr == DCTSIZE-4)
  175446. continue;
  175447. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175448. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175449. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175450. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175451. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175452. wsptr[DCTSIZE*0] = dcval;
  175453. wsptr[DCTSIZE*1] = dcval;
  175454. wsptr[DCTSIZE*2] = dcval;
  175455. wsptr[DCTSIZE*3] = dcval;
  175456. continue;
  175457. }
  175458. /* Even part */
  175459. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175460. tmp0 <<= (CONST_BITS+1);
  175461. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175462. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175463. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175464. tmp10 = tmp0 + tmp2;
  175465. tmp12 = tmp0 - tmp2;
  175466. /* Odd part */
  175467. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175468. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175469. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175470. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175471. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175472. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175473. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175474. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175475. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175476. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175477. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175478. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175479. /* Final output stage */
  175480. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175481. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175482. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175483. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175484. }
  175485. /* Pass 2: process 4 rows from work array, store into output array. */
  175486. wsptr = workspace;
  175487. for (ctr = 0; ctr < 4; ctr++) {
  175488. outptr = output_buf[ctr] + output_col;
  175489. /* It's not clear whether a zero row test is worthwhile here ... */
  175490. #ifndef NO_ZERO_ROW_TEST
  175491. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175492. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175493. /* AC terms all zero */
  175494. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175495. & RANGE_MASK];
  175496. outptr[0] = dcval;
  175497. outptr[1] = dcval;
  175498. outptr[2] = dcval;
  175499. outptr[3] = dcval;
  175500. wsptr += DCTSIZE; /* advance pointer to next row */
  175501. continue;
  175502. }
  175503. #endif
  175504. /* Even part */
  175505. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175506. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175507. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175508. tmp10 = tmp0 + tmp2;
  175509. tmp12 = tmp0 - tmp2;
  175510. /* Odd part */
  175511. z1 = (INT32) wsptr[7];
  175512. z2 = (INT32) wsptr[5];
  175513. z3 = (INT32) wsptr[3];
  175514. z4 = (INT32) wsptr[1];
  175515. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175516. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175517. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175518. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175519. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175520. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175521. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175522. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175523. /* Final output stage */
  175524. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175525. CONST_BITS+PASS1_BITS+3+1)
  175526. & RANGE_MASK];
  175527. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175528. CONST_BITS+PASS1_BITS+3+1)
  175529. & RANGE_MASK];
  175530. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175531. CONST_BITS+PASS1_BITS+3+1)
  175532. & RANGE_MASK];
  175533. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175534. CONST_BITS+PASS1_BITS+3+1)
  175535. & RANGE_MASK];
  175536. wsptr += DCTSIZE; /* advance pointer to next row */
  175537. }
  175538. }
  175539. /*
  175540. * Perform dequantization and inverse DCT on one block of coefficients,
  175541. * producing a reduced-size 2x2 output block.
  175542. */
  175543. GLOBAL(void)
  175544. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175545. JCOEFPTR coef_block,
  175546. JSAMPARRAY output_buf, JDIMENSION output_col)
  175547. {
  175548. INT32 tmp0, tmp10, z1;
  175549. JCOEFPTR inptr;
  175550. ISLOW_MULT_TYPE * quantptr;
  175551. int * wsptr;
  175552. JSAMPROW outptr;
  175553. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175554. int ctr;
  175555. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175556. SHIFT_TEMPS
  175557. /* Pass 1: process columns from input, store into work array. */
  175558. inptr = coef_block;
  175559. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175560. wsptr = workspace;
  175561. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175562. /* Don't bother to process columns 2,4,6 */
  175563. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175564. continue;
  175565. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175566. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175567. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175568. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175569. wsptr[DCTSIZE*0] = dcval;
  175570. wsptr[DCTSIZE*1] = dcval;
  175571. continue;
  175572. }
  175573. /* Even part */
  175574. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175575. tmp10 = z1 << (CONST_BITS+2);
  175576. /* Odd part */
  175577. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175578. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175579. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175580. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175581. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175582. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175583. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175584. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175585. /* Final output stage */
  175586. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175587. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175588. }
  175589. /* Pass 2: process 2 rows from work array, store into output array. */
  175590. wsptr = workspace;
  175591. for (ctr = 0; ctr < 2; ctr++) {
  175592. outptr = output_buf[ctr] + output_col;
  175593. /* It's not clear whether a zero row test is worthwhile here ... */
  175594. #ifndef NO_ZERO_ROW_TEST
  175595. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175596. /* AC terms all zero */
  175597. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175598. & RANGE_MASK];
  175599. outptr[0] = dcval;
  175600. outptr[1] = dcval;
  175601. wsptr += DCTSIZE; /* advance pointer to next row */
  175602. continue;
  175603. }
  175604. #endif
  175605. /* Even part */
  175606. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175607. /* Odd part */
  175608. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175609. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175610. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175611. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175612. /* Final output stage */
  175613. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175614. CONST_BITS+PASS1_BITS+3+2)
  175615. & RANGE_MASK];
  175616. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175617. CONST_BITS+PASS1_BITS+3+2)
  175618. & RANGE_MASK];
  175619. wsptr += DCTSIZE; /* advance pointer to next row */
  175620. }
  175621. }
  175622. /*
  175623. * Perform dequantization and inverse DCT on one block of coefficients,
  175624. * producing a reduced-size 1x1 output block.
  175625. */
  175626. GLOBAL(void)
  175627. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175628. JCOEFPTR coef_block,
  175629. JSAMPARRAY output_buf, JDIMENSION output_col)
  175630. {
  175631. int dcval;
  175632. ISLOW_MULT_TYPE * quantptr;
  175633. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175634. SHIFT_TEMPS
  175635. /* We hardly need an inverse DCT routine for this: just take the
  175636. * average pixel value, which is one-eighth of the DC coefficient.
  175637. */
  175638. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175639. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175640. dcval = (int) DESCALE((INT32) dcval, 3);
  175641. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175642. }
  175643. #endif /* IDCT_SCALING_SUPPORTED */
  175644. /*** End of inlined file: jidctred.c ***/
  175645. /*** Start of inlined file: jmemmgr.c ***/
  175646. #define JPEG_INTERNALS
  175647. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175648. /*** Start of inlined file: jmemsys.h ***/
  175649. #ifndef __jmemsys_h__
  175650. #define __jmemsys_h__
  175651. /* Short forms of external names for systems with brain-damaged linkers. */
  175652. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175653. #define jpeg_get_small jGetSmall
  175654. #define jpeg_free_small jFreeSmall
  175655. #define jpeg_get_large jGetLarge
  175656. #define jpeg_free_large jFreeLarge
  175657. #define jpeg_mem_available jMemAvail
  175658. #define jpeg_open_backing_store jOpenBackStore
  175659. #define jpeg_mem_init jMemInit
  175660. #define jpeg_mem_term jMemTerm
  175661. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175662. /*
  175663. * These two functions are used to allocate and release small chunks of
  175664. * memory. (Typically the total amount requested through jpeg_get_small is
  175665. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175666. * Behavior should be the same as for the standard library functions malloc
  175667. * and free; in particular, jpeg_get_small must return NULL on failure.
  175668. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175669. * size of the object being freed, just in case it's needed.
  175670. * On an 80x86 machine using small-data memory model, these manage near heap.
  175671. */
  175672. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175673. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175674. size_t sizeofobject));
  175675. /*
  175676. * These two functions are used to allocate and release large chunks of
  175677. * memory (up to the total free space designated by jpeg_mem_available).
  175678. * The interface is the same as above, except that on an 80x86 machine,
  175679. * far pointers are used. On most other machines these are identical to
  175680. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175681. * in case a different allocation strategy is desirable for large chunks.
  175682. */
  175683. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175684. size_t sizeofobject));
  175685. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175686. size_t sizeofobject));
  175687. /*
  175688. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175689. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175690. * matter, but that case should never come into play). This macro is needed
  175691. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175692. * On those machines, we expect that jconfig.h will provide a proper value.
  175693. * On machines with 32-bit flat address spaces, any large constant may be used.
  175694. *
  175695. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175696. * size_t and will be a multiple of sizeof(align_type).
  175697. */
  175698. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175699. #define MAX_ALLOC_CHUNK 1000000000L
  175700. #endif
  175701. /*
  175702. * This routine computes the total space still available for allocation by
  175703. * jpeg_get_large. If more space than this is needed, backing store will be
  175704. * used. NOTE: any memory already allocated must not be counted.
  175705. *
  175706. * There is a minimum space requirement, corresponding to the minimum
  175707. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175708. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175709. * all working storage in memory, is also passed in case it is useful.
  175710. * Finally, the total space already allocated is passed. If no better
  175711. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175712. * is often a suitable calculation.
  175713. *
  175714. * It is OK for jpeg_mem_available to underestimate the space available
  175715. * (that'll just lead to more backing-store access than is really necessary).
  175716. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175717. * a slop factor from the true available space. 5% should be enough.
  175718. *
  175719. * On machines with lots of virtual memory, any large constant may be returned.
  175720. * Conversely, zero may be returned to always use the minimum amount of memory.
  175721. */
  175722. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175723. long min_bytes_needed,
  175724. long max_bytes_needed,
  175725. long already_allocated));
  175726. /*
  175727. * This structure holds whatever state is needed to access a single
  175728. * backing-store object. The read/write/close method pointers are called
  175729. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175730. * are private to the system-dependent backing store routines.
  175731. */
  175732. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175733. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175734. typedef unsigned short XMSH; /* type of extended-memory handles */
  175735. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175736. typedef union {
  175737. short file_handle; /* DOS file handle if it's a temp file */
  175738. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175739. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175740. } handle_union;
  175741. #endif /* USE_MSDOS_MEMMGR */
  175742. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175743. #include <Files.h>
  175744. #endif /* USE_MAC_MEMMGR */
  175745. //typedef struct backing_store_struct * backing_store_ptr;
  175746. typedef struct backing_store_struct {
  175747. /* Methods for reading/writing/closing this backing-store object */
  175748. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175749. struct backing_store_struct *info,
  175750. void FAR * buffer_address,
  175751. long file_offset, long byte_count));
  175752. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175753. struct backing_store_struct *info,
  175754. void FAR * buffer_address,
  175755. long file_offset, long byte_count));
  175756. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175757. struct backing_store_struct *info));
  175758. /* Private fields for system-dependent backing-store management */
  175759. #ifdef USE_MSDOS_MEMMGR
  175760. /* For the MS-DOS manager (jmemdos.c), we need: */
  175761. handle_union handle; /* reference to backing-store storage object */
  175762. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175763. #else
  175764. #ifdef USE_MAC_MEMMGR
  175765. /* For the Mac manager (jmemmac.c), we need: */
  175766. short temp_file; /* file reference number to temp file */
  175767. FSSpec tempSpec; /* the FSSpec for the temp file */
  175768. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175769. #else
  175770. /* For a typical implementation with temp files, we need: */
  175771. FILE * temp_file; /* stdio reference to temp file */
  175772. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175773. #endif
  175774. #endif
  175775. } backing_store_info;
  175776. /*
  175777. * Initial opening of a backing-store object. This must fill in the
  175778. * read/write/close pointers in the object. The read/write routines
  175779. * may take an error exit if the specified maximum file size is exceeded.
  175780. * (If jpeg_mem_available always returns a large value, this routine can
  175781. * just take an error exit.)
  175782. */
  175783. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175784. struct backing_store_struct *info,
  175785. long total_bytes_needed));
  175786. /*
  175787. * These routines take care of any system-dependent initialization and
  175788. * cleanup required. jpeg_mem_init will be called before anything is
  175789. * allocated (and, therefore, nothing in cinfo is of use except the error
  175790. * manager pointer). It should return a suitable default value for
  175791. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175792. * application. (Note that max_memory_to_use is only important if
  175793. * jpeg_mem_available chooses to consult it ... no one else will.)
  175794. * jpeg_mem_term may assume that all requested memory has been freed and that
  175795. * all opened backing-store objects have been closed.
  175796. */
  175797. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175798. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175799. #endif
  175800. /*** End of inlined file: jmemsys.h ***/
  175801. /* import the system-dependent declarations */
  175802. #ifndef NO_GETENV
  175803. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175804. extern char * getenv JPP((const char * name));
  175805. #endif
  175806. #endif
  175807. /*
  175808. * Some important notes:
  175809. * The allocation routines provided here must never return NULL.
  175810. * They should exit to error_exit if unsuccessful.
  175811. *
  175812. * It's not a good idea to try to merge the sarray and barray routines,
  175813. * even though they are textually almost the same, because samples are
  175814. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175815. * in machines where byte pointers have a different representation from
  175816. * word pointers, the resulting machine code could not be the same.
  175817. */
  175818. /*
  175819. * Many machines require storage alignment: longs must start on 4-byte
  175820. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175821. * always returns pointers that are multiples of the worst-case alignment
  175822. * requirement, and we had better do so too.
  175823. * There isn't any really portable way to determine the worst-case alignment
  175824. * requirement. This module assumes that the alignment requirement is
  175825. * multiples of sizeof(ALIGN_TYPE).
  175826. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175827. * workstations (where doubles really do need 8-byte alignment) and will work
  175828. * fine on nearly everything. If your machine has lesser alignment needs,
  175829. * you can save a few bytes by making ALIGN_TYPE smaller.
  175830. * The only place I know of where this will NOT work is certain Macintosh
  175831. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175832. * Doing 10-byte alignment is counterproductive because longwords won't be
  175833. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175834. * such a compiler.
  175835. */
  175836. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175837. #define ALIGN_TYPE double
  175838. #endif
  175839. /*
  175840. * We allocate objects from "pools", where each pool is gotten with a single
  175841. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175842. * overhead within a pool, except for alignment padding. Each pool has a
  175843. * header with a link to the next pool of the same class.
  175844. * Small and large pool headers are identical except that the latter's
  175845. * link pointer must be FAR on 80x86 machines.
  175846. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175847. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175848. * of the alignment requirement of ALIGN_TYPE.
  175849. */
  175850. typedef union small_pool_struct * small_pool_ptr;
  175851. typedef union small_pool_struct {
  175852. struct {
  175853. small_pool_ptr next; /* next in list of pools */
  175854. size_t bytes_used; /* how many bytes already used within pool */
  175855. size_t bytes_left; /* bytes still available in this pool */
  175856. } hdr;
  175857. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175858. } small_pool_hdr;
  175859. typedef union large_pool_struct FAR * large_pool_ptr;
  175860. typedef union large_pool_struct {
  175861. struct {
  175862. large_pool_ptr next; /* next in list of pools */
  175863. size_t bytes_used; /* how many bytes already used within pool */
  175864. size_t bytes_left; /* bytes still available in this pool */
  175865. } hdr;
  175866. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175867. } large_pool_hdr;
  175868. /*
  175869. * Here is the full definition of a memory manager object.
  175870. */
  175871. typedef struct {
  175872. struct jpeg_memory_mgr pub; /* public fields */
  175873. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175874. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175875. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175876. /* Since we only have one lifetime class of virtual arrays, only one
  175877. * linked list is necessary (for each datatype). Note that the virtual
  175878. * array control blocks being linked together are actually stored somewhere
  175879. * in the small-pool list.
  175880. */
  175881. jvirt_sarray_ptr virt_sarray_list;
  175882. jvirt_barray_ptr virt_barray_list;
  175883. /* This counts total space obtained from jpeg_get_small/large */
  175884. long total_space_allocated;
  175885. /* alloc_sarray and alloc_barray set this value for use by virtual
  175886. * array routines.
  175887. */
  175888. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175889. } my_memory_mgr;
  175890. typedef my_memory_mgr * my_mem_ptr;
  175891. /*
  175892. * The control blocks for virtual arrays.
  175893. * Note that these blocks are allocated in the "small" pool area.
  175894. * System-dependent info for the associated backing store (if any) is hidden
  175895. * inside the backing_store_info struct.
  175896. */
  175897. struct jvirt_sarray_control {
  175898. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175899. JDIMENSION rows_in_array; /* total virtual array height */
  175900. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175901. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175902. JDIMENSION rows_in_mem; /* height of memory buffer */
  175903. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175904. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175905. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175906. boolean pre_zero; /* pre-zero mode requested? */
  175907. boolean dirty; /* do current buffer contents need written? */
  175908. boolean b_s_open; /* is backing-store data valid? */
  175909. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175910. backing_store_info b_s_info; /* System-dependent control info */
  175911. };
  175912. struct jvirt_barray_control {
  175913. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175914. JDIMENSION rows_in_array; /* total virtual array height */
  175915. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175916. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175917. JDIMENSION rows_in_mem; /* height of memory buffer */
  175918. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175919. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175920. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175921. boolean pre_zero; /* pre-zero mode requested? */
  175922. boolean dirty; /* do current buffer contents need written? */
  175923. boolean b_s_open; /* is backing-store data valid? */
  175924. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175925. backing_store_info b_s_info; /* System-dependent control info */
  175926. };
  175927. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175928. LOCAL(void)
  175929. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175930. {
  175931. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175932. small_pool_ptr shdr_ptr;
  175933. large_pool_ptr lhdr_ptr;
  175934. /* Since this is only a debugging stub, we can cheat a little by using
  175935. * fprintf directly rather than going through the trace message code.
  175936. * This is helpful because message parm array can't handle longs.
  175937. */
  175938. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175939. pool_id, mem->total_space_allocated);
  175940. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175941. lhdr_ptr = lhdr_ptr->hdr.next) {
  175942. fprintf(stderr, " Large chunk used %ld\n",
  175943. (long) lhdr_ptr->hdr.bytes_used);
  175944. }
  175945. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175946. shdr_ptr = shdr_ptr->hdr.next) {
  175947. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175948. (long) shdr_ptr->hdr.bytes_used,
  175949. (long) shdr_ptr->hdr.bytes_left);
  175950. }
  175951. }
  175952. #endif /* MEM_STATS */
  175953. LOCAL(void)
  175954. out_of_memory (j_common_ptr cinfo, int which)
  175955. /* Report an out-of-memory error and stop execution */
  175956. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175957. {
  175958. #ifdef MEM_STATS
  175959. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175960. #endif
  175961. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175962. }
  175963. /*
  175964. * Allocation of "small" objects.
  175965. *
  175966. * For these, we use pooled storage. When a new pool must be created,
  175967. * we try to get enough space for the current request plus a "slop" factor,
  175968. * where the slop will be the amount of leftover space in the new pool.
  175969. * The speed vs. space tradeoff is largely determined by the slop values.
  175970. * A different slop value is provided for each pool class (lifetime),
  175971. * and we also distinguish the first pool of a class from later ones.
  175972. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175973. * machines, but may be too small if longs are 64 bits or more.
  175974. */
  175975. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175976. {
  175977. 1600, /* first PERMANENT pool */
  175978. 16000 /* first IMAGE pool */
  175979. };
  175980. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175981. {
  175982. 0, /* additional PERMANENT pools */
  175983. 5000 /* additional IMAGE pools */
  175984. };
  175985. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175986. METHODDEF(void *)
  175987. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175988. /* Allocate a "small" object */
  175989. {
  175990. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175991. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175992. char * data_ptr;
  175993. size_t odd_bytes, min_request, slop;
  175994. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175995. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175996. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175997. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175998. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175999. if (odd_bytes > 0)
  176000. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176001. /* See if space is available in any existing pool */
  176002. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176003. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176004. prev_hdr_ptr = NULL;
  176005. hdr_ptr = mem->small_list[pool_id];
  176006. while (hdr_ptr != NULL) {
  176007. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176008. break; /* found pool with enough space */
  176009. prev_hdr_ptr = hdr_ptr;
  176010. hdr_ptr = hdr_ptr->hdr.next;
  176011. }
  176012. /* Time to make a new pool? */
  176013. if (hdr_ptr == NULL) {
  176014. /* min_request is what we need now, slop is what will be leftover */
  176015. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176016. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176017. slop = first_pool_slop[pool_id];
  176018. else
  176019. slop = extra_pool_slop[pool_id];
  176020. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176021. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176022. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176023. /* Try to get space, if fail reduce slop and try again */
  176024. for (;;) {
  176025. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176026. if (hdr_ptr != NULL)
  176027. break;
  176028. slop /= 2;
  176029. if (slop < MIN_SLOP) /* give up when it gets real small */
  176030. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176031. }
  176032. mem->total_space_allocated += min_request + slop;
  176033. /* Success, initialize the new pool header and add to end of list */
  176034. hdr_ptr->hdr.next = NULL;
  176035. hdr_ptr->hdr.bytes_used = 0;
  176036. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176037. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176038. mem->small_list[pool_id] = hdr_ptr;
  176039. else
  176040. prev_hdr_ptr->hdr.next = hdr_ptr;
  176041. }
  176042. /* OK, allocate the object from the current pool */
  176043. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176044. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176045. hdr_ptr->hdr.bytes_used += sizeofobject;
  176046. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176047. return (void *) data_ptr;
  176048. }
  176049. /*
  176050. * Allocation of "large" objects.
  176051. *
  176052. * The external semantics of these are the same as "small" objects,
  176053. * except that FAR pointers are used on 80x86. However the pool
  176054. * management heuristics are quite different. We assume that each
  176055. * request is large enough that it may as well be passed directly to
  176056. * jpeg_get_large; the pool management just links everything together
  176057. * so that we can free it all on demand.
  176058. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176059. * structures. The routines that create these structures (see below)
  176060. * deliberately bunch rows together to ensure a large request size.
  176061. */
  176062. METHODDEF(void FAR *)
  176063. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176064. /* Allocate a "large" object */
  176065. {
  176066. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176067. large_pool_ptr hdr_ptr;
  176068. size_t odd_bytes;
  176069. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176070. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176071. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176072. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176073. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176074. if (odd_bytes > 0)
  176075. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176076. /* Always make a new pool */
  176077. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176078. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176079. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176080. SIZEOF(large_pool_hdr));
  176081. if (hdr_ptr == NULL)
  176082. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176083. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176084. /* Success, initialize the new pool header and add to list */
  176085. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176086. /* We maintain space counts in each pool header for statistical purposes,
  176087. * even though they are not needed for allocation.
  176088. */
  176089. hdr_ptr->hdr.bytes_used = sizeofobject;
  176090. hdr_ptr->hdr.bytes_left = 0;
  176091. mem->large_list[pool_id] = hdr_ptr;
  176092. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176093. }
  176094. /*
  176095. * Creation of 2-D sample arrays.
  176096. * The pointers are in near heap, the samples themselves in FAR heap.
  176097. *
  176098. * To minimize allocation overhead and to allow I/O of large contiguous
  176099. * blocks, we allocate the sample rows in groups of as many rows as possible
  176100. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176101. * NB: the virtual array control routines, later in this file, know about
  176102. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176103. * object so that it can be saved away if this sarray is the workspace for
  176104. * a virtual array.
  176105. */
  176106. METHODDEF(JSAMPARRAY)
  176107. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176108. JDIMENSION samplesperrow, JDIMENSION numrows)
  176109. /* Allocate a 2-D sample array */
  176110. {
  176111. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176112. JSAMPARRAY result;
  176113. JSAMPROW workspace;
  176114. JDIMENSION rowsperchunk, currow, i;
  176115. long ltemp;
  176116. /* Calculate max # of rows allowed in one allocation chunk */
  176117. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176118. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176119. if (ltemp <= 0)
  176120. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176121. if (ltemp < (long) numrows)
  176122. rowsperchunk = (JDIMENSION) ltemp;
  176123. else
  176124. rowsperchunk = numrows;
  176125. mem->last_rowsperchunk = rowsperchunk;
  176126. /* Get space for row pointers (small object) */
  176127. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176128. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176129. /* Get the rows themselves (large objects) */
  176130. currow = 0;
  176131. while (currow < numrows) {
  176132. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176133. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176134. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176135. * SIZEOF(JSAMPLE)));
  176136. for (i = rowsperchunk; i > 0; i--) {
  176137. result[currow++] = workspace;
  176138. workspace += samplesperrow;
  176139. }
  176140. }
  176141. return result;
  176142. }
  176143. /*
  176144. * Creation of 2-D coefficient-block arrays.
  176145. * This is essentially the same as the code for sample arrays, above.
  176146. */
  176147. METHODDEF(JBLOCKARRAY)
  176148. alloc_barray (j_common_ptr cinfo, int pool_id,
  176149. JDIMENSION blocksperrow, JDIMENSION numrows)
  176150. /* Allocate a 2-D coefficient-block array */
  176151. {
  176152. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176153. JBLOCKARRAY result;
  176154. JBLOCKROW workspace;
  176155. JDIMENSION rowsperchunk, currow, i;
  176156. long ltemp;
  176157. /* Calculate max # of rows allowed in one allocation chunk */
  176158. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176159. ((long) blocksperrow * SIZEOF(JBLOCK));
  176160. if (ltemp <= 0)
  176161. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176162. if (ltemp < (long) numrows)
  176163. rowsperchunk = (JDIMENSION) ltemp;
  176164. else
  176165. rowsperchunk = numrows;
  176166. mem->last_rowsperchunk = rowsperchunk;
  176167. /* Get space for row pointers (small object) */
  176168. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176169. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176170. /* Get the rows themselves (large objects) */
  176171. currow = 0;
  176172. while (currow < numrows) {
  176173. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176174. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176175. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176176. * SIZEOF(JBLOCK)));
  176177. for (i = rowsperchunk; i > 0; i--) {
  176178. result[currow++] = workspace;
  176179. workspace += blocksperrow;
  176180. }
  176181. }
  176182. return result;
  176183. }
  176184. /*
  176185. * About virtual array management:
  176186. *
  176187. * The above "normal" array routines are only used to allocate strip buffers
  176188. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176189. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176190. * time, but the memory manager must save the whole array for repeated
  176191. * accesses. The intended implementation is that there is a strip buffer in
  176192. * memory (as high as is possible given the desired memory limit), plus a
  176193. * backing file that holds the rest of the array.
  176194. *
  176195. * The request_virt_array routines are told the total size of the image and
  176196. * the maximum number of rows that will be accessed at once. The in-memory
  176197. * buffer must be at least as large as the maxaccess value.
  176198. *
  176199. * The request routines create control blocks but not the in-memory buffers.
  176200. * That is postponed until realize_virt_arrays is called. At that time the
  176201. * total amount of space needed is known (approximately, anyway), so free
  176202. * memory can be divided up fairly.
  176203. *
  176204. * The access_virt_array routines are responsible for making a specific strip
  176205. * area accessible (after reading or writing the backing file, if necessary).
  176206. * Note that the access routines are told whether the caller intends to modify
  176207. * the accessed strip; during a read-only pass this saves having to rewrite
  176208. * data to disk. The access routines are also responsible for pre-zeroing
  176209. * any newly accessed rows, if pre-zeroing was requested.
  176210. *
  176211. * In current usage, the access requests are usually for nonoverlapping
  176212. * strips; that is, successive access start_row numbers differ by exactly
  176213. * num_rows = maxaccess. This means we can get good performance with simple
  176214. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176215. * of the access height; then there will never be accesses across bufferload
  176216. * boundaries. The code will still work with overlapping access requests,
  176217. * but it doesn't handle bufferload overlaps very efficiently.
  176218. */
  176219. METHODDEF(jvirt_sarray_ptr)
  176220. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176221. JDIMENSION samplesperrow, JDIMENSION numrows,
  176222. JDIMENSION maxaccess)
  176223. /* Request a virtual 2-D sample array */
  176224. {
  176225. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176226. jvirt_sarray_ptr result;
  176227. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176228. if (pool_id != JPOOL_IMAGE)
  176229. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176230. /* get control block */
  176231. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176232. SIZEOF(struct jvirt_sarray_control));
  176233. result->mem_buffer = NULL; /* marks array not yet realized */
  176234. result->rows_in_array = numrows;
  176235. result->samplesperrow = samplesperrow;
  176236. result->maxaccess = maxaccess;
  176237. result->pre_zero = pre_zero;
  176238. result->b_s_open = FALSE; /* no associated backing-store object */
  176239. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176240. mem->virt_sarray_list = result;
  176241. return result;
  176242. }
  176243. METHODDEF(jvirt_barray_ptr)
  176244. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176245. JDIMENSION blocksperrow, JDIMENSION numrows,
  176246. JDIMENSION maxaccess)
  176247. /* Request a virtual 2-D coefficient-block array */
  176248. {
  176249. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176250. jvirt_barray_ptr result;
  176251. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176252. if (pool_id != JPOOL_IMAGE)
  176253. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176254. /* get control block */
  176255. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176256. SIZEOF(struct jvirt_barray_control));
  176257. result->mem_buffer = NULL; /* marks array not yet realized */
  176258. result->rows_in_array = numrows;
  176259. result->blocksperrow = blocksperrow;
  176260. result->maxaccess = maxaccess;
  176261. result->pre_zero = pre_zero;
  176262. result->b_s_open = FALSE; /* no associated backing-store object */
  176263. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176264. mem->virt_barray_list = result;
  176265. return result;
  176266. }
  176267. METHODDEF(void)
  176268. realize_virt_arrays (j_common_ptr cinfo)
  176269. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176270. {
  176271. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176272. long space_per_minheight, maximum_space, avail_mem;
  176273. long minheights, max_minheights;
  176274. jvirt_sarray_ptr sptr;
  176275. jvirt_barray_ptr bptr;
  176276. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176277. * and the maximum space needed (full image height in each buffer).
  176278. * These may be of use to the system-dependent jpeg_mem_available routine.
  176279. */
  176280. space_per_minheight = 0;
  176281. maximum_space = 0;
  176282. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176283. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176284. space_per_minheight += (long) sptr->maxaccess *
  176285. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176286. maximum_space += (long) sptr->rows_in_array *
  176287. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176288. }
  176289. }
  176290. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176291. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176292. space_per_minheight += (long) bptr->maxaccess *
  176293. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176294. maximum_space += (long) bptr->rows_in_array *
  176295. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176296. }
  176297. }
  176298. if (space_per_minheight <= 0)
  176299. return; /* no unrealized arrays, no work */
  176300. /* Determine amount of memory to actually use; this is system-dependent. */
  176301. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176302. mem->total_space_allocated);
  176303. /* If the maximum space needed is available, make all the buffers full
  176304. * height; otherwise parcel it out with the same number of minheights
  176305. * in each buffer.
  176306. */
  176307. if (avail_mem >= maximum_space)
  176308. max_minheights = 1000000000L;
  176309. else {
  176310. max_minheights = avail_mem / space_per_minheight;
  176311. /* If there doesn't seem to be enough space, try to get the minimum
  176312. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176313. */
  176314. if (max_minheights <= 0)
  176315. max_minheights = 1;
  176316. }
  176317. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176318. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176319. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176320. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176321. if (minheights <= max_minheights) {
  176322. /* This buffer fits in memory */
  176323. sptr->rows_in_mem = sptr->rows_in_array;
  176324. } else {
  176325. /* It doesn't fit in memory, create backing store. */
  176326. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176327. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176328. (long) sptr->rows_in_array *
  176329. (long) sptr->samplesperrow *
  176330. (long) SIZEOF(JSAMPLE));
  176331. sptr->b_s_open = TRUE;
  176332. }
  176333. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176334. sptr->samplesperrow, sptr->rows_in_mem);
  176335. sptr->rowsperchunk = mem->last_rowsperchunk;
  176336. sptr->cur_start_row = 0;
  176337. sptr->first_undef_row = 0;
  176338. sptr->dirty = FALSE;
  176339. }
  176340. }
  176341. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176342. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176343. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176344. if (minheights <= max_minheights) {
  176345. /* This buffer fits in memory */
  176346. bptr->rows_in_mem = bptr->rows_in_array;
  176347. } else {
  176348. /* It doesn't fit in memory, create backing store. */
  176349. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176350. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176351. (long) bptr->rows_in_array *
  176352. (long) bptr->blocksperrow *
  176353. (long) SIZEOF(JBLOCK));
  176354. bptr->b_s_open = TRUE;
  176355. }
  176356. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176357. bptr->blocksperrow, bptr->rows_in_mem);
  176358. bptr->rowsperchunk = mem->last_rowsperchunk;
  176359. bptr->cur_start_row = 0;
  176360. bptr->first_undef_row = 0;
  176361. bptr->dirty = FALSE;
  176362. }
  176363. }
  176364. }
  176365. LOCAL(void)
  176366. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176367. /* Do backing store read or write of a virtual sample array */
  176368. {
  176369. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176370. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176371. file_offset = ptr->cur_start_row * bytesperrow;
  176372. /* Loop to read or write each allocation chunk in mem_buffer */
  176373. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176374. /* One chunk, but check for short chunk at end of buffer */
  176375. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176376. /* Transfer no more than is currently defined */
  176377. thisrow = (long) ptr->cur_start_row + i;
  176378. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176379. /* Transfer no more than fits in file */
  176380. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176381. if (rows <= 0) /* this chunk might be past end of file! */
  176382. break;
  176383. byte_count = rows * bytesperrow;
  176384. if (writing)
  176385. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176386. (void FAR *) ptr->mem_buffer[i],
  176387. file_offset, byte_count);
  176388. else
  176389. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176390. (void FAR *) ptr->mem_buffer[i],
  176391. file_offset, byte_count);
  176392. file_offset += byte_count;
  176393. }
  176394. }
  176395. LOCAL(void)
  176396. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176397. /* Do backing store read or write of a virtual coefficient-block array */
  176398. {
  176399. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176400. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176401. file_offset = ptr->cur_start_row * bytesperrow;
  176402. /* Loop to read or write each allocation chunk in mem_buffer */
  176403. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176404. /* One chunk, but check for short chunk at end of buffer */
  176405. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176406. /* Transfer no more than is currently defined */
  176407. thisrow = (long) ptr->cur_start_row + i;
  176408. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176409. /* Transfer no more than fits in file */
  176410. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176411. if (rows <= 0) /* this chunk might be past end of file! */
  176412. break;
  176413. byte_count = rows * bytesperrow;
  176414. if (writing)
  176415. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176416. (void FAR *) ptr->mem_buffer[i],
  176417. file_offset, byte_count);
  176418. else
  176419. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176420. (void FAR *) ptr->mem_buffer[i],
  176421. file_offset, byte_count);
  176422. file_offset += byte_count;
  176423. }
  176424. }
  176425. METHODDEF(JSAMPARRAY)
  176426. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176427. JDIMENSION start_row, JDIMENSION num_rows,
  176428. boolean writable)
  176429. /* Access the part of a virtual sample array starting at start_row */
  176430. /* and extending for num_rows rows. writable is true if */
  176431. /* caller intends to modify the accessed area. */
  176432. {
  176433. JDIMENSION end_row = start_row + num_rows;
  176434. JDIMENSION undef_row;
  176435. /* debugging check */
  176436. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176437. ptr->mem_buffer == NULL)
  176438. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176439. /* Make the desired part of the virtual array accessible */
  176440. if (start_row < ptr->cur_start_row ||
  176441. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176442. if (! ptr->b_s_open)
  176443. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176444. /* Flush old buffer contents if necessary */
  176445. if (ptr->dirty) {
  176446. do_sarray_io(cinfo, ptr, TRUE);
  176447. ptr->dirty = FALSE;
  176448. }
  176449. /* Decide what part of virtual array to access.
  176450. * Algorithm: if target address > current window, assume forward scan,
  176451. * load starting at target address. If target address < current window,
  176452. * assume backward scan, load so that target area is top of window.
  176453. * Note that when switching from forward write to forward read, will have
  176454. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176455. */
  176456. if (start_row > ptr->cur_start_row) {
  176457. ptr->cur_start_row = start_row;
  176458. } else {
  176459. /* use long arithmetic here to avoid overflow & unsigned problems */
  176460. long ltemp;
  176461. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176462. if (ltemp < 0)
  176463. ltemp = 0; /* don't fall off front end of file */
  176464. ptr->cur_start_row = (JDIMENSION) ltemp;
  176465. }
  176466. /* Read in the selected part of the array.
  176467. * During the initial write pass, we will do no actual read
  176468. * because the selected part is all undefined.
  176469. */
  176470. do_sarray_io(cinfo, ptr, FALSE);
  176471. }
  176472. /* Ensure the accessed part of the array is defined; prezero if needed.
  176473. * To improve locality of access, we only prezero the part of the array
  176474. * that the caller is about to access, not the entire in-memory array.
  176475. */
  176476. if (ptr->first_undef_row < end_row) {
  176477. if (ptr->first_undef_row < start_row) {
  176478. if (writable) /* writer skipped over a section of array */
  176479. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176480. undef_row = start_row; /* but reader is allowed to read ahead */
  176481. } else {
  176482. undef_row = ptr->first_undef_row;
  176483. }
  176484. if (writable)
  176485. ptr->first_undef_row = end_row;
  176486. if (ptr->pre_zero) {
  176487. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176488. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176489. end_row -= ptr->cur_start_row;
  176490. while (undef_row < end_row) {
  176491. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176492. undef_row++;
  176493. }
  176494. } else {
  176495. if (! writable) /* reader looking at undefined data */
  176496. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176497. }
  176498. }
  176499. /* Flag the buffer dirty if caller will write in it */
  176500. if (writable)
  176501. ptr->dirty = TRUE;
  176502. /* Return address of proper part of the buffer */
  176503. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176504. }
  176505. METHODDEF(JBLOCKARRAY)
  176506. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176507. JDIMENSION start_row, JDIMENSION num_rows,
  176508. boolean writable)
  176509. /* Access the part of a virtual block array starting at start_row */
  176510. /* and extending for num_rows rows. writable is true if */
  176511. /* caller intends to modify the accessed area. */
  176512. {
  176513. JDIMENSION end_row = start_row + num_rows;
  176514. JDIMENSION undef_row;
  176515. /* debugging check */
  176516. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176517. ptr->mem_buffer == NULL)
  176518. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176519. /* Make the desired part of the virtual array accessible */
  176520. if (start_row < ptr->cur_start_row ||
  176521. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176522. if (! ptr->b_s_open)
  176523. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176524. /* Flush old buffer contents if necessary */
  176525. if (ptr->dirty) {
  176526. do_barray_io(cinfo, ptr, TRUE);
  176527. ptr->dirty = FALSE;
  176528. }
  176529. /* Decide what part of virtual array to access.
  176530. * Algorithm: if target address > current window, assume forward scan,
  176531. * load starting at target address. If target address < current window,
  176532. * assume backward scan, load so that target area is top of window.
  176533. * Note that when switching from forward write to forward read, will have
  176534. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176535. */
  176536. if (start_row > ptr->cur_start_row) {
  176537. ptr->cur_start_row = start_row;
  176538. } else {
  176539. /* use long arithmetic here to avoid overflow & unsigned problems */
  176540. long ltemp;
  176541. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176542. if (ltemp < 0)
  176543. ltemp = 0; /* don't fall off front end of file */
  176544. ptr->cur_start_row = (JDIMENSION) ltemp;
  176545. }
  176546. /* Read in the selected part of the array.
  176547. * During the initial write pass, we will do no actual read
  176548. * because the selected part is all undefined.
  176549. */
  176550. do_barray_io(cinfo, ptr, FALSE);
  176551. }
  176552. /* Ensure the accessed part of the array is defined; prezero if needed.
  176553. * To improve locality of access, we only prezero the part of the array
  176554. * that the caller is about to access, not the entire in-memory array.
  176555. */
  176556. if (ptr->first_undef_row < end_row) {
  176557. if (ptr->first_undef_row < start_row) {
  176558. if (writable) /* writer skipped over a section of array */
  176559. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176560. undef_row = start_row; /* but reader is allowed to read ahead */
  176561. } else {
  176562. undef_row = ptr->first_undef_row;
  176563. }
  176564. if (writable)
  176565. ptr->first_undef_row = end_row;
  176566. if (ptr->pre_zero) {
  176567. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176568. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176569. end_row -= ptr->cur_start_row;
  176570. while (undef_row < end_row) {
  176571. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176572. undef_row++;
  176573. }
  176574. } else {
  176575. if (! writable) /* reader looking at undefined data */
  176576. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176577. }
  176578. }
  176579. /* Flag the buffer dirty if caller will write in it */
  176580. if (writable)
  176581. ptr->dirty = TRUE;
  176582. /* Return address of proper part of the buffer */
  176583. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176584. }
  176585. /*
  176586. * Release all objects belonging to a specified pool.
  176587. */
  176588. METHODDEF(void)
  176589. free_pool (j_common_ptr cinfo, int pool_id)
  176590. {
  176591. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176592. small_pool_ptr shdr_ptr;
  176593. large_pool_ptr lhdr_ptr;
  176594. size_t space_freed;
  176595. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176596. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176597. #ifdef MEM_STATS
  176598. if (cinfo->err->trace_level > 1)
  176599. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176600. #endif
  176601. /* If freeing IMAGE pool, close any virtual arrays first */
  176602. if (pool_id == JPOOL_IMAGE) {
  176603. jvirt_sarray_ptr sptr;
  176604. jvirt_barray_ptr bptr;
  176605. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176606. if (sptr->b_s_open) { /* there may be no backing store */
  176607. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176608. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176609. }
  176610. }
  176611. mem->virt_sarray_list = NULL;
  176612. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176613. if (bptr->b_s_open) { /* there may be no backing store */
  176614. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176615. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176616. }
  176617. }
  176618. mem->virt_barray_list = NULL;
  176619. }
  176620. /* Release large objects */
  176621. lhdr_ptr = mem->large_list[pool_id];
  176622. mem->large_list[pool_id] = NULL;
  176623. while (lhdr_ptr != NULL) {
  176624. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176625. space_freed = lhdr_ptr->hdr.bytes_used +
  176626. lhdr_ptr->hdr.bytes_left +
  176627. SIZEOF(large_pool_hdr);
  176628. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176629. mem->total_space_allocated -= space_freed;
  176630. lhdr_ptr = next_lhdr_ptr;
  176631. }
  176632. /* Release small objects */
  176633. shdr_ptr = mem->small_list[pool_id];
  176634. mem->small_list[pool_id] = NULL;
  176635. while (shdr_ptr != NULL) {
  176636. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176637. space_freed = shdr_ptr->hdr.bytes_used +
  176638. shdr_ptr->hdr.bytes_left +
  176639. SIZEOF(small_pool_hdr);
  176640. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176641. mem->total_space_allocated -= space_freed;
  176642. shdr_ptr = next_shdr_ptr;
  176643. }
  176644. }
  176645. /*
  176646. * Close up shop entirely.
  176647. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176648. */
  176649. METHODDEF(void)
  176650. self_destruct (j_common_ptr cinfo)
  176651. {
  176652. int pool;
  176653. /* Close all backing store, release all memory.
  176654. * Releasing pools in reverse order might help avoid fragmentation
  176655. * with some (brain-damaged) malloc libraries.
  176656. */
  176657. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176658. free_pool(cinfo, pool);
  176659. }
  176660. /* Release the memory manager control block too. */
  176661. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176662. cinfo->mem = NULL; /* ensures I will be called only once */
  176663. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176664. }
  176665. /*
  176666. * Memory manager initialization.
  176667. * When this is called, only the error manager pointer is valid in cinfo!
  176668. */
  176669. GLOBAL(void)
  176670. jinit_memory_mgr (j_common_ptr cinfo)
  176671. {
  176672. my_mem_ptr mem;
  176673. long max_to_use;
  176674. int pool;
  176675. size_t test_mac;
  176676. cinfo->mem = NULL; /* for safety if init fails */
  176677. /* Check for configuration errors.
  176678. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176679. * doesn't reflect any real hardware alignment requirement.
  176680. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176681. * in common if and only if X is a power of 2, ie has only one one-bit.
  176682. * Some compilers may give an "unreachable code" warning here; ignore it.
  176683. */
  176684. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176685. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176686. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176687. * a multiple of SIZEOF(ALIGN_TYPE).
  176688. * Again, an "unreachable code" warning may be ignored here.
  176689. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176690. */
  176691. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176692. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176693. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176694. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176695. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176696. /* Attempt to allocate memory manager's control block */
  176697. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176698. if (mem == NULL) {
  176699. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176700. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176701. }
  176702. /* OK, fill in the method pointers */
  176703. mem->pub.alloc_small = alloc_small;
  176704. mem->pub.alloc_large = alloc_large;
  176705. mem->pub.alloc_sarray = alloc_sarray;
  176706. mem->pub.alloc_barray = alloc_barray;
  176707. mem->pub.request_virt_sarray = request_virt_sarray;
  176708. mem->pub.request_virt_barray = request_virt_barray;
  176709. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176710. mem->pub.access_virt_sarray = access_virt_sarray;
  176711. mem->pub.access_virt_barray = access_virt_barray;
  176712. mem->pub.free_pool = free_pool;
  176713. mem->pub.self_destruct = self_destruct;
  176714. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176715. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176716. /* Initialize working state */
  176717. mem->pub.max_memory_to_use = max_to_use;
  176718. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176719. mem->small_list[pool] = NULL;
  176720. mem->large_list[pool] = NULL;
  176721. }
  176722. mem->virt_sarray_list = NULL;
  176723. mem->virt_barray_list = NULL;
  176724. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176725. /* Declare ourselves open for business */
  176726. cinfo->mem = & mem->pub;
  176727. /* Check for an environment variable JPEGMEM; if found, override the
  176728. * default max_memory setting from jpeg_mem_init. Note that the
  176729. * surrounding application may again override this value.
  176730. * If your system doesn't support getenv(), define NO_GETENV to disable
  176731. * this feature.
  176732. */
  176733. #ifndef NO_GETENV
  176734. { char * memenv;
  176735. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176736. char ch = 'x';
  176737. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176738. if (ch == 'm' || ch == 'M')
  176739. max_to_use *= 1000L;
  176740. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176741. }
  176742. }
  176743. }
  176744. #endif
  176745. }
  176746. /*** End of inlined file: jmemmgr.c ***/
  176747. /*** Start of inlined file: jmemnobs.c ***/
  176748. #define JPEG_INTERNALS
  176749. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176750. extern void * malloc JPP((size_t size));
  176751. extern void free JPP((void *ptr));
  176752. #endif
  176753. /*
  176754. * Memory allocation and freeing are controlled by the regular library
  176755. * routines malloc() and free().
  176756. */
  176757. GLOBAL(void *)
  176758. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176759. {
  176760. return (void *) malloc(sizeofobject);
  176761. }
  176762. GLOBAL(void)
  176763. jpeg_free_small (j_common_ptr , void * object, size_t)
  176764. {
  176765. free(object);
  176766. }
  176767. /*
  176768. * "Large" objects are treated the same as "small" ones.
  176769. * NB: although we include FAR keywords in the routine declarations,
  176770. * this file won't actually work in 80x86 small/medium model; at least,
  176771. * you probably won't be able to process useful-size images in only 64KB.
  176772. */
  176773. GLOBAL(void FAR *)
  176774. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176775. {
  176776. return (void FAR *) malloc(sizeofobject);
  176777. }
  176778. GLOBAL(void)
  176779. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176780. {
  176781. free(object);
  176782. }
  176783. /*
  176784. * This routine computes the total memory space available for allocation.
  176785. * Here we always say, "we got all you want bud!"
  176786. */
  176787. GLOBAL(long)
  176788. jpeg_mem_available (j_common_ptr, long,
  176789. long max_bytes_needed, long)
  176790. {
  176791. return max_bytes_needed;
  176792. }
  176793. /*
  176794. * Backing store (temporary file) management.
  176795. * Since jpeg_mem_available always promised the moon,
  176796. * this should never be called and we can just error out.
  176797. */
  176798. GLOBAL(void)
  176799. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176800. long )
  176801. {
  176802. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176803. }
  176804. /*
  176805. * These routines take care of any system-dependent initialization and
  176806. * cleanup required. Here, there isn't any.
  176807. */
  176808. GLOBAL(long)
  176809. jpeg_mem_init (j_common_ptr)
  176810. {
  176811. return 0; /* just set max_memory_to_use to 0 */
  176812. }
  176813. GLOBAL(void)
  176814. jpeg_mem_term (j_common_ptr)
  176815. {
  176816. /* no work */
  176817. }
  176818. /*** End of inlined file: jmemnobs.c ***/
  176819. /*** Start of inlined file: jquant1.c ***/
  176820. #define JPEG_INTERNALS
  176821. #ifdef QUANT_1PASS_SUPPORTED
  176822. /*
  176823. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176824. * high quality, colormapped output capability. A 2-pass quantizer usually
  176825. * gives better visual quality; however, for quantized grayscale output this
  176826. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176827. * quantizer, though you can turn it off if you really want to.
  176828. *
  176829. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176830. * image. We use a map consisting of all combinations of Ncolors[i] color
  176831. * values for the i'th component. The Ncolors[] values are chosen so that
  176832. * their product, the total number of colors, is no more than that requested.
  176833. * (In most cases, the product will be somewhat less.)
  176834. *
  176835. * Since the colormap is orthogonal, the representative value for each color
  176836. * component can be determined without considering the other components;
  176837. * then these indexes can be combined into a colormap index by a standard
  176838. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176839. * can be precalculated and stored in the lookup table colorindex[].
  176840. * colorindex[i][j] maps pixel value j in component i to the nearest
  176841. * representative value (grid plane) for that component; this index is
  176842. * multiplied by the array stride for component i, so that the
  176843. * index of the colormap entry closest to a given pixel value is just
  176844. * sum( colorindex[component-number][pixel-component-value] )
  176845. * Aside from being fast, this scheme allows for variable spacing between
  176846. * representative values with no additional lookup cost.
  176847. *
  176848. * If gamma correction has been applied in color conversion, it might be wise
  176849. * to adjust the color grid spacing so that the representative colors are
  176850. * equidistant in linear space. At this writing, gamma correction is not
  176851. * implemented by jdcolor, so nothing is done here.
  176852. */
  176853. /* Declarations for ordered dithering.
  176854. *
  176855. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176856. * dithering is described in many references, for instance Dale Schumacher's
  176857. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176858. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176859. * "dither" value to the input pixel and then round the result to the nearest
  176860. * output value. The dither value is equivalent to (0.5 - threshold) times
  176861. * the distance between output values. For ordered dithering, we assume that
  176862. * the output colors are equally spaced; if not, results will probably be
  176863. * worse, since the dither may be too much or too little at a given point.
  176864. *
  176865. * The normal calculation would be to form pixel value + dither, range-limit
  176866. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176867. * We can skip the separate range-limiting step by extending the colorindex
  176868. * table in both directions.
  176869. */
  176870. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176871. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176872. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176873. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176874. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176875. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176876. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176877. /* Bayer's order-4 dither array. Generated by the code given in
  176878. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176879. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176880. */
  176881. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176882. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176883. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176884. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176885. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176886. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176887. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176888. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176889. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176890. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176891. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176892. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176893. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176894. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176895. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176896. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176897. };
  176898. /* Declarations for Floyd-Steinberg dithering.
  176899. *
  176900. * Errors are accumulated into the array fserrors[], at a resolution of
  176901. * 1/16th of a pixel count. The error at a given pixel is propagated
  176902. * to its not-yet-processed neighbors using the standard F-S fractions,
  176903. * ... (here) 7/16
  176904. * 3/16 5/16 1/16
  176905. * We work left-to-right on even rows, right-to-left on odd rows.
  176906. *
  176907. * We can get away with a single array (holding one row's worth of errors)
  176908. * by using it to store the current row's errors at pixel columns not yet
  176909. * processed, but the next row's errors at columns already processed. We
  176910. * need only a few extra variables to hold the errors immediately around the
  176911. * current column. (If we are lucky, those variables are in registers, but
  176912. * even if not, they're probably cheaper to access than array elements are.)
  176913. *
  176914. * The fserrors[] array is indexed [component#][position].
  176915. * We provide (#columns + 2) entries per component; the extra entry at each
  176916. * end saves us from special-casing the first and last pixels.
  176917. *
  176918. * Note: on a wide image, we might not have enough room in a PC's near data
  176919. * segment to hold the error array; so it is allocated with alloc_large.
  176920. */
  176921. #if BITS_IN_JSAMPLE == 8
  176922. typedef INT16 FSERROR; /* 16 bits should be enough */
  176923. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176924. #else
  176925. typedef INT32 FSERROR; /* may need more than 16 bits */
  176926. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176927. #endif
  176928. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176929. /* Private subobject */
  176930. #define MAX_Q_COMPS 4 /* max components I can handle */
  176931. typedef struct {
  176932. struct jpeg_color_quantizer pub; /* public fields */
  176933. /* Initially allocated colormap is saved here */
  176934. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176935. int sv_actual; /* number of entries in use */
  176936. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176937. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176938. * premultiplied as described above. Since colormap indexes must fit into
  176939. * JSAMPLEs, the entries of this array will too.
  176940. */
  176941. boolean is_padded; /* is the colorindex padded for odither? */
  176942. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176943. /* Variables for ordered dithering */
  176944. int row_index; /* cur row's vertical index in dither matrix */
  176945. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176946. /* Variables for Floyd-Steinberg dithering */
  176947. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176948. boolean on_odd_row; /* flag to remember which row we are on */
  176949. } my_cquantizer;
  176950. typedef my_cquantizer * my_cquantize_ptr;
  176951. /*
  176952. * Policy-making subroutines for create_colormap and create_colorindex.
  176953. * These routines determine the colormap to be used. The rest of the module
  176954. * only assumes that the colormap is orthogonal.
  176955. *
  176956. * * select_ncolors decides how to divvy up the available colors
  176957. * among the components.
  176958. * * output_value defines the set of representative values for a component.
  176959. * * largest_input_value defines the mapping from input values to
  176960. * representative values for a component.
  176961. * Note that the latter two routines may impose different policies for
  176962. * different components, though this is not currently done.
  176963. */
  176964. LOCAL(int)
  176965. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176966. /* Determine allocation of desired colors to components, */
  176967. /* and fill in Ncolors[] array to indicate choice. */
  176968. /* Return value is total number of colors (product of Ncolors[] values). */
  176969. {
  176970. int nc = cinfo->out_color_components; /* number of color components */
  176971. int max_colors = cinfo->desired_number_of_colors;
  176972. int total_colors, iroot, i, j;
  176973. boolean changed;
  176974. long temp;
  176975. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176976. /* We can allocate at least the nc'th root of max_colors per component. */
  176977. /* Compute floor(nc'th root of max_colors). */
  176978. iroot = 1;
  176979. do {
  176980. iroot++;
  176981. temp = iroot; /* set temp = iroot ** nc */
  176982. for (i = 1; i < nc; i++)
  176983. temp *= iroot;
  176984. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176985. iroot--; /* now iroot = floor(root) */
  176986. /* Must have at least 2 color values per component */
  176987. if (iroot < 2)
  176988. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176989. /* Initialize to iroot color values for each component */
  176990. total_colors = 1;
  176991. for (i = 0; i < nc; i++) {
  176992. Ncolors[i] = iroot;
  176993. total_colors *= iroot;
  176994. }
  176995. /* We may be able to increment the count for one or more components without
  176996. * exceeding max_colors, though we know not all can be incremented.
  176997. * Sometimes, the first component can be incremented more than once!
  176998. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176999. * In RGB colorspace, try to increment G first, then R, then B.
  177000. */
  177001. do {
  177002. changed = FALSE;
  177003. for (i = 0; i < nc; i++) {
  177004. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177005. /* calculate new total_colors if Ncolors[j] is incremented */
  177006. temp = total_colors / Ncolors[j];
  177007. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177008. if (temp > (long) max_colors)
  177009. break; /* won't fit, done with this pass */
  177010. Ncolors[j]++; /* OK, apply the increment */
  177011. total_colors = (int) temp;
  177012. changed = TRUE;
  177013. }
  177014. } while (changed);
  177015. return total_colors;
  177016. }
  177017. LOCAL(int)
  177018. output_value (j_decompress_ptr, int, int j, int maxj)
  177019. /* Return j'th output value, where j will range from 0 to maxj */
  177020. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177021. {
  177022. /* We always provide values 0 and MAXJSAMPLE for each component;
  177023. * any additional values are equally spaced between these limits.
  177024. * (Forcing the upper and lower values to the limits ensures that
  177025. * dithering can't produce a color outside the selected gamut.)
  177026. */
  177027. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177028. }
  177029. LOCAL(int)
  177030. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177031. /* Return largest input value that should map to j'th output value */
  177032. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177033. {
  177034. /* Breakpoints are halfway between values returned by output_value */
  177035. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177036. }
  177037. /*
  177038. * Create the colormap.
  177039. */
  177040. LOCAL(void)
  177041. create_colormap (j_decompress_ptr cinfo)
  177042. {
  177043. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177044. JSAMPARRAY colormap; /* Created colormap */
  177045. int total_colors; /* Number of distinct output colors */
  177046. int i,j,k, nci, blksize, blkdist, ptr, val;
  177047. /* Select number of colors for each component */
  177048. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177049. /* Report selected color counts */
  177050. if (cinfo->out_color_components == 3)
  177051. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177052. total_colors, cquantize->Ncolors[0],
  177053. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177054. else
  177055. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177056. /* Allocate and fill in the colormap. */
  177057. /* The colors are ordered in the map in standard row-major order, */
  177058. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177059. colormap = (*cinfo->mem->alloc_sarray)
  177060. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177061. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177062. /* blksize is number of adjacent repeated entries for a component */
  177063. /* blkdist is distance between groups of identical entries for a component */
  177064. blkdist = total_colors;
  177065. for (i = 0; i < cinfo->out_color_components; i++) {
  177066. /* fill in colormap entries for i'th color component */
  177067. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177068. blksize = blkdist / nci;
  177069. for (j = 0; j < nci; j++) {
  177070. /* Compute j'th output value (out of nci) for component */
  177071. val = output_value(cinfo, i, j, nci-1);
  177072. /* Fill in all colormap entries that have this value of this component */
  177073. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177074. /* fill in blksize entries beginning at ptr */
  177075. for (k = 0; k < blksize; k++)
  177076. colormap[i][ptr+k] = (JSAMPLE) val;
  177077. }
  177078. }
  177079. blkdist = blksize; /* blksize of this color is blkdist of next */
  177080. }
  177081. /* Save the colormap in private storage,
  177082. * where it will survive color quantization mode changes.
  177083. */
  177084. cquantize->sv_colormap = colormap;
  177085. cquantize->sv_actual = total_colors;
  177086. }
  177087. /*
  177088. * Create the color index table.
  177089. */
  177090. LOCAL(void)
  177091. create_colorindex (j_decompress_ptr cinfo)
  177092. {
  177093. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177094. JSAMPROW indexptr;
  177095. int i,j,k, nci, blksize, val, pad;
  177096. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177097. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177098. * This is not necessary in the other dithering modes. However, we
  177099. * flag whether it was done in case user changes dithering mode.
  177100. */
  177101. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177102. pad = MAXJSAMPLE*2;
  177103. cquantize->is_padded = TRUE;
  177104. } else {
  177105. pad = 0;
  177106. cquantize->is_padded = FALSE;
  177107. }
  177108. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177109. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177110. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177111. (JDIMENSION) cinfo->out_color_components);
  177112. /* blksize is number of adjacent repeated entries for a component */
  177113. blksize = cquantize->sv_actual;
  177114. for (i = 0; i < cinfo->out_color_components; i++) {
  177115. /* fill in colorindex entries for i'th color component */
  177116. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177117. blksize = blksize / nci;
  177118. /* adjust colorindex pointers to provide padding at negative indexes. */
  177119. if (pad)
  177120. cquantize->colorindex[i] += MAXJSAMPLE;
  177121. /* in loop, val = index of current output value, */
  177122. /* and k = largest j that maps to current val */
  177123. indexptr = cquantize->colorindex[i];
  177124. val = 0;
  177125. k = largest_input_value(cinfo, i, 0, nci-1);
  177126. for (j = 0; j <= MAXJSAMPLE; j++) {
  177127. while (j > k) /* advance val if past boundary */
  177128. k = largest_input_value(cinfo, i, ++val, nci-1);
  177129. /* premultiply so that no multiplication needed in main processing */
  177130. indexptr[j] = (JSAMPLE) (val * blksize);
  177131. }
  177132. /* Pad at both ends if necessary */
  177133. if (pad)
  177134. for (j = 1; j <= MAXJSAMPLE; j++) {
  177135. indexptr[-j] = indexptr[0];
  177136. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177137. }
  177138. }
  177139. }
  177140. /*
  177141. * Create an ordered-dither array for a component having ncolors
  177142. * distinct output values.
  177143. */
  177144. LOCAL(ODITHER_MATRIX_PTR)
  177145. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177146. {
  177147. ODITHER_MATRIX_PTR odither;
  177148. int j,k;
  177149. INT32 num,den;
  177150. odither = (ODITHER_MATRIX_PTR)
  177151. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177152. SIZEOF(ODITHER_MATRIX));
  177153. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177154. * Hence the dither value for the matrix cell with fill order f
  177155. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177156. * On 16-bit-int machine, be careful to avoid overflow.
  177157. */
  177158. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177159. for (j = 0; j < ODITHER_SIZE; j++) {
  177160. for (k = 0; k < ODITHER_SIZE; k++) {
  177161. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177162. * MAXJSAMPLE;
  177163. /* Ensure round towards zero despite C's lack of consistency
  177164. * about rounding negative values in integer division...
  177165. */
  177166. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177167. }
  177168. }
  177169. return odither;
  177170. }
  177171. /*
  177172. * Create the ordered-dither tables.
  177173. * Components having the same number of representative colors may
  177174. * share a dither table.
  177175. */
  177176. LOCAL(void)
  177177. create_odither_tables (j_decompress_ptr cinfo)
  177178. {
  177179. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177180. ODITHER_MATRIX_PTR odither;
  177181. int i, j, nci;
  177182. for (i = 0; i < cinfo->out_color_components; i++) {
  177183. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177184. odither = NULL; /* search for matching prior component */
  177185. for (j = 0; j < i; j++) {
  177186. if (nci == cquantize->Ncolors[j]) {
  177187. odither = cquantize->odither[j];
  177188. break;
  177189. }
  177190. }
  177191. if (odither == NULL) /* need a new table? */
  177192. odither = make_odither_array(cinfo, nci);
  177193. cquantize->odither[i] = odither;
  177194. }
  177195. }
  177196. /*
  177197. * Map some rows of pixels to the output colormapped representation.
  177198. */
  177199. METHODDEF(void)
  177200. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177201. JSAMPARRAY output_buf, int num_rows)
  177202. /* General case, no dithering */
  177203. {
  177204. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177205. JSAMPARRAY colorindex = cquantize->colorindex;
  177206. register int pixcode, ci;
  177207. register JSAMPROW ptrin, ptrout;
  177208. int row;
  177209. JDIMENSION col;
  177210. JDIMENSION width = cinfo->output_width;
  177211. register int nc = cinfo->out_color_components;
  177212. for (row = 0; row < num_rows; row++) {
  177213. ptrin = input_buf[row];
  177214. ptrout = output_buf[row];
  177215. for (col = width; col > 0; col--) {
  177216. pixcode = 0;
  177217. for (ci = 0; ci < nc; ci++) {
  177218. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177219. }
  177220. *ptrout++ = (JSAMPLE) pixcode;
  177221. }
  177222. }
  177223. }
  177224. METHODDEF(void)
  177225. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177226. JSAMPARRAY output_buf, int num_rows)
  177227. /* Fast path for out_color_components==3, no dithering */
  177228. {
  177229. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177230. register int pixcode;
  177231. register JSAMPROW ptrin, ptrout;
  177232. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177233. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177234. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177235. int row;
  177236. JDIMENSION col;
  177237. JDIMENSION width = cinfo->output_width;
  177238. for (row = 0; row < num_rows; row++) {
  177239. ptrin = input_buf[row];
  177240. ptrout = output_buf[row];
  177241. for (col = width; col > 0; col--) {
  177242. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177243. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177244. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177245. *ptrout++ = (JSAMPLE) pixcode;
  177246. }
  177247. }
  177248. }
  177249. METHODDEF(void)
  177250. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177251. JSAMPARRAY output_buf, int num_rows)
  177252. /* General case, with ordered dithering */
  177253. {
  177254. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177255. register JSAMPROW input_ptr;
  177256. register JSAMPROW output_ptr;
  177257. JSAMPROW colorindex_ci;
  177258. int * dither; /* points to active row of dither matrix */
  177259. int row_index, col_index; /* current indexes into dither matrix */
  177260. int nc = cinfo->out_color_components;
  177261. int ci;
  177262. int row;
  177263. JDIMENSION col;
  177264. JDIMENSION width = cinfo->output_width;
  177265. for (row = 0; row < num_rows; row++) {
  177266. /* Initialize output values to 0 so can process components separately */
  177267. jzero_far((void FAR *) output_buf[row],
  177268. (size_t) (width * SIZEOF(JSAMPLE)));
  177269. row_index = cquantize->row_index;
  177270. for (ci = 0; ci < nc; ci++) {
  177271. input_ptr = input_buf[row] + ci;
  177272. output_ptr = output_buf[row];
  177273. colorindex_ci = cquantize->colorindex[ci];
  177274. dither = cquantize->odither[ci][row_index];
  177275. col_index = 0;
  177276. for (col = width; col > 0; col--) {
  177277. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177278. * select output value, accumulate into output code for this pixel.
  177279. * Range-limiting need not be done explicitly, as we have extended
  177280. * the colorindex table to produce the right answers for out-of-range
  177281. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177282. * required amount of padding.
  177283. */
  177284. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177285. input_ptr += nc;
  177286. output_ptr++;
  177287. col_index = (col_index + 1) & ODITHER_MASK;
  177288. }
  177289. }
  177290. /* Advance row index for next row */
  177291. row_index = (row_index + 1) & ODITHER_MASK;
  177292. cquantize->row_index = row_index;
  177293. }
  177294. }
  177295. METHODDEF(void)
  177296. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177297. JSAMPARRAY output_buf, int num_rows)
  177298. /* Fast path for out_color_components==3, with ordered dithering */
  177299. {
  177300. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177301. register int pixcode;
  177302. register JSAMPROW input_ptr;
  177303. register JSAMPROW output_ptr;
  177304. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177305. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177306. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177307. int * dither0; /* points to active row of dither matrix */
  177308. int * dither1;
  177309. int * dither2;
  177310. int row_index, col_index; /* current indexes into dither matrix */
  177311. int row;
  177312. JDIMENSION col;
  177313. JDIMENSION width = cinfo->output_width;
  177314. for (row = 0; row < num_rows; row++) {
  177315. row_index = cquantize->row_index;
  177316. input_ptr = input_buf[row];
  177317. output_ptr = output_buf[row];
  177318. dither0 = cquantize->odither[0][row_index];
  177319. dither1 = cquantize->odither[1][row_index];
  177320. dither2 = cquantize->odither[2][row_index];
  177321. col_index = 0;
  177322. for (col = width; col > 0; col--) {
  177323. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177324. dither0[col_index]]);
  177325. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177326. dither1[col_index]]);
  177327. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177328. dither2[col_index]]);
  177329. *output_ptr++ = (JSAMPLE) pixcode;
  177330. col_index = (col_index + 1) & ODITHER_MASK;
  177331. }
  177332. row_index = (row_index + 1) & ODITHER_MASK;
  177333. cquantize->row_index = row_index;
  177334. }
  177335. }
  177336. METHODDEF(void)
  177337. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177338. JSAMPARRAY output_buf, int num_rows)
  177339. /* General case, with Floyd-Steinberg dithering */
  177340. {
  177341. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177342. register LOCFSERROR cur; /* current error or pixel value */
  177343. LOCFSERROR belowerr; /* error for pixel below cur */
  177344. LOCFSERROR bpreverr; /* error for below/prev col */
  177345. LOCFSERROR bnexterr; /* error for below/next col */
  177346. LOCFSERROR delta;
  177347. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177348. register JSAMPROW input_ptr;
  177349. register JSAMPROW output_ptr;
  177350. JSAMPROW colorindex_ci;
  177351. JSAMPROW colormap_ci;
  177352. int pixcode;
  177353. int nc = cinfo->out_color_components;
  177354. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177355. int dirnc; /* dir * nc */
  177356. int ci;
  177357. int row;
  177358. JDIMENSION col;
  177359. JDIMENSION width = cinfo->output_width;
  177360. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177361. SHIFT_TEMPS
  177362. for (row = 0; row < num_rows; row++) {
  177363. /* Initialize output values to 0 so can process components separately */
  177364. jzero_far((void FAR *) output_buf[row],
  177365. (size_t) (width * SIZEOF(JSAMPLE)));
  177366. for (ci = 0; ci < nc; ci++) {
  177367. input_ptr = input_buf[row] + ci;
  177368. output_ptr = output_buf[row];
  177369. if (cquantize->on_odd_row) {
  177370. /* work right to left in this row */
  177371. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177372. output_ptr += width-1;
  177373. dir = -1;
  177374. dirnc = -nc;
  177375. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177376. } else {
  177377. /* work left to right in this row */
  177378. dir = 1;
  177379. dirnc = nc;
  177380. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177381. }
  177382. colorindex_ci = cquantize->colorindex[ci];
  177383. colormap_ci = cquantize->sv_colormap[ci];
  177384. /* Preset error values: no error propagated to first pixel from left */
  177385. cur = 0;
  177386. /* and no error propagated to row below yet */
  177387. belowerr = bpreverr = 0;
  177388. for (col = width; col > 0; col--) {
  177389. /* cur holds the error propagated from the previous pixel on the
  177390. * current line. Add the error propagated from the previous line
  177391. * to form the complete error correction term for this pixel, and
  177392. * round the error term (which is expressed * 16) to an integer.
  177393. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177394. * for either sign of the error value.
  177395. * Note: errorptr points to *previous* column's array entry.
  177396. */
  177397. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177398. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177399. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177400. * of the range_limit array.
  177401. */
  177402. cur += GETJSAMPLE(*input_ptr);
  177403. cur = GETJSAMPLE(range_limit[cur]);
  177404. /* Select output value, accumulate into output code for this pixel */
  177405. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177406. *output_ptr += (JSAMPLE) pixcode;
  177407. /* Compute actual representation error at this pixel */
  177408. /* Note: we can do this even though we don't have the final */
  177409. /* pixel code, because the colormap is orthogonal. */
  177410. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177411. /* Compute error fractions to be propagated to adjacent pixels.
  177412. * Add these into the running sums, and simultaneously shift the
  177413. * next-line error sums left by 1 column.
  177414. */
  177415. bnexterr = cur;
  177416. delta = cur * 2;
  177417. cur += delta; /* form error * 3 */
  177418. errorptr[0] = (FSERROR) (bpreverr + cur);
  177419. cur += delta; /* form error * 5 */
  177420. bpreverr = belowerr + cur;
  177421. belowerr = bnexterr;
  177422. cur += delta; /* form error * 7 */
  177423. /* At this point cur contains the 7/16 error value to be propagated
  177424. * to the next pixel on the current line, and all the errors for the
  177425. * next line have been shifted over. We are therefore ready to move on.
  177426. */
  177427. input_ptr += dirnc; /* advance input ptr to next column */
  177428. output_ptr += dir; /* advance output ptr to next column */
  177429. errorptr += dir; /* advance errorptr to current column */
  177430. }
  177431. /* Post-loop cleanup: we must unload the final error value into the
  177432. * final fserrors[] entry. Note we need not unload belowerr because
  177433. * it is for the dummy column before or after the actual array.
  177434. */
  177435. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177436. }
  177437. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177438. }
  177439. }
  177440. /*
  177441. * Allocate workspace for Floyd-Steinberg errors.
  177442. */
  177443. LOCAL(void)
  177444. alloc_fs_workspace (j_decompress_ptr cinfo)
  177445. {
  177446. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177447. size_t arraysize;
  177448. int i;
  177449. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177450. for (i = 0; i < cinfo->out_color_components; i++) {
  177451. cquantize->fserrors[i] = (FSERRPTR)
  177452. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177453. }
  177454. }
  177455. /*
  177456. * Initialize for one-pass color quantization.
  177457. */
  177458. METHODDEF(void)
  177459. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177460. {
  177461. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177462. size_t arraysize;
  177463. int i;
  177464. /* Install my colormap. */
  177465. cinfo->colormap = cquantize->sv_colormap;
  177466. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177467. /* Initialize for desired dithering mode. */
  177468. switch (cinfo->dither_mode) {
  177469. case JDITHER_NONE:
  177470. if (cinfo->out_color_components == 3)
  177471. cquantize->pub.color_quantize = color_quantize3;
  177472. else
  177473. cquantize->pub.color_quantize = color_quantize;
  177474. break;
  177475. case JDITHER_ORDERED:
  177476. if (cinfo->out_color_components == 3)
  177477. cquantize->pub.color_quantize = quantize3_ord_dither;
  177478. else
  177479. cquantize->pub.color_quantize = quantize_ord_dither;
  177480. cquantize->row_index = 0; /* initialize state for ordered dither */
  177481. /* If user changed to ordered dither from another mode,
  177482. * we must recreate the color index table with padding.
  177483. * This will cost extra space, but probably isn't very likely.
  177484. */
  177485. if (! cquantize->is_padded)
  177486. create_colorindex(cinfo);
  177487. /* Create ordered-dither tables if we didn't already. */
  177488. if (cquantize->odither[0] == NULL)
  177489. create_odither_tables(cinfo);
  177490. break;
  177491. case JDITHER_FS:
  177492. cquantize->pub.color_quantize = quantize_fs_dither;
  177493. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177494. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177495. if (cquantize->fserrors[0] == NULL)
  177496. alloc_fs_workspace(cinfo);
  177497. /* Initialize the propagated errors to zero. */
  177498. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177499. for (i = 0; i < cinfo->out_color_components; i++)
  177500. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177501. break;
  177502. default:
  177503. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177504. break;
  177505. }
  177506. }
  177507. /*
  177508. * Finish up at the end of the pass.
  177509. */
  177510. METHODDEF(void)
  177511. finish_pass_1_quant (j_decompress_ptr)
  177512. {
  177513. /* no work in 1-pass case */
  177514. }
  177515. /*
  177516. * Switch to a new external colormap between output passes.
  177517. * Shouldn't get to this module!
  177518. */
  177519. METHODDEF(void)
  177520. new_color_map_1_quant (j_decompress_ptr cinfo)
  177521. {
  177522. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177523. }
  177524. /*
  177525. * Module initialization routine for 1-pass color quantization.
  177526. */
  177527. GLOBAL(void)
  177528. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177529. {
  177530. my_cquantize_ptr cquantize;
  177531. cquantize = (my_cquantize_ptr)
  177532. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177533. SIZEOF(my_cquantizer));
  177534. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177535. cquantize->pub.start_pass = start_pass_1_quant;
  177536. cquantize->pub.finish_pass = finish_pass_1_quant;
  177537. cquantize->pub.new_color_map = new_color_map_1_quant;
  177538. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177539. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177540. /* Make sure my internal arrays won't overflow */
  177541. if (cinfo->out_color_components > MAX_Q_COMPS)
  177542. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177543. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177544. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177545. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177546. /* Create the colormap and color index table. */
  177547. create_colormap(cinfo);
  177548. create_colorindex(cinfo);
  177549. /* Allocate Floyd-Steinberg workspace now if requested.
  177550. * We do this now since it is FAR storage and may affect the memory
  177551. * manager's space calculations. If the user changes to FS dither
  177552. * mode in a later pass, we will allocate the space then, and will
  177553. * possibly overrun the max_memory_to_use setting.
  177554. */
  177555. if (cinfo->dither_mode == JDITHER_FS)
  177556. alloc_fs_workspace(cinfo);
  177557. }
  177558. #endif /* QUANT_1PASS_SUPPORTED */
  177559. /*** End of inlined file: jquant1.c ***/
  177560. /*** Start of inlined file: jquant2.c ***/
  177561. #define JPEG_INTERNALS
  177562. #ifdef QUANT_2PASS_SUPPORTED
  177563. /*
  177564. * This module implements the well-known Heckbert paradigm for color
  177565. * quantization. Most of the ideas used here can be traced back to
  177566. * Heckbert's seminal paper
  177567. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177568. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177569. *
  177570. * In the first pass over the image, we accumulate a histogram showing the
  177571. * usage count of each possible color. To keep the histogram to a reasonable
  177572. * size, we reduce the precision of the input; typical practice is to retain
  177573. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177574. * in the same histogram cell.
  177575. *
  177576. * Next, the color-selection step begins with a box representing the whole
  177577. * color space, and repeatedly splits the "largest" remaining box until we
  177578. * have as many boxes as desired colors. Then the mean color in each
  177579. * remaining box becomes one of the possible output colors.
  177580. *
  177581. * The second pass over the image maps each input pixel to the closest output
  177582. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177583. * This mapping is logically trivial, but making it go fast enough requires
  177584. * considerable care.
  177585. *
  177586. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177587. * the "largest" box and deciding where to cut it. The particular policies
  177588. * used here have proved out well in experimental comparisons, but better ones
  177589. * may yet be found.
  177590. *
  177591. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177592. * space, processing the raw upsampled data without a color conversion step.
  177593. * This allowed the color conversion math to be done only once per colormap
  177594. * entry, not once per pixel. However, that optimization precluded other
  177595. * useful optimizations (such as merging color conversion with upsampling)
  177596. * and it also interfered with desired capabilities such as quantizing to an
  177597. * externally-supplied colormap. We have therefore abandoned that approach.
  177598. * The present code works in the post-conversion color space, typically RGB.
  177599. *
  177600. * To improve the visual quality of the results, we actually work in scaled
  177601. * RGB space, giving G distances more weight than R, and R in turn more than
  177602. * B. To do everything in integer math, we must use integer scale factors.
  177603. * The 2/3/1 scale factors used here correspond loosely to the relative
  177604. * weights of the colors in the NTSC grayscale equation.
  177605. * If you want to use this code to quantize a non-RGB color space, you'll
  177606. * probably need to change these scale factors.
  177607. */
  177608. #define R_SCALE 2 /* scale R distances by this much */
  177609. #define G_SCALE 3 /* scale G distances by this much */
  177610. #define B_SCALE 1 /* and B by this much */
  177611. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177612. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177613. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177614. * you'll get compile errors until you extend this logic. In that case
  177615. * you'll probably want to tweak the histogram sizes too.
  177616. */
  177617. #if RGB_RED == 0
  177618. #define C0_SCALE R_SCALE
  177619. #endif
  177620. #if RGB_BLUE == 0
  177621. #define C0_SCALE B_SCALE
  177622. #endif
  177623. #if RGB_GREEN == 1
  177624. #define C1_SCALE G_SCALE
  177625. #endif
  177626. #if RGB_RED == 2
  177627. #define C2_SCALE R_SCALE
  177628. #endif
  177629. #if RGB_BLUE == 2
  177630. #define C2_SCALE B_SCALE
  177631. #endif
  177632. /*
  177633. * First we have the histogram data structure and routines for creating it.
  177634. *
  177635. * The number of bits of precision can be adjusted by changing these symbols.
  177636. * We recommend keeping 6 bits for G and 5 each for R and B.
  177637. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177638. * better results; if you are short of memory, 5 bits all around will save
  177639. * some space but degrade the results.
  177640. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177641. * (preferably unsigned long) for each cell. In practice this is overkill;
  177642. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177643. * and clamping those that do overflow to the maximum value will give close-
  177644. * enough results. This reduces the recommended histogram size from 256Kb
  177645. * to 128Kb, which is a useful savings on PC-class machines.
  177646. * (In the second pass the histogram space is re-used for pixel mapping data;
  177647. * in that capacity, each cell must be able to store zero to the number of
  177648. * desired colors. 16 bits/cell is plenty for that too.)
  177649. * Since the JPEG code is intended to run in small memory model on 80x86
  177650. * machines, we can't just allocate the histogram in one chunk. Instead
  177651. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177652. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177653. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177654. * on 80x86 machines, the pointer row is in near memory but the actual
  177655. * arrays are in far memory (same arrangement as we use for image arrays).
  177656. */
  177657. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177658. /* These will do the right thing for either R,G,B or B,G,R color order,
  177659. * but you may not like the results for other color orders.
  177660. */
  177661. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177662. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177663. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177664. /* Number of elements along histogram axes. */
  177665. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177666. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177667. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177668. /* These are the amounts to shift an input value to get a histogram index. */
  177669. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177670. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177671. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177672. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177673. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177674. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177675. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177676. typedef hist2d * hist3d; /* type for top-level pointer */
  177677. /* Declarations for Floyd-Steinberg dithering.
  177678. *
  177679. * Errors are accumulated into the array fserrors[], at a resolution of
  177680. * 1/16th of a pixel count. The error at a given pixel is propagated
  177681. * to its not-yet-processed neighbors using the standard F-S fractions,
  177682. * ... (here) 7/16
  177683. * 3/16 5/16 1/16
  177684. * We work left-to-right on even rows, right-to-left on odd rows.
  177685. *
  177686. * We can get away with a single array (holding one row's worth of errors)
  177687. * by using it to store the current row's errors at pixel columns not yet
  177688. * processed, but the next row's errors at columns already processed. We
  177689. * need only a few extra variables to hold the errors immediately around the
  177690. * current column. (If we are lucky, those variables are in registers, but
  177691. * even if not, they're probably cheaper to access than array elements are.)
  177692. *
  177693. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177694. * each end saves us from special-casing the first and last pixels.
  177695. * Each entry is three values long, one value for each color component.
  177696. *
  177697. * Note: on a wide image, we might not have enough room in a PC's near data
  177698. * segment to hold the error array; so it is allocated with alloc_large.
  177699. */
  177700. #if BITS_IN_JSAMPLE == 8
  177701. typedef INT16 FSERROR; /* 16 bits should be enough */
  177702. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177703. #else
  177704. typedef INT32 FSERROR; /* may need more than 16 bits */
  177705. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177706. #endif
  177707. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177708. /* Private subobject */
  177709. typedef struct {
  177710. struct jpeg_color_quantizer pub; /* public fields */
  177711. /* Space for the eventually created colormap is stashed here */
  177712. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177713. int desired; /* desired # of colors = size of colormap */
  177714. /* Variables for accumulating image statistics */
  177715. hist3d histogram; /* pointer to the histogram */
  177716. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177717. /* Variables for Floyd-Steinberg dithering */
  177718. FSERRPTR fserrors; /* accumulated errors */
  177719. boolean on_odd_row; /* flag to remember which row we are on */
  177720. int * error_limiter; /* table for clamping the applied error */
  177721. } my_cquantizer2;
  177722. typedef my_cquantizer2 * my_cquantize_ptr2;
  177723. /*
  177724. * Prescan some rows of pixels.
  177725. * In this module the prescan simply updates the histogram, which has been
  177726. * initialized to zeroes by start_pass.
  177727. * An output_buf parameter is required by the method signature, but no data
  177728. * is actually output (in fact the buffer controller is probably passing a
  177729. * NULL pointer).
  177730. */
  177731. METHODDEF(void)
  177732. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177733. JSAMPARRAY, int num_rows)
  177734. {
  177735. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177736. register JSAMPROW ptr;
  177737. register histptr histp;
  177738. register hist3d histogram = cquantize->histogram;
  177739. int row;
  177740. JDIMENSION col;
  177741. JDIMENSION width = cinfo->output_width;
  177742. for (row = 0; row < num_rows; row++) {
  177743. ptr = input_buf[row];
  177744. for (col = width; col > 0; col--) {
  177745. /* get pixel value and index into the histogram */
  177746. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177747. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177748. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177749. /* increment, check for overflow and undo increment if so. */
  177750. if (++(*histp) <= 0)
  177751. (*histp)--;
  177752. ptr += 3;
  177753. }
  177754. }
  177755. }
  177756. /*
  177757. * Next we have the really interesting routines: selection of a colormap
  177758. * given the completed histogram.
  177759. * These routines work with a list of "boxes", each representing a rectangular
  177760. * subset of the input color space (to histogram precision).
  177761. */
  177762. typedef struct {
  177763. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177764. int c0min, c0max;
  177765. int c1min, c1max;
  177766. int c2min, c2max;
  177767. /* The volume (actually 2-norm) of the box */
  177768. INT32 volume;
  177769. /* The number of nonzero histogram cells within this box */
  177770. long colorcount;
  177771. } box;
  177772. typedef box * boxptr;
  177773. LOCAL(boxptr)
  177774. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177775. /* Find the splittable box with the largest color population */
  177776. /* Returns NULL if no splittable boxes remain */
  177777. {
  177778. register boxptr boxp;
  177779. register int i;
  177780. register long maxc = 0;
  177781. boxptr which = NULL;
  177782. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177783. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177784. which = boxp;
  177785. maxc = boxp->colorcount;
  177786. }
  177787. }
  177788. return which;
  177789. }
  177790. LOCAL(boxptr)
  177791. find_biggest_volume (boxptr boxlist, int numboxes)
  177792. /* Find the splittable box with the largest (scaled) volume */
  177793. /* Returns NULL if no splittable boxes remain */
  177794. {
  177795. register boxptr boxp;
  177796. register int i;
  177797. register INT32 maxv = 0;
  177798. boxptr which = NULL;
  177799. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177800. if (boxp->volume > maxv) {
  177801. which = boxp;
  177802. maxv = boxp->volume;
  177803. }
  177804. }
  177805. return which;
  177806. }
  177807. LOCAL(void)
  177808. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177809. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177810. /* and recompute its volume and population */
  177811. {
  177812. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177813. hist3d histogram = cquantize->histogram;
  177814. histptr histp;
  177815. int c0,c1,c2;
  177816. int c0min,c0max,c1min,c1max,c2min,c2max;
  177817. INT32 dist0,dist1,dist2;
  177818. long ccount;
  177819. c0min = boxp->c0min; c0max = boxp->c0max;
  177820. c1min = boxp->c1min; c1max = boxp->c1max;
  177821. c2min = boxp->c2min; c2max = boxp->c2max;
  177822. if (c0max > c0min)
  177823. for (c0 = c0min; c0 <= c0max; c0++)
  177824. for (c1 = c1min; c1 <= c1max; c1++) {
  177825. histp = & histogram[c0][c1][c2min];
  177826. for (c2 = c2min; c2 <= c2max; c2++)
  177827. if (*histp++ != 0) {
  177828. boxp->c0min = c0min = c0;
  177829. goto have_c0min;
  177830. }
  177831. }
  177832. have_c0min:
  177833. if (c0max > c0min)
  177834. for (c0 = c0max; c0 >= c0min; c0--)
  177835. for (c1 = c1min; c1 <= c1max; c1++) {
  177836. histp = & histogram[c0][c1][c2min];
  177837. for (c2 = c2min; c2 <= c2max; c2++)
  177838. if (*histp++ != 0) {
  177839. boxp->c0max = c0max = c0;
  177840. goto have_c0max;
  177841. }
  177842. }
  177843. have_c0max:
  177844. if (c1max > c1min)
  177845. for (c1 = c1min; c1 <= c1max; c1++)
  177846. for (c0 = c0min; c0 <= c0max; c0++) {
  177847. histp = & histogram[c0][c1][c2min];
  177848. for (c2 = c2min; c2 <= c2max; c2++)
  177849. if (*histp++ != 0) {
  177850. boxp->c1min = c1min = c1;
  177851. goto have_c1min;
  177852. }
  177853. }
  177854. have_c1min:
  177855. if (c1max > c1min)
  177856. for (c1 = c1max; c1 >= c1min; c1--)
  177857. for (c0 = c0min; c0 <= c0max; c0++) {
  177858. histp = & histogram[c0][c1][c2min];
  177859. for (c2 = c2min; c2 <= c2max; c2++)
  177860. if (*histp++ != 0) {
  177861. boxp->c1max = c1max = c1;
  177862. goto have_c1max;
  177863. }
  177864. }
  177865. have_c1max:
  177866. if (c2max > c2min)
  177867. for (c2 = c2min; c2 <= c2max; c2++)
  177868. for (c0 = c0min; c0 <= c0max; c0++) {
  177869. histp = & histogram[c0][c1min][c2];
  177870. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177871. if (*histp != 0) {
  177872. boxp->c2min = c2min = c2;
  177873. goto have_c2min;
  177874. }
  177875. }
  177876. have_c2min:
  177877. if (c2max > c2min)
  177878. for (c2 = c2max; c2 >= c2min; c2--)
  177879. for (c0 = c0min; c0 <= c0max; c0++) {
  177880. histp = & histogram[c0][c1min][c2];
  177881. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177882. if (*histp != 0) {
  177883. boxp->c2max = c2max = c2;
  177884. goto have_c2max;
  177885. }
  177886. }
  177887. have_c2max:
  177888. /* Update box volume.
  177889. * We use 2-norm rather than real volume here; this biases the method
  177890. * against making long narrow boxes, and it has the side benefit that
  177891. * a box is splittable iff norm > 0.
  177892. * Since the differences are expressed in histogram-cell units,
  177893. * we have to shift back to JSAMPLE units to get consistent distances;
  177894. * after which, we scale according to the selected distance scale factors.
  177895. */
  177896. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177897. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177898. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177899. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177900. /* Now scan remaining volume of box and compute population */
  177901. ccount = 0;
  177902. for (c0 = c0min; c0 <= c0max; c0++)
  177903. for (c1 = c1min; c1 <= c1max; c1++) {
  177904. histp = & histogram[c0][c1][c2min];
  177905. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177906. if (*histp != 0) {
  177907. ccount++;
  177908. }
  177909. }
  177910. boxp->colorcount = ccount;
  177911. }
  177912. LOCAL(int)
  177913. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177914. int desired_colors)
  177915. /* Repeatedly select and split the largest box until we have enough boxes */
  177916. {
  177917. int n,lb;
  177918. int c0,c1,c2,cmax;
  177919. register boxptr b1,b2;
  177920. while (numboxes < desired_colors) {
  177921. /* Select box to split.
  177922. * Current algorithm: by population for first half, then by volume.
  177923. */
  177924. if (numboxes*2 <= desired_colors) {
  177925. b1 = find_biggest_color_pop(boxlist, numboxes);
  177926. } else {
  177927. b1 = find_biggest_volume(boxlist, numboxes);
  177928. }
  177929. if (b1 == NULL) /* no splittable boxes left! */
  177930. break;
  177931. b2 = &boxlist[numboxes]; /* where new box will go */
  177932. /* Copy the color bounds to the new box. */
  177933. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177934. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177935. /* Choose which axis to split the box on.
  177936. * Current algorithm: longest scaled axis.
  177937. * See notes in update_box about scaling distances.
  177938. */
  177939. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177940. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177941. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177942. /* We want to break any ties in favor of green, then red, blue last.
  177943. * This code does the right thing for R,G,B or B,G,R color orders only.
  177944. */
  177945. #if RGB_RED == 0
  177946. cmax = c1; n = 1;
  177947. if (c0 > cmax) { cmax = c0; n = 0; }
  177948. if (c2 > cmax) { n = 2; }
  177949. #else
  177950. cmax = c1; n = 1;
  177951. if (c2 > cmax) { cmax = c2; n = 2; }
  177952. if (c0 > cmax) { n = 0; }
  177953. #endif
  177954. /* Choose split point along selected axis, and update box bounds.
  177955. * Current algorithm: split at halfway point.
  177956. * (Since the box has been shrunk to minimum volume,
  177957. * any split will produce two nonempty subboxes.)
  177958. * Note that lb value is max for lower box, so must be < old max.
  177959. */
  177960. switch (n) {
  177961. case 0:
  177962. lb = (b1->c0max + b1->c0min) / 2;
  177963. b1->c0max = lb;
  177964. b2->c0min = lb+1;
  177965. break;
  177966. case 1:
  177967. lb = (b1->c1max + b1->c1min) / 2;
  177968. b1->c1max = lb;
  177969. b2->c1min = lb+1;
  177970. break;
  177971. case 2:
  177972. lb = (b1->c2max + b1->c2min) / 2;
  177973. b1->c2max = lb;
  177974. b2->c2min = lb+1;
  177975. break;
  177976. }
  177977. /* Update stats for boxes */
  177978. update_box(cinfo, b1);
  177979. update_box(cinfo, b2);
  177980. numboxes++;
  177981. }
  177982. return numboxes;
  177983. }
  177984. LOCAL(void)
  177985. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177986. /* Compute representative color for a box, put it in colormap[icolor] */
  177987. {
  177988. /* Current algorithm: mean weighted by pixels (not colors) */
  177989. /* Note it is important to get the rounding correct! */
  177990. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177991. hist3d histogram = cquantize->histogram;
  177992. histptr histp;
  177993. int c0,c1,c2;
  177994. int c0min,c0max,c1min,c1max,c2min,c2max;
  177995. long count;
  177996. long total = 0;
  177997. long c0total = 0;
  177998. long c1total = 0;
  177999. long c2total = 0;
  178000. c0min = boxp->c0min; c0max = boxp->c0max;
  178001. c1min = boxp->c1min; c1max = boxp->c1max;
  178002. c2min = boxp->c2min; c2max = boxp->c2max;
  178003. for (c0 = c0min; c0 <= c0max; c0++)
  178004. for (c1 = c1min; c1 <= c1max; c1++) {
  178005. histp = & histogram[c0][c1][c2min];
  178006. for (c2 = c2min; c2 <= c2max; c2++) {
  178007. if ((count = *histp++) != 0) {
  178008. total += count;
  178009. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178010. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178011. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178012. }
  178013. }
  178014. }
  178015. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178016. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178017. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178018. }
  178019. LOCAL(void)
  178020. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178021. /* Master routine for color selection */
  178022. {
  178023. boxptr boxlist;
  178024. int numboxes;
  178025. int i;
  178026. /* Allocate workspace for box list */
  178027. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178028. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178029. /* Initialize one box containing whole space */
  178030. numboxes = 1;
  178031. boxlist[0].c0min = 0;
  178032. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178033. boxlist[0].c1min = 0;
  178034. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178035. boxlist[0].c2min = 0;
  178036. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178037. /* Shrink it to actually-used volume and set its statistics */
  178038. update_box(cinfo, & boxlist[0]);
  178039. /* Perform median-cut to produce final box list */
  178040. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178041. /* Compute the representative color for each box, fill colormap */
  178042. for (i = 0; i < numboxes; i++)
  178043. compute_color(cinfo, & boxlist[i], i);
  178044. cinfo->actual_number_of_colors = numboxes;
  178045. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178046. }
  178047. /*
  178048. * These routines are concerned with the time-critical task of mapping input
  178049. * colors to the nearest color in the selected colormap.
  178050. *
  178051. * We re-use the histogram space as an "inverse color map", essentially a
  178052. * cache for the results of nearest-color searches. All colors within a
  178053. * histogram cell will be mapped to the same colormap entry, namely the one
  178054. * closest to the cell's center. This may not be quite the closest entry to
  178055. * the actual input color, but it's almost as good. A zero in the cache
  178056. * indicates we haven't found the nearest color for that cell yet; the array
  178057. * is cleared to zeroes before starting the mapping pass. When we find the
  178058. * nearest color for a cell, its colormap index plus one is recorded in the
  178059. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178060. * when they need to use an unfilled entry in the cache.
  178061. *
  178062. * Our method of efficiently finding nearest colors is based on the "locally
  178063. * sorted search" idea described by Heckbert and on the incremental distance
  178064. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178065. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178066. * the distances from a given colormap entry to each cell of the histogram can
  178067. * be computed quickly using an incremental method: the differences between
  178068. * distances to adjacent cells themselves differ by a constant. This allows a
  178069. * fairly fast implementation of the "brute force" approach of computing the
  178070. * distance from every colormap entry to every histogram cell. Unfortunately,
  178071. * it needs a work array to hold the best-distance-so-far for each histogram
  178072. * cell (because the inner loop has to be over cells, not colormap entries).
  178073. * The work array elements have to be INT32s, so the work array would need
  178074. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178075. *
  178076. * To get around these problems, we apply Thomas' method to compute the
  178077. * nearest colors for only the cells within a small subbox of the histogram.
  178078. * The work array need be only as big as the subbox, so the memory usage
  178079. * problem is solved. Furthermore, we need not fill subboxes that are never
  178080. * referenced in pass2; many images use only part of the color gamut, so a
  178081. * fair amount of work is saved. An additional advantage of this
  178082. * approach is that we can apply Heckbert's locality criterion to quickly
  178083. * eliminate colormap entries that are far away from the subbox; typically
  178084. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178085. * and we need not compute their distances to individual cells in the subbox.
  178086. * The speed of this approach is heavily influenced by the subbox size: too
  178087. * small means too much overhead, too big loses because Heckbert's criterion
  178088. * can't eliminate as many colormap entries. Empirically the best subbox
  178089. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178090. *
  178091. * Thomas' article also describes a refined method which is asymptotically
  178092. * faster than the brute-force method, but it is also far more complex and
  178093. * cannot efficiently be applied to small subboxes. It is therefore not
  178094. * useful for programs intended to be portable to DOS machines. On machines
  178095. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178096. * refined method might be faster than the present code --- but then again,
  178097. * it might not be any faster, and it's certainly more complicated.
  178098. */
  178099. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178100. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178101. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178102. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178103. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178104. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178105. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178106. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178107. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178108. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178109. /*
  178110. * The next three routines implement inverse colormap filling. They could
  178111. * all be folded into one big routine, but splitting them up this way saves
  178112. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178113. * and may allow some compilers to produce better code by registerizing more
  178114. * inner-loop variables.
  178115. */
  178116. LOCAL(int)
  178117. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178118. JSAMPLE colorlist[])
  178119. /* Locate the colormap entries close enough to an update box to be candidates
  178120. * for the nearest entry to some cell(s) in the update box. The update box
  178121. * is specified by the center coordinates of its first cell. The number of
  178122. * candidate colormap entries is returned, and their colormap indexes are
  178123. * placed in colorlist[].
  178124. * This routine uses Heckbert's "locally sorted search" criterion to select
  178125. * the colors that need further consideration.
  178126. */
  178127. {
  178128. int numcolors = cinfo->actual_number_of_colors;
  178129. int maxc0, maxc1, maxc2;
  178130. int centerc0, centerc1, centerc2;
  178131. int i, x, ncolors;
  178132. INT32 minmaxdist, min_dist, max_dist, tdist;
  178133. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178134. /* Compute true coordinates of update box's upper corner and center.
  178135. * Actually we compute the coordinates of the center of the upper-corner
  178136. * histogram cell, which are the upper bounds of the volume we care about.
  178137. * Note that since ">>" rounds down, the "center" values may be closer to
  178138. * min than to max; hence comparisons to them must be "<=", not "<".
  178139. */
  178140. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178141. centerc0 = (minc0 + maxc0) >> 1;
  178142. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178143. centerc1 = (minc1 + maxc1) >> 1;
  178144. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178145. centerc2 = (minc2 + maxc2) >> 1;
  178146. /* For each color in colormap, find:
  178147. * 1. its minimum squared-distance to any point in the update box
  178148. * (zero if color is within update box);
  178149. * 2. its maximum squared-distance to any point in the update box.
  178150. * Both of these can be found by considering only the corners of the box.
  178151. * We save the minimum distance for each color in mindist[];
  178152. * only the smallest maximum distance is of interest.
  178153. */
  178154. minmaxdist = 0x7FFFFFFFL;
  178155. for (i = 0; i < numcolors; i++) {
  178156. /* We compute the squared-c0-distance term, then add in the other two. */
  178157. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178158. if (x < minc0) {
  178159. tdist = (x - minc0) * C0_SCALE;
  178160. min_dist = tdist*tdist;
  178161. tdist = (x - maxc0) * C0_SCALE;
  178162. max_dist = tdist*tdist;
  178163. } else if (x > maxc0) {
  178164. tdist = (x - maxc0) * C0_SCALE;
  178165. min_dist = tdist*tdist;
  178166. tdist = (x - minc0) * C0_SCALE;
  178167. max_dist = tdist*tdist;
  178168. } else {
  178169. /* within cell range so no contribution to min_dist */
  178170. min_dist = 0;
  178171. if (x <= centerc0) {
  178172. tdist = (x - maxc0) * C0_SCALE;
  178173. max_dist = tdist*tdist;
  178174. } else {
  178175. tdist = (x - minc0) * C0_SCALE;
  178176. max_dist = tdist*tdist;
  178177. }
  178178. }
  178179. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178180. if (x < minc1) {
  178181. tdist = (x - minc1) * C1_SCALE;
  178182. min_dist += tdist*tdist;
  178183. tdist = (x - maxc1) * C1_SCALE;
  178184. max_dist += tdist*tdist;
  178185. } else if (x > maxc1) {
  178186. tdist = (x - maxc1) * C1_SCALE;
  178187. min_dist += tdist*tdist;
  178188. tdist = (x - minc1) * C1_SCALE;
  178189. max_dist += tdist*tdist;
  178190. } else {
  178191. /* within cell range so no contribution to min_dist */
  178192. if (x <= centerc1) {
  178193. tdist = (x - maxc1) * C1_SCALE;
  178194. max_dist += tdist*tdist;
  178195. } else {
  178196. tdist = (x - minc1) * C1_SCALE;
  178197. max_dist += tdist*tdist;
  178198. }
  178199. }
  178200. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178201. if (x < minc2) {
  178202. tdist = (x - minc2) * C2_SCALE;
  178203. min_dist += tdist*tdist;
  178204. tdist = (x - maxc2) * C2_SCALE;
  178205. max_dist += tdist*tdist;
  178206. } else if (x > maxc2) {
  178207. tdist = (x - maxc2) * C2_SCALE;
  178208. min_dist += tdist*tdist;
  178209. tdist = (x - minc2) * C2_SCALE;
  178210. max_dist += tdist*tdist;
  178211. } else {
  178212. /* within cell range so no contribution to min_dist */
  178213. if (x <= centerc2) {
  178214. tdist = (x - maxc2) * C2_SCALE;
  178215. max_dist += tdist*tdist;
  178216. } else {
  178217. tdist = (x - minc2) * C2_SCALE;
  178218. max_dist += tdist*tdist;
  178219. }
  178220. }
  178221. mindist[i] = min_dist; /* save away the results */
  178222. if (max_dist < minmaxdist)
  178223. minmaxdist = max_dist;
  178224. }
  178225. /* Now we know that no cell in the update box is more than minmaxdist
  178226. * away from some colormap entry. Therefore, only colors that are
  178227. * within minmaxdist of some part of the box need be considered.
  178228. */
  178229. ncolors = 0;
  178230. for (i = 0; i < numcolors; i++) {
  178231. if (mindist[i] <= minmaxdist)
  178232. colorlist[ncolors++] = (JSAMPLE) i;
  178233. }
  178234. return ncolors;
  178235. }
  178236. LOCAL(void)
  178237. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178238. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178239. /* Find the closest colormap entry for each cell in the update box,
  178240. * given the list of candidate colors prepared by find_nearby_colors.
  178241. * Return the indexes of the closest entries in the bestcolor[] array.
  178242. * This routine uses Thomas' incremental distance calculation method to
  178243. * find the distance from a colormap entry to successive cells in the box.
  178244. */
  178245. {
  178246. int ic0, ic1, ic2;
  178247. int i, icolor;
  178248. register INT32 * bptr; /* pointer into bestdist[] array */
  178249. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178250. INT32 dist0, dist1; /* initial distance values */
  178251. register INT32 dist2; /* current distance in inner loop */
  178252. INT32 xx0, xx1; /* distance increments */
  178253. register INT32 xx2;
  178254. INT32 inc0, inc1, inc2; /* initial values for increments */
  178255. /* This array holds the distance to the nearest-so-far color for each cell */
  178256. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178257. /* Initialize best-distance for each cell of the update box */
  178258. bptr = bestdist;
  178259. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178260. *bptr++ = 0x7FFFFFFFL;
  178261. /* For each color selected by find_nearby_colors,
  178262. * compute its distance to the center of each cell in the box.
  178263. * If that's less than best-so-far, update best distance and color number.
  178264. */
  178265. /* Nominal steps between cell centers ("x" in Thomas article) */
  178266. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178267. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178268. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178269. for (i = 0; i < numcolors; i++) {
  178270. icolor = GETJSAMPLE(colorlist[i]);
  178271. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178272. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178273. dist0 = inc0*inc0;
  178274. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178275. dist0 += inc1*inc1;
  178276. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178277. dist0 += inc2*inc2;
  178278. /* Form the initial difference increments */
  178279. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178280. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178281. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178282. /* Now loop over all cells in box, updating distance per Thomas method */
  178283. bptr = bestdist;
  178284. cptr = bestcolor;
  178285. xx0 = inc0;
  178286. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178287. dist1 = dist0;
  178288. xx1 = inc1;
  178289. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178290. dist2 = dist1;
  178291. xx2 = inc2;
  178292. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178293. if (dist2 < *bptr) {
  178294. *bptr = dist2;
  178295. *cptr = (JSAMPLE) icolor;
  178296. }
  178297. dist2 += xx2;
  178298. xx2 += 2 * STEP_C2 * STEP_C2;
  178299. bptr++;
  178300. cptr++;
  178301. }
  178302. dist1 += xx1;
  178303. xx1 += 2 * STEP_C1 * STEP_C1;
  178304. }
  178305. dist0 += xx0;
  178306. xx0 += 2 * STEP_C0 * STEP_C0;
  178307. }
  178308. }
  178309. }
  178310. LOCAL(void)
  178311. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178312. /* Fill the inverse-colormap entries in the update box that contains */
  178313. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178314. /* we can fill as many others as we wish.) */
  178315. {
  178316. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178317. hist3d histogram = cquantize->histogram;
  178318. int minc0, minc1, minc2; /* lower left corner of update box */
  178319. int ic0, ic1, ic2;
  178320. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178321. register histptr cachep; /* pointer into main cache array */
  178322. /* This array lists the candidate colormap indexes. */
  178323. JSAMPLE colorlist[MAXNUMCOLORS];
  178324. int numcolors; /* number of candidate colors */
  178325. /* This array holds the actually closest colormap index for each cell. */
  178326. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178327. /* Convert cell coordinates to update box ID */
  178328. c0 >>= BOX_C0_LOG;
  178329. c1 >>= BOX_C1_LOG;
  178330. c2 >>= BOX_C2_LOG;
  178331. /* Compute true coordinates of update box's origin corner.
  178332. * Actually we compute the coordinates of the center of the corner
  178333. * histogram cell, which are the lower bounds of the volume we care about.
  178334. */
  178335. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178336. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178337. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178338. /* Determine which colormap entries are close enough to be candidates
  178339. * for the nearest entry to some cell in the update box.
  178340. */
  178341. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178342. /* Determine the actually nearest colors. */
  178343. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178344. bestcolor);
  178345. /* Save the best color numbers (plus 1) in the main cache array */
  178346. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178347. c1 <<= BOX_C1_LOG;
  178348. c2 <<= BOX_C2_LOG;
  178349. cptr = bestcolor;
  178350. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178351. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178352. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178353. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178354. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178355. }
  178356. }
  178357. }
  178358. }
  178359. /*
  178360. * Map some rows of pixels to the output colormapped representation.
  178361. */
  178362. METHODDEF(void)
  178363. pass2_no_dither (j_decompress_ptr cinfo,
  178364. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178365. /* This version performs no dithering */
  178366. {
  178367. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178368. hist3d histogram = cquantize->histogram;
  178369. register JSAMPROW inptr, outptr;
  178370. register histptr cachep;
  178371. register int c0, c1, c2;
  178372. int row;
  178373. JDIMENSION col;
  178374. JDIMENSION width = cinfo->output_width;
  178375. for (row = 0; row < num_rows; row++) {
  178376. inptr = input_buf[row];
  178377. outptr = output_buf[row];
  178378. for (col = width; col > 0; col--) {
  178379. /* get pixel value and index into the cache */
  178380. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178381. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178382. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178383. cachep = & histogram[c0][c1][c2];
  178384. /* If we have not seen this color before, find nearest colormap entry */
  178385. /* and update the cache */
  178386. if (*cachep == 0)
  178387. fill_inverse_cmap(cinfo, c0,c1,c2);
  178388. /* Now emit the colormap index for this cell */
  178389. *outptr++ = (JSAMPLE) (*cachep - 1);
  178390. }
  178391. }
  178392. }
  178393. METHODDEF(void)
  178394. pass2_fs_dither (j_decompress_ptr cinfo,
  178395. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178396. /* This version performs Floyd-Steinberg dithering */
  178397. {
  178398. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178399. hist3d histogram = cquantize->histogram;
  178400. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178401. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178402. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178403. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178404. JSAMPROW inptr; /* => current input pixel */
  178405. JSAMPROW outptr; /* => current output pixel */
  178406. histptr cachep;
  178407. int dir; /* +1 or -1 depending on direction */
  178408. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178409. int row;
  178410. JDIMENSION col;
  178411. JDIMENSION width = cinfo->output_width;
  178412. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178413. int *error_limit = cquantize->error_limiter;
  178414. JSAMPROW colormap0 = cinfo->colormap[0];
  178415. JSAMPROW colormap1 = cinfo->colormap[1];
  178416. JSAMPROW colormap2 = cinfo->colormap[2];
  178417. SHIFT_TEMPS
  178418. for (row = 0; row < num_rows; row++) {
  178419. inptr = input_buf[row];
  178420. outptr = output_buf[row];
  178421. if (cquantize->on_odd_row) {
  178422. /* work right to left in this row */
  178423. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178424. outptr += width-1;
  178425. dir = -1;
  178426. dir3 = -3;
  178427. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178428. cquantize->on_odd_row = FALSE; /* flip for next time */
  178429. } else {
  178430. /* work left to right in this row */
  178431. dir = 1;
  178432. dir3 = 3;
  178433. errorptr = cquantize->fserrors; /* => entry before first real column */
  178434. cquantize->on_odd_row = TRUE; /* flip for next time */
  178435. }
  178436. /* Preset error values: no error propagated to first pixel from left */
  178437. cur0 = cur1 = cur2 = 0;
  178438. /* and no error propagated to row below yet */
  178439. belowerr0 = belowerr1 = belowerr2 = 0;
  178440. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178441. for (col = width; col > 0; col--) {
  178442. /* curN holds the error propagated from the previous pixel on the
  178443. * current line. Add the error propagated from the previous line
  178444. * to form the complete error correction term for this pixel, and
  178445. * round the error term (which is expressed * 16) to an integer.
  178446. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178447. * for either sign of the error value.
  178448. * Note: errorptr points to *previous* column's array entry.
  178449. */
  178450. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178451. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178452. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178453. /* Limit the error using transfer function set by init_error_limit.
  178454. * See comments with init_error_limit for rationale.
  178455. */
  178456. cur0 = error_limit[cur0];
  178457. cur1 = error_limit[cur1];
  178458. cur2 = error_limit[cur2];
  178459. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178460. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178461. * this sets the required size of the range_limit array.
  178462. */
  178463. cur0 += GETJSAMPLE(inptr[0]);
  178464. cur1 += GETJSAMPLE(inptr[1]);
  178465. cur2 += GETJSAMPLE(inptr[2]);
  178466. cur0 = GETJSAMPLE(range_limit[cur0]);
  178467. cur1 = GETJSAMPLE(range_limit[cur1]);
  178468. cur2 = GETJSAMPLE(range_limit[cur2]);
  178469. /* Index into the cache with adjusted pixel value */
  178470. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178471. /* If we have not seen this color before, find nearest colormap */
  178472. /* entry and update the cache */
  178473. if (*cachep == 0)
  178474. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178475. /* Now emit the colormap index for this cell */
  178476. { register int pixcode = *cachep - 1;
  178477. *outptr = (JSAMPLE) pixcode;
  178478. /* Compute representation error for this pixel */
  178479. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178480. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178481. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178482. }
  178483. /* Compute error fractions to be propagated to adjacent pixels.
  178484. * Add these into the running sums, and simultaneously shift the
  178485. * next-line error sums left by 1 column.
  178486. */
  178487. { register LOCFSERROR bnexterr, delta;
  178488. bnexterr = cur0; /* Process component 0 */
  178489. delta = cur0 * 2;
  178490. cur0 += delta; /* form error * 3 */
  178491. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178492. cur0 += delta; /* form error * 5 */
  178493. bpreverr0 = belowerr0 + cur0;
  178494. belowerr0 = bnexterr;
  178495. cur0 += delta; /* form error * 7 */
  178496. bnexterr = cur1; /* Process component 1 */
  178497. delta = cur1 * 2;
  178498. cur1 += delta; /* form error * 3 */
  178499. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178500. cur1 += delta; /* form error * 5 */
  178501. bpreverr1 = belowerr1 + cur1;
  178502. belowerr1 = bnexterr;
  178503. cur1 += delta; /* form error * 7 */
  178504. bnexterr = cur2; /* Process component 2 */
  178505. delta = cur2 * 2;
  178506. cur2 += delta; /* form error * 3 */
  178507. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178508. cur2 += delta; /* form error * 5 */
  178509. bpreverr2 = belowerr2 + cur2;
  178510. belowerr2 = bnexterr;
  178511. cur2 += delta; /* form error * 7 */
  178512. }
  178513. /* At this point curN contains the 7/16 error value to be propagated
  178514. * to the next pixel on the current line, and all the errors for the
  178515. * next line have been shifted over. We are therefore ready to move on.
  178516. */
  178517. inptr += dir3; /* Advance pixel pointers to next column */
  178518. outptr += dir;
  178519. errorptr += dir3; /* advance errorptr to current column */
  178520. }
  178521. /* Post-loop cleanup: we must unload the final error values into the
  178522. * final fserrors[] entry. Note we need not unload belowerrN because
  178523. * it is for the dummy column before or after the actual array.
  178524. */
  178525. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178526. errorptr[1] = (FSERROR) bpreverr1;
  178527. errorptr[2] = (FSERROR) bpreverr2;
  178528. }
  178529. }
  178530. /*
  178531. * Initialize the error-limiting transfer function (lookup table).
  178532. * The raw F-S error computation can potentially compute error values of up to
  178533. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178534. * much less, otherwise obviously wrong pixels will be created. (Typical
  178535. * effects include weird fringes at color-area boundaries, isolated bright
  178536. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178537. * is to ensure that the "corners" of the color cube are allocated as output
  178538. * colors; then repeated errors in the same direction cannot cause cascading
  178539. * error buildup. However, that only prevents the error from getting
  178540. * completely out of hand; Aaron Giles reports that error limiting improves
  178541. * the results even with corner colors allocated.
  178542. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178543. * well, but the smoother transfer function used below is even better. Thanks
  178544. * to Aaron Giles for this idea.
  178545. */
  178546. LOCAL(void)
  178547. init_error_limit (j_decompress_ptr cinfo)
  178548. /* Allocate and fill in the error_limiter table */
  178549. {
  178550. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178551. int * table;
  178552. int in, out;
  178553. table = (int *) (*cinfo->mem->alloc_small)
  178554. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178555. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178556. cquantize->error_limiter = table;
  178557. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178558. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178559. out = 0;
  178560. for (in = 0; in < STEPSIZE; in++, out++) {
  178561. table[in] = out; table[-in] = -out;
  178562. }
  178563. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178564. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178565. table[in] = out; table[-in] = -out;
  178566. }
  178567. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178568. for (; in <= MAXJSAMPLE; in++) {
  178569. table[in] = out; table[-in] = -out;
  178570. }
  178571. #undef STEPSIZE
  178572. }
  178573. /*
  178574. * Finish up at the end of each pass.
  178575. */
  178576. METHODDEF(void)
  178577. finish_pass1 (j_decompress_ptr cinfo)
  178578. {
  178579. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178580. /* Select the representative colors and fill in cinfo->colormap */
  178581. cinfo->colormap = cquantize->sv_colormap;
  178582. select_colors(cinfo, cquantize->desired);
  178583. /* Force next pass to zero the color index table */
  178584. cquantize->needs_zeroed = TRUE;
  178585. }
  178586. METHODDEF(void)
  178587. finish_pass2 (j_decompress_ptr)
  178588. {
  178589. /* no work */
  178590. }
  178591. /*
  178592. * Initialize for each processing pass.
  178593. */
  178594. METHODDEF(void)
  178595. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178596. {
  178597. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178598. hist3d histogram = cquantize->histogram;
  178599. int i;
  178600. /* Only F-S dithering or no dithering is supported. */
  178601. /* If user asks for ordered dither, give him F-S. */
  178602. if (cinfo->dither_mode != JDITHER_NONE)
  178603. cinfo->dither_mode = JDITHER_FS;
  178604. if (is_pre_scan) {
  178605. /* Set up method pointers */
  178606. cquantize->pub.color_quantize = prescan_quantize;
  178607. cquantize->pub.finish_pass = finish_pass1;
  178608. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178609. } else {
  178610. /* Set up method pointers */
  178611. if (cinfo->dither_mode == JDITHER_FS)
  178612. cquantize->pub.color_quantize = pass2_fs_dither;
  178613. else
  178614. cquantize->pub.color_quantize = pass2_no_dither;
  178615. cquantize->pub.finish_pass = finish_pass2;
  178616. /* Make sure color count is acceptable */
  178617. i = cinfo->actual_number_of_colors;
  178618. if (i < 1)
  178619. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178620. if (i > MAXNUMCOLORS)
  178621. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178622. if (cinfo->dither_mode == JDITHER_FS) {
  178623. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178624. (3 * SIZEOF(FSERROR)));
  178625. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178626. if (cquantize->fserrors == NULL)
  178627. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178628. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178629. /* Initialize the propagated errors to zero. */
  178630. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178631. /* Make the error-limit table if we didn't already. */
  178632. if (cquantize->error_limiter == NULL)
  178633. init_error_limit(cinfo);
  178634. cquantize->on_odd_row = FALSE;
  178635. }
  178636. }
  178637. /* Zero the histogram or inverse color map, if necessary */
  178638. if (cquantize->needs_zeroed) {
  178639. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178640. jzero_far((void FAR *) histogram[i],
  178641. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178642. }
  178643. cquantize->needs_zeroed = FALSE;
  178644. }
  178645. }
  178646. /*
  178647. * Switch to a new external colormap between output passes.
  178648. */
  178649. METHODDEF(void)
  178650. new_color_map_2_quant (j_decompress_ptr cinfo)
  178651. {
  178652. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178653. /* Reset the inverse color map */
  178654. cquantize->needs_zeroed = TRUE;
  178655. }
  178656. /*
  178657. * Module initialization routine for 2-pass color quantization.
  178658. */
  178659. GLOBAL(void)
  178660. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178661. {
  178662. my_cquantize_ptr2 cquantize;
  178663. int i;
  178664. cquantize = (my_cquantize_ptr2)
  178665. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178666. SIZEOF(my_cquantizer2));
  178667. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178668. cquantize->pub.start_pass = start_pass_2_quant;
  178669. cquantize->pub.new_color_map = new_color_map_2_quant;
  178670. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178671. cquantize->error_limiter = NULL;
  178672. /* Make sure jdmaster didn't give me a case I can't handle */
  178673. if (cinfo->out_color_components != 3)
  178674. ERREXIT(cinfo, JERR_NOTIMPL);
  178675. /* Allocate the histogram/inverse colormap storage */
  178676. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178677. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178678. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178679. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178680. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178681. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178682. }
  178683. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178684. /* Allocate storage for the completed colormap, if required.
  178685. * We do this now since it is FAR storage and may affect
  178686. * the memory manager's space calculations.
  178687. */
  178688. if (cinfo->enable_2pass_quant) {
  178689. /* Make sure color count is acceptable */
  178690. int desired = cinfo->desired_number_of_colors;
  178691. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178692. if (desired < 8)
  178693. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178694. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178695. if (desired > MAXNUMCOLORS)
  178696. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178697. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178698. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178699. cquantize->desired = desired;
  178700. } else
  178701. cquantize->sv_colormap = NULL;
  178702. /* Only F-S dithering or no dithering is supported. */
  178703. /* If user asks for ordered dither, give him F-S. */
  178704. if (cinfo->dither_mode != JDITHER_NONE)
  178705. cinfo->dither_mode = JDITHER_FS;
  178706. /* Allocate Floyd-Steinberg workspace if necessary.
  178707. * This isn't really needed until pass 2, but again it is FAR storage.
  178708. * Although we will cope with a later change in dither_mode,
  178709. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178710. */
  178711. if (cinfo->dither_mode == JDITHER_FS) {
  178712. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178713. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178714. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178715. /* Might as well create the error-limiting table too. */
  178716. init_error_limit(cinfo);
  178717. }
  178718. }
  178719. #endif /* QUANT_2PASS_SUPPORTED */
  178720. /*** End of inlined file: jquant2.c ***/
  178721. /*** Start of inlined file: jutils.c ***/
  178722. #define JPEG_INTERNALS
  178723. /*
  178724. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178725. * of a DCT block read in natural order (left to right, top to bottom).
  178726. */
  178727. #if 0 /* This table is not actually needed in v6a */
  178728. const int jpeg_zigzag_order[DCTSIZE2] = {
  178729. 0, 1, 5, 6, 14, 15, 27, 28,
  178730. 2, 4, 7, 13, 16, 26, 29, 42,
  178731. 3, 8, 12, 17, 25, 30, 41, 43,
  178732. 9, 11, 18, 24, 31, 40, 44, 53,
  178733. 10, 19, 23, 32, 39, 45, 52, 54,
  178734. 20, 22, 33, 38, 46, 51, 55, 60,
  178735. 21, 34, 37, 47, 50, 56, 59, 61,
  178736. 35, 36, 48, 49, 57, 58, 62, 63
  178737. };
  178738. #endif
  178739. /*
  178740. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178741. * of zigzag order.
  178742. *
  178743. * When reading corrupted data, the Huffman decoders could attempt
  178744. * to reference an entry beyond the end of this array (if the decoded
  178745. * zero run length reaches past the end of the block). To prevent
  178746. * wild stores without adding an inner-loop test, we put some extra
  178747. * "63"s after the real entries. This will cause the extra coefficient
  178748. * to be stored in location 63 of the block, not somewhere random.
  178749. * The worst case would be a run-length of 15, which means we need 16
  178750. * fake entries.
  178751. */
  178752. const int jpeg_natural_order[DCTSIZE2+16] = {
  178753. 0, 1, 8, 16, 9, 2, 3, 10,
  178754. 17, 24, 32, 25, 18, 11, 4, 5,
  178755. 12, 19, 26, 33, 40, 48, 41, 34,
  178756. 27, 20, 13, 6, 7, 14, 21, 28,
  178757. 35, 42, 49, 56, 57, 50, 43, 36,
  178758. 29, 22, 15, 23, 30, 37, 44, 51,
  178759. 58, 59, 52, 45, 38, 31, 39, 46,
  178760. 53, 60, 61, 54, 47, 55, 62, 63,
  178761. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178762. 63, 63, 63, 63, 63, 63, 63, 63
  178763. };
  178764. /*
  178765. * Arithmetic utilities
  178766. */
  178767. GLOBAL(long)
  178768. jdiv_round_up (long a, long b)
  178769. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178770. /* Assumes a >= 0, b > 0 */
  178771. {
  178772. return (a + b - 1L) / b;
  178773. }
  178774. GLOBAL(long)
  178775. jround_up (long a, long b)
  178776. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178777. /* Assumes a >= 0, b > 0 */
  178778. {
  178779. a += b - 1L;
  178780. return a - (a % b);
  178781. }
  178782. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178783. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178784. * are FAR and we're assuming a small-pointer memory model. However, some
  178785. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178786. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178787. * Otherwise, the routines below do it the hard way. (The performance cost
  178788. * is not all that great, because these routines aren't very heavily used.)
  178789. */
  178790. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178791. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178792. #define FMEMZERO(target,size) MEMZERO(target,size)
  178793. #else /* 80x86 case, define if we can */
  178794. #ifdef USE_FMEM
  178795. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178796. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178797. #endif
  178798. #endif
  178799. GLOBAL(void)
  178800. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178801. JSAMPARRAY output_array, int dest_row,
  178802. int num_rows, JDIMENSION num_cols)
  178803. /* Copy some rows of samples from one place to another.
  178804. * num_rows rows are copied from input_array[source_row++]
  178805. * to output_array[dest_row++]; these areas may overlap for duplication.
  178806. * The source and destination arrays must be at least as wide as num_cols.
  178807. */
  178808. {
  178809. register JSAMPROW inptr, outptr;
  178810. #ifdef FMEMCOPY
  178811. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178812. #else
  178813. register JDIMENSION count;
  178814. #endif
  178815. register int row;
  178816. input_array += source_row;
  178817. output_array += dest_row;
  178818. for (row = num_rows; row > 0; row--) {
  178819. inptr = *input_array++;
  178820. outptr = *output_array++;
  178821. #ifdef FMEMCOPY
  178822. FMEMCOPY(outptr, inptr, count);
  178823. #else
  178824. for (count = num_cols; count > 0; count--)
  178825. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178826. #endif
  178827. }
  178828. }
  178829. GLOBAL(void)
  178830. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178831. JDIMENSION num_blocks)
  178832. /* Copy a row of coefficient blocks from one place to another. */
  178833. {
  178834. #ifdef FMEMCOPY
  178835. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178836. #else
  178837. register JCOEFPTR inptr, outptr;
  178838. register long count;
  178839. inptr = (JCOEFPTR) input_row;
  178840. outptr = (JCOEFPTR) output_row;
  178841. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178842. *outptr++ = *inptr++;
  178843. }
  178844. #endif
  178845. }
  178846. GLOBAL(void)
  178847. jzero_far (void FAR * target, size_t bytestozero)
  178848. /* Zero out a chunk of FAR memory. */
  178849. /* This might be sample-array data, block-array data, or alloc_large data. */
  178850. {
  178851. #ifdef FMEMZERO
  178852. FMEMZERO(target, bytestozero);
  178853. #else
  178854. register char FAR * ptr = (char FAR *) target;
  178855. register size_t count;
  178856. for (count = bytestozero; count > 0; count--) {
  178857. *ptr++ = 0;
  178858. }
  178859. #endif
  178860. }
  178861. /*** End of inlined file: jutils.c ***/
  178862. /*** Start of inlined file: transupp.c ***/
  178863. /* Although this file really shouldn't have access to the library internals,
  178864. * it's helpful to let it call jround_up() and jcopy_block_row().
  178865. */
  178866. #define JPEG_INTERNALS
  178867. /*** Start of inlined file: transupp.h ***/
  178868. /* If you happen not to want the image transform support, disable it here */
  178869. #ifndef TRANSFORMS_SUPPORTED
  178870. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178871. #endif
  178872. /* Short forms of external names for systems with brain-damaged linkers. */
  178873. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178874. #define jtransform_request_workspace jTrRequest
  178875. #define jtransform_adjust_parameters jTrAdjust
  178876. #define jtransform_execute_transformation jTrExec
  178877. #define jcopy_markers_setup jCMrkSetup
  178878. #define jcopy_markers_execute jCMrkExec
  178879. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178880. /*
  178881. * Codes for supported types of image transformations.
  178882. */
  178883. typedef enum {
  178884. JXFORM_NONE, /* no transformation */
  178885. JXFORM_FLIP_H, /* horizontal flip */
  178886. JXFORM_FLIP_V, /* vertical flip */
  178887. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178888. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178889. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178890. JXFORM_ROT_180, /* 180-degree rotation */
  178891. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178892. } JXFORM_CODE;
  178893. /*
  178894. * Although rotating and flipping data expressed as DCT coefficients is not
  178895. * hard, there is an asymmetry in the JPEG format specification for images
  178896. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178897. * image edges are padded out to the next iMCU boundary with junk data; but
  178898. * no padding is possible at the top and left edges. If we were to flip
  178899. * the whole image including the pad data, then pad garbage would become
  178900. * visible at the top and/or left, and real pixels would disappear into the
  178901. * pad margins --- perhaps permanently, since encoders & decoders may not
  178902. * bother to preserve DCT blocks that appear to be completely outside the
  178903. * nominal image area. So, we have to exclude any partial iMCUs from the
  178904. * basic transformation.
  178905. *
  178906. * Transpose is the only transformation that can handle partial iMCUs at the
  178907. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178908. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178909. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178910. * The other transforms are defined as combinations of these basic transforms
  178911. * and process edge blocks in a way that preserves the equivalence.
  178912. *
  178913. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178914. * this is not strictly lossless, but it usually gives the best-looking
  178915. * result for odd-size images. Note that when this option is active,
  178916. * the expected mathematical equivalences between the transforms may not hold.
  178917. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178918. * followed by -rot 180 -trim trims both edges.)
  178919. *
  178920. * We also offer a "force to grayscale" option, which simply discards the
  178921. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178922. * the luminance channel is preserved exactly. It's not the same kind of
  178923. * thing as the rotate/flip transformations, but it's convenient to handle it
  178924. * as part of this package, mainly because the transformation routines have to
  178925. * be aware of the option to know how many components to work on.
  178926. */
  178927. typedef struct {
  178928. /* Options: set by caller */
  178929. JXFORM_CODE transform; /* image transform operator */
  178930. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178931. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178932. /* Internal workspace: caller should not touch these */
  178933. int num_components; /* # of components in workspace */
  178934. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178935. } jpeg_transform_info;
  178936. #if TRANSFORMS_SUPPORTED
  178937. /* Request any required workspace */
  178938. EXTERN(void) jtransform_request_workspace
  178939. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178940. /* Adjust output image parameters */
  178941. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178942. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178943. jvirt_barray_ptr *src_coef_arrays,
  178944. jpeg_transform_info *info));
  178945. /* Execute the actual transformation, if any */
  178946. EXTERN(void) jtransform_execute_transformation
  178947. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178948. jvirt_barray_ptr *src_coef_arrays,
  178949. jpeg_transform_info *info));
  178950. #endif /* TRANSFORMS_SUPPORTED */
  178951. /*
  178952. * Support for copying optional markers from source to destination file.
  178953. */
  178954. typedef enum {
  178955. JCOPYOPT_NONE, /* copy no optional markers */
  178956. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178957. JCOPYOPT_ALL /* copy all optional markers */
  178958. } JCOPY_OPTION;
  178959. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178960. /* Setup decompression object to save desired markers in memory */
  178961. EXTERN(void) jcopy_markers_setup
  178962. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178963. /* Copy markers saved in the given source object to the destination object */
  178964. EXTERN(void) jcopy_markers_execute
  178965. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178966. JCOPY_OPTION option));
  178967. /*** End of inlined file: transupp.h ***/
  178968. /* My own external interface */
  178969. #if TRANSFORMS_SUPPORTED
  178970. /*
  178971. * Lossless image transformation routines. These routines work on DCT
  178972. * coefficient arrays and thus do not require any lossy decompression
  178973. * or recompression of the image.
  178974. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178975. *
  178976. * Horizontal flipping is done in-place, using a single top-to-bottom
  178977. * pass through the virtual source array. It will thus be much the
  178978. * fastest option for images larger than main memory.
  178979. *
  178980. * The other routines require a set of destination virtual arrays, so they
  178981. * need twice as much memory as jpegtran normally does. The destination
  178982. * arrays are always written in normal scan order (top to bottom) because
  178983. * the virtual array manager expects this. The source arrays will be scanned
  178984. * in the corresponding order, which means multiple passes through the source
  178985. * arrays for most of the transforms. That could result in much thrashing
  178986. * if the image is larger than main memory.
  178987. *
  178988. * Some notes about the operating environment of the individual transform
  178989. * routines:
  178990. * 1. Both the source and destination virtual arrays are allocated from the
  178991. * source JPEG object, and therefore should be manipulated by calling the
  178992. * source's memory manager.
  178993. * 2. The destination's component count should be used. It may be smaller
  178994. * than the source's when forcing to grayscale.
  178995. * 3. Likewise the destination's sampling factors should be used. When
  178996. * forcing to grayscale the destination's sampling factors will be all 1,
  178997. * and we may as well take that as the effective iMCU size.
  178998. * 4. When "trim" is in effect, the destination's dimensions will be the
  178999. * trimmed values but the source's will be untrimmed.
  179000. * 5. All the routines assume that the source and destination buffers are
  179001. * padded out to a full iMCU boundary. This is true, although for the
  179002. * source buffer it is an undocumented property of jdcoefct.c.
  179003. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179004. * dimensions and ignore the source's.
  179005. */
  179006. LOCAL(void)
  179007. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179008. jvirt_barray_ptr *src_coef_arrays)
  179009. /* Horizontal flip; done in-place, so no separate dest array is required */
  179010. {
  179011. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179012. int ci, k, offset_y;
  179013. JBLOCKARRAY buffer;
  179014. JCOEFPTR ptr1, ptr2;
  179015. JCOEF temp1, temp2;
  179016. jpeg_component_info *compptr;
  179017. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179018. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179019. * mirroring by changing the signs of odd-numbered columns.
  179020. * Partial iMCUs at the right edge are left untouched.
  179021. */
  179022. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179023. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179024. compptr = dstinfo->comp_info + ci;
  179025. comp_width = MCU_cols * compptr->h_samp_factor;
  179026. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179027. blk_y += compptr->v_samp_factor) {
  179028. buffer = (*srcinfo->mem->access_virt_barray)
  179029. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179030. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179031. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179032. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179033. ptr1 = buffer[offset_y][blk_x];
  179034. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179035. /* this unrolled loop doesn't need to know which row it's on... */
  179036. for (k = 0; k < DCTSIZE2; k += 2) {
  179037. temp1 = *ptr1; /* swap even column */
  179038. temp2 = *ptr2;
  179039. *ptr1++ = temp2;
  179040. *ptr2++ = temp1;
  179041. temp1 = *ptr1; /* swap odd column with sign change */
  179042. temp2 = *ptr2;
  179043. *ptr1++ = -temp2;
  179044. *ptr2++ = -temp1;
  179045. }
  179046. }
  179047. }
  179048. }
  179049. }
  179050. }
  179051. LOCAL(void)
  179052. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179053. jvirt_barray_ptr *src_coef_arrays,
  179054. jvirt_barray_ptr *dst_coef_arrays)
  179055. /* Vertical flip */
  179056. {
  179057. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179058. int ci, i, j, offset_y;
  179059. JBLOCKARRAY src_buffer, dst_buffer;
  179060. JBLOCKROW src_row_ptr, dst_row_ptr;
  179061. JCOEFPTR src_ptr, dst_ptr;
  179062. jpeg_component_info *compptr;
  179063. /* We output into a separate array because we can't touch different
  179064. * rows of the source virtual array simultaneously. Otherwise, this
  179065. * is a pretty straightforward analog of horizontal flip.
  179066. * Within a DCT block, vertical mirroring is done by changing the signs
  179067. * of odd-numbered rows.
  179068. * Partial iMCUs at the bottom edge are copied verbatim.
  179069. */
  179070. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179071. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179072. compptr = dstinfo->comp_info + ci;
  179073. comp_height = MCU_rows * compptr->v_samp_factor;
  179074. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179075. dst_blk_y += compptr->v_samp_factor) {
  179076. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179077. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179078. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179079. if (dst_blk_y < comp_height) {
  179080. /* Row is within the mirrorable area. */
  179081. src_buffer = (*srcinfo->mem->access_virt_barray)
  179082. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179083. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179084. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179085. } else {
  179086. /* Bottom-edge blocks will be copied verbatim. */
  179087. src_buffer = (*srcinfo->mem->access_virt_barray)
  179088. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179089. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179090. }
  179091. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179092. if (dst_blk_y < comp_height) {
  179093. /* Row is within the mirrorable area. */
  179094. dst_row_ptr = dst_buffer[offset_y];
  179095. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179096. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179097. dst_blk_x++) {
  179098. dst_ptr = dst_row_ptr[dst_blk_x];
  179099. src_ptr = src_row_ptr[dst_blk_x];
  179100. for (i = 0; i < DCTSIZE; i += 2) {
  179101. /* copy even row */
  179102. for (j = 0; j < DCTSIZE; j++)
  179103. *dst_ptr++ = *src_ptr++;
  179104. /* copy odd row with sign change */
  179105. for (j = 0; j < DCTSIZE; j++)
  179106. *dst_ptr++ = - *src_ptr++;
  179107. }
  179108. }
  179109. } else {
  179110. /* Just copy row verbatim. */
  179111. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179112. compptr->width_in_blocks);
  179113. }
  179114. }
  179115. }
  179116. }
  179117. }
  179118. LOCAL(void)
  179119. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179120. jvirt_barray_ptr *src_coef_arrays,
  179121. jvirt_barray_ptr *dst_coef_arrays)
  179122. /* Transpose source into destination */
  179123. {
  179124. JDIMENSION dst_blk_x, dst_blk_y;
  179125. int ci, i, j, offset_x, offset_y;
  179126. JBLOCKARRAY src_buffer, dst_buffer;
  179127. JCOEFPTR src_ptr, dst_ptr;
  179128. jpeg_component_info *compptr;
  179129. /* Transposing pixels within a block just requires transposing the
  179130. * DCT coefficients.
  179131. * Partial iMCUs at the edges require no special treatment; we simply
  179132. * process all the available DCT blocks for every component.
  179133. */
  179134. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179135. compptr = dstinfo->comp_info + ci;
  179136. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179137. dst_blk_y += compptr->v_samp_factor) {
  179138. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179139. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179140. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179141. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179142. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179143. dst_blk_x += compptr->h_samp_factor) {
  179144. src_buffer = (*srcinfo->mem->access_virt_barray)
  179145. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179146. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179147. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179148. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179149. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179150. for (i = 0; i < DCTSIZE; i++)
  179151. for (j = 0; j < DCTSIZE; j++)
  179152. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179153. }
  179154. }
  179155. }
  179156. }
  179157. }
  179158. }
  179159. LOCAL(void)
  179160. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179161. jvirt_barray_ptr *src_coef_arrays,
  179162. jvirt_barray_ptr *dst_coef_arrays)
  179163. /* 90 degree rotation is equivalent to
  179164. * 1. Transposing the image;
  179165. * 2. Horizontal mirroring.
  179166. * These two steps are merged into a single processing routine.
  179167. */
  179168. {
  179169. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179170. int ci, i, j, offset_x, offset_y;
  179171. JBLOCKARRAY src_buffer, dst_buffer;
  179172. JCOEFPTR src_ptr, dst_ptr;
  179173. jpeg_component_info *compptr;
  179174. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179175. * at the (output) right edge properly. They just get transposed and
  179176. * not mirrored.
  179177. */
  179178. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179179. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179180. compptr = dstinfo->comp_info + ci;
  179181. comp_width = MCU_cols * compptr->h_samp_factor;
  179182. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179183. dst_blk_y += compptr->v_samp_factor) {
  179184. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179185. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179186. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179187. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179188. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179189. dst_blk_x += compptr->h_samp_factor) {
  179190. src_buffer = (*srcinfo->mem->access_virt_barray)
  179191. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179192. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179193. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179194. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179195. if (dst_blk_x < comp_width) {
  179196. /* Block is within the mirrorable area. */
  179197. dst_ptr = dst_buffer[offset_y]
  179198. [comp_width - dst_blk_x - offset_x - 1];
  179199. for (i = 0; i < DCTSIZE; i++) {
  179200. for (j = 0; j < DCTSIZE; j++)
  179201. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179202. i++;
  179203. for (j = 0; j < DCTSIZE; j++)
  179204. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179205. }
  179206. } else {
  179207. /* Edge blocks are transposed but not mirrored. */
  179208. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179209. for (i = 0; i < DCTSIZE; i++)
  179210. for (j = 0; j < DCTSIZE; j++)
  179211. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179212. }
  179213. }
  179214. }
  179215. }
  179216. }
  179217. }
  179218. }
  179219. LOCAL(void)
  179220. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179221. jvirt_barray_ptr *src_coef_arrays,
  179222. jvirt_barray_ptr *dst_coef_arrays)
  179223. /* 270 degree rotation is equivalent to
  179224. * 1. Horizontal mirroring;
  179225. * 2. Transposing the image.
  179226. * These two steps are merged into a single processing routine.
  179227. */
  179228. {
  179229. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179230. int ci, i, j, offset_x, offset_y;
  179231. JBLOCKARRAY src_buffer, dst_buffer;
  179232. JCOEFPTR src_ptr, dst_ptr;
  179233. jpeg_component_info *compptr;
  179234. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179235. * at the (output) bottom edge properly. They just get transposed and
  179236. * not mirrored.
  179237. */
  179238. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179239. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179240. compptr = dstinfo->comp_info + ci;
  179241. comp_height = MCU_rows * compptr->v_samp_factor;
  179242. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179243. dst_blk_y += compptr->v_samp_factor) {
  179244. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179245. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179246. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179247. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179248. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179249. dst_blk_x += compptr->h_samp_factor) {
  179250. src_buffer = (*srcinfo->mem->access_virt_barray)
  179251. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179252. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179253. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179254. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179255. if (dst_blk_y < comp_height) {
  179256. /* Block is within the mirrorable area. */
  179257. src_ptr = src_buffer[offset_x]
  179258. [comp_height - dst_blk_y - offset_y - 1];
  179259. for (i = 0; i < DCTSIZE; i++) {
  179260. for (j = 0; j < DCTSIZE; j++) {
  179261. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179262. j++;
  179263. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179264. }
  179265. }
  179266. } else {
  179267. /* Edge blocks are transposed but not mirrored. */
  179268. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179269. for (i = 0; i < DCTSIZE; i++)
  179270. for (j = 0; j < DCTSIZE; j++)
  179271. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179272. }
  179273. }
  179274. }
  179275. }
  179276. }
  179277. }
  179278. }
  179279. LOCAL(void)
  179280. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179281. jvirt_barray_ptr *src_coef_arrays,
  179282. jvirt_barray_ptr *dst_coef_arrays)
  179283. /* 180 degree rotation is equivalent to
  179284. * 1. Vertical mirroring;
  179285. * 2. Horizontal mirroring.
  179286. * These two steps are merged into a single processing routine.
  179287. */
  179288. {
  179289. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179290. int ci, i, j, offset_y;
  179291. JBLOCKARRAY src_buffer, dst_buffer;
  179292. JBLOCKROW src_row_ptr, dst_row_ptr;
  179293. JCOEFPTR src_ptr, dst_ptr;
  179294. jpeg_component_info *compptr;
  179295. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179296. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179297. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179298. compptr = dstinfo->comp_info + ci;
  179299. comp_width = MCU_cols * compptr->h_samp_factor;
  179300. comp_height = MCU_rows * compptr->v_samp_factor;
  179301. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179302. dst_blk_y += compptr->v_samp_factor) {
  179303. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179304. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179305. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179306. if (dst_blk_y < comp_height) {
  179307. /* Row is within the vertically mirrorable area. */
  179308. src_buffer = (*srcinfo->mem->access_virt_barray)
  179309. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179310. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179311. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179312. } else {
  179313. /* Bottom-edge rows are only mirrored horizontally. */
  179314. src_buffer = (*srcinfo->mem->access_virt_barray)
  179315. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179316. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179317. }
  179318. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179319. if (dst_blk_y < comp_height) {
  179320. /* Row is within the mirrorable area. */
  179321. dst_row_ptr = dst_buffer[offset_y];
  179322. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179323. /* Process the blocks that can be mirrored both ways. */
  179324. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179325. dst_ptr = dst_row_ptr[dst_blk_x];
  179326. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179327. for (i = 0; i < DCTSIZE; i += 2) {
  179328. /* For even row, negate every odd column. */
  179329. for (j = 0; j < DCTSIZE; j += 2) {
  179330. *dst_ptr++ = *src_ptr++;
  179331. *dst_ptr++ = - *src_ptr++;
  179332. }
  179333. /* For odd row, negate every even column. */
  179334. for (j = 0; j < DCTSIZE; j += 2) {
  179335. *dst_ptr++ = - *src_ptr++;
  179336. *dst_ptr++ = *src_ptr++;
  179337. }
  179338. }
  179339. }
  179340. /* Any remaining right-edge blocks are only mirrored vertically. */
  179341. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179342. dst_ptr = dst_row_ptr[dst_blk_x];
  179343. src_ptr = src_row_ptr[dst_blk_x];
  179344. for (i = 0; i < DCTSIZE; i += 2) {
  179345. for (j = 0; j < DCTSIZE; j++)
  179346. *dst_ptr++ = *src_ptr++;
  179347. for (j = 0; j < DCTSIZE; j++)
  179348. *dst_ptr++ = - *src_ptr++;
  179349. }
  179350. }
  179351. } else {
  179352. /* Remaining rows are just mirrored horizontally. */
  179353. dst_row_ptr = dst_buffer[offset_y];
  179354. src_row_ptr = src_buffer[offset_y];
  179355. /* Process the blocks that can be mirrored. */
  179356. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179357. dst_ptr = dst_row_ptr[dst_blk_x];
  179358. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179359. for (i = 0; i < DCTSIZE2; i += 2) {
  179360. *dst_ptr++ = *src_ptr++;
  179361. *dst_ptr++ = - *src_ptr++;
  179362. }
  179363. }
  179364. /* Any remaining right-edge blocks are only copied. */
  179365. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179366. dst_ptr = dst_row_ptr[dst_blk_x];
  179367. src_ptr = src_row_ptr[dst_blk_x];
  179368. for (i = 0; i < DCTSIZE2; i++)
  179369. *dst_ptr++ = *src_ptr++;
  179370. }
  179371. }
  179372. }
  179373. }
  179374. }
  179375. }
  179376. LOCAL(void)
  179377. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179378. jvirt_barray_ptr *src_coef_arrays,
  179379. jvirt_barray_ptr *dst_coef_arrays)
  179380. /* Transverse transpose is equivalent to
  179381. * 1. 180 degree rotation;
  179382. * 2. Transposition;
  179383. * or
  179384. * 1. Horizontal mirroring;
  179385. * 2. Transposition;
  179386. * 3. Horizontal mirroring.
  179387. * These steps are merged into a single processing routine.
  179388. */
  179389. {
  179390. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179391. int ci, i, j, offset_x, offset_y;
  179392. JBLOCKARRAY src_buffer, dst_buffer;
  179393. JCOEFPTR src_ptr, dst_ptr;
  179394. jpeg_component_info *compptr;
  179395. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179396. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179397. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179398. compptr = dstinfo->comp_info + ci;
  179399. comp_width = MCU_cols * compptr->h_samp_factor;
  179400. comp_height = MCU_rows * compptr->v_samp_factor;
  179401. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179402. dst_blk_y += compptr->v_samp_factor) {
  179403. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179404. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179405. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179406. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179407. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179408. dst_blk_x += compptr->h_samp_factor) {
  179409. src_buffer = (*srcinfo->mem->access_virt_barray)
  179410. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179411. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179412. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179413. if (dst_blk_y < comp_height) {
  179414. src_ptr = src_buffer[offset_x]
  179415. [comp_height - dst_blk_y - offset_y - 1];
  179416. if (dst_blk_x < comp_width) {
  179417. /* Block is within the mirrorable area. */
  179418. dst_ptr = dst_buffer[offset_y]
  179419. [comp_width - dst_blk_x - offset_x - 1];
  179420. for (i = 0; i < DCTSIZE; i++) {
  179421. for (j = 0; j < DCTSIZE; j++) {
  179422. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179423. j++;
  179424. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179425. }
  179426. i++;
  179427. for (j = 0; j < DCTSIZE; j++) {
  179428. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179429. j++;
  179430. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179431. }
  179432. }
  179433. } else {
  179434. /* Right-edge blocks are mirrored in y only */
  179435. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179436. for (i = 0; i < DCTSIZE; i++) {
  179437. for (j = 0; j < DCTSIZE; j++) {
  179438. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179439. j++;
  179440. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179441. }
  179442. }
  179443. }
  179444. } else {
  179445. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179446. if (dst_blk_x < comp_width) {
  179447. /* Bottom-edge blocks are mirrored in x only */
  179448. dst_ptr = dst_buffer[offset_y]
  179449. [comp_width - dst_blk_x - offset_x - 1];
  179450. for (i = 0; i < DCTSIZE; i++) {
  179451. for (j = 0; j < DCTSIZE; j++)
  179452. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179453. i++;
  179454. for (j = 0; j < DCTSIZE; j++)
  179455. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179456. }
  179457. } else {
  179458. /* At lower right corner, just transpose, no mirroring */
  179459. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179460. for (i = 0; i < DCTSIZE; i++)
  179461. for (j = 0; j < DCTSIZE; j++)
  179462. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179463. }
  179464. }
  179465. }
  179466. }
  179467. }
  179468. }
  179469. }
  179470. }
  179471. /* Request any required workspace.
  179472. *
  179473. * We allocate the workspace virtual arrays from the source decompression
  179474. * object, so that all the arrays (both the original data and the workspace)
  179475. * will be taken into account while making memory management decisions.
  179476. * Hence, this routine must be called after jpeg_read_header (which reads
  179477. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179478. * the source's virtual arrays).
  179479. */
  179480. GLOBAL(void)
  179481. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179482. jpeg_transform_info *info)
  179483. {
  179484. jvirt_barray_ptr *coef_arrays = NULL;
  179485. jpeg_component_info *compptr;
  179486. int ci;
  179487. if (info->force_grayscale &&
  179488. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179489. srcinfo->num_components == 3) {
  179490. /* We'll only process the first component */
  179491. info->num_components = 1;
  179492. } else {
  179493. /* Process all the components */
  179494. info->num_components = srcinfo->num_components;
  179495. }
  179496. switch (info->transform) {
  179497. case JXFORM_NONE:
  179498. case JXFORM_FLIP_H:
  179499. /* Don't need a workspace array */
  179500. break;
  179501. case JXFORM_FLIP_V:
  179502. case JXFORM_ROT_180:
  179503. /* Need workspace arrays having same dimensions as source image.
  179504. * Note that we allocate arrays padded out to the next iMCU boundary,
  179505. * so that transform routines need not worry about missing edge blocks.
  179506. */
  179507. coef_arrays = (jvirt_barray_ptr *)
  179508. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179509. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179510. for (ci = 0; ci < info->num_components; ci++) {
  179511. compptr = srcinfo->comp_info + ci;
  179512. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179513. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179514. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179515. (long) compptr->h_samp_factor),
  179516. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179517. (long) compptr->v_samp_factor),
  179518. (JDIMENSION) compptr->v_samp_factor);
  179519. }
  179520. break;
  179521. case JXFORM_TRANSPOSE:
  179522. case JXFORM_TRANSVERSE:
  179523. case JXFORM_ROT_90:
  179524. case JXFORM_ROT_270:
  179525. /* Need workspace arrays having transposed dimensions.
  179526. * Note that we allocate arrays padded out to the next iMCU boundary,
  179527. * so that transform routines need not worry about missing edge blocks.
  179528. */
  179529. coef_arrays = (jvirt_barray_ptr *)
  179530. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179531. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179532. for (ci = 0; ci < info->num_components; ci++) {
  179533. compptr = srcinfo->comp_info + ci;
  179534. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179535. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179536. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179537. (long) compptr->v_samp_factor),
  179538. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179539. (long) compptr->h_samp_factor),
  179540. (JDIMENSION) compptr->h_samp_factor);
  179541. }
  179542. break;
  179543. }
  179544. info->workspace_coef_arrays = coef_arrays;
  179545. }
  179546. /* Transpose destination image parameters */
  179547. LOCAL(void)
  179548. transpose_critical_parameters (j_compress_ptr dstinfo)
  179549. {
  179550. int tblno, i, j, ci, itemp;
  179551. jpeg_component_info *compptr;
  179552. JQUANT_TBL *qtblptr;
  179553. JDIMENSION dtemp;
  179554. UINT16 qtemp;
  179555. /* Transpose basic image dimensions */
  179556. dtemp = dstinfo->image_width;
  179557. dstinfo->image_width = dstinfo->image_height;
  179558. dstinfo->image_height = dtemp;
  179559. /* Transpose sampling factors */
  179560. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179561. compptr = dstinfo->comp_info + ci;
  179562. itemp = compptr->h_samp_factor;
  179563. compptr->h_samp_factor = compptr->v_samp_factor;
  179564. compptr->v_samp_factor = itemp;
  179565. }
  179566. /* Transpose quantization tables */
  179567. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179568. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179569. if (qtblptr != NULL) {
  179570. for (i = 0; i < DCTSIZE; i++) {
  179571. for (j = 0; j < i; j++) {
  179572. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179573. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179574. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179575. }
  179576. }
  179577. }
  179578. }
  179579. }
  179580. /* Trim off any partial iMCUs on the indicated destination edge */
  179581. LOCAL(void)
  179582. trim_right_edge (j_compress_ptr dstinfo)
  179583. {
  179584. int ci, max_h_samp_factor;
  179585. JDIMENSION MCU_cols;
  179586. /* We have to compute max_h_samp_factor ourselves,
  179587. * because it hasn't been set yet in the destination
  179588. * (and we don't want to use the source's value).
  179589. */
  179590. max_h_samp_factor = 1;
  179591. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179592. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179593. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179594. }
  179595. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179596. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179597. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179598. }
  179599. LOCAL(void)
  179600. trim_bottom_edge (j_compress_ptr dstinfo)
  179601. {
  179602. int ci, max_v_samp_factor;
  179603. JDIMENSION MCU_rows;
  179604. /* We have to compute max_v_samp_factor ourselves,
  179605. * because it hasn't been set yet in the destination
  179606. * (and we don't want to use the source's value).
  179607. */
  179608. max_v_samp_factor = 1;
  179609. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179610. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179611. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179612. }
  179613. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179614. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179615. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179616. }
  179617. /* Adjust output image parameters as needed.
  179618. *
  179619. * This must be called after jpeg_copy_critical_parameters()
  179620. * and before jpeg_write_coefficients().
  179621. *
  179622. * The return value is the set of virtual coefficient arrays to be written
  179623. * (either the ones allocated by jtransform_request_workspace, or the
  179624. * original source data arrays). The caller will need to pass this value
  179625. * to jpeg_write_coefficients().
  179626. */
  179627. GLOBAL(jvirt_barray_ptr *)
  179628. jtransform_adjust_parameters (j_decompress_ptr,
  179629. j_compress_ptr dstinfo,
  179630. jvirt_barray_ptr *src_coef_arrays,
  179631. jpeg_transform_info *info)
  179632. {
  179633. /* If force-to-grayscale is requested, adjust destination parameters */
  179634. if (info->force_grayscale) {
  179635. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179636. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179637. * will get set to 1, which typically won't match the source.
  179638. * In fact we do this even if the source is already grayscale; that
  179639. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179640. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179641. */
  179642. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179643. dstinfo->num_components == 3) ||
  179644. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179645. dstinfo->num_components == 1)) {
  179646. /* We have to preserve the source's quantization table number. */
  179647. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179648. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179649. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179650. } else {
  179651. /* Sorry, can't do it */
  179652. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179653. }
  179654. }
  179655. /* Correct the destination's image dimensions etc if necessary */
  179656. switch (info->transform) {
  179657. case JXFORM_NONE:
  179658. /* Nothing to do */
  179659. break;
  179660. case JXFORM_FLIP_H:
  179661. if (info->trim)
  179662. trim_right_edge(dstinfo);
  179663. break;
  179664. case JXFORM_FLIP_V:
  179665. if (info->trim)
  179666. trim_bottom_edge(dstinfo);
  179667. break;
  179668. case JXFORM_TRANSPOSE:
  179669. transpose_critical_parameters(dstinfo);
  179670. /* transpose does NOT have to trim anything */
  179671. break;
  179672. case JXFORM_TRANSVERSE:
  179673. transpose_critical_parameters(dstinfo);
  179674. if (info->trim) {
  179675. trim_right_edge(dstinfo);
  179676. trim_bottom_edge(dstinfo);
  179677. }
  179678. break;
  179679. case JXFORM_ROT_90:
  179680. transpose_critical_parameters(dstinfo);
  179681. if (info->trim)
  179682. trim_right_edge(dstinfo);
  179683. break;
  179684. case JXFORM_ROT_180:
  179685. if (info->trim) {
  179686. trim_right_edge(dstinfo);
  179687. trim_bottom_edge(dstinfo);
  179688. }
  179689. break;
  179690. case JXFORM_ROT_270:
  179691. transpose_critical_parameters(dstinfo);
  179692. if (info->trim)
  179693. trim_bottom_edge(dstinfo);
  179694. break;
  179695. }
  179696. /* Return the appropriate output data set */
  179697. if (info->workspace_coef_arrays != NULL)
  179698. return info->workspace_coef_arrays;
  179699. return src_coef_arrays;
  179700. }
  179701. /* Execute the actual transformation, if any.
  179702. *
  179703. * This must be called *after* jpeg_write_coefficients, because it depends
  179704. * on jpeg_write_coefficients to have computed subsidiary values such as
  179705. * the per-component width and height fields in the destination object.
  179706. *
  179707. * Note that some transformations will modify the source data arrays!
  179708. */
  179709. GLOBAL(void)
  179710. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179711. j_compress_ptr dstinfo,
  179712. jvirt_barray_ptr *src_coef_arrays,
  179713. jpeg_transform_info *info)
  179714. {
  179715. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179716. switch (info->transform) {
  179717. case JXFORM_NONE:
  179718. break;
  179719. case JXFORM_FLIP_H:
  179720. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179721. break;
  179722. case JXFORM_FLIP_V:
  179723. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179724. break;
  179725. case JXFORM_TRANSPOSE:
  179726. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179727. break;
  179728. case JXFORM_TRANSVERSE:
  179729. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179730. break;
  179731. case JXFORM_ROT_90:
  179732. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179733. break;
  179734. case JXFORM_ROT_180:
  179735. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179736. break;
  179737. case JXFORM_ROT_270:
  179738. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179739. break;
  179740. }
  179741. }
  179742. #endif /* TRANSFORMS_SUPPORTED */
  179743. /* Setup decompression object to save desired markers in memory.
  179744. * This must be called before jpeg_read_header() to have the desired effect.
  179745. */
  179746. GLOBAL(void)
  179747. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179748. {
  179749. #ifdef SAVE_MARKERS_SUPPORTED
  179750. int m;
  179751. /* Save comments except under NONE option */
  179752. if (option != JCOPYOPT_NONE) {
  179753. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179754. }
  179755. /* Save all types of APPn markers iff ALL option */
  179756. if (option == JCOPYOPT_ALL) {
  179757. for (m = 0; m < 16; m++)
  179758. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179759. }
  179760. #endif /* SAVE_MARKERS_SUPPORTED */
  179761. }
  179762. /* Copy markers saved in the given source object to the destination object.
  179763. * This should be called just after jpeg_start_compress() or
  179764. * jpeg_write_coefficients().
  179765. * Note that those routines will have written the SOI, and also the
  179766. * JFIF APP0 or Adobe APP14 markers if selected.
  179767. */
  179768. GLOBAL(void)
  179769. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179770. JCOPY_OPTION)
  179771. {
  179772. jpeg_saved_marker_ptr marker;
  179773. /* In the current implementation, we don't actually need to examine the
  179774. * option flag here; we just copy everything that got saved.
  179775. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179776. * if the encoder library already wrote one.
  179777. */
  179778. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179779. if (dstinfo->write_JFIF_header &&
  179780. marker->marker == JPEG_APP0 &&
  179781. marker->data_length >= 5 &&
  179782. GETJOCTET(marker->data[0]) == 0x4A &&
  179783. GETJOCTET(marker->data[1]) == 0x46 &&
  179784. GETJOCTET(marker->data[2]) == 0x49 &&
  179785. GETJOCTET(marker->data[3]) == 0x46 &&
  179786. GETJOCTET(marker->data[4]) == 0)
  179787. continue; /* reject duplicate JFIF */
  179788. if (dstinfo->write_Adobe_marker &&
  179789. marker->marker == JPEG_APP0+14 &&
  179790. marker->data_length >= 5 &&
  179791. GETJOCTET(marker->data[0]) == 0x41 &&
  179792. GETJOCTET(marker->data[1]) == 0x64 &&
  179793. GETJOCTET(marker->data[2]) == 0x6F &&
  179794. GETJOCTET(marker->data[3]) == 0x62 &&
  179795. GETJOCTET(marker->data[4]) == 0x65)
  179796. continue; /* reject duplicate Adobe */
  179797. #ifdef NEED_FAR_POINTERS
  179798. /* We could use jpeg_write_marker if the data weren't FAR... */
  179799. {
  179800. unsigned int i;
  179801. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179802. for (i = 0; i < marker->data_length; i++)
  179803. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179804. }
  179805. #else
  179806. jpeg_write_marker(dstinfo, marker->marker,
  179807. marker->data, marker->data_length);
  179808. #endif
  179809. }
  179810. }
  179811. /*** End of inlined file: transupp.c ***/
  179812. #else
  179813. #define JPEG_INTERNALS
  179814. #undef FAR
  179815. #include <jpeglib.h>
  179816. #endif
  179817. }
  179818. #undef max
  179819. #undef min
  179820. #if JUCE_MSVC
  179821. #pragma warning (pop)
  179822. #endif
  179823. BEGIN_JUCE_NAMESPACE
  179824. namespace JPEGHelpers
  179825. {
  179826. using namespace jpeglibNamespace;
  179827. #if ! JUCE_MSVC
  179828. using jpeglibNamespace::boolean;
  179829. #endif
  179830. struct JPEGDecodingFailure {};
  179831. void fatalErrorHandler (j_common_ptr)
  179832. {
  179833. throw JPEGDecodingFailure();
  179834. }
  179835. void silentErrorCallback1 (j_common_ptr) {}
  179836. void silentErrorCallback2 (j_common_ptr, int) {}
  179837. void silentErrorCallback3 (j_common_ptr, char*) {}
  179838. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179839. {
  179840. zerostruct (err);
  179841. err.error_exit = fatalErrorHandler;
  179842. err.emit_message = silentErrorCallback2;
  179843. err.output_message = silentErrorCallback1;
  179844. err.format_message = silentErrorCallback3;
  179845. err.reset_error_mgr = silentErrorCallback1;
  179846. }
  179847. void dummyCallback1 (j_decompress_ptr)
  179848. {
  179849. }
  179850. void jpegSkip (j_decompress_ptr decompStruct, long num)
  179851. {
  179852. decompStruct->src->next_input_byte += num;
  179853. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179854. decompStruct->src->bytes_in_buffer -= num;
  179855. }
  179856. boolean jpegFill (j_decompress_ptr)
  179857. {
  179858. return 0;
  179859. }
  179860. const int jpegBufferSize = 512;
  179861. struct JuceJpegDest : public jpeg_destination_mgr
  179862. {
  179863. OutputStream* output;
  179864. char* buffer;
  179865. };
  179866. void jpegWriteInit (j_compress_ptr)
  179867. {
  179868. }
  179869. void jpegWriteTerminate (j_compress_ptr cinfo)
  179870. {
  179871. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179872. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179873. dest->output->write (dest->buffer, (int) numToWrite);
  179874. }
  179875. boolean jpegWriteFlush (j_compress_ptr cinfo)
  179876. {
  179877. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179878. const int numToWrite = jpegBufferSize;
  179879. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179880. dest->free_in_buffer = jpegBufferSize;
  179881. return dest->output->write (dest->buffer, numToWrite);
  179882. }
  179883. }
  179884. JPEGImageFormat::JPEGImageFormat()
  179885. : quality (-1.0f)
  179886. {
  179887. }
  179888. JPEGImageFormat::~JPEGImageFormat() {}
  179889. void JPEGImageFormat::setQuality (const float newQuality)
  179890. {
  179891. quality = newQuality;
  179892. }
  179893. const String JPEGImageFormat::getFormatName()
  179894. {
  179895. return "JPEG";
  179896. }
  179897. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179898. {
  179899. const int bytesNeeded = 10;
  179900. uint8 header [bytesNeeded];
  179901. if (in.read (header, bytesNeeded) == bytesNeeded)
  179902. {
  179903. return header[0] == 0xff
  179904. && header[1] == 0xd8
  179905. && header[2] == 0xff
  179906. && (header[3] == 0xe0 || header[3] == 0xe1);
  179907. }
  179908. return false;
  179909. }
  179910. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179911. const Image juce_loadWithCoreImage (InputStream& input);
  179912. #endif
  179913. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179914. {
  179915. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179916. return juce_loadWithCoreImage (in);
  179917. #else
  179918. using namespace jpeglibNamespace;
  179919. using namespace JPEGHelpers;
  179920. MemoryOutputStream mb;
  179921. mb.writeFromInputStream (in, -1);
  179922. Image image;
  179923. if (mb.getDataSize() > 16)
  179924. {
  179925. struct jpeg_decompress_struct jpegDecompStruct;
  179926. struct jpeg_error_mgr jerr;
  179927. setupSilentErrorHandler (jerr);
  179928. jpegDecompStruct.err = &jerr;
  179929. jpeg_create_decompress (&jpegDecompStruct);
  179930. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179931. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179932. jpegDecompStruct.src->init_source = dummyCallback1;
  179933. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179934. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179935. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179936. jpegDecompStruct.src->term_source = dummyCallback1;
  179937. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179938. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  179939. try
  179940. {
  179941. jpeg_read_header (&jpegDecompStruct, TRUE);
  179942. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179943. const int width = jpegDecompStruct.output_width;
  179944. const int height = jpegDecompStruct.output_height;
  179945. jpegDecompStruct.out_color_space = JCS_RGB;
  179946. JSAMPARRAY buffer
  179947. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179948. JPOOL_IMAGE,
  179949. width * 3, 1);
  179950. if (jpeg_start_decompress (&jpegDecompStruct))
  179951. {
  179952. image = Image (Image::RGB, width, height, false);
  179953. image.getProperties()->set ("originalImageHadAlpha", false);
  179954. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179955. const Image::BitmapData destData (image, true);
  179956. for (int y = 0; y < height; ++y)
  179957. {
  179958. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179959. const uint8* src = *buffer;
  179960. uint8* dest = destData.getLinePointer (y);
  179961. if (hasAlphaChan)
  179962. {
  179963. for (int i = width; --i >= 0;)
  179964. {
  179965. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179966. ((PixelARGB*) dest)->premultiply();
  179967. dest += destData.pixelStride;
  179968. src += 3;
  179969. }
  179970. }
  179971. else
  179972. {
  179973. for (int i = width; --i >= 0;)
  179974. {
  179975. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179976. dest += destData.pixelStride;
  179977. src += 3;
  179978. }
  179979. }
  179980. }
  179981. jpeg_finish_decompress (&jpegDecompStruct);
  179982. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179983. }
  179984. jpeg_destroy_decompress (&jpegDecompStruct);
  179985. }
  179986. catch (...)
  179987. {}
  179988. }
  179989. return image;
  179990. #endif
  179991. }
  179992. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179993. {
  179994. using namespace jpeglibNamespace;
  179995. using namespace JPEGHelpers;
  179996. if (image.hasAlphaChannel())
  179997. {
  179998. // this method could fill the background in white and still save the image..
  179999. jassertfalse;
  180000. return true;
  180001. }
  180002. struct jpeg_compress_struct jpegCompStruct;
  180003. struct jpeg_error_mgr jerr;
  180004. setupSilentErrorHandler (jerr);
  180005. jpegCompStruct.err = &jerr;
  180006. jpeg_create_compress (&jpegCompStruct);
  180007. JuceJpegDest dest;
  180008. jpegCompStruct.dest = &dest;
  180009. dest.output = &out;
  180010. HeapBlock <char> tempBuffer (jpegBufferSize);
  180011. dest.buffer = tempBuffer;
  180012. dest.next_output_byte = (JOCTET*) dest.buffer;
  180013. dest.free_in_buffer = jpegBufferSize;
  180014. dest.init_destination = jpegWriteInit;
  180015. dest.empty_output_buffer = jpegWriteFlush;
  180016. dest.term_destination = jpegWriteTerminate;
  180017. jpegCompStruct.image_width = image.getWidth();
  180018. jpegCompStruct.image_height = image.getHeight();
  180019. jpegCompStruct.input_components = 3;
  180020. jpegCompStruct.in_color_space = JCS_RGB;
  180021. jpegCompStruct.write_JFIF_header = 1;
  180022. jpegCompStruct.X_density = 72;
  180023. jpegCompStruct.Y_density = 72;
  180024. jpeg_set_defaults (&jpegCompStruct);
  180025. jpegCompStruct.dct_method = JDCT_FLOAT;
  180026. jpegCompStruct.optimize_coding = 1;
  180027. //jpegCompStruct.smoothing_factor = 10;
  180028. if (quality < 0.0f)
  180029. quality = 0.85f;
  180030. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180031. jpeg_start_compress (&jpegCompStruct, TRUE);
  180032. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180033. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180034. JPOOL_IMAGE, strideBytes, 1);
  180035. const Image::BitmapData srcData (image, false);
  180036. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180037. {
  180038. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180039. uint8* dst = *buffer;
  180040. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180041. {
  180042. *dst++ = ((const PixelRGB*) src)->getRed();
  180043. *dst++ = ((const PixelRGB*) src)->getGreen();
  180044. *dst++ = ((const PixelRGB*) src)->getBlue();
  180045. src += srcData.pixelStride;
  180046. }
  180047. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180048. }
  180049. jpeg_finish_compress (&jpegCompStruct);
  180050. jpeg_destroy_compress (&jpegCompStruct);
  180051. out.flush();
  180052. return true;
  180053. }
  180054. END_JUCE_NAMESPACE
  180055. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180056. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180057. #if JUCE_MSVC
  180058. #pragma warning (push)
  180059. #pragma warning (disable: 4390 4611)
  180060. #endif
  180061. namespace zlibNamespace
  180062. {
  180063. #if JUCE_INCLUDE_ZLIB_CODE
  180064. #undef OS_CODE
  180065. #undef fdopen
  180066. #undef OS_CODE
  180067. #else
  180068. #include <zlib.h>
  180069. #endif
  180070. }
  180071. namespace pnglibNamespace
  180072. {
  180073. using namespace zlibNamespace;
  180074. #if JUCE_INCLUDE_PNGLIB_CODE
  180075. #if _MSC_VER != 1310
  180076. using ::calloc; // (causes conflict in VS.NET 2003)
  180077. using ::malloc;
  180078. using ::free;
  180079. #endif
  180080. using ::abs;
  180081. #define PNG_INTERNAL
  180082. #define NO_DUMMY_DECL
  180083. #define PNG_SETJMP_NOT_SUPPORTED
  180084. /*** Start of inlined file: png.h ***/
  180085. /* png.h - header file for PNG reference library
  180086. *
  180087. * libpng version 1.2.21 - October 4, 2007
  180088. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180089. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180090. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180091. *
  180092. * Authors and maintainers:
  180093. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180094. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180095. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180096. * See also "Contributing Authors", below.
  180097. *
  180098. * Note about libpng version numbers:
  180099. *
  180100. * Due to various miscommunications, unforeseen code incompatibilities
  180101. * and occasional factors outside the authors' control, version numbering
  180102. * on the library has not always been consistent and straightforward.
  180103. * The following table summarizes matters since version 0.89c, which was
  180104. * the first widely used release:
  180105. *
  180106. * source png.h png.h shared-lib
  180107. * version string int version
  180108. * ------- ------ ----- ----------
  180109. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180110. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180111. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180112. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180113. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180114. * 0.97c 0.97 97 2.0.97
  180115. * 0.98 0.98 98 2.0.98
  180116. * 0.99 0.99 98 2.0.99
  180117. * 0.99a-m 0.99 99 2.0.99
  180118. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180119. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180120. * 1.0.1 png.h string is 10001 2.1.0
  180121. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180122. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180123. * 1.0.2a-b 10003 version, except as noted.
  180124. * 1.0.3 10003
  180125. * 1.0.3a-d 10004
  180126. * 1.0.4 10004
  180127. * 1.0.4a-f 10005
  180128. * 1.0.5 (+ 2 patches) 10005
  180129. * 1.0.5a-d 10006
  180130. * 1.0.5e-r 10100 (not source compatible)
  180131. * 1.0.5s-v 10006 (not binary compatible)
  180132. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180133. * 1.0.6d-f 10007 (still binary incompatible)
  180134. * 1.0.6g 10007
  180135. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180136. * 1.0.6i 10007 10.6i
  180137. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180138. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180139. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180140. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180141. * 1.0.7 1 10007 (still compatible)
  180142. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180143. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180144. * 1.0.8 1 10008 2.1.0.8
  180145. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180146. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180147. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180148. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180149. * 1.0.9 1 10009 2.1.0.9
  180150. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180151. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180152. * 1.0.10 1 10010 2.1.0.10
  180153. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180154. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180155. * 1.0.11 1 10011 2.1.0.11
  180156. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180157. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180158. * 1.0.12 2 10012 2.1.0.12
  180159. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180160. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180161. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180162. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180163. * 1.2.0 3 10200 3.1.2.0
  180164. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180165. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180166. * 1.2.1 3 10201 3.1.2.1
  180167. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180168. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180169. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180170. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180171. * 1.0.13 10 10013 10.so.0.1.0.13
  180172. * 1.2.2 12 10202 12.so.0.1.2.2
  180173. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180174. * 1.2.3 12 10203 12.so.0.1.2.3
  180175. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180176. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180177. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180178. * 1.0.14 10 10014 10.so.0.1.0.14
  180179. * 1.2.4 13 10204 12.so.0.1.2.4
  180180. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180181. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180182. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180183. * 1.0.15 10 10015 10.so.0.1.0.15
  180184. * 1.2.5 13 10205 12.so.0.1.2.5
  180185. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180186. * 1.0.16 10 10016 10.so.0.1.0.16
  180187. * 1.2.6 13 10206 12.so.0.1.2.6
  180188. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180189. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180190. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180191. * 1.0.17 10 10017 10.so.0.1.0.17
  180192. * 1.2.7 13 10207 12.so.0.1.2.7
  180193. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180194. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180195. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180196. * 1.0.18 10 10018 10.so.0.1.0.18
  180197. * 1.2.8 13 10208 12.so.0.1.2.8
  180198. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180199. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180200. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180201. * 1.2.9 13 10209 12.so.0.9[.0]
  180202. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180203. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180204. * 1.2.10 13 10210 12.so.0.10[.0]
  180205. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180206. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180207. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180208. * 1.0.19 10 10019 10.so.0.19[.0]
  180209. * 1.2.11 13 10211 12.so.0.11[.0]
  180210. * 1.0.20 10 10020 10.so.0.20[.0]
  180211. * 1.2.12 13 10212 12.so.0.12[.0]
  180212. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180213. * 1.0.21 10 10021 10.so.0.21[.0]
  180214. * 1.2.13 13 10213 12.so.0.13[.0]
  180215. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180216. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180217. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180218. * 1.0.22 10 10022 10.so.0.22[.0]
  180219. * 1.2.14 13 10214 12.so.0.14[.0]
  180220. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180221. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180222. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180223. * 1.0.23 10 10023 10.so.0.23[.0]
  180224. * 1.2.15 13 10215 12.so.0.15[.0]
  180225. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180226. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180227. * 1.0.24 10 10024 10.so.0.24[.0]
  180228. * 1.2.16 13 10216 12.so.0.16[.0]
  180229. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180230. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180231. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180232. * 1.0.25 10 10025 10.so.0.25[.0]
  180233. * 1.2.17 13 10217 12.so.0.17[.0]
  180234. * 1.0.26 10 10026 10.so.0.26[.0]
  180235. * 1.2.18 13 10218 12.so.0.18[.0]
  180236. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180237. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180238. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180239. * 1.0.27 10 10027 10.so.0.27[.0]
  180240. * 1.2.19 13 10219 12.so.0.19[.0]
  180241. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180242. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180243. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180244. * 1.0.28 10 10028 10.so.0.28[.0]
  180245. * 1.2.20 13 10220 12.so.0.20[.0]
  180246. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180247. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180248. * 1.0.29 10 10029 10.so.0.29[.0]
  180249. * 1.2.21 13 10221 12.so.0.21[.0]
  180250. *
  180251. * Henceforth the source version will match the shared-library major
  180252. * and minor numbers; the shared-library major version number will be
  180253. * used for changes in backward compatibility, as it is intended. The
  180254. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180255. * for applications, is an unsigned integer of the form xyyzz corresponding
  180256. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180257. * were given the previous public release number plus a letter, until
  180258. * version 1.0.6j; from then on they were given the upcoming public
  180259. * release number plus "betaNN" or "rcN".
  180260. *
  180261. * Binary incompatibility exists only when applications make direct access
  180262. * to the info_ptr or png_ptr members through png.h, and the compiled
  180263. * application is loaded with a different version of the library.
  180264. *
  180265. * DLLNUM will change each time there are forward or backward changes
  180266. * in binary compatibility (e.g., when a new feature is added).
  180267. *
  180268. * See libpng.txt or libpng.3 for more information. The PNG specification
  180269. * is available as a W3C Recommendation and as an ISO Specification,
  180270. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180271. */
  180272. /*
  180273. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180274. *
  180275. * If you modify libpng you may insert additional notices immediately following
  180276. * this sentence.
  180277. *
  180278. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180279. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180280. * distributed according to the same disclaimer and license as libpng-1.2.5
  180281. * with the following individual added to the list of Contributing Authors:
  180282. *
  180283. * Cosmin Truta
  180284. *
  180285. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180286. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180287. * distributed according to the same disclaimer and license as libpng-1.0.6
  180288. * with the following individuals added to the list of Contributing Authors:
  180289. *
  180290. * Simon-Pierre Cadieux
  180291. * Eric S. Raymond
  180292. * Gilles Vollant
  180293. *
  180294. * and with the following additions to the disclaimer:
  180295. *
  180296. * There is no warranty against interference with your enjoyment of the
  180297. * library or against infringement. There is no warranty that our
  180298. * efforts or the library will fulfill any of your particular purposes
  180299. * or needs. This library is provided with all faults, and the entire
  180300. * risk of satisfactory quality, performance, accuracy, and effort is with
  180301. * the user.
  180302. *
  180303. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180304. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180305. * distributed according to the same disclaimer and license as libpng-0.96,
  180306. * with the following individuals added to the list of Contributing Authors:
  180307. *
  180308. * Tom Lane
  180309. * Glenn Randers-Pehrson
  180310. * Willem van Schaik
  180311. *
  180312. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180313. * Copyright (c) 1996, 1997 Andreas Dilger
  180314. * Distributed according to the same disclaimer and license as libpng-0.88,
  180315. * with the following individuals added to the list of Contributing Authors:
  180316. *
  180317. * John Bowler
  180318. * Kevin Bracey
  180319. * Sam Bushell
  180320. * Magnus Holmgren
  180321. * Greg Roelofs
  180322. * Tom Tanner
  180323. *
  180324. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180325. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180326. *
  180327. * For the purposes of this copyright and license, "Contributing Authors"
  180328. * is defined as the following set of individuals:
  180329. *
  180330. * Andreas Dilger
  180331. * Dave Martindale
  180332. * Guy Eric Schalnat
  180333. * Paul Schmidt
  180334. * Tim Wegner
  180335. *
  180336. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180337. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180338. * including, without limitation, the warranties of merchantability and of
  180339. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180340. * assume no liability for direct, indirect, incidental, special, exemplary,
  180341. * or consequential damages, which may result from the use of the PNG
  180342. * Reference Library, even if advised of the possibility of such damage.
  180343. *
  180344. * Permission is hereby granted to use, copy, modify, and distribute this
  180345. * source code, or portions hereof, for any purpose, without fee, subject
  180346. * to the following restrictions:
  180347. *
  180348. * 1. The origin of this source code must not be misrepresented.
  180349. *
  180350. * 2. Altered versions must be plainly marked as such and
  180351. * must not be misrepresented as being the original source.
  180352. *
  180353. * 3. This Copyright notice may not be removed or altered from
  180354. * any source or altered source distribution.
  180355. *
  180356. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180357. * fee, and encourage the use of this source code as a component to
  180358. * supporting the PNG file format in commercial products. If you use this
  180359. * source code in a product, acknowledgment is not required but would be
  180360. * appreciated.
  180361. */
  180362. /*
  180363. * A "png_get_copyright" function is available, for convenient use in "about"
  180364. * boxes and the like:
  180365. *
  180366. * printf("%s",png_get_copyright(NULL));
  180367. *
  180368. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180369. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180370. */
  180371. /*
  180372. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180373. * certification mark of the Open Source Initiative.
  180374. */
  180375. /*
  180376. * The contributing authors would like to thank all those who helped
  180377. * with testing, bug fixes, and patience. This wouldn't have been
  180378. * possible without all of you.
  180379. *
  180380. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180381. */
  180382. /*
  180383. * Y2K compliance in libpng:
  180384. * =========================
  180385. *
  180386. * October 4, 2007
  180387. *
  180388. * Since the PNG Development group is an ad-hoc body, we can't make
  180389. * an official declaration.
  180390. *
  180391. * This is your unofficial assurance that libpng from version 0.71 and
  180392. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180393. * versions were also Y2K compliant.
  180394. *
  180395. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180396. * that will hold years up to 65535. The other two hold the date in text
  180397. * format, and will hold years up to 9999.
  180398. *
  180399. * The integer is
  180400. * "png_uint_16 year" in png_time_struct.
  180401. *
  180402. * The strings are
  180403. * "png_charp time_buffer" in png_struct and
  180404. * "near_time_buffer", which is a local character string in png.c.
  180405. *
  180406. * There are seven time-related functions:
  180407. * png.c: png_convert_to_rfc_1123() in png.c
  180408. * (formerly png_convert_to_rfc_1152() in error)
  180409. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180410. * png_convert_from_time_t() in pngwrite.c
  180411. * png_get_tIME() in pngget.c
  180412. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180413. * png_set_tIME() in pngset.c
  180414. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180415. *
  180416. * All handle dates properly in a Y2K environment. The
  180417. * png_convert_from_time_t() function calls gmtime() to convert from system
  180418. * clock time, which returns (year - 1900), which we properly convert to
  180419. * the full 4-digit year. There is a possibility that applications using
  180420. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180421. * function, or that they are incorrectly passing only a 2-digit year
  180422. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180423. * but this is not under our control. The libpng documentation has always
  180424. * stated that it works with 4-digit years, and the APIs have been
  180425. * documented as such.
  180426. *
  180427. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180428. * integer to hold the year, and can hold years as large as 65535.
  180429. *
  180430. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180431. * no date-related code.
  180432. *
  180433. * Glenn Randers-Pehrson
  180434. * libpng maintainer
  180435. * PNG Development Group
  180436. */
  180437. #ifndef PNG_H
  180438. #define PNG_H
  180439. /* This is not the place to learn how to use libpng. The file libpng.txt
  180440. * describes how to use libpng, and the file example.c summarizes it
  180441. * with some code on which to build. This file is useful for looking
  180442. * at the actual function definitions and structure components.
  180443. */
  180444. /* Version information for png.h - this should match the version in png.c */
  180445. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180446. #define PNG_HEADER_VERSION_STRING \
  180447. " libpng version 1.2.21 - October 4, 2007\n"
  180448. #define PNG_LIBPNG_VER_SONUM 0
  180449. #define PNG_LIBPNG_VER_DLLNUM 13
  180450. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180451. #define PNG_LIBPNG_VER_MAJOR 1
  180452. #define PNG_LIBPNG_VER_MINOR 2
  180453. #define PNG_LIBPNG_VER_RELEASE 21
  180454. /* This should match the numeric part of the final component of
  180455. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180456. #define PNG_LIBPNG_VER_BUILD 0
  180457. /* Release Status */
  180458. #define PNG_LIBPNG_BUILD_ALPHA 1
  180459. #define PNG_LIBPNG_BUILD_BETA 2
  180460. #define PNG_LIBPNG_BUILD_RC 3
  180461. #define PNG_LIBPNG_BUILD_STABLE 4
  180462. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180463. /* Release-Specific Flags */
  180464. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180465. PNG_LIBPNG_BUILD_STABLE only */
  180466. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180467. PNG_LIBPNG_BUILD_SPECIAL */
  180468. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180469. PNG_LIBPNG_BUILD_PRIVATE */
  180470. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180471. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180472. * We must not include leading zeros.
  180473. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180474. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180475. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180476. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180477. #ifndef PNG_VERSION_INFO_ONLY
  180478. /* include the compression library's header */
  180479. #endif
  180480. /* include all user configurable info, including optional assembler routines */
  180481. /*** Start of inlined file: pngconf.h ***/
  180482. /* pngconf.h - machine configurable file for libpng
  180483. *
  180484. * libpng version 1.2.21 - October 4, 2007
  180485. * For conditions of distribution and use, see copyright notice in png.h
  180486. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180487. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180488. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180489. */
  180490. /* Any machine specific code is near the front of this file, so if you
  180491. * are configuring libpng for a machine, you may want to read the section
  180492. * starting here down to where it starts to typedef png_color, png_text,
  180493. * and png_info.
  180494. */
  180495. #ifndef PNGCONF_H
  180496. #define PNGCONF_H
  180497. #define PNG_1_2_X
  180498. // These are some Juce config settings that should remove any unnecessary code bloat..
  180499. #define PNG_NO_STDIO 1
  180500. #define PNG_DEBUG 0
  180501. #define PNG_NO_WARNINGS 1
  180502. #define PNG_NO_ERROR_TEXT 1
  180503. #define PNG_NO_ERROR_NUMBERS 1
  180504. #define PNG_NO_USER_MEM 1
  180505. #define PNG_NO_READ_iCCP 1
  180506. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180507. #define PNG_NO_READ_USER_CHUNKS 1
  180508. #define PNG_NO_READ_iTXt 1
  180509. #define PNG_NO_READ_sCAL 1
  180510. #define PNG_NO_READ_sPLT 1
  180511. #define png_error(a, b) png_err(a)
  180512. #define png_warning(a, b)
  180513. #define png_chunk_error(a, b) png_err(a)
  180514. #define png_chunk_warning(a, b)
  180515. /*
  180516. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180517. * includes the resource compiler for Windows DLL configurations.
  180518. */
  180519. #ifdef PNG_USER_CONFIG
  180520. # ifndef PNG_USER_PRIVATEBUILD
  180521. # define PNG_USER_PRIVATEBUILD
  180522. # endif
  180523. #include "pngusr.h"
  180524. #endif
  180525. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180526. #ifdef PNG_CONFIGURE_LIBPNG
  180527. #ifdef HAVE_CONFIG_H
  180528. #include "config.h"
  180529. #endif
  180530. #endif
  180531. /*
  180532. * Added at libpng-1.2.8
  180533. *
  180534. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180535. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180536. * the DLL was built>
  180537. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180538. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180539. * distinguish your DLL from those of the official release. These
  180540. * correspond to the trailing letters that come after the version
  180541. * number and must match your private DLL name>
  180542. * e.g. // private DLL "libpng13gx.dll"
  180543. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180544. *
  180545. * The following macros are also at your disposal if you want to complete the
  180546. * DLL VERSIONINFO structure.
  180547. * - PNG_USER_VERSIONINFO_COMMENTS
  180548. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180549. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180550. */
  180551. #ifdef __STDC__
  180552. #ifdef SPECIALBUILD
  180553. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180554. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180555. #endif
  180556. #ifdef PRIVATEBUILD
  180557. # pragma message("PRIVATEBUILD is deprecated.\
  180558. Use PNG_USER_PRIVATEBUILD instead.")
  180559. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180560. #endif
  180561. #endif /* __STDC__ */
  180562. #ifndef PNG_VERSION_INFO_ONLY
  180563. /* End of material added to libpng-1.2.8 */
  180564. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180565. Restored at libpng-1.2.21 */
  180566. # define PNG_WARN_UNINITIALIZED_ROW 1
  180567. /* End of material added at libpng-1.2.19/1.2.21 */
  180568. /* This is the size of the compression buffer, and thus the size of
  180569. * an IDAT chunk. Make this whatever size you feel is best for your
  180570. * machine. One of these will be allocated per png_struct. When this
  180571. * is full, it writes the data to the disk, and does some other
  180572. * calculations. Making this an extremely small size will slow
  180573. * the library down, but you may want to experiment to determine
  180574. * where it becomes significant, if you are concerned with memory
  180575. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180576. * this describes the size of the buffer available to read the data in.
  180577. * Unless this gets smaller than the size of a row (compressed),
  180578. * it should not make much difference how big this is.
  180579. */
  180580. #ifndef PNG_ZBUF_SIZE
  180581. # define PNG_ZBUF_SIZE 8192
  180582. #endif
  180583. /* Enable if you want a write-only libpng */
  180584. #ifndef PNG_NO_READ_SUPPORTED
  180585. # define PNG_READ_SUPPORTED
  180586. #endif
  180587. /* Enable if you want a read-only libpng */
  180588. #ifndef PNG_NO_WRITE_SUPPORTED
  180589. # define PNG_WRITE_SUPPORTED
  180590. #endif
  180591. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180592. support PNGs that are embedded in MNG datastreams */
  180593. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180594. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180595. # define PNG_MNG_FEATURES_SUPPORTED
  180596. # endif
  180597. #endif
  180598. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180599. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180600. # define PNG_FLOATING_POINT_SUPPORTED
  180601. # endif
  180602. #endif
  180603. /* If you are running on a machine where you cannot allocate more
  180604. * than 64K of memory at once, uncomment this. While libpng will not
  180605. * normally need that much memory in a chunk (unless you load up a very
  180606. * large file), zlib needs to know how big of a chunk it can use, and
  180607. * libpng thus makes sure to check any memory allocation to verify it
  180608. * will fit into memory.
  180609. #define PNG_MAX_MALLOC_64K
  180610. */
  180611. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180612. # define PNG_MAX_MALLOC_64K
  180613. #endif
  180614. /* Special munging to support doing things the 'cygwin' way:
  180615. * 'Normal' png-on-win32 defines/defaults:
  180616. * PNG_BUILD_DLL -- building dll
  180617. * PNG_USE_DLL -- building an application, linking to dll
  180618. * (no define) -- building static library, or building an
  180619. * application and linking to the static lib
  180620. * 'Cygwin' defines/defaults:
  180621. * PNG_BUILD_DLL -- (ignored) building the dll
  180622. * (no define) -- (ignored) building an application, linking to the dll
  180623. * PNG_STATIC -- (ignored) building the static lib, or building an
  180624. * application that links to the static lib.
  180625. * ALL_STATIC -- (ignored) building various static libs, or building an
  180626. * application that links to the static libs.
  180627. * Thus,
  180628. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180629. * this bit of #ifdefs will define the 'correct' config variables based on
  180630. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180631. * unnecessary.
  180632. *
  180633. * Also, the precedence order is:
  180634. * ALL_STATIC (since we can't #undef something outside our namespace)
  180635. * PNG_BUILD_DLL
  180636. * PNG_STATIC
  180637. * (nothing) == PNG_USE_DLL
  180638. *
  180639. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180640. * of auto-import in binutils, we no longer need to worry about
  180641. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180642. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180643. * to __declspec() stuff. However, we DO need to worry about
  180644. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180645. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180646. */
  180647. #if defined(__CYGWIN__)
  180648. # if defined(ALL_STATIC)
  180649. # if defined(PNG_BUILD_DLL)
  180650. # undef PNG_BUILD_DLL
  180651. # endif
  180652. # if defined(PNG_USE_DLL)
  180653. # undef PNG_USE_DLL
  180654. # endif
  180655. # if defined(PNG_DLL)
  180656. # undef PNG_DLL
  180657. # endif
  180658. # if !defined(PNG_STATIC)
  180659. # define PNG_STATIC
  180660. # endif
  180661. # else
  180662. # if defined (PNG_BUILD_DLL)
  180663. # if defined(PNG_STATIC)
  180664. # undef PNG_STATIC
  180665. # endif
  180666. # if defined(PNG_USE_DLL)
  180667. # undef PNG_USE_DLL
  180668. # endif
  180669. # if !defined(PNG_DLL)
  180670. # define PNG_DLL
  180671. # endif
  180672. # else
  180673. # if defined(PNG_STATIC)
  180674. # if defined(PNG_USE_DLL)
  180675. # undef PNG_USE_DLL
  180676. # endif
  180677. # if defined(PNG_DLL)
  180678. # undef PNG_DLL
  180679. # endif
  180680. # else
  180681. # if !defined(PNG_USE_DLL)
  180682. # define PNG_USE_DLL
  180683. # endif
  180684. # if !defined(PNG_DLL)
  180685. # define PNG_DLL
  180686. # endif
  180687. # endif
  180688. # endif
  180689. # endif
  180690. #endif
  180691. /* This protects us against compilers that run on a windowing system
  180692. * and thus don't have or would rather us not use the stdio types:
  180693. * stdin, stdout, and stderr. The only one currently used is stderr
  180694. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180695. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180696. * will also prevent these, plus will prevent the entire set of stdio
  180697. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180698. * unless (PNG_DEBUG > 0) has been #defined.
  180699. *
  180700. * #define PNG_NO_CONSOLE_IO
  180701. * #define PNG_NO_STDIO
  180702. */
  180703. #if defined(_WIN32_WCE)
  180704. # include <windows.h>
  180705. /* Console I/O functions are not supported on WindowsCE */
  180706. # define PNG_NO_CONSOLE_IO
  180707. # ifdef PNG_DEBUG
  180708. # undef PNG_DEBUG
  180709. # endif
  180710. #endif
  180711. #ifdef PNG_BUILD_DLL
  180712. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180713. # ifndef PNG_NO_CONSOLE_IO
  180714. # define PNG_NO_CONSOLE_IO
  180715. # endif
  180716. # endif
  180717. #endif
  180718. # ifdef PNG_NO_STDIO
  180719. # ifndef PNG_NO_CONSOLE_IO
  180720. # define PNG_NO_CONSOLE_IO
  180721. # endif
  180722. # ifdef PNG_DEBUG
  180723. # if (PNG_DEBUG > 0)
  180724. # include <stdio.h>
  180725. # endif
  180726. # endif
  180727. # else
  180728. # if !defined(_WIN32_WCE)
  180729. /* "stdio.h" functions are not supported on WindowsCE */
  180730. # include <stdio.h>
  180731. # endif
  180732. # endif
  180733. /* This macro protects us against machines that don't have function
  180734. * prototypes (ie K&R style headers). If your compiler does not handle
  180735. * function prototypes, define this macro and use the included ansi2knr.
  180736. * I've always been able to use _NO_PROTO as the indicator, but you may
  180737. * need to drag the empty declaration out in front of here, or change the
  180738. * ifdef to suit your own needs.
  180739. */
  180740. #ifndef PNGARG
  180741. #ifdef OF /* zlib prototype munger */
  180742. # define PNGARG(arglist) OF(arglist)
  180743. #else
  180744. #ifdef _NO_PROTO
  180745. # define PNGARG(arglist) ()
  180746. # ifndef PNG_TYPECAST_NULL
  180747. # define PNG_TYPECAST_NULL
  180748. # endif
  180749. #else
  180750. # define PNGARG(arglist) arglist
  180751. #endif /* _NO_PROTO */
  180752. #endif /* OF */
  180753. #endif /* PNGARG */
  180754. /* Try to determine if we are compiling on a Mac. Note that testing for
  180755. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180756. * on non-Mac platforms.
  180757. */
  180758. #ifndef MACOS
  180759. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180760. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180761. # define MACOS
  180762. # endif
  180763. #endif
  180764. /* enough people need this for various reasons to include it here */
  180765. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180766. # include <sys/types.h>
  180767. #endif
  180768. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180769. # define PNG_SETJMP_SUPPORTED
  180770. #endif
  180771. #ifdef PNG_SETJMP_SUPPORTED
  180772. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180773. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180774. */
  180775. # ifdef __linux__
  180776. # ifdef _BSD_SOURCE
  180777. # define PNG_SAVE_BSD_SOURCE
  180778. # undef _BSD_SOURCE
  180779. # endif
  180780. # ifdef _SETJMP_H
  180781. /* If you encounter a compiler error here, see the explanation
  180782. * near the end of INSTALL.
  180783. */
  180784. __png.h__ already includes setjmp.h;
  180785. __dont__ include it again.;
  180786. # endif
  180787. # endif /* __linux__ */
  180788. /* include setjmp.h for error handling */
  180789. # include <setjmp.h>
  180790. # ifdef __linux__
  180791. # ifdef PNG_SAVE_BSD_SOURCE
  180792. # define _BSD_SOURCE
  180793. # undef PNG_SAVE_BSD_SOURCE
  180794. # endif
  180795. # endif /* __linux__ */
  180796. #endif /* PNG_SETJMP_SUPPORTED */
  180797. #ifdef BSD
  180798. #if ! JUCE_MAC
  180799. # include <strings.h>
  180800. #endif
  180801. #else
  180802. # include <string.h>
  180803. #endif
  180804. /* Other defines for things like memory and the like can go here. */
  180805. #ifdef PNG_INTERNAL
  180806. #include <stdlib.h>
  180807. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180808. * aren't usually used outside the library (as far as I know), so it is
  180809. * debatable if they should be exported at all. In the future, when it is
  180810. * possible to have run-time registry of chunk-handling functions, some of
  180811. * these will be made available again.
  180812. #define PNG_EXTERN extern
  180813. */
  180814. #define PNG_EXTERN
  180815. /* Other defines specific to compilers can go here. Try to keep
  180816. * them inside an appropriate ifdef/endif pair for portability.
  180817. */
  180818. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180819. # if defined(MACOS)
  180820. /* We need to check that <math.h> hasn't already been included earlier
  180821. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180822. * <fp.h> if possible.
  180823. */
  180824. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180825. # include <fp.h>
  180826. # endif
  180827. # else
  180828. # include <math.h>
  180829. # endif
  180830. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180831. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180832. * MATH=68881
  180833. */
  180834. # include <m68881.h>
  180835. # endif
  180836. #endif
  180837. /* Codewarrior on NT has linking problems without this. */
  180838. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180839. # define PNG_ALWAYS_EXTERN
  180840. #endif
  180841. /* This provides the non-ANSI (far) memory allocation routines. */
  180842. #if defined(__TURBOC__) && defined(__MSDOS__)
  180843. # include <mem.h>
  180844. # include <alloc.h>
  180845. #endif
  180846. /* I have no idea why is this necessary... */
  180847. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180848. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180849. # include <malloc.h>
  180850. #endif
  180851. /* This controls how fine the dithering gets. As this allocates
  180852. * a largish chunk of memory (32K), those who are not as concerned
  180853. * with dithering quality can decrease some or all of these.
  180854. */
  180855. #ifndef PNG_DITHER_RED_BITS
  180856. # define PNG_DITHER_RED_BITS 5
  180857. #endif
  180858. #ifndef PNG_DITHER_GREEN_BITS
  180859. # define PNG_DITHER_GREEN_BITS 5
  180860. #endif
  180861. #ifndef PNG_DITHER_BLUE_BITS
  180862. # define PNG_DITHER_BLUE_BITS 5
  180863. #endif
  180864. /* This controls how fine the gamma correction becomes when you
  180865. * are only interested in 8 bits anyway. Increasing this value
  180866. * results in more memory being used, and more pow() functions
  180867. * being called to fill in the gamma tables. Don't set this value
  180868. * less then 8, and even that may not work (I haven't tested it).
  180869. */
  180870. #ifndef PNG_MAX_GAMMA_8
  180871. # define PNG_MAX_GAMMA_8 11
  180872. #endif
  180873. /* This controls how much a difference in gamma we can tolerate before
  180874. * we actually start doing gamma conversion.
  180875. */
  180876. #ifndef PNG_GAMMA_THRESHOLD
  180877. # define PNG_GAMMA_THRESHOLD 0.05
  180878. #endif
  180879. #endif /* PNG_INTERNAL */
  180880. /* The following uses const char * instead of char * for error
  180881. * and warning message functions, so some compilers won't complain.
  180882. * If you do not want to use const, define PNG_NO_CONST here.
  180883. */
  180884. #ifndef PNG_NO_CONST
  180885. # define PNG_CONST const
  180886. #else
  180887. # define PNG_CONST
  180888. #endif
  180889. /* The following defines give you the ability to remove code from the
  180890. * library that you will not be using. I wish I could figure out how to
  180891. * automate this, but I can't do that without making it seriously hard
  180892. * on the users. So if you are not using an ability, change the #define
  180893. * to and #undef, and that part of the library will not be compiled. If
  180894. * your linker can't find a function, you may want to make sure the
  180895. * ability is defined here. Some of these depend upon some others being
  180896. * defined. I haven't figured out all the interactions here, so you may
  180897. * have to experiment awhile to get everything to compile. If you are
  180898. * creating or using a shared library, you probably shouldn't touch this,
  180899. * as it will affect the size of the structures, and this will cause bad
  180900. * things to happen if the library and/or application ever change.
  180901. */
  180902. /* Any features you will not be using can be undef'ed here */
  180903. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180904. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180905. * on the compile line, then pick and choose which ones to define without
  180906. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180907. * if you only want to have a png-compliant reader/writer but don't need
  180908. * any of the extra transformations. This saves about 80 kbytes in a
  180909. * typical installation of the library. (PNG_NO_* form added in version
  180910. * 1.0.1c, for consistency)
  180911. */
  180912. /* The size of the png_text structure changed in libpng-1.0.6 when
  180913. * iTXt support was added. iTXt support was turned off by default through
  180914. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180915. * instead of calling png_set_text() and letting libpng malloc it. It
  180916. * was turned on by default in libpng-1.3.0.
  180917. */
  180918. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180919. # ifndef PNG_NO_iTXt_SUPPORTED
  180920. # define PNG_NO_iTXt_SUPPORTED
  180921. # endif
  180922. # ifndef PNG_NO_READ_iTXt
  180923. # define PNG_NO_READ_iTXt
  180924. # endif
  180925. # ifndef PNG_NO_WRITE_iTXt
  180926. # define PNG_NO_WRITE_iTXt
  180927. # endif
  180928. #endif
  180929. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180930. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180931. # define PNG_READ_iTXt
  180932. # endif
  180933. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180934. # define PNG_WRITE_iTXt
  180935. # endif
  180936. #endif
  180937. /* The following support, added after version 1.0.0, can be turned off here en
  180938. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180939. * with old applications that require the length of png_struct and png_info
  180940. * to remain unchanged.
  180941. */
  180942. #ifdef PNG_LEGACY_SUPPORTED
  180943. # define PNG_NO_FREE_ME
  180944. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180945. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180946. # define PNG_NO_READ_USER_CHUNKS
  180947. # define PNG_NO_READ_iCCP
  180948. # define PNG_NO_WRITE_iCCP
  180949. # define PNG_NO_READ_iTXt
  180950. # define PNG_NO_WRITE_iTXt
  180951. # define PNG_NO_READ_sCAL
  180952. # define PNG_NO_WRITE_sCAL
  180953. # define PNG_NO_READ_sPLT
  180954. # define PNG_NO_WRITE_sPLT
  180955. # define PNG_NO_INFO_IMAGE
  180956. # define PNG_NO_READ_RGB_TO_GRAY
  180957. # define PNG_NO_READ_USER_TRANSFORM
  180958. # define PNG_NO_WRITE_USER_TRANSFORM
  180959. # define PNG_NO_USER_MEM
  180960. # define PNG_NO_READ_EMPTY_PLTE
  180961. # define PNG_NO_MNG_FEATURES
  180962. # define PNG_NO_FIXED_POINT_SUPPORTED
  180963. #endif
  180964. /* Ignore attempt to turn off both floating and fixed point support */
  180965. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180966. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180967. # define PNG_FIXED_POINT_SUPPORTED
  180968. #endif
  180969. #ifndef PNG_NO_FREE_ME
  180970. # define PNG_FREE_ME_SUPPORTED
  180971. #endif
  180972. #if defined(PNG_READ_SUPPORTED)
  180973. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180974. !defined(PNG_NO_READ_TRANSFORMS)
  180975. # define PNG_READ_TRANSFORMS_SUPPORTED
  180976. #endif
  180977. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180978. # ifndef PNG_NO_READ_EXPAND
  180979. # define PNG_READ_EXPAND_SUPPORTED
  180980. # endif
  180981. # ifndef PNG_NO_READ_SHIFT
  180982. # define PNG_READ_SHIFT_SUPPORTED
  180983. # endif
  180984. # ifndef PNG_NO_READ_PACK
  180985. # define PNG_READ_PACK_SUPPORTED
  180986. # endif
  180987. # ifndef PNG_NO_READ_BGR
  180988. # define PNG_READ_BGR_SUPPORTED
  180989. # endif
  180990. # ifndef PNG_NO_READ_SWAP
  180991. # define PNG_READ_SWAP_SUPPORTED
  180992. # endif
  180993. # ifndef PNG_NO_READ_PACKSWAP
  180994. # define PNG_READ_PACKSWAP_SUPPORTED
  180995. # endif
  180996. # ifndef PNG_NO_READ_INVERT
  180997. # define PNG_READ_INVERT_SUPPORTED
  180998. # endif
  180999. # ifndef PNG_NO_READ_DITHER
  181000. # define PNG_READ_DITHER_SUPPORTED
  181001. # endif
  181002. # ifndef PNG_NO_READ_BACKGROUND
  181003. # define PNG_READ_BACKGROUND_SUPPORTED
  181004. # endif
  181005. # ifndef PNG_NO_READ_16_TO_8
  181006. # define PNG_READ_16_TO_8_SUPPORTED
  181007. # endif
  181008. # ifndef PNG_NO_READ_FILLER
  181009. # define PNG_READ_FILLER_SUPPORTED
  181010. # endif
  181011. # ifndef PNG_NO_READ_GAMMA
  181012. # define PNG_READ_GAMMA_SUPPORTED
  181013. # endif
  181014. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181015. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181016. # endif
  181017. # ifndef PNG_NO_READ_SWAP_ALPHA
  181018. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181019. # endif
  181020. # ifndef PNG_NO_READ_INVERT_ALPHA
  181021. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181022. # endif
  181023. # ifndef PNG_NO_READ_STRIP_ALPHA
  181024. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181025. # endif
  181026. # ifndef PNG_NO_READ_USER_TRANSFORM
  181027. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181028. # endif
  181029. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181030. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181031. # endif
  181032. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181033. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181034. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181035. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181036. #endif /* about interlacing capability! You'll */
  181037. /* still have interlacing unless you change the following line: */
  181038. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181039. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181040. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181041. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181042. # endif
  181043. #endif
  181044. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181045. /* Deprecated, will be removed from version 2.0.0.
  181046. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181047. #ifndef PNG_NO_READ_EMPTY_PLTE
  181048. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181049. #endif
  181050. #endif
  181051. #endif /* PNG_READ_SUPPORTED */
  181052. #if defined(PNG_WRITE_SUPPORTED)
  181053. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181054. !defined(PNG_NO_WRITE_TRANSFORMS)
  181055. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181056. #endif
  181057. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181058. # ifndef PNG_NO_WRITE_SHIFT
  181059. # define PNG_WRITE_SHIFT_SUPPORTED
  181060. # endif
  181061. # ifndef PNG_NO_WRITE_PACK
  181062. # define PNG_WRITE_PACK_SUPPORTED
  181063. # endif
  181064. # ifndef PNG_NO_WRITE_BGR
  181065. # define PNG_WRITE_BGR_SUPPORTED
  181066. # endif
  181067. # ifndef PNG_NO_WRITE_SWAP
  181068. # define PNG_WRITE_SWAP_SUPPORTED
  181069. # endif
  181070. # ifndef PNG_NO_WRITE_PACKSWAP
  181071. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181072. # endif
  181073. # ifndef PNG_NO_WRITE_INVERT
  181074. # define PNG_WRITE_INVERT_SUPPORTED
  181075. # endif
  181076. # ifndef PNG_NO_WRITE_FILLER
  181077. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181078. # endif
  181079. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181080. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181081. # endif
  181082. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181083. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181084. # endif
  181085. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181086. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181087. # endif
  181088. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181089. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181090. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181091. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181092. encoders, but can cause trouble
  181093. if left undefined */
  181094. #endif
  181095. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181096. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181097. defined(PNG_FLOATING_POINT_SUPPORTED)
  181098. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181099. #endif
  181100. #ifndef PNG_NO_WRITE_FLUSH
  181101. # define PNG_WRITE_FLUSH_SUPPORTED
  181102. #endif
  181103. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181104. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181105. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181106. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181107. #endif
  181108. #endif
  181109. #endif /* PNG_WRITE_SUPPORTED */
  181110. #ifndef PNG_1_0_X
  181111. # ifndef PNG_NO_ERROR_NUMBERS
  181112. # define PNG_ERROR_NUMBERS_SUPPORTED
  181113. # endif
  181114. #endif /* PNG_1_0_X */
  181115. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181116. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181117. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181118. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181119. # endif
  181120. #endif
  181121. #ifndef PNG_NO_STDIO
  181122. # define PNG_TIME_RFC1123_SUPPORTED
  181123. #endif
  181124. /* This adds extra functions in pngget.c for accessing data from the
  181125. * info pointer (added in version 0.99)
  181126. * png_get_image_width()
  181127. * png_get_image_height()
  181128. * png_get_bit_depth()
  181129. * png_get_color_type()
  181130. * png_get_compression_type()
  181131. * png_get_filter_type()
  181132. * png_get_interlace_type()
  181133. * png_get_pixel_aspect_ratio()
  181134. * png_get_pixels_per_meter()
  181135. * png_get_x_offset_pixels()
  181136. * png_get_y_offset_pixels()
  181137. * png_get_x_offset_microns()
  181138. * png_get_y_offset_microns()
  181139. */
  181140. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181141. # define PNG_EASY_ACCESS_SUPPORTED
  181142. #endif
  181143. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181144. * and removed from version 1.2.20. The following will be removed
  181145. * from libpng-1.4.0
  181146. */
  181147. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181148. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181149. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181150. # endif
  181151. #endif
  181152. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181153. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181154. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181155. # endif
  181156. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181157. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181158. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181159. # define PNG_NO_MMX_CODE
  181160. # endif
  181161. # endif
  181162. # if defined(__APPLE__)
  181163. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181164. # define PNG_NO_MMX_CODE
  181165. # endif
  181166. # endif
  181167. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181168. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181169. # define PNG_NO_MMX_CODE
  181170. # endif
  181171. # endif
  181172. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181173. # define PNG_MMX_CODE_SUPPORTED
  181174. # endif
  181175. #endif
  181176. /* end of obsolete code to be removed from libpng-1.4.0 */
  181177. #if !defined(PNG_1_0_X)
  181178. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181179. # define PNG_USER_MEM_SUPPORTED
  181180. #endif
  181181. #endif /* PNG_1_0_X */
  181182. /* Added at libpng-1.2.6 */
  181183. #if !defined(PNG_1_0_X)
  181184. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181185. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181186. # define PNG_SET_USER_LIMITS_SUPPORTED
  181187. #endif
  181188. #endif
  181189. #endif /* PNG_1_0_X */
  181190. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181191. * how large, set these limits to 0x7fffffffL
  181192. */
  181193. #ifndef PNG_USER_WIDTH_MAX
  181194. # define PNG_USER_WIDTH_MAX 1000000L
  181195. #endif
  181196. #ifndef PNG_USER_HEIGHT_MAX
  181197. # define PNG_USER_HEIGHT_MAX 1000000L
  181198. #endif
  181199. /* These are currently experimental features, define them if you want */
  181200. /* very little testing */
  181201. /*
  181202. #ifdef PNG_READ_SUPPORTED
  181203. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181204. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181205. # endif
  181206. #endif
  181207. */
  181208. /* This is only for PowerPC big-endian and 680x0 systems */
  181209. /* some testing */
  181210. /*
  181211. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181212. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181213. #endif
  181214. */
  181215. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181216. /*
  181217. #define PNG_NO_POINTER_INDEXING
  181218. */
  181219. /* These functions are turned off by default, as they will be phased out. */
  181220. /*
  181221. #define PNG_USELESS_TESTS_SUPPORTED
  181222. #define PNG_CORRECT_PALETTE_SUPPORTED
  181223. */
  181224. /* Any chunks you are not interested in, you can undef here. The
  181225. * ones that allocate memory may be expecially important (hIST,
  181226. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181227. * a bit smaller.
  181228. */
  181229. #if defined(PNG_READ_SUPPORTED) && \
  181230. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181231. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181232. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181233. #endif
  181234. #if defined(PNG_WRITE_SUPPORTED) && \
  181235. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181236. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181237. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181238. #endif
  181239. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181240. #ifdef PNG_NO_READ_TEXT
  181241. # define PNG_NO_READ_iTXt
  181242. # define PNG_NO_READ_tEXt
  181243. # define PNG_NO_READ_zTXt
  181244. #endif
  181245. #ifndef PNG_NO_READ_bKGD
  181246. # define PNG_READ_bKGD_SUPPORTED
  181247. # define PNG_bKGD_SUPPORTED
  181248. #endif
  181249. #ifndef PNG_NO_READ_cHRM
  181250. # define PNG_READ_cHRM_SUPPORTED
  181251. # define PNG_cHRM_SUPPORTED
  181252. #endif
  181253. #ifndef PNG_NO_READ_gAMA
  181254. # define PNG_READ_gAMA_SUPPORTED
  181255. # define PNG_gAMA_SUPPORTED
  181256. #endif
  181257. #ifndef PNG_NO_READ_hIST
  181258. # define PNG_READ_hIST_SUPPORTED
  181259. # define PNG_hIST_SUPPORTED
  181260. #endif
  181261. #ifndef PNG_NO_READ_iCCP
  181262. # define PNG_READ_iCCP_SUPPORTED
  181263. # define PNG_iCCP_SUPPORTED
  181264. #endif
  181265. #ifndef PNG_NO_READ_iTXt
  181266. # ifndef PNG_READ_iTXt_SUPPORTED
  181267. # define PNG_READ_iTXt_SUPPORTED
  181268. # endif
  181269. # ifndef PNG_iTXt_SUPPORTED
  181270. # define PNG_iTXt_SUPPORTED
  181271. # endif
  181272. #endif
  181273. #ifndef PNG_NO_READ_oFFs
  181274. # define PNG_READ_oFFs_SUPPORTED
  181275. # define PNG_oFFs_SUPPORTED
  181276. #endif
  181277. #ifndef PNG_NO_READ_pCAL
  181278. # define PNG_READ_pCAL_SUPPORTED
  181279. # define PNG_pCAL_SUPPORTED
  181280. #endif
  181281. #ifndef PNG_NO_READ_sCAL
  181282. # define PNG_READ_sCAL_SUPPORTED
  181283. # define PNG_sCAL_SUPPORTED
  181284. #endif
  181285. #ifndef PNG_NO_READ_pHYs
  181286. # define PNG_READ_pHYs_SUPPORTED
  181287. # define PNG_pHYs_SUPPORTED
  181288. #endif
  181289. #ifndef PNG_NO_READ_sBIT
  181290. # define PNG_READ_sBIT_SUPPORTED
  181291. # define PNG_sBIT_SUPPORTED
  181292. #endif
  181293. #ifndef PNG_NO_READ_sPLT
  181294. # define PNG_READ_sPLT_SUPPORTED
  181295. # define PNG_sPLT_SUPPORTED
  181296. #endif
  181297. #ifndef PNG_NO_READ_sRGB
  181298. # define PNG_READ_sRGB_SUPPORTED
  181299. # define PNG_sRGB_SUPPORTED
  181300. #endif
  181301. #ifndef PNG_NO_READ_tEXt
  181302. # define PNG_READ_tEXt_SUPPORTED
  181303. # define PNG_tEXt_SUPPORTED
  181304. #endif
  181305. #ifndef PNG_NO_READ_tIME
  181306. # define PNG_READ_tIME_SUPPORTED
  181307. # define PNG_tIME_SUPPORTED
  181308. #endif
  181309. #ifndef PNG_NO_READ_tRNS
  181310. # define PNG_READ_tRNS_SUPPORTED
  181311. # define PNG_tRNS_SUPPORTED
  181312. #endif
  181313. #ifndef PNG_NO_READ_zTXt
  181314. # define PNG_READ_zTXt_SUPPORTED
  181315. # define PNG_zTXt_SUPPORTED
  181316. #endif
  181317. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181318. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181319. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181320. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181321. # endif
  181322. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181323. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181324. # endif
  181325. #endif
  181326. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181327. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181328. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181329. # define PNG_USER_CHUNKS_SUPPORTED
  181330. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181331. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181332. # endif
  181333. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181334. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181335. # endif
  181336. #endif
  181337. #ifndef PNG_NO_READ_OPT_PLTE
  181338. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181339. #endif /* optional PLTE chunk in RGB and RGBA images */
  181340. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181341. defined(PNG_READ_zTXt_SUPPORTED)
  181342. # define PNG_READ_TEXT_SUPPORTED
  181343. # define PNG_TEXT_SUPPORTED
  181344. #endif
  181345. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181346. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181347. #ifdef PNG_NO_WRITE_TEXT
  181348. # define PNG_NO_WRITE_iTXt
  181349. # define PNG_NO_WRITE_tEXt
  181350. # define PNG_NO_WRITE_zTXt
  181351. #endif
  181352. #ifndef PNG_NO_WRITE_bKGD
  181353. # define PNG_WRITE_bKGD_SUPPORTED
  181354. # ifndef PNG_bKGD_SUPPORTED
  181355. # define PNG_bKGD_SUPPORTED
  181356. # endif
  181357. #endif
  181358. #ifndef PNG_NO_WRITE_cHRM
  181359. # define PNG_WRITE_cHRM_SUPPORTED
  181360. # ifndef PNG_cHRM_SUPPORTED
  181361. # define PNG_cHRM_SUPPORTED
  181362. # endif
  181363. #endif
  181364. #ifndef PNG_NO_WRITE_gAMA
  181365. # define PNG_WRITE_gAMA_SUPPORTED
  181366. # ifndef PNG_gAMA_SUPPORTED
  181367. # define PNG_gAMA_SUPPORTED
  181368. # endif
  181369. #endif
  181370. #ifndef PNG_NO_WRITE_hIST
  181371. # define PNG_WRITE_hIST_SUPPORTED
  181372. # ifndef PNG_hIST_SUPPORTED
  181373. # define PNG_hIST_SUPPORTED
  181374. # endif
  181375. #endif
  181376. #ifndef PNG_NO_WRITE_iCCP
  181377. # define PNG_WRITE_iCCP_SUPPORTED
  181378. # ifndef PNG_iCCP_SUPPORTED
  181379. # define PNG_iCCP_SUPPORTED
  181380. # endif
  181381. #endif
  181382. #ifndef PNG_NO_WRITE_iTXt
  181383. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181384. # define PNG_WRITE_iTXt_SUPPORTED
  181385. # endif
  181386. # ifndef PNG_iTXt_SUPPORTED
  181387. # define PNG_iTXt_SUPPORTED
  181388. # endif
  181389. #endif
  181390. #ifndef PNG_NO_WRITE_oFFs
  181391. # define PNG_WRITE_oFFs_SUPPORTED
  181392. # ifndef PNG_oFFs_SUPPORTED
  181393. # define PNG_oFFs_SUPPORTED
  181394. # endif
  181395. #endif
  181396. #ifndef PNG_NO_WRITE_pCAL
  181397. # define PNG_WRITE_pCAL_SUPPORTED
  181398. # ifndef PNG_pCAL_SUPPORTED
  181399. # define PNG_pCAL_SUPPORTED
  181400. # endif
  181401. #endif
  181402. #ifndef PNG_NO_WRITE_sCAL
  181403. # define PNG_WRITE_sCAL_SUPPORTED
  181404. # ifndef PNG_sCAL_SUPPORTED
  181405. # define PNG_sCAL_SUPPORTED
  181406. # endif
  181407. #endif
  181408. #ifndef PNG_NO_WRITE_pHYs
  181409. # define PNG_WRITE_pHYs_SUPPORTED
  181410. # ifndef PNG_pHYs_SUPPORTED
  181411. # define PNG_pHYs_SUPPORTED
  181412. # endif
  181413. #endif
  181414. #ifndef PNG_NO_WRITE_sBIT
  181415. # define PNG_WRITE_sBIT_SUPPORTED
  181416. # ifndef PNG_sBIT_SUPPORTED
  181417. # define PNG_sBIT_SUPPORTED
  181418. # endif
  181419. #endif
  181420. #ifndef PNG_NO_WRITE_sPLT
  181421. # define PNG_WRITE_sPLT_SUPPORTED
  181422. # ifndef PNG_sPLT_SUPPORTED
  181423. # define PNG_sPLT_SUPPORTED
  181424. # endif
  181425. #endif
  181426. #ifndef PNG_NO_WRITE_sRGB
  181427. # define PNG_WRITE_sRGB_SUPPORTED
  181428. # ifndef PNG_sRGB_SUPPORTED
  181429. # define PNG_sRGB_SUPPORTED
  181430. # endif
  181431. #endif
  181432. #ifndef PNG_NO_WRITE_tEXt
  181433. # define PNG_WRITE_tEXt_SUPPORTED
  181434. # ifndef PNG_tEXt_SUPPORTED
  181435. # define PNG_tEXt_SUPPORTED
  181436. # endif
  181437. #endif
  181438. #ifndef PNG_NO_WRITE_tIME
  181439. # define PNG_WRITE_tIME_SUPPORTED
  181440. # ifndef PNG_tIME_SUPPORTED
  181441. # define PNG_tIME_SUPPORTED
  181442. # endif
  181443. #endif
  181444. #ifndef PNG_NO_WRITE_tRNS
  181445. # define PNG_WRITE_tRNS_SUPPORTED
  181446. # ifndef PNG_tRNS_SUPPORTED
  181447. # define PNG_tRNS_SUPPORTED
  181448. # endif
  181449. #endif
  181450. #ifndef PNG_NO_WRITE_zTXt
  181451. # define PNG_WRITE_zTXt_SUPPORTED
  181452. # ifndef PNG_zTXt_SUPPORTED
  181453. # define PNG_zTXt_SUPPORTED
  181454. # endif
  181455. #endif
  181456. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181457. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181458. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181459. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181460. # endif
  181461. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181462. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181463. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181464. # endif
  181465. # endif
  181466. #endif
  181467. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181468. defined(PNG_WRITE_zTXt_SUPPORTED)
  181469. # define PNG_WRITE_TEXT_SUPPORTED
  181470. # ifndef PNG_TEXT_SUPPORTED
  181471. # define PNG_TEXT_SUPPORTED
  181472. # endif
  181473. #endif
  181474. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181475. /* Turn this off to disable png_read_png() and
  181476. * png_write_png() and leave the row_pointers member
  181477. * out of the info structure.
  181478. */
  181479. #ifndef PNG_NO_INFO_IMAGE
  181480. # define PNG_INFO_IMAGE_SUPPORTED
  181481. #endif
  181482. /* need the time information for reading tIME chunks */
  181483. #if defined(PNG_tIME_SUPPORTED)
  181484. # if !defined(_WIN32_WCE)
  181485. /* "time.h" functions are not supported on WindowsCE */
  181486. # include <time.h>
  181487. # endif
  181488. #endif
  181489. /* Some typedefs to get us started. These should be safe on most of the
  181490. * common platforms. The typedefs should be at least as large as the
  181491. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181492. * don't have to be exactly that size. Some compilers dislike passing
  181493. * unsigned shorts as function parameters, so you may be better off using
  181494. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181495. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181496. */
  181497. typedef unsigned long png_uint_32;
  181498. typedef long png_int_32;
  181499. typedef unsigned short png_uint_16;
  181500. typedef short png_int_16;
  181501. typedef unsigned char png_byte;
  181502. /* This is usually size_t. It is typedef'ed just in case you need it to
  181503. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181504. #ifdef PNG_SIZE_T
  181505. typedef PNG_SIZE_T png_size_t;
  181506. # define png_sizeof(x) png_convert_size(sizeof (x))
  181507. #else
  181508. typedef size_t png_size_t;
  181509. # define png_sizeof(x) sizeof (x)
  181510. #endif
  181511. /* The following is needed for medium model support. It cannot be in the
  181512. * PNG_INTERNAL section. Needs modification for other compilers besides
  181513. * MSC. Model independent support declares all arrays and pointers to be
  181514. * large using the far keyword. The zlib version used must also support
  181515. * model independent data. As of version zlib 1.0.4, the necessary changes
  181516. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181517. * changes that are needed. (Tim Wegner)
  181518. */
  181519. /* Separate compiler dependencies (problem here is that zlib.h always
  181520. defines FAR. (SJT) */
  181521. #ifdef __BORLANDC__
  181522. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181523. # define LDATA 1
  181524. # else
  181525. # define LDATA 0
  181526. # endif
  181527. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181528. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181529. # define PNG_MAX_MALLOC_64K
  181530. # if (LDATA != 1)
  181531. # ifndef FAR
  181532. # define FAR __far
  181533. # endif
  181534. # define USE_FAR_KEYWORD
  181535. # endif /* LDATA != 1 */
  181536. /* Possibly useful for moving data out of default segment.
  181537. * Uncomment it if you want. Could also define FARDATA as
  181538. * const if your compiler supports it. (SJT)
  181539. # define FARDATA FAR
  181540. */
  181541. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181542. #endif /* __BORLANDC__ */
  181543. /* Suggest testing for specific compiler first before testing for
  181544. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181545. * making reliance oncertain keywords suspect. (SJT)
  181546. */
  181547. /* MSC Medium model */
  181548. #if defined(FAR)
  181549. # if defined(M_I86MM)
  181550. # define USE_FAR_KEYWORD
  181551. # define FARDATA FAR
  181552. # include <dos.h>
  181553. # endif
  181554. #endif
  181555. /* SJT: default case */
  181556. #ifndef FAR
  181557. # define FAR
  181558. #endif
  181559. /* At this point FAR is always defined */
  181560. #ifndef FARDATA
  181561. # define FARDATA
  181562. #endif
  181563. /* Typedef for floating-point numbers that are converted
  181564. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181565. typedef png_int_32 png_fixed_point;
  181566. /* Add typedefs for pointers */
  181567. typedef void FAR * png_voidp;
  181568. typedef png_byte FAR * png_bytep;
  181569. typedef png_uint_32 FAR * png_uint_32p;
  181570. typedef png_int_32 FAR * png_int_32p;
  181571. typedef png_uint_16 FAR * png_uint_16p;
  181572. typedef png_int_16 FAR * png_int_16p;
  181573. typedef PNG_CONST char FAR * png_const_charp;
  181574. typedef char FAR * png_charp;
  181575. typedef png_fixed_point FAR * png_fixed_point_p;
  181576. #ifndef PNG_NO_STDIO
  181577. #if defined(_WIN32_WCE)
  181578. typedef HANDLE png_FILE_p;
  181579. #else
  181580. typedef FILE * png_FILE_p;
  181581. #endif
  181582. #endif
  181583. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181584. typedef double FAR * png_doublep;
  181585. #endif
  181586. /* Pointers to pointers; i.e. arrays */
  181587. typedef png_byte FAR * FAR * png_bytepp;
  181588. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181589. typedef png_int_32 FAR * FAR * png_int_32pp;
  181590. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181591. typedef png_int_16 FAR * FAR * png_int_16pp;
  181592. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181593. typedef char FAR * FAR * png_charpp;
  181594. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181595. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181596. typedef double FAR * FAR * png_doublepp;
  181597. #endif
  181598. /* Pointers to pointers to pointers; i.e., pointer to array */
  181599. typedef char FAR * FAR * FAR * png_charppp;
  181600. #if 0
  181601. /* SPC - Is this stuff deprecated? */
  181602. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181603. /* libpng typedefs for types in zlib. If zlib changes
  181604. * or another compression library is used, then change these.
  181605. * Eliminates need to change all the source files.
  181606. */
  181607. typedef charf * png_zcharp;
  181608. typedef charf * FAR * png_zcharpp;
  181609. typedef z_stream FAR * png_zstreamp;
  181610. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181611. /*
  181612. * Define PNG_BUILD_DLL if the module being built is a Windows
  181613. * LIBPNG DLL.
  181614. *
  181615. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181616. * It is equivalent to Microsoft predefined macro _DLL that is
  181617. * automatically defined when you compile using the share
  181618. * version of the CRT (C Run-Time library)
  181619. *
  181620. * The cygwin mods make this behavior a little different:
  181621. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181622. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181623. * -or- if you are building an application that you want to link to the
  181624. * static library.
  181625. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181626. * the other flags is defined.
  181627. */
  181628. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181629. # define PNG_DLL
  181630. #endif
  181631. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181632. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181633. * command-line override
  181634. */
  181635. #if defined(__CYGWIN__)
  181636. # if !defined(PNG_STATIC)
  181637. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181638. # undef PNG_USE_GLOBAL_ARRAYS
  181639. # endif
  181640. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181641. # define PNG_USE_LOCAL_ARRAYS
  181642. # endif
  181643. # else
  181644. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181645. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181646. # undef PNG_USE_GLOBAL_ARRAYS
  181647. # endif
  181648. # endif
  181649. # endif
  181650. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181651. # define PNG_USE_LOCAL_ARRAYS
  181652. # endif
  181653. #endif
  181654. /* Do not use global arrays (helps with building DLL's)
  181655. * They are no longer used in libpng itself, since version 1.0.5c,
  181656. * but might be required for some pre-1.0.5c applications.
  181657. */
  181658. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181659. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181660. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181661. # define PNG_USE_LOCAL_ARRAYS
  181662. # else
  181663. # define PNG_USE_GLOBAL_ARRAYS
  181664. # endif
  181665. #endif
  181666. #if defined(__CYGWIN__)
  181667. # undef PNGAPI
  181668. # define PNGAPI __cdecl
  181669. # undef PNG_IMPEXP
  181670. # define PNG_IMPEXP
  181671. #endif
  181672. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181673. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181674. * Don't ignore those warnings; you must also reset the default calling
  181675. * convention in your compiler to match your PNGAPI, and you must build
  181676. * zlib and your applications the same way you build libpng.
  181677. */
  181678. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181679. # ifndef PNG_NO_MODULEDEF
  181680. # define PNG_NO_MODULEDEF
  181681. # endif
  181682. #endif
  181683. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181684. # define PNG_IMPEXP
  181685. #endif
  181686. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181687. (( defined(_Windows) || defined(_WINDOWS) || \
  181688. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181689. # ifndef PNGAPI
  181690. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181691. # define PNGAPI __cdecl
  181692. # else
  181693. # define PNGAPI _cdecl
  181694. # endif
  181695. # endif
  181696. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181697. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181698. # define PNG_IMPEXP
  181699. # endif
  181700. # if !defined(PNG_IMPEXP)
  181701. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181702. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181703. /* Borland/Microsoft */
  181704. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181705. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181706. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181707. # else
  181708. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181709. # if defined(PNG_BUILD_DLL)
  181710. # define PNG_IMPEXP __export
  181711. # else
  181712. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181713. VC++ */
  181714. # endif /* Exists in Borland C++ for
  181715. C++ classes (== huge) */
  181716. # endif
  181717. # endif
  181718. # if !defined(PNG_IMPEXP)
  181719. # if defined(PNG_BUILD_DLL)
  181720. # define PNG_IMPEXP __declspec(dllexport)
  181721. # else
  181722. # define PNG_IMPEXP __declspec(dllimport)
  181723. # endif
  181724. # endif
  181725. # endif /* PNG_IMPEXP */
  181726. #else /* !(DLL || non-cygwin WINDOWS) */
  181727. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181728. # ifndef PNGAPI
  181729. # define PNGAPI _System
  181730. # endif
  181731. # else
  181732. # if 0 /* ... other platforms, with other meanings */
  181733. # endif
  181734. # endif
  181735. #endif
  181736. #ifndef PNGAPI
  181737. # define PNGAPI
  181738. #endif
  181739. #ifndef PNG_IMPEXP
  181740. # define PNG_IMPEXP
  181741. #endif
  181742. #ifdef PNG_BUILDSYMS
  181743. # ifndef PNG_EXPORT
  181744. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181745. # endif
  181746. # ifdef PNG_USE_GLOBAL_ARRAYS
  181747. # ifndef PNG_EXPORT_VAR
  181748. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181749. # endif
  181750. # endif
  181751. #endif
  181752. #ifndef PNG_EXPORT
  181753. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181754. #endif
  181755. #ifdef PNG_USE_GLOBAL_ARRAYS
  181756. # ifndef PNG_EXPORT_VAR
  181757. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181758. # endif
  181759. #endif
  181760. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181761. * functions that are passed far data must be model independent.
  181762. */
  181763. #ifndef PNG_ABORT
  181764. # define PNG_ABORT() abort()
  181765. #endif
  181766. #ifdef PNG_SETJMP_SUPPORTED
  181767. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181768. #else
  181769. # define png_jmpbuf(png_ptr) \
  181770. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181771. #endif
  181772. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181773. /* use this to make far-to-near assignments */
  181774. # define CHECK 1
  181775. # define NOCHECK 0
  181776. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181777. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181778. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181779. # define png_strcpy _fstrcpy
  181780. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181781. # define png_strlen _fstrlen
  181782. # define png_memcmp _fmemcmp /* SJT: added */
  181783. # define png_memcpy _fmemcpy
  181784. # define png_memset _fmemset
  181785. #else /* use the usual functions */
  181786. # define CVT_PTR(ptr) (ptr)
  181787. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181788. # ifndef PNG_NO_SNPRINTF
  181789. # ifdef _MSC_VER
  181790. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181791. # define png_snprintf2 _snprintf
  181792. # define png_snprintf6 _snprintf
  181793. # else
  181794. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181795. # define png_snprintf2 snprintf
  181796. # define png_snprintf6 snprintf
  181797. # endif
  181798. # else
  181799. /* You don't have or don't want to use snprintf(). Caution: Using
  181800. * sprintf instead of snprintf exposes your application to accidental
  181801. * or malevolent buffer overflows. If you don't have snprintf()
  181802. * as a general rule you should provide one (you can get one from
  181803. * Portable OpenSSH). */
  181804. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181805. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181806. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181807. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181808. # endif
  181809. # define png_strcpy strcpy
  181810. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181811. # define png_strlen strlen
  181812. # define png_memcmp memcmp /* SJT: added */
  181813. # define png_memcpy memcpy
  181814. # define png_memset memset
  181815. #endif
  181816. /* End of memory model independent support */
  181817. /* Just a little check that someone hasn't tried to define something
  181818. * contradictory.
  181819. */
  181820. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181821. # undef PNG_ZBUF_SIZE
  181822. # define PNG_ZBUF_SIZE 65536L
  181823. #endif
  181824. /* Added at libpng-1.2.8 */
  181825. #endif /* PNG_VERSION_INFO_ONLY */
  181826. #endif /* PNGCONF_H */
  181827. /*** End of inlined file: pngconf.h ***/
  181828. #ifdef _MSC_VER
  181829. #pragma warning (disable: 4996 4100)
  181830. #endif
  181831. /*
  181832. * Added at libpng-1.2.8 */
  181833. /* Ref MSDN: Private as priority over Special
  181834. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181835. * procedures. If this value is given, the StringFileInfo block must
  181836. * contain a PrivateBuild string.
  181837. *
  181838. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181839. * standard release procedures but is a variation of the standard
  181840. * file of the same version number. If this value is given, the
  181841. * StringFileInfo block must contain a SpecialBuild string.
  181842. */
  181843. #if defined(PNG_USER_PRIVATEBUILD)
  181844. # define PNG_LIBPNG_BUILD_TYPE \
  181845. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181846. #else
  181847. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181848. # define PNG_LIBPNG_BUILD_TYPE \
  181849. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181850. # else
  181851. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181852. # endif
  181853. #endif
  181854. #ifndef PNG_VERSION_INFO_ONLY
  181855. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181856. #ifdef __cplusplus
  181857. //extern "C" {
  181858. #endif /* __cplusplus */
  181859. /* This file is arranged in several sections. The first section contains
  181860. * structure and type definitions. The second section contains the external
  181861. * library functions, while the third has the internal library functions,
  181862. * which applications aren't expected to use directly.
  181863. */
  181864. #ifndef PNG_NO_TYPECAST_NULL
  181865. #define int_p_NULL (int *)NULL
  181866. #define png_bytep_NULL (png_bytep)NULL
  181867. #define png_bytepp_NULL (png_bytepp)NULL
  181868. #define png_doublep_NULL (png_doublep)NULL
  181869. #define png_error_ptr_NULL (png_error_ptr)NULL
  181870. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181871. #define png_free_ptr_NULL (png_free_ptr)NULL
  181872. #define png_infopp_NULL (png_infopp)NULL
  181873. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181874. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181875. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181876. #define png_structp_NULL (png_structp)NULL
  181877. #define png_uint_16p_NULL (png_uint_16p)NULL
  181878. #define png_voidp_NULL (png_voidp)NULL
  181879. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181880. #else
  181881. #define int_p_NULL NULL
  181882. #define png_bytep_NULL NULL
  181883. #define png_bytepp_NULL NULL
  181884. #define png_doublep_NULL NULL
  181885. #define png_error_ptr_NULL NULL
  181886. #define png_flush_ptr_NULL NULL
  181887. #define png_free_ptr_NULL NULL
  181888. #define png_infopp_NULL NULL
  181889. #define png_malloc_ptr_NULL NULL
  181890. #define png_read_status_ptr_NULL NULL
  181891. #define png_rw_ptr_NULL NULL
  181892. #define png_structp_NULL NULL
  181893. #define png_uint_16p_NULL NULL
  181894. #define png_voidp_NULL NULL
  181895. #define png_write_status_ptr_NULL NULL
  181896. #endif
  181897. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181898. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181899. /* Version information for C files, stored in png.c. This had better match
  181900. * the version above.
  181901. */
  181902. #ifdef PNG_USE_GLOBAL_ARRAYS
  181903. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181904. /* need room for 99.99.99beta99z */
  181905. #else
  181906. #define png_libpng_ver png_get_header_ver(NULL)
  181907. #endif
  181908. #ifdef PNG_USE_GLOBAL_ARRAYS
  181909. /* This was removed in version 1.0.5c */
  181910. /* Structures to facilitate easy interlacing. See png.c for more details */
  181911. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181912. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181913. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181914. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181915. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181916. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181917. /* This isn't currently used. If you need it, see png.c for more details.
  181918. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181919. */
  181920. #endif
  181921. #endif /* PNG_NO_EXTERN */
  181922. /* Three color definitions. The order of the red, green, and blue, (and the
  181923. * exact size) is not important, although the size of the fields need to
  181924. * be png_byte or png_uint_16 (as defined below).
  181925. */
  181926. typedef struct png_color_struct
  181927. {
  181928. png_byte red;
  181929. png_byte green;
  181930. png_byte blue;
  181931. } png_color;
  181932. typedef png_color FAR * png_colorp;
  181933. typedef png_color FAR * FAR * png_colorpp;
  181934. typedef struct png_color_16_struct
  181935. {
  181936. png_byte index; /* used for palette files */
  181937. png_uint_16 red; /* for use in red green blue files */
  181938. png_uint_16 green;
  181939. png_uint_16 blue;
  181940. png_uint_16 gray; /* for use in grayscale files */
  181941. } png_color_16;
  181942. typedef png_color_16 FAR * png_color_16p;
  181943. typedef png_color_16 FAR * FAR * png_color_16pp;
  181944. typedef struct png_color_8_struct
  181945. {
  181946. png_byte red; /* for use in red green blue files */
  181947. png_byte green;
  181948. png_byte blue;
  181949. png_byte gray; /* for use in grayscale files */
  181950. png_byte alpha; /* for alpha channel files */
  181951. } png_color_8;
  181952. typedef png_color_8 FAR * png_color_8p;
  181953. typedef png_color_8 FAR * FAR * png_color_8pp;
  181954. /*
  181955. * The following two structures are used for the in-core representation
  181956. * of sPLT chunks.
  181957. */
  181958. typedef struct png_sPLT_entry_struct
  181959. {
  181960. png_uint_16 red;
  181961. png_uint_16 green;
  181962. png_uint_16 blue;
  181963. png_uint_16 alpha;
  181964. png_uint_16 frequency;
  181965. } png_sPLT_entry;
  181966. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181967. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181968. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181969. * occupy the LSB of their respective members, and the MSB of each member
  181970. * is zero-filled. The frequency member always occupies the full 16 bits.
  181971. */
  181972. typedef struct png_sPLT_struct
  181973. {
  181974. png_charp name; /* palette name */
  181975. png_byte depth; /* depth of palette samples */
  181976. png_sPLT_entryp entries; /* palette entries */
  181977. png_int_32 nentries; /* number of palette entries */
  181978. } png_sPLT_t;
  181979. typedef png_sPLT_t FAR * png_sPLT_tp;
  181980. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181981. #ifdef PNG_TEXT_SUPPORTED
  181982. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181983. * and whether that contents is compressed or not. The "key" field
  181984. * points to a regular zero-terminated C string. The "text", "lang", and
  181985. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181986. * However, the * structure returned by png_get_text() will always contain
  181987. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181988. * so they can be safely used in printf() and other string-handling functions.
  181989. */
  181990. typedef struct png_text_struct
  181991. {
  181992. int compression; /* compression value:
  181993. -1: tEXt, none
  181994. 0: zTXt, deflate
  181995. 1: iTXt, none
  181996. 2: iTXt, deflate */
  181997. png_charp key; /* keyword, 1-79 character description of "text" */
  181998. png_charp text; /* comment, may be an empty string (ie "")
  181999. or a NULL pointer */
  182000. png_size_t text_length; /* length of the text string */
  182001. #ifdef PNG_iTXt_SUPPORTED
  182002. png_size_t itxt_length; /* length of the itxt string */
  182003. png_charp lang; /* language code, 0-79 characters
  182004. or a NULL pointer */
  182005. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182006. chars or a NULL pointer */
  182007. #endif
  182008. } png_text;
  182009. typedef png_text FAR * png_textp;
  182010. typedef png_text FAR * FAR * png_textpp;
  182011. #endif
  182012. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182013. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182014. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182015. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182016. #define PNG_TEXT_COMPRESSION_NONE -1
  182017. #define PNG_TEXT_COMPRESSION_zTXt 0
  182018. #define PNG_ITXT_COMPRESSION_NONE 1
  182019. #define PNG_ITXT_COMPRESSION_zTXt 2
  182020. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182021. /* png_time is a way to hold the time in an machine independent way.
  182022. * Two conversions are provided, both from time_t and struct tm. There
  182023. * is no portable way to convert to either of these structures, as far
  182024. * as I know. If you know of a portable way, send it to me. As a side
  182025. * note - PNG has always been Year 2000 compliant!
  182026. */
  182027. typedef struct png_time_struct
  182028. {
  182029. png_uint_16 year; /* full year, as in, 1995 */
  182030. png_byte month; /* month of year, 1 - 12 */
  182031. png_byte day; /* day of month, 1 - 31 */
  182032. png_byte hour; /* hour of day, 0 - 23 */
  182033. png_byte minute; /* minute of hour, 0 - 59 */
  182034. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182035. } png_time;
  182036. typedef png_time FAR * png_timep;
  182037. typedef png_time FAR * FAR * png_timepp;
  182038. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182039. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182040. * no specific support. The idea is that we can use this to queue
  182041. * up private chunks for output even though the library doesn't actually
  182042. * know about their semantics.
  182043. */
  182044. typedef struct png_unknown_chunk_t
  182045. {
  182046. png_byte name[5];
  182047. png_byte *data;
  182048. png_size_t size;
  182049. /* libpng-using applications should NOT directly modify this byte. */
  182050. png_byte location; /* mode of operation at read time */
  182051. }
  182052. png_unknown_chunk;
  182053. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182054. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182055. #endif
  182056. /* png_info is a structure that holds the information in a PNG file so
  182057. * that the application can find out the characteristics of the image.
  182058. * If you are reading the file, this structure will tell you what is
  182059. * in the PNG file. If you are writing the file, fill in the information
  182060. * you want to put into the PNG file, then call png_write_info().
  182061. * The names chosen should be very close to the PNG specification, so
  182062. * consult that document for information about the meaning of each field.
  182063. *
  182064. * With libpng < 0.95, it was only possible to directly set and read the
  182065. * the values in the png_info_struct, which meant that the contents and
  182066. * order of the values had to remain fixed. With libpng 0.95 and later,
  182067. * however, there are now functions that abstract the contents of
  182068. * png_info_struct from the application, so this makes it easier to use
  182069. * libpng with dynamic libraries, and even makes it possible to use
  182070. * libraries that don't have all of the libpng ancillary chunk-handing
  182071. * functionality.
  182072. *
  182073. * In any case, the order of the parameters in png_info_struct should NOT
  182074. * be changed for as long as possible to keep compatibility with applications
  182075. * that use the old direct-access method with png_info_struct.
  182076. *
  182077. * The following members may have allocated storage attached that should be
  182078. * cleaned up before the structure is discarded: palette, trans, text,
  182079. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182080. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182081. * are automatically freed when the info structure is deallocated, if they were
  182082. * allocated internally by libpng. This behavior can be changed by means
  182083. * of the png_data_freer() function.
  182084. *
  182085. * More allocation details: all the chunk-reading functions that
  182086. * change these members go through the corresponding png_set_*
  182087. * functions. A function to clear these members is available: see
  182088. * png_free_data(). The png_set_* functions do not depend on being
  182089. * able to point info structure members to any of the storage they are
  182090. * passed (they make their own copies), EXCEPT that the png_set_text
  182091. * functions use the same storage passed to them in the text_ptr or
  182092. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182093. * functions do not make their own copies.
  182094. */
  182095. typedef struct png_info_struct
  182096. {
  182097. /* the following are necessary for every PNG file */
  182098. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182099. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182100. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182101. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182102. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182103. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182104. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182105. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182106. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182107. /* The following three should have been named *_method not *_type */
  182108. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182109. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182110. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182111. /* The following is informational only on read, and not used on writes. */
  182112. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182113. png_byte pixel_depth; /* number of bits per pixel */
  182114. png_byte spare_byte; /* to align the data, and for future use */
  182115. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182116. /* The rest of the data is optional. If you are reading, check the
  182117. * valid field to see if the information in these are valid. If you
  182118. * are writing, set the valid field to those chunks you want written,
  182119. * and initialize the appropriate fields below.
  182120. */
  182121. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182122. /* The gAMA chunk describes the gamma characteristics of the system
  182123. * on which the image was created, normally in the range [1.0, 2.5].
  182124. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182125. */
  182126. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182127. #endif
  182128. #if defined(PNG_sRGB_SUPPORTED)
  182129. /* GR-P, 0.96a */
  182130. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182131. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182132. #endif
  182133. #if defined(PNG_TEXT_SUPPORTED)
  182134. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182135. * uncompressed, compressed, and optionally compressed forms, respectively.
  182136. * The data in "text" is an array of pointers to uncompressed,
  182137. * null-terminated C strings. Each chunk has a keyword that describes the
  182138. * textual data contained in that chunk. Keywords are not required to be
  182139. * unique, and the text string may be empty. Any number of text chunks may
  182140. * be in an image.
  182141. */
  182142. int num_text; /* number of comments read/to write */
  182143. int max_text; /* current size of text array */
  182144. png_textp text; /* array of comments read/to write */
  182145. #endif /* PNG_TEXT_SUPPORTED */
  182146. #if defined(PNG_tIME_SUPPORTED)
  182147. /* The tIME chunk holds the last time the displayed image data was
  182148. * modified. See the png_time struct for the contents of this struct.
  182149. */
  182150. png_time mod_time;
  182151. #endif
  182152. #if defined(PNG_sBIT_SUPPORTED)
  182153. /* The sBIT chunk specifies the number of significant high-order bits
  182154. * in the pixel data. Values are in the range [1, bit_depth], and are
  182155. * only specified for the channels in the pixel data. The contents of
  182156. * the low-order bits is not specified. Data is valid if
  182157. * (valid & PNG_INFO_sBIT) is non-zero.
  182158. */
  182159. png_color_8 sig_bit; /* significant bits in color channels */
  182160. #endif
  182161. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182162. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182163. /* The tRNS chunk supplies transparency data for paletted images and
  182164. * other image types that don't need a full alpha channel. There are
  182165. * "num_trans" transparency values for a paletted image, stored in the
  182166. * same order as the palette colors, starting from index 0. Values
  182167. * for the data are in the range [0, 255], ranging from fully transparent
  182168. * to fully opaque, respectively. For non-paletted images, there is a
  182169. * single color specified that should be treated as fully transparent.
  182170. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182171. */
  182172. png_bytep trans; /* transparent values for paletted image */
  182173. png_color_16 trans_values; /* transparent color for non-palette image */
  182174. #endif
  182175. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182176. /* The bKGD chunk gives the suggested image background color if the
  182177. * display program does not have its own background color and the image
  182178. * is needs to composited onto a background before display. The colors
  182179. * in "background" are normally in the same color space/depth as the
  182180. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182181. */
  182182. png_color_16 background;
  182183. #endif
  182184. #if defined(PNG_oFFs_SUPPORTED)
  182185. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182186. * and downwards from the top-left corner of the display, page, or other
  182187. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182188. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182189. */
  182190. png_int_32 x_offset; /* x offset on page */
  182191. png_int_32 y_offset; /* y offset on page */
  182192. png_byte offset_unit_type; /* offset units type */
  182193. #endif
  182194. #if defined(PNG_pHYs_SUPPORTED)
  182195. /* The pHYs chunk gives the physical pixel density of the image for
  182196. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182197. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182198. */
  182199. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182200. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182201. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182202. #endif
  182203. #if defined(PNG_hIST_SUPPORTED)
  182204. /* The hIST chunk contains the relative frequency or importance of the
  182205. * various palette entries, so that a viewer can intelligently select a
  182206. * reduced-color palette, if required. Data is an array of "num_palette"
  182207. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182208. * is non-zero.
  182209. */
  182210. png_uint_16p hist;
  182211. #endif
  182212. #ifdef PNG_cHRM_SUPPORTED
  182213. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182214. * on which the PNG was created. This data allows the viewer to do gamut
  182215. * mapping of the input image to ensure that the viewer sees the same
  182216. * colors in the image as the creator. Values are in the range
  182217. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182218. */
  182219. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182220. float x_white;
  182221. float y_white;
  182222. float x_red;
  182223. float y_red;
  182224. float x_green;
  182225. float y_green;
  182226. float x_blue;
  182227. float y_blue;
  182228. #endif
  182229. #endif
  182230. #if defined(PNG_pCAL_SUPPORTED)
  182231. /* The pCAL chunk describes a transformation between the stored pixel
  182232. * values and original physical data values used to create the image.
  182233. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182234. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182235. * (possibly non-linear) transformation function given by "pcal_type"
  182236. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182237. * defines below, and the PNG-Group's PNG extensions document for a
  182238. * complete description of the transformations and how they should be
  182239. * implemented, and for a description of the ASCII parameter strings.
  182240. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182241. */
  182242. png_charp pcal_purpose; /* pCAL chunk description string */
  182243. png_int_32 pcal_X0; /* minimum value */
  182244. png_int_32 pcal_X1; /* maximum value */
  182245. png_charp pcal_units; /* Latin-1 string giving physical units */
  182246. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182247. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182248. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182249. #endif
  182250. /* New members added in libpng-1.0.6 */
  182251. #ifdef PNG_FREE_ME_SUPPORTED
  182252. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182253. #endif
  182254. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182255. /* storage for unknown chunks that the library doesn't recognize. */
  182256. png_unknown_chunkp unknown_chunks;
  182257. png_size_t unknown_chunks_num;
  182258. #endif
  182259. #if defined(PNG_iCCP_SUPPORTED)
  182260. /* iCCP chunk data. */
  182261. png_charp iccp_name; /* profile name */
  182262. png_charp iccp_profile; /* International Color Consortium profile data */
  182263. /* Note to maintainer: should be png_bytep */
  182264. png_uint_32 iccp_proflen; /* ICC profile data length */
  182265. png_byte iccp_compression; /* Always zero */
  182266. #endif
  182267. #if defined(PNG_sPLT_SUPPORTED)
  182268. /* data on sPLT chunks (there may be more than one). */
  182269. png_sPLT_tp splt_palettes;
  182270. png_uint_32 splt_palettes_num;
  182271. #endif
  182272. #if defined(PNG_sCAL_SUPPORTED)
  182273. /* The sCAL chunk describes the actual physical dimensions of the
  182274. * subject matter of the graphic. The chunk contains a unit specification
  182275. * a byte value, and two ASCII strings representing floating-point
  182276. * values. The values are width and height corresponsing to one pixel
  182277. * in the image. This external representation is converted to double
  182278. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182279. */
  182280. png_byte scal_unit; /* unit of physical scale */
  182281. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182282. double scal_pixel_width; /* width of one pixel */
  182283. double scal_pixel_height; /* height of one pixel */
  182284. #endif
  182285. #ifdef PNG_FIXED_POINT_SUPPORTED
  182286. png_charp scal_s_width; /* string containing height */
  182287. png_charp scal_s_height; /* string containing width */
  182288. #endif
  182289. #endif
  182290. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182291. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182292. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182293. png_bytepp row_pointers; /* the image bits */
  182294. #endif
  182295. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182296. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182297. #endif
  182298. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182299. png_fixed_point int_x_white;
  182300. png_fixed_point int_y_white;
  182301. png_fixed_point int_x_red;
  182302. png_fixed_point int_y_red;
  182303. png_fixed_point int_x_green;
  182304. png_fixed_point int_y_green;
  182305. png_fixed_point int_x_blue;
  182306. png_fixed_point int_y_blue;
  182307. #endif
  182308. } png_info;
  182309. typedef png_info FAR * png_infop;
  182310. typedef png_info FAR * FAR * png_infopp;
  182311. /* Maximum positive integer used in PNG is (2^31)-1 */
  182312. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182313. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182314. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182315. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182316. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182317. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182318. #endif
  182319. /* These describe the color_type field in png_info. */
  182320. /* color type masks */
  182321. #define PNG_COLOR_MASK_PALETTE 1
  182322. #define PNG_COLOR_MASK_COLOR 2
  182323. #define PNG_COLOR_MASK_ALPHA 4
  182324. /* color types. Note that not all combinations are legal */
  182325. #define PNG_COLOR_TYPE_GRAY 0
  182326. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182327. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182328. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182329. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182330. /* aliases */
  182331. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182332. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182333. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182334. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182335. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182336. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182337. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182338. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182339. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182340. /* These are for the interlacing type. These values should NOT be changed. */
  182341. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182342. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182343. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182344. /* These are for the oFFs chunk. These values should NOT be changed. */
  182345. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182346. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182347. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182348. /* These are for the pCAL chunk. These values should NOT be changed. */
  182349. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182350. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182351. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182352. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182353. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182354. /* These are for the sCAL chunk. These values should NOT be changed. */
  182355. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182356. #define PNG_SCALE_METER 1 /* meters per pixel */
  182357. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182358. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182359. /* These are for the pHYs chunk. These values should NOT be changed. */
  182360. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182361. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182362. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182363. /* These are for the sRGB chunk. These values should NOT be changed. */
  182364. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182365. #define PNG_sRGB_INTENT_RELATIVE 1
  182366. #define PNG_sRGB_INTENT_SATURATION 2
  182367. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182368. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182369. /* This is for text chunks */
  182370. #define PNG_KEYWORD_MAX_LENGTH 79
  182371. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182372. #define PNG_MAX_PALETTE_LENGTH 256
  182373. /* These determine if an ancillary chunk's data has been successfully read
  182374. * from the PNG header, or if the application has filled in the corresponding
  182375. * data in the info_struct to be written into the output file. The values
  182376. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182377. */
  182378. #define PNG_INFO_gAMA 0x0001
  182379. #define PNG_INFO_sBIT 0x0002
  182380. #define PNG_INFO_cHRM 0x0004
  182381. #define PNG_INFO_PLTE 0x0008
  182382. #define PNG_INFO_tRNS 0x0010
  182383. #define PNG_INFO_bKGD 0x0020
  182384. #define PNG_INFO_hIST 0x0040
  182385. #define PNG_INFO_pHYs 0x0080
  182386. #define PNG_INFO_oFFs 0x0100
  182387. #define PNG_INFO_tIME 0x0200
  182388. #define PNG_INFO_pCAL 0x0400
  182389. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182390. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182391. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182392. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182393. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182394. /* This is used for the transformation routines, as some of them
  182395. * change these values for the row. It also should enable using
  182396. * the routines for other purposes.
  182397. */
  182398. typedef struct png_row_info_struct
  182399. {
  182400. png_uint_32 width; /* width of row */
  182401. png_uint_32 rowbytes; /* number of bytes in row */
  182402. png_byte color_type; /* color type of row */
  182403. png_byte bit_depth; /* bit depth of row */
  182404. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182405. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182406. } png_row_info;
  182407. typedef png_row_info FAR * png_row_infop;
  182408. typedef png_row_info FAR * FAR * png_row_infopp;
  182409. /* These are the function types for the I/O functions and for the functions
  182410. * that allow the user to override the default I/O functions with his or her
  182411. * own. The png_error_ptr type should match that of user-supplied warning
  182412. * and error functions, while the png_rw_ptr type should match that of the
  182413. * user read/write data functions.
  182414. */
  182415. typedef struct png_struct_def png_struct;
  182416. typedef png_struct FAR * png_structp;
  182417. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182418. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182419. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182420. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182421. int));
  182422. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182423. int));
  182424. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182425. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182426. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182427. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182428. png_uint_32, int));
  182429. #endif
  182430. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182431. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182432. defined(PNG_LEGACY_SUPPORTED)
  182433. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182434. png_row_infop, png_bytep));
  182435. #endif
  182436. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182437. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182438. #endif
  182439. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182440. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182441. #endif
  182442. /* Transform masks for the high-level interface */
  182443. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182444. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182445. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182446. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182447. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182448. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182449. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182450. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182451. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182452. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182453. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182454. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182455. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182456. /* Flags for MNG supported features */
  182457. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182458. #define PNG_FLAG_MNG_FILTER_64 0x04
  182459. #define PNG_ALL_MNG_FEATURES 0x05
  182460. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182461. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182462. /* The structure that holds the information to read and write PNG files.
  182463. * The only people who need to care about what is inside of this are the
  182464. * people who will be modifying the library for their own special needs.
  182465. * It should NOT be accessed directly by an application, except to store
  182466. * the jmp_buf.
  182467. */
  182468. struct png_struct_def
  182469. {
  182470. #ifdef PNG_SETJMP_SUPPORTED
  182471. jmp_buf jmpbuf; /* used in png_error */
  182472. #endif
  182473. png_error_ptr error_fn; /* function for printing errors and aborting */
  182474. png_error_ptr warning_fn; /* function for printing warnings */
  182475. png_voidp error_ptr; /* user supplied struct for error functions */
  182476. png_rw_ptr write_data_fn; /* function for writing output data */
  182477. png_rw_ptr read_data_fn; /* function for reading input data */
  182478. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182479. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182480. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182481. #endif
  182482. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182483. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182484. #endif
  182485. /* These were added in libpng-1.0.2 */
  182486. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182487. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182488. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182489. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182490. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182491. png_byte user_transform_channels; /* channels in user transformed pixels */
  182492. #endif
  182493. #endif
  182494. png_uint_32 mode; /* tells us where we are in the PNG file */
  182495. png_uint_32 flags; /* flags indicating various things to libpng */
  182496. png_uint_32 transformations; /* which transformations to perform */
  182497. z_stream zstream; /* pointer to decompression structure (below) */
  182498. png_bytep zbuf; /* buffer for zlib */
  182499. png_size_t zbuf_size; /* size of zbuf */
  182500. int zlib_level; /* holds zlib compression level */
  182501. int zlib_method; /* holds zlib compression method */
  182502. int zlib_window_bits; /* holds zlib compression window bits */
  182503. int zlib_mem_level; /* holds zlib compression memory level */
  182504. int zlib_strategy; /* holds zlib compression strategy */
  182505. png_uint_32 width; /* width of image in pixels */
  182506. png_uint_32 height; /* height of image in pixels */
  182507. png_uint_32 num_rows; /* number of rows in current pass */
  182508. png_uint_32 usr_width; /* width of row at start of write */
  182509. png_uint_32 rowbytes; /* size of row in bytes */
  182510. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182511. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182512. png_uint_32 row_number; /* current row in interlace pass */
  182513. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182514. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182515. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182516. png_bytep up_row; /* buffer to save "up" row when filtering */
  182517. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182518. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182519. png_row_info row_info; /* used for transformation routines */
  182520. png_uint_32 idat_size; /* current IDAT size for read */
  182521. png_uint_32 crc; /* current chunk CRC value */
  182522. png_colorp palette; /* palette from the input file */
  182523. png_uint_16 num_palette; /* number of color entries in palette */
  182524. png_uint_16 num_trans; /* number of transparency values */
  182525. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182526. png_byte compression; /* file compression type (always 0) */
  182527. png_byte filter; /* file filter type (always 0) */
  182528. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182529. png_byte pass; /* current interlace pass (0 - 6) */
  182530. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182531. png_byte color_type; /* color type of file */
  182532. png_byte bit_depth; /* bit depth of file */
  182533. png_byte usr_bit_depth; /* bit depth of users row */
  182534. png_byte pixel_depth; /* number of bits per pixel */
  182535. png_byte channels; /* number of channels in file */
  182536. png_byte usr_channels; /* channels at start of write */
  182537. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182538. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182539. #ifdef PNG_LEGACY_SUPPORTED
  182540. png_byte filler; /* filler byte for pixel expansion */
  182541. #else
  182542. png_uint_16 filler; /* filler bytes for pixel expansion */
  182543. #endif
  182544. #endif
  182545. #if defined(PNG_bKGD_SUPPORTED)
  182546. png_byte background_gamma_type;
  182547. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182548. float background_gamma;
  182549. # endif
  182550. png_color_16 background; /* background color in screen gamma space */
  182551. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182552. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182553. #endif
  182554. #endif /* PNG_bKGD_SUPPORTED */
  182555. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182556. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182557. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182558. png_uint_32 flush_rows; /* number of rows written since last flush */
  182559. #endif
  182560. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182561. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182562. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182563. float gamma; /* file gamma value */
  182564. float screen_gamma; /* screen gamma value (display_exponent) */
  182565. #endif
  182566. #endif
  182567. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182568. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182569. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182570. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182571. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182572. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182573. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182574. #endif
  182575. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182576. png_color_8 sig_bit; /* significant bits in each available channel */
  182577. #endif
  182578. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182579. png_color_8 shift; /* shift for significant bit tranformation */
  182580. #endif
  182581. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182582. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182583. png_bytep trans; /* transparency values for paletted files */
  182584. png_color_16 trans_values; /* transparency values for non-paletted files */
  182585. #endif
  182586. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182587. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182588. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182589. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182590. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182591. png_progressive_end_ptr end_fn; /* called after image is complete */
  182592. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182593. png_bytep save_buffer; /* buffer for previously read data */
  182594. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182595. png_bytep current_buffer; /* buffer for recently used data */
  182596. png_uint_32 push_length; /* size of current input chunk */
  182597. png_uint_32 skip_length; /* bytes to skip in input data */
  182598. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182599. png_size_t save_buffer_max; /* total size of save_buffer */
  182600. png_size_t buffer_size; /* total amount of available input data */
  182601. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182602. int process_mode; /* what push library is currently doing */
  182603. int cur_palette; /* current push library palette index */
  182604. # if defined(PNG_TEXT_SUPPORTED)
  182605. png_size_t current_text_size; /* current size of text input data */
  182606. png_size_t current_text_left; /* how much text left to read in input */
  182607. png_charp current_text; /* current text chunk buffer */
  182608. png_charp current_text_ptr; /* current location in current_text */
  182609. # endif /* PNG_TEXT_SUPPORTED */
  182610. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182611. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182612. /* for the Borland special 64K segment handler */
  182613. png_bytepp offset_table_ptr;
  182614. png_bytep offset_table;
  182615. png_uint_16 offset_table_number;
  182616. png_uint_16 offset_table_count;
  182617. png_uint_16 offset_table_count_free;
  182618. #endif
  182619. #if defined(PNG_READ_DITHER_SUPPORTED)
  182620. png_bytep palette_lookup; /* lookup table for dithering */
  182621. png_bytep dither_index; /* index translation for palette files */
  182622. #endif
  182623. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182624. png_uint_16p hist; /* histogram */
  182625. #endif
  182626. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182627. png_byte heuristic_method; /* heuristic for row filter selection */
  182628. png_byte num_prev_filters; /* number of weights for previous rows */
  182629. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182630. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182631. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182632. png_uint_16p filter_costs; /* relative filter calculation cost */
  182633. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182634. #endif
  182635. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182636. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182637. #endif
  182638. /* New members added in libpng-1.0.6 */
  182639. #ifdef PNG_FREE_ME_SUPPORTED
  182640. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182641. #endif
  182642. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182643. png_voidp user_chunk_ptr;
  182644. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182645. #endif
  182646. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182647. int num_chunk_list;
  182648. png_bytep chunk_list;
  182649. #endif
  182650. /* New members added in libpng-1.0.3 */
  182651. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182652. png_byte rgb_to_gray_status;
  182653. /* These were changed from png_byte in libpng-1.0.6 */
  182654. png_uint_16 rgb_to_gray_red_coeff;
  182655. png_uint_16 rgb_to_gray_green_coeff;
  182656. png_uint_16 rgb_to_gray_blue_coeff;
  182657. #endif
  182658. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182659. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182660. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182661. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182662. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182663. #ifdef PNG_1_0_X
  182664. png_byte mng_features_permitted;
  182665. #else
  182666. png_uint_32 mng_features_permitted;
  182667. #endif /* PNG_1_0_X */
  182668. #endif
  182669. /* New member added in libpng-1.0.7 */
  182670. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182671. png_fixed_point int_gamma;
  182672. #endif
  182673. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182674. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182675. png_byte filter_type;
  182676. #endif
  182677. #if defined(PNG_1_0_X)
  182678. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182679. png_uint_32 row_buf_size;
  182680. #endif
  182681. /* New members added in libpng-1.2.0 */
  182682. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182683. # if !defined(PNG_1_0_X)
  182684. # if defined(PNG_MMX_CODE_SUPPORTED)
  182685. png_byte mmx_bitdepth_threshold;
  182686. png_uint_32 mmx_rowbytes_threshold;
  182687. # endif
  182688. png_uint_32 asm_flags;
  182689. # endif
  182690. #endif
  182691. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182692. #ifdef PNG_USER_MEM_SUPPORTED
  182693. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182694. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182695. png_free_ptr free_fn; /* function for freeing memory */
  182696. #endif
  182697. /* New member added in libpng-1.0.13 and 1.2.0 */
  182698. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182699. #if defined(PNG_READ_DITHER_SUPPORTED)
  182700. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182701. png_bytep dither_sort; /* working sort array */
  182702. png_bytep index_to_palette; /* where the original index currently is */
  182703. /* in the palette */
  182704. png_bytep palette_to_index; /* which original index points to this */
  182705. /* palette color */
  182706. #endif
  182707. /* New members added in libpng-1.0.16 and 1.2.6 */
  182708. png_byte compression_type;
  182709. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182710. png_uint_32 user_width_max;
  182711. png_uint_32 user_height_max;
  182712. #endif
  182713. /* New member added in libpng-1.0.25 and 1.2.17 */
  182714. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182715. /* storage for unknown chunk that the library doesn't recognize. */
  182716. png_unknown_chunk unknown_chunk;
  182717. #endif
  182718. };
  182719. /* This triggers a compiler error in png.c, if png.c and png.h
  182720. * do not agree upon the version number.
  182721. */
  182722. typedef png_structp version_1_2_21;
  182723. typedef png_struct FAR * FAR * png_structpp;
  182724. /* Here are the function definitions most commonly used. This is not
  182725. * the place to find out how to use libpng. See libpng.txt for the
  182726. * full explanation, see example.c for the summary. This just provides
  182727. * a simple one line description of the use of each function.
  182728. */
  182729. /* Returns the version number of the library */
  182730. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182731. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182732. * Handling more than 8 bytes from the beginning of the file is an error.
  182733. */
  182734. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182735. int num_bytes));
  182736. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182737. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182738. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182739. * start > 7 will always fail (ie return non-zero).
  182740. */
  182741. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182742. png_size_t num_to_check));
  182743. /* Simple signature checking function. This is the same as calling
  182744. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182745. */
  182746. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182747. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182748. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182749. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182750. png_error_ptr error_fn, png_error_ptr warn_fn));
  182751. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182752. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182753. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182754. png_error_ptr error_fn, png_error_ptr warn_fn));
  182755. #ifdef PNG_WRITE_SUPPORTED
  182756. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182757. PNGARG((png_structp png_ptr));
  182758. #endif
  182759. #ifdef PNG_WRITE_SUPPORTED
  182760. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182761. PNGARG((png_structp png_ptr, png_uint_32 size));
  182762. #endif
  182763. /* Reset the compression stream */
  182764. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182765. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182766. #ifdef PNG_USER_MEM_SUPPORTED
  182767. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182768. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182769. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182770. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182771. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182772. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182773. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182774. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182775. #endif
  182776. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182777. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182778. png_bytep chunk_name, png_bytep data, png_size_t length));
  182779. /* Write the start of a PNG chunk - length and chunk name. */
  182780. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182781. png_bytep chunk_name, png_uint_32 length));
  182782. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182783. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182784. png_bytep data, png_size_t length));
  182785. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182786. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182787. /* Allocate and initialize the info structure */
  182788. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182789. PNGARG((png_structp png_ptr));
  182790. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182791. /* Initialize the info structure (old interface - DEPRECATED) */
  182792. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182793. #undef png_info_init
  182794. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182795. png_sizeof(png_info));
  182796. #endif
  182797. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182798. png_size_t png_info_struct_size));
  182799. /* Writes all the PNG information before the image. */
  182800. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182801. png_infop info_ptr));
  182802. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182803. png_infop info_ptr));
  182804. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182805. /* read the information before the actual image data. */
  182806. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182807. png_infop info_ptr));
  182808. #endif
  182809. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182810. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182811. PNGARG((png_structp png_ptr, png_timep ptime));
  182812. #endif
  182813. #if !defined(_WIN32_WCE)
  182814. /* "time.h" functions are not supported on WindowsCE */
  182815. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182816. /* convert from a struct tm to png_time */
  182817. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182818. struct tm FAR * ttime));
  182819. /* convert from time_t to png_time. Uses gmtime() */
  182820. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182821. time_t ttime));
  182822. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182823. #endif /* _WIN32_WCE */
  182824. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182825. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182826. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182827. #if !defined(PNG_1_0_X)
  182828. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182829. png_ptr));
  182830. #endif
  182831. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182832. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182833. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182834. /* Deprecated */
  182835. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182836. #endif
  182837. #endif
  182838. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182839. /* Use blue, green, red order for pixels. */
  182840. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182841. #endif
  182842. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182843. /* Expand the grayscale to 24-bit RGB if necessary. */
  182844. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182845. #endif
  182846. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182847. /* Reduce RGB to grayscale. */
  182848. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182849. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182850. int error_action, double red, double green ));
  182851. #endif
  182852. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182853. int error_action, png_fixed_point red, png_fixed_point green ));
  182854. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182855. png_ptr));
  182856. #endif
  182857. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182858. png_colorp palette));
  182859. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182860. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182861. #endif
  182862. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182863. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182864. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182865. #endif
  182866. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182867. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182868. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182869. #endif
  182870. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182871. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182872. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182873. png_uint_32 filler, int flags));
  182874. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182875. #define PNG_FILLER_BEFORE 0
  182876. #define PNG_FILLER_AFTER 1
  182877. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182878. #if !defined(PNG_1_0_X)
  182879. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182880. png_uint_32 filler, int flags));
  182881. #endif
  182882. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182883. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182884. /* Swap bytes in 16-bit depth files. */
  182885. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182886. #endif
  182887. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182888. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182889. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182890. #endif
  182891. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182892. /* Swap packing order of pixels in bytes. */
  182893. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182894. #endif
  182895. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182896. /* Converts files to legal bit depths. */
  182897. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182898. png_color_8p true_bits));
  182899. #endif
  182900. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182901. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182902. /* Have the code handle the interlacing. Returns the number of passes. */
  182903. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182904. #endif
  182905. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182906. /* Invert monochrome files */
  182907. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182908. #endif
  182909. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182910. /* Handle alpha and tRNS by replacing with a background color. */
  182911. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182912. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182913. png_color_16p background_color, int background_gamma_code,
  182914. int need_expand, double background_gamma));
  182915. #endif
  182916. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182917. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182918. #define PNG_BACKGROUND_GAMMA_FILE 2
  182919. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182920. #endif
  182921. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182922. /* strip the second byte of information from a 16-bit depth file. */
  182923. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182924. #endif
  182925. #if defined(PNG_READ_DITHER_SUPPORTED)
  182926. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182927. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182928. png_colorp palette, int num_palette, int maximum_colors,
  182929. png_uint_16p histogram, int full_dither));
  182930. #endif
  182931. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182932. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182933. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182934. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182935. double screen_gamma, double default_file_gamma));
  182936. #endif
  182937. #endif
  182938. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182939. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182940. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182941. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182942. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182943. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182944. int empty_plte_permitted));
  182945. #endif
  182946. #endif
  182947. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182948. /* Set how many lines between output flushes - 0 for no flushing */
  182949. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182950. /* Flush the current PNG output buffer */
  182951. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182952. #endif
  182953. /* optional update palette with requested transformations */
  182954. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182955. /* optional call to update the users info structure */
  182956. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182957. png_infop info_ptr));
  182958. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182959. /* read one or more rows of image data. */
  182960. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182961. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182962. #endif
  182963. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182964. /* read a row of data. */
  182965. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182966. png_bytep row,
  182967. png_bytep display_row));
  182968. #endif
  182969. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182970. /* read the whole image into memory at once. */
  182971. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182972. png_bytepp image));
  182973. #endif
  182974. /* write a row of image data */
  182975. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182976. png_bytep row));
  182977. /* write a few rows of image data */
  182978. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182979. png_bytepp row, png_uint_32 num_rows));
  182980. /* write the image data */
  182981. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182982. png_bytepp image));
  182983. /* writes the end of the PNG file. */
  182984. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182985. png_infop info_ptr));
  182986. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182987. /* read the end of the PNG file. */
  182988. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182989. png_infop info_ptr));
  182990. #endif
  182991. /* free any memory associated with the png_info_struct */
  182992. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182993. png_infopp info_ptr_ptr));
  182994. /* free any memory associated with the png_struct and the png_info_structs */
  182995. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182996. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182997. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182998. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182999. png_infop end_info_ptr));
  183000. /* free any memory associated with the png_struct and the png_info_structs */
  183001. extern PNG_EXPORT(void,png_destroy_write_struct)
  183002. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183003. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183004. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183005. /* set the libpng method of handling chunk CRC errors */
  183006. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183007. int crit_action, int ancil_action));
  183008. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183009. * ancillary and critical chunks, and whether to use the data contained
  183010. * therein. Note that it is impossible to "discard" data in a critical
  183011. * chunk. For versions prior to 0.90, the action was always error/quit,
  183012. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183013. * chunks is warn/discard. These values should NOT be changed.
  183014. *
  183015. * value action:critical action:ancillary
  183016. */
  183017. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183018. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183019. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183020. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183021. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183022. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183023. /* These functions give the user control over the scan-line filtering in
  183024. * libpng and the compression methods used by zlib. These functions are
  183025. * mainly useful for testing, as the defaults should work with most users.
  183026. * Those users who are tight on memory or want faster performance at the
  183027. * expense of compression can modify them. See the compression library
  183028. * header file (zlib.h) for an explination of the compression functions.
  183029. */
  183030. /* set the filtering method(s) used by libpng. Currently, the only valid
  183031. * value for "method" is 0.
  183032. */
  183033. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183034. int filters));
  183035. /* Flags for png_set_filter() to say which filters to use. The flags
  183036. * are chosen so that they don't conflict with real filter types
  183037. * below, in case they are supplied instead of the #defined constants.
  183038. * These values should NOT be changed.
  183039. */
  183040. #define PNG_NO_FILTERS 0x00
  183041. #define PNG_FILTER_NONE 0x08
  183042. #define PNG_FILTER_SUB 0x10
  183043. #define PNG_FILTER_UP 0x20
  183044. #define PNG_FILTER_AVG 0x40
  183045. #define PNG_FILTER_PAETH 0x80
  183046. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183047. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183048. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183049. * These defines should NOT be changed.
  183050. */
  183051. #define PNG_FILTER_VALUE_NONE 0
  183052. #define PNG_FILTER_VALUE_SUB 1
  183053. #define PNG_FILTER_VALUE_UP 2
  183054. #define PNG_FILTER_VALUE_AVG 3
  183055. #define PNG_FILTER_VALUE_PAETH 4
  183056. #define PNG_FILTER_VALUE_LAST 5
  183057. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183058. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183059. * defines, either the default (minimum-sum-of-absolute-differences), or
  183060. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183061. *
  183062. * Weights are factors >= 1.0, indicating how important it is to keep the
  183063. * filter type consistent between rows. Larger numbers mean the current
  183064. * filter is that many times as likely to be the same as the "num_weights"
  183065. * previous filters. This is cumulative for each previous row with a weight.
  183066. * There needs to be "num_weights" values in "filter_weights", or it can be
  183067. * NULL if the weights aren't being specified. Weights have no influence on
  183068. * the selection of the first row filter. Well chosen weights can (in theory)
  183069. * improve the compression for a given image.
  183070. *
  183071. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183072. * filter type. Higher costs indicate more decoding expense, and are
  183073. * therefore less likely to be selected over a filter with lower computational
  183074. * costs. There needs to be a value in "filter_costs" for each valid filter
  183075. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183076. * setting the costs. Costs try to improve the speed of decompression without
  183077. * unduly increasing the compressed image size.
  183078. *
  183079. * A negative weight or cost indicates the default value is to be used, and
  183080. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183081. * The default values for both weights and costs are currently 1.0, but may
  183082. * change if good general weighting/cost heuristics can be found. If both
  183083. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183084. * to the UNWEIGHTED method, but with added encoding time/computation.
  183085. */
  183086. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183087. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183088. int heuristic_method, int num_weights, png_doublep filter_weights,
  183089. png_doublep filter_costs));
  183090. #endif
  183091. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183092. /* Heuristic used for row filter selection. These defines should NOT be
  183093. * changed.
  183094. */
  183095. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183096. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183097. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183098. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183099. /* Set the library compression level. Currently, valid values range from
  183100. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183101. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183102. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183103. * for PNG images, and do considerably fewer caclulations. In the future,
  183104. * these values may not correspond directly to the zlib compression levels.
  183105. */
  183106. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183107. int level));
  183108. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183109. PNGARG((png_structp png_ptr, int mem_level));
  183110. extern PNG_EXPORT(void,png_set_compression_strategy)
  183111. PNGARG((png_structp png_ptr, int strategy));
  183112. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183113. PNGARG((png_structp png_ptr, int window_bits));
  183114. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183115. int method));
  183116. /* These next functions are called for input/output, memory, and error
  183117. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183118. * and call standard C I/O routines such as fread(), fwrite(), and
  183119. * fprintf(). These functions can be made to use other I/O routines
  183120. * at run time for those applications that need to handle I/O in a
  183121. * different manner by calling png_set_???_fn(). See libpng.txt for
  183122. * more information.
  183123. */
  183124. #if !defined(PNG_NO_STDIO)
  183125. /* Initialize the input/output for the PNG file to the default functions. */
  183126. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183127. #endif
  183128. /* Replace the (error and abort), and warning functions with user
  183129. * supplied functions. If no messages are to be printed you must still
  183130. * write and use replacement functions. The replacement error_fn should
  183131. * still do a longjmp to the last setjmp location if you are using this
  183132. * method of error handling. If error_fn or warning_fn is NULL, the
  183133. * default function will be used.
  183134. */
  183135. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183136. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183137. /* Return the user pointer associated with the error functions */
  183138. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183139. /* Replace the default data output functions with a user supplied one(s).
  183140. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183141. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183142. * output_flush_fn will be ignored (and thus can be NULL).
  183143. */
  183144. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183145. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183146. /* Replace the default data input function with a user supplied one. */
  183147. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183148. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183149. /* Return the user pointer associated with the I/O functions */
  183150. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183151. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183152. png_read_status_ptr read_row_fn));
  183153. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183154. png_write_status_ptr write_row_fn));
  183155. #ifdef PNG_USER_MEM_SUPPORTED
  183156. /* Replace the default memory allocation functions with user supplied one(s). */
  183157. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183158. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183159. /* Return the user pointer associated with the memory functions */
  183160. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183161. #endif
  183162. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183163. defined(PNG_LEGACY_SUPPORTED)
  183164. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183165. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183166. #endif
  183167. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183168. defined(PNG_LEGACY_SUPPORTED)
  183169. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183170. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183171. #endif
  183172. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183173. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183174. defined(PNG_LEGACY_SUPPORTED)
  183175. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183176. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183177. int user_transform_channels));
  183178. /* Return the user pointer associated with the user transform functions */
  183179. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183180. PNGARG((png_structp png_ptr));
  183181. #endif
  183182. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183183. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183184. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183185. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183186. png_ptr));
  183187. #endif
  183188. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183189. /* Sets the function callbacks for the push reader, and a pointer to a
  183190. * user-defined structure available to the callback functions.
  183191. */
  183192. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183193. png_voidp progressive_ptr,
  183194. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183195. png_progressive_end_ptr end_fn));
  183196. /* returns the user pointer associated with the push read functions */
  183197. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183198. PNGARG((png_structp png_ptr));
  183199. /* function to be called when data becomes available */
  183200. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183201. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183202. /* function that combines rows. Not very much different than the
  183203. * png_combine_row() call. Is this even used?????
  183204. */
  183205. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183206. png_bytep old_row, png_bytep new_row));
  183207. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183208. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183209. png_uint_32 size));
  183210. #if defined(PNG_1_0_X)
  183211. # define png_malloc_warn png_malloc
  183212. #else
  183213. /* Added at libpng version 1.2.4 */
  183214. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183215. png_uint_32 size));
  183216. #endif
  183217. /* frees a pointer allocated by png_malloc() */
  183218. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183219. #if defined(PNG_1_0_X)
  183220. /* Function to allocate memory for zlib. */
  183221. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183222. uInt size));
  183223. /* Function to free memory for zlib */
  183224. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183225. #endif
  183226. /* Free data that was allocated internally */
  183227. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183228. png_infop info_ptr, png_uint_32 free_me, int num));
  183229. #ifdef PNG_FREE_ME_SUPPORTED
  183230. /* Reassign responsibility for freeing existing data, whether allocated
  183231. * by libpng or by the application */
  183232. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183233. png_infop info_ptr, int freer, png_uint_32 mask));
  183234. #endif
  183235. /* assignments for png_data_freer */
  183236. #define PNG_DESTROY_WILL_FREE_DATA 1
  183237. #define PNG_SET_WILL_FREE_DATA 1
  183238. #define PNG_USER_WILL_FREE_DATA 2
  183239. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183240. #define PNG_FREE_HIST 0x0008
  183241. #define PNG_FREE_ICCP 0x0010
  183242. #define PNG_FREE_SPLT 0x0020
  183243. #define PNG_FREE_ROWS 0x0040
  183244. #define PNG_FREE_PCAL 0x0080
  183245. #define PNG_FREE_SCAL 0x0100
  183246. #define PNG_FREE_UNKN 0x0200
  183247. #define PNG_FREE_LIST 0x0400
  183248. #define PNG_FREE_PLTE 0x1000
  183249. #define PNG_FREE_TRNS 0x2000
  183250. #define PNG_FREE_TEXT 0x4000
  183251. #define PNG_FREE_ALL 0x7fff
  183252. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183253. #ifdef PNG_USER_MEM_SUPPORTED
  183254. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183255. png_uint_32 size));
  183256. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183257. png_voidp ptr));
  183258. #endif
  183259. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183260. png_voidp s1, png_voidp s2, png_uint_32 size));
  183261. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183262. png_voidp s1, int value, png_uint_32 size));
  183263. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183264. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183265. int check));
  183266. #endif /* USE_FAR_KEYWORD */
  183267. #ifndef PNG_NO_ERROR_TEXT
  183268. /* Fatal error in PNG image of libpng - can't continue */
  183269. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183270. png_const_charp error_message));
  183271. /* The same, but the chunk name is prepended to the error string. */
  183272. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183273. png_const_charp error_message));
  183274. #else
  183275. /* Fatal error in PNG image of libpng - can't continue */
  183276. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183277. #endif
  183278. #ifndef PNG_NO_WARNINGS
  183279. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183280. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183281. png_const_charp warning_message));
  183282. #ifdef PNG_READ_SUPPORTED
  183283. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183284. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183285. png_const_charp warning_message));
  183286. #endif /* PNG_READ_SUPPORTED */
  183287. #endif /* PNG_NO_WARNINGS */
  183288. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183289. * Similarly, the png_get_<chunk> calls are used to read values from the
  183290. * png_info_struct, either storing the parameters in the passed variables, or
  183291. * setting pointers into the png_info_struct where the data is stored. The
  183292. * png_get_<chunk> functions return a non-zero value if the data was available
  183293. * in info_ptr, or return zero and do not change any of the parameters if the
  183294. * data was not available.
  183295. *
  183296. * These functions should be used instead of directly accessing png_info
  183297. * to avoid problems with future changes in the size and internal layout of
  183298. * png_info_struct.
  183299. */
  183300. /* Returns "flag" if chunk data is valid in info_ptr. */
  183301. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183302. png_infop info_ptr, png_uint_32 flag));
  183303. /* Returns number of bytes needed to hold a transformed row. */
  183304. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183305. png_infop info_ptr));
  183306. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183307. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183308. returned from png_read_png(). */
  183309. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183310. png_infop info_ptr));
  183311. /* Set row_pointers, which is an array of pointers to scanlines for use
  183312. by png_write_png(). */
  183313. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183314. png_infop info_ptr, png_bytepp row_pointers));
  183315. #endif
  183316. /* Returns number of color channels in image. */
  183317. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183318. png_infop info_ptr));
  183319. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183320. /* Returns image width in pixels. */
  183321. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183322. png_ptr, png_infop info_ptr));
  183323. /* Returns image height in pixels. */
  183324. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183325. png_ptr, png_infop info_ptr));
  183326. /* Returns image bit_depth. */
  183327. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183328. png_ptr, png_infop info_ptr));
  183329. /* Returns image color_type. */
  183330. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183331. png_ptr, png_infop info_ptr));
  183332. /* Returns image filter_type. */
  183333. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183334. png_ptr, png_infop info_ptr));
  183335. /* Returns image interlace_type. */
  183336. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183337. png_ptr, png_infop info_ptr));
  183338. /* Returns image compression_type. */
  183339. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183340. png_ptr, png_infop info_ptr));
  183341. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183342. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183343. png_ptr, png_infop info_ptr));
  183344. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183345. png_ptr, png_infop info_ptr));
  183346. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183347. png_ptr, png_infop info_ptr));
  183348. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183349. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183350. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183351. png_ptr, png_infop info_ptr));
  183352. #endif
  183353. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183354. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183355. png_ptr, png_infop info_ptr));
  183356. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183357. png_ptr, png_infop info_ptr));
  183358. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183359. png_ptr, png_infop info_ptr));
  183360. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183361. png_ptr, png_infop info_ptr));
  183362. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183363. /* Returns pointer to signature string read from PNG header */
  183364. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183365. png_infop info_ptr));
  183366. #if defined(PNG_bKGD_SUPPORTED)
  183367. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183368. png_infop info_ptr, png_color_16p *background));
  183369. #endif
  183370. #if defined(PNG_bKGD_SUPPORTED)
  183371. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183372. png_infop info_ptr, png_color_16p background));
  183373. #endif
  183374. #if defined(PNG_cHRM_SUPPORTED)
  183375. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183376. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183377. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183378. double *red_y, double *green_x, double *green_y, double *blue_x,
  183379. double *blue_y));
  183380. #endif
  183381. #ifdef PNG_FIXED_POINT_SUPPORTED
  183382. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183383. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183384. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183385. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183386. *int_blue_x, png_fixed_point *int_blue_y));
  183387. #endif
  183388. #endif
  183389. #if defined(PNG_cHRM_SUPPORTED)
  183390. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183391. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183392. png_infop info_ptr, double white_x, double white_y, double red_x,
  183393. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183394. #endif
  183395. #ifdef PNG_FIXED_POINT_SUPPORTED
  183396. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183397. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183398. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183399. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183400. png_fixed_point int_blue_y));
  183401. #endif
  183402. #endif
  183403. #if defined(PNG_gAMA_SUPPORTED)
  183404. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183405. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183406. png_infop info_ptr, double *file_gamma));
  183407. #endif
  183408. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183409. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183410. #endif
  183411. #if defined(PNG_gAMA_SUPPORTED)
  183412. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183413. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183414. png_infop info_ptr, double file_gamma));
  183415. #endif
  183416. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183417. png_infop info_ptr, png_fixed_point int_file_gamma));
  183418. #endif
  183419. #if defined(PNG_hIST_SUPPORTED)
  183420. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183421. png_infop info_ptr, png_uint_16p *hist));
  183422. #endif
  183423. #if defined(PNG_hIST_SUPPORTED)
  183424. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183425. png_infop info_ptr, png_uint_16p hist));
  183426. #endif
  183427. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183428. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183429. int *bit_depth, int *color_type, int *interlace_method,
  183430. int *compression_method, int *filter_method));
  183431. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183432. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183433. int color_type, int interlace_method, int compression_method,
  183434. int filter_method));
  183435. #if defined(PNG_oFFs_SUPPORTED)
  183436. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183437. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183438. int *unit_type));
  183439. #endif
  183440. #if defined(PNG_oFFs_SUPPORTED)
  183441. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183442. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183443. int unit_type));
  183444. #endif
  183445. #if defined(PNG_pCAL_SUPPORTED)
  183446. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183447. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183448. int *type, int *nparams, png_charp *units, png_charpp *params));
  183449. #endif
  183450. #if defined(PNG_pCAL_SUPPORTED)
  183451. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183452. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183453. int type, int nparams, png_charp units, png_charpp params));
  183454. #endif
  183455. #if defined(PNG_pHYs_SUPPORTED)
  183456. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183457. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183458. #endif
  183459. #if defined(PNG_pHYs_SUPPORTED)
  183460. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183461. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183462. #endif
  183463. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183464. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183465. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183466. png_infop info_ptr, png_colorp palette, int num_palette));
  183467. #if defined(PNG_sBIT_SUPPORTED)
  183468. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183469. png_infop info_ptr, png_color_8p *sig_bit));
  183470. #endif
  183471. #if defined(PNG_sBIT_SUPPORTED)
  183472. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183473. png_infop info_ptr, png_color_8p sig_bit));
  183474. #endif
  183475. #if defined(PNG_sRGB_SUPPORTED)
  183476. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183477. png_infop info_ptr, int *intent));
  183478. #endif
  183479. #if defined(PNG_sRGB_SUPPORTED)
  183480. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183481. png_infop info_ptr, int intent));
  183482. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183483. png_infop info_ptr, int intent));
  183484. #endif
  183485. #if defined(PNG_iCCP_SUPPORTED)
  183486. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183487. png_infop info_ptr, png_charpp name, int *compression_type,
  183488. png_charpp profile, png_uint_32 *proflen));
  183489. /* Note to maintainer: profile should be png_bytepp */
  183490. #endif
  183491. #if defined(PNG_iCCP_SUPPORTED)
  183492. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183493. png_infop info_ptr, png_charp name, int compression_type,
  183494. png_charp profile, png_uint_32 proflen));
  183495. /* Note to maintainer: profile should be png_bytep */
  183496. #endif
  183497. #if defined(PNG_sPLT_SUPPORTED)
  183498. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183499. png_infop info_ptr, png_sPLT_tpp entries));
  183500. #endif
  183501. #if defined(PNG_sPLT_SUPPORTED)
  183502. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183503. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183504. #endif
  183505. #if defined(PNG_TEXT_SUPPORTED)
  183506. /* png_get_text also returns the number of text chunks in *num_text */
  183507. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183508. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183509. #endif
  183510. /*
  183511. * Note while png_set_text() will accept a structure whose text,
  183512. * language, and translated keywords are NULL pointers, the structure
  183513. * returned by png_get_text will always contain regular
  183514. * zero-terminated C strings. They might be empty strings but
  183515. * they will never be NULL pointers.
  183516. */
  183517. #if defined(PNG_TEXT_SUPPORTED)
  183518. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183519. png_infop info_ptr, png_textp text_ptr, int num_text));
  183520. #endif
  183521. #if defined(PNG_tIME_SUPPORTED)
  183522. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183523. png_infop info_ptr, png_timep *mod_time));
  183524. #endif
  183525. #if defined(PNG_tIME_SUPPORTED)
  183526. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183527. png_infop info_ptr, png_timep mod_time));
  183528. #endif
  183529. #if defined(PNG_tRNS_SUPPORTED)
  183530. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183531. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183532. png_color_16p *trans_values));
  183533. #endif
  183534. #if defined(PNG_tRNS_SUPPORTED)
  183535. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183536. png_infop info_ptr, png_bytep trans, int num_trans,
  183537. png_color_16p trans_values));
  183538. #endif
  183539. #if defined(PNG_tRNS_SUPPORTED)
  183540. #endif
  183541. #if defined(PNG_sCAL_SUPPORTED)
  183542. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183543. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183544. png_infop info_ptr, int *unit, double *width, double *height));
  183545. #else
  183546. #ifdef PNG_FIXED_POINT_SUPPORTED
  183547. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183548. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183549. #endif
  183550. #endif
  183551. #endif /* PNG_sCAL_SUPPORTED */
  183552. #if defined(PNG_sCAL_SUPPORTED)
  183553. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183554. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183555. png_infop info_ptr, int unit, double width, double height));
  183556. #else
  183557. #ifdef PNG_FIXED_POINT_SUPPORTED
  183558. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183559. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183560. #endif
  183561. #endif
  183562. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183563. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183564. /* provide a list of chunks and how they are to be handled, if the built-in
  183565. handling or default unknown chunk handling is not desired. Any chunks not
  183566. listed will be handled in the default manner. The IHDR and IEND chunks
  183567. must not be listed.
  183568. keep = 0: follow default behaviour
  183569. = 1: do not keep
  183570. = 2: keep only if safe-to-copy
  183571. = 3: keep even if unsafe-to-copy
  183572. */
  183573. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183574. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183575. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183576. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183577. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183578. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183579. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183580. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183581. #endif
  183582. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183583. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183584. chunk_name));
  183585. #endif
  183586. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183587. If you need to turn it off for a chunk that your application has freed,
  183588. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183589. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183590. png_infop info_ptr, int mask));
  183591. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183592. /* The "params" pointer is currently not used and is for future expansion. */
  183593. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183594. png_infop info_ptr,
  183595. int transforms,
  183596. png_voidp params));
  183597. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183598. png_infop info_ptr,
  183599. int transforms,
  183600. png_voidp params));
  183601. #endif
  183602. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183603. * numbers for PNG_DEBUG mean more debugging information. This has
  183604. * only been added since version 0.95 so it is not implemented throughout
  183605. * libpng yet, but more support will be added as needed.
  183606. */
  183607. #ifdef PNG_DEBUG
  183608. #if (PNG_DEBUG > 0)
  183609. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183610. #include <crtdbg.h>
  183611. #if (PNG_DEBUG > 1)
  183612. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183613. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183614. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183615. #endif
  183616. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183617. #ifndef PNG_DEBUG_FILE
  183618. #define PNG_DEBUG_FILE stderr
  183619. #endif /* PNG_DEBUG_FILE */
  183620. #if (PNG_DEBUG > 1)
  183621. #define png_debug(l,m) \
  183622. { \
  183623. int num_tabs=l; \
  183624. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183625. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183626. }
  183627. #define png_debug1(l,m,p1) \
  183628. { \
  183629. int num_tabs=l; \
  183630. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183631. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183632. }
  183633. #define png_debug2(l,m,p1,p2) \
  183634. { \
  183635. int num_tabs=l; \
  183636. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183637. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183638. }
  183639. #endif /* (PNG_DEBUG > 1) */
  183640. #endif /* _MSC_VER */
  183641. #endif /* (PNG_DEBUG > 0) */
  183642. #endif /* PNG_DEBUG */
  183643. #ifndef png_debug
  183644. #define png_debug(l, m)
  183645. #endif
  183646. #ifndef png_debug1
  183647. #define png_debug1(l, m, p1)
  183648. #endif
  183649. #ifndef png_debug2
  183650. #define png_debug2(l, m, p1, p2)
  183651. #endif
  183652. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183653. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183654. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183655. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183656. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183657. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183658. png_ptr, png_uint_32 mng_features_permitted));
  183659. #endif
  183660. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183661. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183662. #define PNG_HANDLE_CHUNK_NEVER 1
  183663. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183664. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183665. /* Added to version 1.2.0 */
  183666. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183667. #if defined(PNG_MMX_CODE_SUPPORTED)
  183668. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183669. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183670. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183671. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183672. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183673. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183674. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183675. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183676. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183677. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183678. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183679. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183680. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183681. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183682. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183683. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183684. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183685. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183686. | PNG_MMX_READ_FLAGS \
  183687. | PNG_MMX_WRITE_FLAGS )
  183688. #define PNG_SELECT_READ 1
  183689. #define PNG_SELECT_WRITE 2
  183690. #endif /* PNG_MMX_CODE_SUPPORTED */
  183691. #if !defined(PNG_1_0_X)
  183692. /* pngget.c */
  183693. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183694. PNGARG((int flag_select, int *compilerID));
  183695. /* pngget.c */
  183696. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183697. PNGARG((int flag_select));
  183698. /* pngget.c */
  183699. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183700. PNGARG((png_structp png_ptr));
  183701. /* pngget.c */
  183702. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183703. PNGARG((png_structp png_ptr));
  183704. /* pngget.c */
  183705. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183706. PNGARG((png_structp png_ptr));
  183707. /* pngset.c */
  183708. extern PNG_EXPORT(void,png_set_asm_flags)
  183709. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183710. /* pngset.c */
  183711. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183712. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183713. png_uint_32 mmx_rowbytes_threshold));
  183714. #endif /* PNG_1_0_X */
  183715. #if !defined(PNG_1_0_X)
  183716. /* png.c, pnggccrd.c, or pngvcrd.c */
  183717. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183718. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183719. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183720. * messages before passing them to the error or warning handler. */
  183721. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183722. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183723. png_ptr, png_uint_32 strip_mode));
  183724. #endif
  183725. #endif /* PNG_1_0_X */
  183726. /* Added at libpng-1.2.6 */
  183727. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183728. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183729. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183730. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183731. png_ptr));
  183732. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183733. png_ptr));
  183734. #endif
  183735. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183736. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183737. /* With these routines we avoid an integer divide, which will be slower on
  183738. * most machines. However, it does take more operations than the corresponding
  183739. * divide method, so it may be slower on a few RISC systems. There are two
  183740. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183741. *
  183742. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183743. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183744. * standard method.
  183745. *
  183746. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183747. */
  183748. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183749. # define png_composite(composite, fg, alpha, bg) \
  183750. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183751. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183752. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183753. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183754. # define png_composite_16(composite, fg, alpha, bg) \
  183755. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183756. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183757. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183758. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183759. #else /* standard method using integer division */
  183760. # define png_composite(composite, fg, alpha, bg) \
  183761. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183762. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183763. (png_uint_16)127) / 255)
  183764. # define png_composite_16(composite, fg, alpha, bg) \
  183765. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183766. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183767. (png_uint_32)32767) / (png_uint_32)65535L)
  183768. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183769. /* Inline macros to do direct reads of bytes from the input buffer. These
  183770. * require that you are using an architecture that uses PNG byte ordering
  183771. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183772. * in big-endian mode and 680x0 are the only ones that will support this.
  183773. * The x86 line of processors definitely do not. The png_get_int_32()
  183774. * routine also assumes we are using two's complement format for negative
  183775. * values, which is almost certainly true.
  183776. */
  183777. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183778. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183779. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183780. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183781. #else
  183782. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183783. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183784. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183785. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183786. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183787. PNGARG((png_structp png_ptr, png_bytep buf));
  183788. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183789. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183790. */
  183791. extern PNG_EXPORT(void,png_save_uint_32)
  183792. PNGARG((png_bytep buf, png_uint_32 i));
  183793. extern PNG_EXPORT(void,png_save_int_32)
  183794. PNGARG((png_bytep buf, png_int_32 i));
  183795. /* Place a 16-bit number into a buffer in PNG byte order.
  183796. * The parameter is declared unsigned int, not png_uint_16,
  183797. * just to avoid potential problems on pre-ANSI C compilers.
  183798. */
  183799. extern PNG_EXPORT(void,png_save_uint_16)
  183800. PNGARG((png_bytep buf, unsigned int i));
  183801. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183802. /* ************************************************************************* */
  183803. /* These next functions are used internally in the code. They generally
  183804. * shouldn't be used unless you are writing code to add or replace some
  183805. * functionality in libpng. More information about most functions can
  183806. * be found in the files where the functions are located.
  183807. */
  183808. /* Various modes of operation, that are visible to applications because
  183809. * they are used for unknown chunk location.
  183810. */
  183811. #define PNG_HAVE_IHDR 0x01
  183812. #define PNG_HAVE_PLTE 0x02
  183813. #define PNG_HAVE_IDAT 0x04
  183814. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183815. #define PNG_HAVE_IEND 0x10
  183816. #if defined(PNG_INTERNAL)
  183817. /* More modes of operation. Note that after an init, mode is set to
  183818. * zero automatically when the structure is created.
  183819. */
  183820. #define PNG_HAVE_gAMA 0x20
  183821. #define PNG_HAVE_cHRM 0x40
  183822. #define PNG_HAVE_sRGB 0x80
  183823. #define PNG_HAVE_CHUNK_HEADER 0x100
  183824. #define PNG_WROTE_tIME 0x200
  183825. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183826. #define PNG_BACKGROUND_IS_GRAY 0x800
  183827. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183828. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183829. /* flags for the transformations the PNG library does on the image data */
  183830. #define PNG_BGR 0x0001
  183831. #define PNG_INTERLACE 0x0002
  183832. #define PNG_PACK 0x0004
  183833. #define PNG_SHIFT 0x0008
  183834. #define PNG_SWAP_BYTES 0x0010
  183835. #define PNG_INVERT_MONO 0x0020
  183836. #define PNG_DITHER 0x0040
  183837. #define PNG_BACKGROUND 0x0080
  183838. #define PNG_BACKGROUND_EXPAND 0x0100
  183839. /* 0x0200 unused */
  183840. #define PNG_16_TO_8 0x0400
  183841. #define PNG_RGBA 0x0800
  183842. #define PNG_EXPAND 0x1000
  183843. #define PNG_GAMMA 0x2000
  183844. #define PNG_GRAY_TO_RGB 0x4000
  183845. #define PNG_FILLER 0x8000L
  183846. #define PNG_PACKSWAP 0x10000L
  183847. #define PNG_SWAP_ALPHA 0x20000L
  183848. #define PNG_STRIP_ALPHA 0x40000L
  183849. #define PNG_INVERT_ALPHA 0x80000L
  183850. #define PNG_USER_TRANSFORM 0x100000L
  183851. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183852. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183853. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183854. /* 0x800000L Unused */
  183855. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183856. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183857. /* 0x4000000L unused */
  183858. /* 0x8000000L unused */
  183859. /* 0x10000000L unused */
  183860. /* 0x20000000L unused */
  183861. /* 0x40000000L unused */
  183862. /* flags for png_create_struct */
  183863. #define PNG_STRUCT_PNG 0x0001
  183864. #define PNG_STRUCT_INFO 0x0002
  183865. /* Scaling factor for filter heuristic weighting calculations */
  183866. #define PNG_WEIGHT_SHIFT 8
  183867. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183868. #define PNG_COST_SHIFT 3
  183869. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183870. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183871. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183872. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183873. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183874. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183875. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183876. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183877. #define PNG_FLAG_ROW_INIT 0x0040
  183878. #define PNG_FLAG_FILLER_AFTER 0x0080
  183879. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183880. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183881. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183882. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183883. #define PNG_FLAG_FREE_PLTE 0x1000
  183884. #define PNG_FLAG_FREE_TRNS 0x2000
  183885. #define PNG_FLAG_FREE_HIST 0x4000
  183886. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183887. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183888. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183889. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183890. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183891. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183892. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183893. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183894. /* 0x800000L unused */
  183895. /* 0x1000000L unused */
  183896. /* 0x2000000L unused */
  183897. /* 0x4000000L unused */
  183898. /* 0x8000000L unused */
  183899. /* 0x10000000L unused */
  183900. /* 0x20000000L unused */
  183901. /* 0x40000000L unused */
  183902. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183903. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183904. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183905. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183906. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183907. PNG_FLAG_CRC_CRITICAL_MASK)
  183908. /* save typing and make code easier to understand */
  183909. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183910. abs((int)((c1).green) - (int)((c2).green)) + \
  183911. abs((int)((c1).blue) - (int)((c2).blue)))
  183912. /* Added to libpng-1.2.6 JB */
  183913. #define PNG_ROWBYTES(pixel_bits, width) \
  183914. ((pixel_bits) >= 8 ? \
  183915. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183916. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183917. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183918. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183919. "ideal" and "delta" should be constants, normally simple
  183920. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183921. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183922. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183923. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183924. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183925. /* place to hold the signature string for a PNG file. */
  183926. #ifdef PNG_USE_GLOBAL_ARRAYS
  183927. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183928. #else
  183929. #endif
  183930. #endif /* PNG_NO_EXTERN */
  183931. /* Constant strings for known chunk types. If you need to add a chunk,
  183932. * define the name here, and add an invocation of the macro in png.c and
  183933. * wherever it's needed.
  183934. */
  183935. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183936. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183937. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183938. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183939. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183940. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183941. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183942. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183943. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183944. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183945. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183946. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183947. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183948. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183949. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183950. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183951. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183952. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183953. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183954. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183955. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183956. #ifdef PNG_USE_GLOBAL_ARRAYS
  183957. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183958. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183959. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183960. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183961. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183962. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183963. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183964. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183965. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183966. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183967. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183968. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183969. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183970. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183971. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183972. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183973. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183974. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183975. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183976. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183977. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183978. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183979. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183980. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183981. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183982. */
  183983. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183984. #undef png_read_init
  183985. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183986. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183987. #endif
  183988. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183989. png_const_charp user_png_ver, png_size_t png_struct_size));
  183990. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183991. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183992. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183993. png_info_size));
  183994. #endif
  183995. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183996. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183997. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183998. */
  183999. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184000. #undef png_write_init
  184001. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184002. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184003. #endif
  184004. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184005. png_const_charp user_png_ver, png_size_t png_struct_size));
  184006. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184007. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184008. png_info_size));
  184009. /* Allocate memory for an internal libpng struct */
  184010. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184011. /* Free memory from internal libpng struct */
  184012. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184013. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184014. malloc_fn, png_voidp mem_ptr));
  184015. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184016. png_free_ptr free_fn, png_voidp mem_ptr));
  184017. /* Free any memory that info_ptr points to and reset struct. */
  184018. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184019. png_infop info_ptr));
  184020. #ifndef PNG_1_0_X
  184021. /* Function to allocate memory for zlib. */
  184022. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184023. /* Function to free memory for zlib */
  184024. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184025. #ifdef PNG_SIZE_T
  184026. /* Function to convert a sizeof an item to png_sizeof item */
  184027. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184028. #endif
  184029. /* Next four functions are used internally as callbacks. PNGAPI is required
  184030. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184031. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184032. png_bytep data, png_size_t length));
  184033. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184034. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184035. png_bytep buffer, png_size_t length));
  184036. #endif
  184037. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184038. png_bytep data, png_size_t length));
  184039. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184040. #if !defined(PNG_NO_STDIO)
  184041. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184042. #endif
  184043. #endif
  184044. #else /* PNG_1_0_X */
  184045. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184046. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184047. png_bytep buffer, png_size_t length));
  184048. #endif
  184049. #endif /* PNG_1_0_X */
  184050. /* Reset the CRC variable */
  184051. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184052. /* Write the "data" buffer to whatever output you are using. */
  184053. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184054. png_size_t length));
  184055. /* Read data from whatever input you are using into the "data" buffer */
  184056. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184057. png_size_t length));
  184058. /* Read bytes into buf, and update png_ptr->crc */
  184059. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184060. png_size_t length));
  184061. /* Decompress data in a chunk that uses compression */
  184062. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184063. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184064. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184065. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184066. png_size_t prefix_length, png_size_t *data_length));
  184067. #endif
  184068. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184069. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184070. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184071. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184072. /* Calculate the CRC over a section of data. Note that we are only
  184073. * passing a maximum of 64K on systems that have this as a memory limit,
  184074. * since this is the maximum buffer size we can specify.
  184075. */
  184076. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184077. png_size_t length));
  184078. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184079. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184080. #endif
  184081. /* simple function to write the signature */
  184082. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184083. /* write various chunks */
  184084. /* Write the IHDR chunk, and update the png_struct with the necessary
  184085. * information.
  184086. */
  184087. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184088. png_uint_32 height,
  184089. int bit_depth, int color_type, int compression_method, int filter_method,
  184090. int interlace_method));
  184091. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184092. png_uint_32 num_pal));
  184093. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184094. png_size_t length));
  184095. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184096. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184097. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184098. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184099. #endif
  184100. #ifdef PNG_FIXED_POINT_SUPPORTED
  184101. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184102. file_gamma));
  184103. #endif
  184104. #endif
  184105. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184106. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184107. int color_type));
  184108. #endif
  184109. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184110. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184111. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184112. double white_x, double white_y,
  184113. double red_x, double red_y, double green_x, double green_y,
  184114. double blue_x, double blue_y));
  184115. #endif
  184116. #ifdef PNG_FIXED_POINT_SUPPORTED
  184117. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184118. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184119. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184120. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184121. png_fixed_point int_blue_y));
  184122. #endif
  184123. #endif
  184124. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184125. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184126. int intent));
  184127. #endif
  184128. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184129. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184130. png_charp name, int compression_type,
  184131. png_charp profile, int proflen));
  184132. /* Note to maintainer: profile should be png_bytep */
  184133. #endif
  184134. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184135. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184136. png_sPLT_tp palette));
  184137. #endif
  184138. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184139. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184140. png_color_16p values, int number, int color_type));
  184141. #endif
  184142. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184143. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184144. png_color_16p values, int color_type));
  184145. #endif
  184146. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184147. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184148. int num_hist));
  184149. #endif
  184150. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184151. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184152. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184153. png_charp key, png_charpp new_key));
  184154. #endif
  184155. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184156. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184157. png_charp text, png_size_t text_len));
  184158. #endif
  184159. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184160. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184161. png_charp text, png_size_t text_len, int compression));
  184162. #endif
  184163. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184164. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184165. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184166. png_charp text));
  184167. #endif
  184168. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184169. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184170. png_infop info_ptr, png_textp text_ptr, int num_text));
  184171. #endif
  184172. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184173. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184174. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184175. #endif
  184176. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184177. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184178. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184179. png_charp units, png_charpp params));
  184180. #endif
  184181. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184182. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184183. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184184. int unit_type));
  184185. #endif
  184186. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184187. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184188. png_timep mod_time));
  184189. #endif
  184190. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184191. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184192. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184193. int unit, double width, double height));
  184194. #else
  184195. #ifdef PNG_FIXED_POINT_SUPPORTED
  184196. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184197. int unit, png_charp width, png_charp height));
  184198. #endif
  184199. #endif
  184200. #endif
  184201. /* Called when finished processing a row of data */
  184202. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184203. /* Internal use only. Called before first row of data */
  184204. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184205. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184206. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184207. #endif
  184208. /* combine a row of data, dealing with alpha, etc. if requested */
  184209. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184210. int mask));
  184211. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184212. /* expand an interlaced row */
  184213. /* OLD pre-1.0.9 interface:
  184214. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184215. png_bytep row, int pass, png_uint_32 transformations));
  184216. */
  184217. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184218. #endif
  184219. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184220. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184221. /* grab pixels out of a row for an interlaced pass */
  184222. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184223. png_bytep row, int pass));
  184224. #endif
  184225. /* unfilter a row */
  184226. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184227. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184228. /* Choose the best filter to use and filter the row data */
  184229. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184230. png_row_infop row_info));
  184231. /* Write out the filtered row. */
  184232. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184233. png_bytep filtered_row));
  184234. /* finish a row while reading, dealing with interlacing passes, etc. */
  184235. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184236. /* initialize the row buffers, etc. */
  184237. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184238. /* optional call to update the users info structure */
  184239. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184240. png_infop info_ptr));
  184241. /* these are the functions that do the transformations */
  184242. #if defined(PNG_READ_FILLER_SUPPORTED)
  184243. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184244. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184245. #endif
  184246. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184247. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184248. png_bytep row));
  184249. #endif
  184250. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184251. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184252. png_bytep row));
  184253. #endif
  184254. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184255. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184256. png_bytep row));
  184257. #endif
  184258. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184259. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184260. png_bytep row));
  184261. #endif
  184262. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184263. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184264. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184265. png_bytep row, png_uint_32 flags));
  184266. #endif
  184267. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184268. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184269. #endif
  184270. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184271. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184272. #endif
  184273. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184274. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184275. row_info, png_bytep row));
  184276. #endif
  184277. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184278. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184279. png_bytep row));
  184280. #endif
  184281. #if defined(PNG_READ_PACK_SUPPORTED)
  184282. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184283. #endif
  184284. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184285. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184286. png_color_8p sig_bits));
  184287. #endif
  184288. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184289. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184290. #endif
  184291. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184292. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184293. #endif
  184294. #if defined(PNG_READ_DITHER_SUPPORTED)
  184295. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184296. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184297. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184298. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184299. png_colorp palette, int num_palette));
  184300. # endif
  184301. #endif
  184302. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184303. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184304. #endif
  184305. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184306. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184307. png_bytep row, png_uint_32 bit_depth));
  184308. #endif
  184309. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184310. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184311. png_color_8p bit_depth));
  184312. #endif
  184313. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184314. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184315. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184316. png_color_16p trans_values, png_color_16p background,
  184317. png_color_16p background_1,
  184318. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184319. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184320. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184321. #else
  184322. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184323. png_color_16p trans_values, png_color_16p background));
  184324. #endif
  184325. #endif
  184326. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184327. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184328. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184329. int gamma_shift));
  184330. #endif
  184331. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184332. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184333. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184334. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184335. png_bytep row, png_color_16p trans_value));
  184336. #endif
  184337. /* The following decodes the appropriate chunks, and does error correction,
  184338. * then calls the appropriate callback for the chunk if it is valid.
  184339. */
  184340. /* decode the IHDR chunk */
  184341. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184342. png_uint_32 length));
  184343. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184344. png_uint_32 length));
  184345. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184346. png_uint_32 length));
  184347. #if defined(PNG_READ_bKGD_SUPPORTED)
  184348. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184349. png_uint_32 length));
  184350. #endif
  184351. #if defined(PNG_READ_cHRM_SUPPORTED)
  184352. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184353. png_uint_32 length));
  184354. #endif
  184355. #if defined(PNG_READ_gAMA_SUPPORTED)
  184356. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184357. png_uint_32 length));
  184358. #endif
  184359. #if defined(PNG_READ_hIST_SUPPORTED)
  184360. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184361. png_uint_32 length));
  184362. #endif
  184363. #if defined(PNG_READ_iCCP_SUPPORTED)
  184364. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184365. png_uint_32 length));
  184366. #endif /* PNG_READ_iCCP_SUPPORTED */
  184367. #if defined(PNG_READ_iTXt_SUPPORTED)
  184368. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184369. png_uint_32 length));
  184370. #endif
  184371. #if defined(PNG_READ_oFFs_SUPPORTED)
  184372. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184373. png_uint_32 length));
  184374. #endif
  184375. #if defined(PNG_READ_pCAL_SUPPORTED)
  184376. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184377. png_uint_32 length));
  184378. #endif
  184379. #if defined(PNG_READ_pHYs_SUPPORTED)
  184380. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184381. png_uint_32 length));
  184382. #endif
  184383. #if defined(PNG_READ_sBIT_SUPPORTED)
  184384. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184385. png_uint_32 length));
  184386. #endif
  184387. #if defined(PNG_READ_sCAL_SUPPORTED)
  184388. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184389. png_uint_32 length));
  184390. #endif
  184391. #if defined(PNG_READ_sPLT_SUPPORTED)
  184392. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184393. png_uint_32 length));
  184394. #endif /* PNG_READ_sPLT_SUPPORTED */
  184395. #if defined(PNG_READ_sRGB_SUPPORTED)
  184396. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184397. png_uint_32 length));
  184398. #endif
  184399. #if defined(PNG_READ_tEXt_SUPPORTED)
  184400. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184401. png_uint_32 length));
  184402. #endif
  184403. #if defined(PNG_READ_tIME_SUPPORTED)
  184404. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184405. png_uint_32 length));
  184406. #endif
  184407. #if defined(PNG_READ_tRNS_SUPPORTED)
  184408. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184409. png_uint_32 length));
  184410. #endif
  184411. #if defined(PNG_READ_zTXt_SUPPORTED)
  184412. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184413. png_uint_32 length));
  184414. #endif
  184415. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184416. png_infop info_ptr, png_uint_32 length));
  184417. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184418. png_bytep chunk_name));
  184419. /* handle the transformations for reading and writing */
  184420. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184421. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184422. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184423. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184424. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184425. png_infop info_ptr));
  184426. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184427. png_infop info_ptr));
  184428. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184429. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184430. png_uint_32 length));
  184431. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184432. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184433. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184434. png_bytep buffer, png_size_t buffer_length));
  184435. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184436. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184437. png_bytep buffer, png_size_t buffer_length));
  184438. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184439. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184440. png_infop info_ptr, png_uint_32 length));
  184441. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184442. png_infop info_ptr));
  184443. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184444. png_infop info_ptr));
  184445. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184446. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184447. png_infop info_ptr));
  184448. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184449. png_infop info_ptr));
  184450. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184451. #if defined(PNG_READ_tEXt_SUPPORTED)
  184452. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184453. png_infop info_ptr, png_uint_32 length));
  184454. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184455. png_infop info_ptr));
  184456. #endif
  184457. #if defined(PNG_READ_zTXt_SUPPORTED)
  184458. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184459. png_infop info_ptr, png_uint_32 length));
  184460. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184461. png_infop info_ptr));
  184462. #endif
  184463. #if defined(PNG_READ_iTXt_SUPPORTED)
  184464. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184465. png_infop info_ptr, png_uint_32 length));
  184466. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184467. png_infop info_ptr));
  184468. #endif
  184469. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184470. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184471. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184472. png_bytep row));
  184473. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184474. png_bytep row));
  184475. #endif
  184476. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184477. #if defined(PNG_MMX_CODE_SUPPORTED)
  184478. /* png.c */ /* PRIVATE */
  184479. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184480. #endif
  184481. #endif
  184482. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184483. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184484. png_infop info_ptr));
  184485. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184486. png_infop info_ptr));
  184487. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184488. png_infop info_ptr));
  184489. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184490. png_infop info_ptr));
  184491. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184492. png_infop info_ptr));
  184493. #if defined(PNG_pHYs_SUPPORTED)
  184494. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184495. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184496. #endif /* PNG_pHYs_SUPPORTED */
  184497. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184498. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184499. #endif /* PNG_INTERNAL */
  184500. #ifdef __cplusplus
  184501. //}
  184502. #endif
  184503. #endif /* PNG_VERSION_INFO_ONLY */
  184504. /* do not put anything past this line */
  184505. #endif /* PNG_H */
  184506. /*** End of inlined file: png.h ***/
  184507. #define PNG_NO_EXTERN
  184508. /*** Start of inlined file: png.c ***/
  184509. /* png.c - location for general purpose libpng functions
  184510. *
  184511. * Last changed in libpng 1.2.21 [October 4, 2007]
  184512. * For conditions of distribution and use, see copyright notice in png.h
  184513. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184514. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184515. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184516. */
  184517. #define PNG_INTERNAL
  184518. #define PNG_NO_EXTERN
  184519. /* Generate a compiler error if there is an old png.h in the search path. */
  184520. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184521. /* Version information for C files. This had better match the version
  184522. * string defined in png.h. */
  184523. #ifdef PNG_USE_GLOBAL_ARRAYS
  184524. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184525. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184526. #ifdef PNG_READ_SUPPORTED
  184527. /* png_sig was changed to a function in version 1.0.5c */
  184528. /* Place to hold the signature string for a PNG file. */
  184529. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184530. #endif /* PNG_READ_SUPPORTED */
  184531. /* Invoke global declarations for constant strings for known chunk types */
  184532. PNG_IHDR;
  184533. PNG_IDAT;
  184534. PNG_IEND;
  184535. PNG_PLTE;
  184536. PNG_bKGD;
  184537. PNG_cHRM;
  184538. PNG_gAMA;
  184539. PNG_hIST;
  184540. PNG_iCCP;
  184541. PNG_iTXt;
  184542. PNG_oFFs;
  184543. PNG_pCAL;
  184544. PNG_sCAL;
  184545. PNG_pHYs;
  184546. PNG_sBIT;
  184547. PNG_sPLT;
  184548. PNG_sRGB;
  184549. PNG_tEXt;
  184550. PNG_tIME;
  184551. PNG_tRNS;
  184552. PNG_zTXt;
  184553. #ifdef PNG_READ_SUPPORTED
  184554. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184555. /* start of interlace block */
  184556. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184557. /* offset to next interlace block */
  184558. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184559. /* start of interlace block in the y direction */
  184560. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184561. /* offset to next interlace block in the y direction */
  184562. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184563. /* Height of interlace block. This is not currently used - if you need
  184564. * it, uncomment it here and in png.h
  184565. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184566. */
  184567. /* Mask to determine which pixels are valid in a pass */
  184568. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184569. /* Mask to determine which pixels to overwrite while displaying */
  184570. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184571. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184572. #endif /* PNG_READ_SUPPORTED */
  184573. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184574. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184575. * of the PNG file signature. If the PNG data is embedded into another
  184576. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184577. * or write any of the magic bytes before it starts on the IHDR.
  184578. */
  184579. #ifdef PNG_READ_SUPPORTED
  184580. void PNGAPI
  184581. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184582. {
  184583. if(png_ptr == NULL) return;
  184584. png_debug(1, "in png_set_sig_bytes\n");
  184585. if (num_bytes > 8)
  184586. png_error(png_ptr, "Too many bytes for PNG signature.");
  184587. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184588. }
  184589. /* Checks whether the supplied bytes match the PNG signature. We allow
  184590. * checking less than the full 8-byte signature so that those apps that
  184591. * already read the first few bytes of a file to determine the file type
  184592. * can simply check the remaining bytes for extra assurance. Returns
  184593. * an integer less than, equal to, or greater than zero if sig is found,
  184594. * respectively, to be less than, to match, or be greater than the correct
  184595. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184596. */
  184597. int PNGAPI
  184598. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184599. {
  184600. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184601. if (num_to_check > 8)
  184602. num_to_check = 8;
  184603. else if (num_to_check < 1)
  184604. return (-1);
  184605. if (start > 7)
  184606. return (-1);
  184607. if (start + num_to_check > 8)
  184608. num_to_check = 8 - start;
  184609. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184610. }
  184611. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184612. /* (Obsolete) function to check signature bytes. It does not allow one
  184613. * to check a partial signature. This function might be removed in the
  184614. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184615. */
  184616. int PNGAPI
  184617. png_check_sig(png_bytep sig, int num)
  184618. {
  184619. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184620. }
  184621. #endif
  184622. #endif /* PNG_READ_SUPPORTED */
  184623. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184624. /* Function to allocate memory for zlib and clear it to 0. */
  184625. #ifdef PNG_1_0_X
  184626. voidpf PNGAPI
  184627. #else
  184628. voidpf /* private */
  184629. #endif
  184630. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184631. {
  184632. png_voidp ptr;
  184633. png_structp p=(png_structp)png_ptr;
  184634. png_uint_32 save_flags=p->flags;
  184635. png_uint_32 num_bytes;
  184636. if(png_ptr == NULL) return (NULL);
  184637. if (items > PNG_UINT_32_MAX/size)
  184638. {
  184639. png_warning (p, "Potential overflow in png_zalloc()");
  184640. return (NULL);
  184641. }
  184642. num_bytes = (png_uint_32)items * size;
  184643. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184644. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184645. p->flags=save_flags;
  184646. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184647. if (ptr == NULL)
  184648. return ((voidpf)ptr);
  184649. if (num_bytes > (png_uint_32)0x8000L)
  184650. {
  184651. png_memset(ptr, 0, (png_size_t)0x8000L);
  184652. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184653. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184654. }
  184655. else
  184656. {
  184657. png_memset(ptr, 0, (png_size_t)num_bytes);
  184658. }
  184659. #endif
  184660. return ((voidpf)ptr);
  184661. }
  184662. /* function to free memory for zlib */
  184663. #ifdef PNG_1_0_X
  184664. void PNGAPI
  184665. #else
  184666. void /* private */
  184667. #endif
  184668. png_zfree(voidpf png_ptr, voidpf ptr)
  184669. {
  184670. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184671. }
  184672. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184673. * in case CRC is > 32 bits to leave the top bits 0.
  184674. */
  184675. void /* PRIVATE */
  184676. png_reset_crc(png_structp png_ptr)
  184677. {
  184678. png_ptr->crc = crc32(0, Z_NULL, 0);
  184679. }
  184680. /* Calculate the CRC over a section of data. We can only pass as
  184681. * much data to this routine as the largest single buffer size. We
  184682. * also check that this data will actually be used before going to the
  184683. * trouble of calculating it.
  184684. */
  184685. void /* PRIVATE */
  184686. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184687. {
  184688. int need_crc = 1;
  184689. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184690. {
  184691. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184692. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184693. need_crc = 0;
  184694. }
  184695. else /* critical */
  184696. {
  184697. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184698. need_crc = 0;
  184699. }
  184700. if (need_crc)
  184701. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184702. }
  184703. /* Allocate the memory for an info_struct for the application. We don't
  184704. * really need the png_ptr, but it could potentially be useful in the
  184705. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184706. * and png_info_init() so that applications that want to use a shared
  184707. * libpng don't have to be recompiled if png_info changes size.
  184708. */
  184709. png_infop PNGAPI
  184710. png_create_info_struct(png_structp png_ptr)
  184711. {
  184712. png_infop info_ptr;
  184713. png_debug(1, "in png_create_info_struct\n");
  184714. if(png_ptr == NULL) return (NULL);
  184715. #ifdef PNG_USER_MEM_SUPPORTED
  184716. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184717. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184718. #else
  184719. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184720. #endif
  184721. if (info_ptr != NULL)
  184722. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184723. return (info_ptr);
  184724. }
  184725. /* This function frees the memory associated with a single info struct.
  184726. * Normally, one would use either png_destroy_read_struct() or
  184727. * png_destroy_write_struct() to free an info struct, but this may be
  184728. * useful for some applications.
  184729. */
  184730. void PNGAPI
  184731. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184732. {
  184733. png_infop info_ptr = NULL;
  184734. if(png_ptr == NULL) return;
  184735. png_debug(1, "in png_destroy_info_struct\n");
  184736. if (info_ptr_ptr != NULL)
  184737. info_ptr = *info_ptr_ptr;
  184738. if (info_ptr != NULL)
  184739. {
  184740. png_info_destroy(png_ptr, info_ptr);
  184741. #ifdef PNG_USER_MEM_SUPPORTED
  184742. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184743. png_ptr->mem_ptr);
  184744. #else
  184745. png_destroy_struct((png_voidp)info_ptr);
  184746. #endif
  184747. *info_ptr_ptr = NULL;
  184748. }
  184749. }
  184750. /* Initialize the info structure. This is now an internal function (0.89)
  184751. * and applications using it are urged to use png_create_info_struct()
  184752. * instead.
  184753. */
  184754. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184755. #undef png_info_init
  184756. void PNGAPI
  184757. png_info_init(png_infop info_ptr)
  184758. {
  184759. /* We only come here via pre-1.0.12-compiled applications */
  184760. png_info_init_3(&info_ptr, 0);
  184761. }
  184762. #endif
  184763. void PNGAPI
  184764. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184765. {
  184766. png_infop info_ptr = *ptr_ptr;
  184767. if(info_ptr == NULL) return;
  184768. png_debug(1, "in png_info_init_3\n");
  184769. if(png_sizeof(png_info) > png_info_struct_size)
  184770. {
  184771. png_destroy_struct(info_ptr);
  184772. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184773. *ptr_ptr = info_ptr;
  184774. }
  184775. /* set everything to 0 */
  184776. png_memset(info_ptr, 0, png_sizeof (png_info));
  184777. }
  184778. #ifdef PNG_FREE_ME_SUPPORTED
  184779. void PNGAPI
  184780. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184781. int freer, png_uint_32 mask)
  184782. {
  184783. png_debug(1, "in png_data_freer\n");
  184784. if (png_ptr == NULL || info_ptr == NULL)
  184785. return;
  184786. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184787. info_ptr->free_me |= mask;
  184788. else if(freer == PNG_USER_WILL_FREE_DATA)
  184789. info_ptr->free_me &= ~mask;
  184790. else
  184791. png_warning(png_ptr,
  184792. "Unknown freer parameter in png_data_freer.");
  184793. }
  184794. #endif
  184795. void PNGAPI
  184796. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184797. int num)
  184798. {
  184799. png_debug(1, "in png_free_data\n");
  184800. if (png_ptr == NULL || info_ptr == NULL)
  184801. return;
  184802. #if defined(PNG_TEXT_SUPPORTED)
  184803. /* free text item num or (if num == -1) all text items */
  184804. #ifdef PNG_FREE_ME_SUPPORTED
  184805. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184806. #else
  184807. if (mask & PNG_FREE_TEXT)
  184808. #endif
  184809. {
  184810. if (num != -1)
  184811. {
  184812. if (info_ptr->text && info_ptr->text[num].key)
  184813. {
  184814. png_free(png_ptr, info_ptr->text[num].key);
  184815. info_ptr->text[num].key = NULL;
  184816. }
  184817. }
  184818. else
  184819. {
  184820. int i;
  184821. for (i = 0; i < info_ptr->num_text; i++)
  184822. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184823. png_free(png_ptr, info_ptr->text);
  184824. info_ptr->text = NULL;
  184825. info_ptr->num_text=0;
  184826. }
  184827. }
  184828. #endif
  184829. #if defined(PNG_tRNS_SUPPORTED)
  184830. /* free any tRNS entry */
  184831. #ifdef PNG_FREE_ME_SUPPORTED
  184832. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184833. #else
  184834. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184835. #endif
  184836. {
  184837. png_free(png_ptr, info_ptr->trans);
  184838. info_ptr->valid &= ~PNG_INFO_tRNS;
  184839. #ifndef PNG_FREE_ME_SUPPORTED
  184840. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184841. #endif
  184842. info_ptr->trans = NULL;
  184843. }
  184844. #endif
  184845. #if defined(PNG_sCAL_SUPPORTED)
  184846. /* free any sCAL entry */
  184847. #ifdef PNG_FREE_ME_SUPPORTED
  184848. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184849. #else
  184850. if (mask & PNG_FREE_SCAL)
  184851. #endif
  184852. {
  184853. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184854. png_free(png_ptr, info_ptr->scal_s_width);
  184855. png_free(png_ptr, info_ptr->scal_s_height);
  184856. info_ptr->scal_s_width = NULL;
  184857. info_ptr->scal_s_height = NULL;
  184858. #endif
  184859. info_ptr->valid &= ~PNG_INFO_sCAL;
  184860. }
  184861. #endif
  184862. #if defined(PNG_pCAL_SUPPORTED)
  184863. /* free any pCAL entry */
  184864. #ifdef PNG_FREE_ME_SUPPORTED
  184865. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184866. #else
  184867. if (mask & PNG_FREE_PCAL)
  184868. #endif
  184869. {
  184870. png_free(png_ptr, info_ptr->pcal_purpose);
  184871. png_free(png_ptr, info_ptr->pcal_units);
  184872. info_ptr->pcal_purpose = NULL;
  184873. info_ptr->pcal_units = NULL;
  184874. if (info_ptr->pcal_params != NULL)
  184875. {
  184876. int i;
  184877. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184878. {
  184879. png_free(png_ptr, info_ptr->pcal_params[i]);
  184880. info_ptr->pcal_params[i]=NULL;
  184881. }
  184882. png_free(png_ptr, info_ptr->pcal_params);
  184883. info_ptr->pcal_params = NULL;
  184884. }
  184885. info_ptr->valid &= ~PNG_INFO_pCAL;
  184886. }
  184887. #endif
  184888. #if defined(PNG_iCCP_SUPPORTED)
  184889. /* free any iCCP entry */
  184890. #ifdef PNG_FREE_ME_SUPPORTED
  184891. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184892. #else
  184893. if (mask & PNG_FREE_ICCP)
  184894. #endif
  184895. {
  184896. png_free(png_ptr, info_ptr->iccp_name);
  184897. png_free(png_ptr, info_ptr->iccp_profile);
  184898. info_ptr->iccp_name = NULL;
  184899. info_ptr->iccp_profile = NULL;
  184900. info_ptr->valid &= ~PNG_INFO_iCCP;
  184901. }
  184902. #endif
  184903. #if defined(PNG_sPLT_SUPPORTED)
  184904. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184905. #ifdef PNG_FREE_ME_SUPPORTED
  184906. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184907. #else
  184908. if (mask & PNG_FREE_SPLT)
  184909. #endif
  184910. {
  184911. if (num != -1)
  184912. {
  184913. if(info_ptr->splt_palettes)
  184914. {
  184915. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184916. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184917. info_ptr->splt_palettes[num].name = NULL;
  184918. info_ptr->splt_palettes[num].entries = NULL;
  184919. }
  184920. }
  184921. else
  184922. {
  184923. if(info_ptr->splt_palettes_num)
  184924. {
  184925. int i;
  184926. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184927. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184928. png_free(png_ptr, info_ptr->splt_palettes);
  184929. info_ptr->splt_palettes = NULL;
  184930. info_ptr->splt_palettes_num = 0;
  184931. }
  184932. info_ptr->valid &= ~PNG_INFO_sPLT;
  184933. }
  184934. }
  184935. #endif
  184936. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184937. if(png_ptr->unknown_chunk.data)
  184938. {
  184939. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184940. png_ptr->unknown_chunk.data = NULL;
  184941. }
  184942. #ifdef PNG_FREE_ME_SUPPORTED
  184943. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184944. #else
  184945. if (mask & PNG_FREE_UNKN)
  184946. #endif
  184947. {
  184948. if (num != -1)
  184949. {
  184950. if(info_ptr->unknown_chunks)
  184951. {
  184952. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184953. info_ptr->unknown_chunks[num].data = NULL;
  184954. }
  184955. }
  184956. else
  184957. {
  184958. int i;
  184959. if(info_ptr->unknown_chunks_num)
  184960. {
  184961. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184962. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184963. png_free(png_ptr, info_ptr->unknown_chunks);
  184964. info_ptr->unknown_chunks = NULL;
  184965. info_ptr->unknown_chunks_num = 0;
  184966. }
  184967. }
  184968. }
  184969. #endif
  184970. #if defined(PNG_hIST_SUPPORTED)
  184971. /* free any hIST entry */
  184972. #ifdef PNG_FREE_ME_SUPPORTED
  184973. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184974. #else
  184975. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184976. #endif
  184977. {
  184978. png_free(png_ptr, info_ptr->hist);
  184979. info_ptr->hist = NULL;
  184980. info_ptr->valid &= ~PNG_INFO_hIST;
  184981. #ifndef PNG_FREE_ME_SUPPORTED
  184982. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184983. #endif
  184984. }
  184985. #endif
  184986. /* free any PLTE entry that was internally allocated */
  184987. #ifdef PNG_FREE_ME_SUPPORTED
  184988. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184989. #else
  184990. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184991. #endif
  184992. {
  184993. png_zfree(png_ptr, info_ptr->palette);
  184994. info_ptr->palette = NULL;
  184995. info_ptr->valid &= ~PNG_INFO_PLTE;
  184996. #ifndef PNG_FREE_ME_SUPPORTED
  184997. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184998. #endif
  184999. info_ptr->num_palette = 0;
  185000. }
  185001. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185002. /* free any image bits attached to the info structure */
  185003. #ifdef PNG_FREE_ME_SUPPORTED
  185004. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185005. #else
  185006. if (mask & PNG_FREE_ROWS)
  185007. #endif
  185008. {
  185009. if(info_ptr->row_pointers)
  185010. {
  185011. int row;
  185012. for (row = 0; row < (int)info_ptr->height; row++)
  185013. {
  185014. png_free(png_ptr, info_ptr->row_pointers[row]);
  185015. info_ptr->row_pointers[row]=NULL;
  185016. }
  185017. png_free(png_ptr, info_ptr->row_pointers);
  185018. info_ptr->row_pointers=NULL;
  185019. }
  185020. info_ptr->valid &= ~PNG_INFO_IDAT;
  185021. }
  185022. #endif
  185023. #ifdef PNG_FREE_ME_SUPPORTED
  185024. if(num == -1)
  185025. info_ptr->free_me &= ~mask;
  185026. else
  185027. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185028. #endif
  185029. }
  185030. /* This is an internal routine to free any memory that the info struct is
  185031. * pointing to before re-using it or freeing the struct itself. Recall
  185032. * that png_free() checks for NULL pointers for us.
  185033. */
  185034. void /* PRIVATE */
  185035. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185036. {
  185037. png_debug(1, "in png_info_destroy\n");
  185038. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185039. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185040. if (png_ptr->num_chunk_list)
  185041. {
  185042. png_free(png_ptr, png_ptr->chunk_list);
  185043. png_ptr->chunk_list=NULL;
  185044. png_ptr->num_chunk_list=0;
  185045. }
  185046. #endif
  185047. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185048. }
  185049. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185050. /* This function returns a pointer to the io_ptr associated with the user
  185051. * functions. The application should free any memory associated with this
  185052. * pointer before png_write_destroy() or png_read_destroy() are called.
  185053. */
  185054. png_voidp PNGAPI
  185055. png_get_io_ptr(png_structp png_ptr)
  185056. {
  185057. if(png_ptr == NULL) return (NULL);
  185058. return (png_ptr->io_ptr);
  185059. }
  185060. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185061. #if !defined(PNG_NO_STDIO)
  185062. /* Initialize the default input/output functions for the PNG file. If you
  185063. * use your own read or write routines, you can call either png_set_read_fn()
  185064. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185065. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185066. * necessarily available.
  185067. */
  185068. void PNGAPI
  185069. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185070. {
  185071. png_debug(1, "in png_init_io\n");
  185072. if(png_ptr == NULL) return;
  185073. png_ptr->io_ptr = (png_voidp)fp;
  185074. }
  185075. #endif
  185076. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185077. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185078. * a "Creation Time" or other text-based time string.
  185079. */
  185080. png_charp PNGAPI
  185081. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185082. {
  185083. static PNG_CONST char short_months[12][4] =
  185084. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185085. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185086. if(png_ptr == NULL) return (NULL);
  185087. if (png_ptr->time_buffer == NULL)
  185088. {
  185089. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185090. png_sizeof(char)));
  185091. }
  185092. #if defined(_WIN32_WCE)
  185093. {
  185094. wchar_t time_buf[29];
  185095. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185096. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185097. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185098. ptime->second % 61);
  185099. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185100. NULL, NULL);
  185101. }
  185102. #else
  185103. #ifdef USE_FAR_KEYWORD
  185104. {
  185105. char near_time_buf[29];
  185106. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185107. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185108. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185109. ptime->second % 61);
  185110. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185111. 29*png_sizeof(char));
  185112. }
  185113. #else
  185114. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185115. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185116. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185117. ptime->second % 61);
  185118. #endif
  185119. #endif /* _WIN32_WCE */
  185120. return ((png_charp)png_ptr->time_buffer);
  185121. }
  185122. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185123. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185124. png_charp PNGAPI
  185125. png_get_copyright(png_structp png_ptr)
  185126. {
  185127. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185128. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185129. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185130. Copyright (c) 1996-1997 Andreas Dilger\n\
  185131. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185132. }
  185133. /* The following return the library version as a short string in the
  185134. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185135. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185136. * is defined in png.h.
  185137. * Note: now there is no difference between png_get_libpng_ver() and
  185138. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185139. * it is guaranteed that png.c uses the correct version of png.h.
  185140. */
  185141. png_charp PNGAPI
  185142. png_get_libpng_ver(png_structp png_ptr)
  185143. {
  185144. /* Version of *.c files used when building libpng */
  185145. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185146. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185147. }
  185148. png_charp PNGAPI
  185149. png_get_header_ver(png_structp png_ptr)
  185150. {
  185151. /* Version of *.h files used when building libpng */
  185152. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185153. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185154. }
  185155. png_charp PNGAPI
  185156. png_get_header_version(png_structp png_ptr)
  185157. {
  185158. /* Returns longer string containing both version and date */
  185159. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185160. return ((png_charp) PNG_HEADER_VERSION_STRING
  185161. #ifndef PNG_READ_SUPPORTED
  185162. " (NO READ SUPPORT)"
  185163. #endif
  185164. "\n");
  185165. }
  185166. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185167. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185168. int PNGAPI
  185169. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185170. {
  185171. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185172. int i;
  185173. png_bytep p;
  185174. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185175. return 0;
  185176. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185177. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185178. if (!png_memcmp(chunk_name, p, 4))
  185179. return ((int)*(p+4));
  185180. return 0;
  185181. }
  185182. #endif
  185183. /* This function, added to libpng-1.0.6g, is untested. */
  185184. int PNGAPI
  185185. png_reset_zstream(png_structp png_ptr)
  185186. {
  185187. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185188. return (inflateReset(&png_ptr->zstream));
  185189. }
  185190. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185191. /* This function was added to libpng-1.0.7 */
  185192. png_uint_32 PNGAPI
  185193. png_access_version_number(void)
  185194. {
  185195. /* Version of *.c files used when building libpng */
  185196. return((png_uint_32) PNG_LIBPNG_VER);
  185197. }
  185198. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185199. #if !defined(PNG_1_0_X)
  185200. /* this function was added to libpng 1.2.0 */
  185201. int PNGAPI
  185202. png_mmx_support(void)
  185203. {
  185204. /* obsolete, to be removed from libpng-1.4.0 */
  185205. return -1;
  185206. }
  185207. #endif /* PNG_1_0_X */
  185208. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185209. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185210. #ifdef PNG_SIZE_T
  185211. /* Added at libpng version 1.2.6 */
  185212. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185213. png_size_t PNGAPI
  185214. png_convert_size(size_t size)
  185215. {
  185216. if (size > (png_size_t)-1)
  185217. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185218. return ((png_size_t)size);
  185219. }
  185220. #endif /* PNG_SIZE_T */
  185221. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185222. /*** End of inlined file: png.c ***/
  185223. /*** Start of inlined file: pngerror.c ***/
  185224. /* pngerror.c - stub functions for i/o and memory allocation
  185225. *
  185226. * Last changed in libpng 1.2.20 October 4, 2007
  185227. * For conditions of distribution and use, see copyright notice in png.h
  185228. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185229. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185230. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185231. *
  185232. * This file provides a location for all error handling. Users who
  185233. * need special error handling are expected to write replacement functions
  185234. * and use png_set_error_fn() to use those functions. See the instructions
  185235. * at each function.
  185236. */
  185237. #define PNG_INTERNAL
  185238. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185239. static void /* PRIVATE */
  185240. png_default_error PNGARG((png_structp png_ptr,
  185241. png_const_charp error_message));
  185242. #ifndef PNG_NO_WARNINGS
  185243. static void /* PRIVATE */
  185244. png_default_warning PNGARG((png_structp png_ptr,
  185245. png_const_charp warning_message));
  185246. #endif /* PNG_NO_WARNINGS */
  185247. /* This function is called whenever there is a fatal error. This function
  185248. * should not be changed. If there is a need to handle errors differently,
  185249. * you should supply a replacement error function and use png_set_error_fn()
  185250. * to replace the error function at run-time.
  185251. */
  185252. #ifndef PNG_NO_ERROR_TEXT
  185253. void PNGAPI
  185254. png_error(png_structp png_ptr, png_const_charp error_message)
  185255. {
  185256. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185257. char msg[16];
  185258. if (png_ptr != NULL)
  185259. {
  185260. if (png_ptr->flags&
  185261. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185262. {
  185263. if (*error_message == '#')
  185264. {
  185265. int offset;
  185266. for (offset=1; offset<15; offset++)
  185267. if (*(error_message+offset) == ' ')
  185268. break;
  185269. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185270. {
  185271. int i;
  185272. for (i=0; i<offset-1; i++)
  185273. msg[i]=error_message[i+1];
  185274. msg[i]='\0';
  185275. error_message=msg;
  185276. }
  185277. else
  185278. error_message+=offset;
  185279. }
  185280. else
  185281. {
  185282. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185283. {
  185284. msg[0]='0';
  185285. msg[1]='\0';
  185286. error_message=msg;
  185287. }
  185288. }
  185289. }
  185290. }
  185291. #endif
  185292. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185293. (*(png_ptr->error_fn))(png_ptr, error_message);
  185294. /* If the custom handler doesn't exist, or if it returns,
  185295. use the default handler, which will not return. */
  185296. png_default_error(png_ptr, error_message);
  185297. }
  185298. #else
  185299. void PNGAPI
  185300. png_err(png_structp png_ptr)
  185301. {
  185302. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185303. (*(png_ptr->error_fn))(png_ptr, '\0');
  185304. /* If the custom handler doesn't exist, or if it returns,
  185305. use the default handler, which will not return. */
  185306. png_default_error(png_ptr, '\0');
  185307. }
  185308. #endif /* PNG_NO_ERROR_TEXT */
  185309. #ifndef PNG_NO_WARNINGS
  185310. /* This function is called whenever there is a non-fatal error. This function
  185311. * should not be changed. If there is a need to handle warnings differently,
  185312. * you should supply a replacement warning function and use
  185313. * png_set_error_fn() to replace the warning function at run-time.
  185314. */
  185315. void PNGAPI
  185316. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185317. {
  185318. int offset = 0;
  185319. if (png_ptr != NULL)
  185320. {
  185321. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185322. if (png_ptr->flags&
  185323. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185324. #endif
  185325. {
  185326. if (*warning_message == '#')
  185327. {
  185328. for (offset=1; offset<15; offset++)
  185329. if (*(warning_message+offset) == ' ')
  185330. break;
  185331. }
  185332. }
  185333. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185334. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185335. }
  185336. else
  185337. png_default_warning(png_ptr, warning_message+offset);
  185338. }
  185339. #endif /* PNG_NO_WARNINGS */
  185340. /* These utilities are used internally to build an error message that relates
  185341. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185342. * this is used to prefix the message. The message is limited in length
  185343. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185344. * if the character is invalid.
  185345. */
  185346. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185347. /*static PNG_CONST char png_digit[16] = {
  185348. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185349. 'A', 'B', 'C', 'D', 'E', 'F'
  185350. };*/
  185351. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185352. static void /* PRIVATE */
  185353. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185354. error_message)
  185355. {
  185356. int iout = 0, iin = 0;
  185357. while (iin < 4)
  185358. {
  185359. int c = png_ptr->chunk_name[iin++];
  185360. if (isnonalpha(c))
  185361. {
  185362. buffer[iout++] = '[';
  185363. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185364. buffer[iout++] = png_digit[c & 0x0f];
  185365. buffer[iout++] = ']';
  185366. }
  185367. else
  185368. {
  185369. buffer[iout++] = (png_byte)c;
  185370. }
  185371. }
  185372. if (error_message == NULL)
  185373. buffer[iout] = 0;
  185374. else
  185375. {
  185376. buffer[iout++] = ':';
  185377. buffer[iout++] = ' ';
  185378. png_strncpy(buffer+iout, error_message, 63);
  185379. buffer[iout+63] = 0;
  185380. }
  185381. }
  185382. #ifdef PNG_READ_SUPPORTED
  185383. void PNGAPI
  185384. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185385. {
  185386. char msg[18+64];
  185387. if (png_ptr == NULL)
  185388. png_error(png_ptr, error_message);
  185389. else
  185390. {
  185391. png_format_buffer(png_ptr, msg, error_message);
  185392. png_error(png_ptr, msg);
  185393. }
  185394. }
  185395. #endif /* PNG_READ_SUPPORTED */
  185396. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185397. #ifndef PNG_NO_WARNINGS
  185398. void PNGAPI
  185399. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185400. {
  185401. char msg[18+64];
  185402. if (png_ptr == NULL)
  185403. png_warning(png_ptr, warning_message);
  185404. else
  185405. {
  185406. png_format_buffer(png_ptr, msg, warning_message);
  185407. png_warning(png_ptr, msg);
  185408. }
  185409. }
  185410. #endif /* PNG_NO_WARNINGS */
  185411. /* This is the default error handling function. Note that replacements for
  185412. * this function MUST NOT RETURN, or the program will likely crash. This
  185413. * function is used by default, or if the program supplies NULL for the
  185414. * error function pointer in png_set_error_fn().
  185415. */
  185416. static void /* PRIVATE */
  185417. png_default_error(png_structp, png_const_charp error_message)
  185418. {
  185419. #ifndef PNG_NO_CONSOLE_IO
  185420. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185421. if (*error_message == '#')
  185422. {
  185423. int offset;
  185424. char error_number[16];
  185425. for (offset=0; offset<15; offset++)
  185426. {
  185427. error_number[offset] = *(error_message+offset+1);
  185428. if (*(error_message+offset) == ' ')
  185429. break;
  185430. }
  185431. if((offset > 1) && (offset < 15))
  185432. {
  185433. error_number[offset-1]='\0';
  185434. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185435. error_message+offset);
  185436. }
  185437. else
  185438. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185439. }
  185440. else
  185441. #endif
  185442. fprintf(stderr, "libpng error: %s\n", error_message);
  185443. #endif
  185444. #ifdef PNG_SETJMP_SUPPORTED
  185445. if (png_ptr)
  185446. {
  185447. # ifdef USE_FAR_KEYWORD
  185448. {
  185449. jmp_buf jmpbuf;
  185450. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185451. longjmp(jmpbuf, 1);
  185452. }
  185453. # else
  185454. longjmp(png_ptr->jmpbuf, 1);
  185455. # endif
  185456. }
  185457. #else
  185458. PNG_ABORT();
  185459. #endif
  185460. #ifdef PNG_NO_CONSOLE_IO
  185461. error_message = error_message; /* make compiler happy */
  185462. #endif
  185463. }
  185464. #ifndef PNG_NO_WARNINGS
  185465. /* This function is called when there is a warning, but the library thinks
  185466. * it can continue anyway. Replacement functions don't have to do anything
  185467. * here if you don't want them to. In the default configuration, png_ptr is
  185468. * not used, but it is passed in case it may be useful.
  185469. */
  185470. static void /* PRIVATE */
  185471. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185472. {
  185473. #ifndef PNG_NO_CONSOLE_IO
  185474. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185475. if (*warning_message == '#')
  185476. {
  185477. int offset;
  185478. char warning_number[16];
  185479. for (offset=0; offset<15; offset++)
  185480. {
  185481. warning_number[offset]=*(warning_message+offset+1);
  185482. if (*(warning_message+offset) == ' ')
  185483. break;
  185484. }
  185485. if((offset > 1) && (offset < 15))
  185486. {
  185487. warning_number[offset-1]='\0';
  185488. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185489. warning_message+offset);
  185490. }
  185491. else
  185492. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185493. }
  185494. else
  185495. # endif
  185496. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185497. #else
  185498. warning_message = warning_message; /* make compiler happy */
  185499. #endif
  185500. png_ptr = png_ptr; /* make compiler happy */
  185501. }
  185502. #endif /* PNG_NO_WARNINGS */
  185503. /* This function is called when the application wants to use another method
  185504. * of handling errors and warnings. Note that the error function MUST NOT
  185505. * return to the calling routine or serious problems will occur. The return
  185506. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185507. */
  185508. void PNGAPI
  185509. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185510. png_error_ptr error_fn, png_error_ptr warning_fn)
  185511. {
  185512. if (png_ptr == NULL)
  185513. return;
  185514. png_ptr->error_ptr = error_ptr;
  185515. png_ptr->error_fn = error_fn;
  185516. png_ptr->warning_fn = warning_fn;
  185517. }
  185518. /* This function returns a pointer to the error_ptr associated with the user
  185519. * functions. The application should free any memory associated with this
  185520. * pointer before png_write_destroy and png_read_destroy are called.
  185521. */
  185522. png_voidp PNGAPI
  185523. png_get_error_ptr(png_structp png_ptr)
  185524. {
  185525. if (png_ptr == NULL)
  185526. return NULL;
  185527. return ((png_voidp)png_ptr->error_ptr);
  185528. }
  185529. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185530. void PNGAPI
  185531. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185532. {
  185533. if(png_ptr != NULL)
  185534. {
  185535. png_ptr->flags &=
  185536. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185537. }
  185538. }
  185539. #endif
  185540. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185541. /*** End of inlined file: pngerror.c ***/
  185542. /*** Start of inlined file: pngget.c ***/
  185543. /* pngget.c - retrieval of values from info struct
  185544. *
  185545. * Last changed in libpng 1.2.15 January 5, 2007
  185546. * For conditions of distribution and use, see copyright notice in png.h
  185547. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185548. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185549. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185550. */
  185551. #define PNG_INTERNAL
  185552. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185553. png_uint_32 PNGAPI
  185554. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185555. {
  185556. if (png_ptr != NULL && info_ptr != NULL)
  185557. return(info_ptr->valid & flag);
  185558. else
  185559. return(0);
  185560. }
  185561. png_uint_32 PNGAPI
  185562. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185563. {
  185564. if (png_ptr != NULL && info_ptr != NULL)
  185565. return(info_ptr->rowbytes);
  185566. else
  185567. return(0);
  185568. }
  185569. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185570. png_bytepp PNGAPI
  185571. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185572. {
  185573. if (png_ptr != NULL && info_ptr != NULL)
  185574. return(info_ptr->row_pointers);
  185575. else
  185576. return(0);
  185577. }
  185578. #endif
  185579. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185580. /* easy access to info, added in libpng-0.99 */
  185581. png_uint_32 PNGAPI
  185582. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185583. {
  185584. if (png_ptr != NULL && info_ptr != NULL)
  185585. {
  185586. return info_ptr->width;
  185587. }
  185588. return (0);
  185589. }
  185590. png_uint_32 PNGAPI
  185591. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185592. {
  185593. if (png_ptr != NULL && info_ptr != NULL)
  185594. {
  185595. return info_ptr->height;
  185596. }
  185597. return (0);
  185598. }
  185599. png_byte PNGAPI
  185600. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185601. {
  185602. if (png_ptr != NULL && info_ptr != NULL)
  185603. {
  185604. return info_ptr->bit_depth;
  185605. }
  185606. return (0);
  185607. }
  185608. png_byte PNGAPI
  185609. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185610. {
  185611. if (png_ptr != NULL && info_ptr != NULL)
  185612. {
  185613. return info_ptr->color_type;
  185614. }
  185615. return (0);
  185616. }
  185617. png_byte PNGAPI
  185618. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185619. {
  185620. if (png_ptr != NULL && info_ptr != NULL)
  185621. {
  185622. return info_ptr->filter_type;
  185623. }
  185624. return (0);
  185625. }
  185626. png_byte PNGAPI
  185627. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185628. {
  185629. if (png_ptr != NULL && info_ptr != NULL)
  185630. {
  185631. return info_ptr->interlace_type;
  185632. }
  185633. return (0);
  185634. }
  185635. png_byte PNGAPI
  185636. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185637. {
  185638. if (png_ptr != NULL && info_ptr != NULL)
  185639. {
  185640. return info_ptr->compression_type;
  185641. }
  185642. return (0);
  185643. }
  185644. png_uint_32 PNGAPI
  185645. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185646. {
  185647. if (png_ptr != NULL && info_ptr != NULL)
  185648. #if defined(PNG_pHYs_SUPPORTED)
  185649. if (info_ptr->valid & PNG_INFO_pHYs)
  185650. {
  185651. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185652. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185653. return (0);
  185654. else return (info_ptr->x_pixels_per_unit);
  185655. }
  185656. #else
  185657. return (0);
  185658. #endif
  185659. return (0);
  185660. }
  185661. png_uint_32 PNGAPI
  185662. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185663. {
  185664. if (png_ptr != NULL && info_ptr != NULL)
  185665. #if defined(PNG_pHYs_SUPPORTED)
  185666. if (info_ptr->valid & PNG_INFO_pHYs)
  185667. {
  185668. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185669. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185670. return (0);
  185671. else return (info_ptr->y_pixels_per_unit);
  185672. }
  185673. #else
  185674. return (0);
  185675. #endif
  185676. return (0);
  185677. }
  185678. png_uint_32 PNGAPI
  185679. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185680. {
  185681. if (png_ptr != NULL && info_ptr != NULL)
  185682. #if defined(PNG_pHYs_SUPPORTED)
  185683. if (info_ptr->valid & PNG_INFO_pHYs)
  185684. {
  185685. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185686. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185687. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185688. return (0);
  185689. else return (info_ptr->x_pixels_per_unit);
  185690. }
  185691. #else
  185692. return (0);
  185693. #endif
  185694. return (0);
  185695. }
  185696. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185697. float PNGAPI
  185698. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185699. {
  185700. if (png_ptr != NULL && info_ptr != NULL)
  185701. #if defined(PNG_pHYs_SUPPORTED)
  185702. if (info_ptr->valid & PNG_INFO_pHYs)
  185703. {
  185704. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185705. if (info_ptr->x_pixels_per_unit == 0)
  185706. return ((float)0.0);
  185707. else
  185708. return ((float)((float)info_ptr->y_pixels_per_unit
  185709. /(float)info_ptr->x_pixels_per_unit));
  185710. }
  185711. #else
  185712. return (0.0);
  185713. #endif
  185714. return ((float)0.0);
  185715. }
  185716. #endif
  185717. png_int_32 PNGAPI
  185718. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185719. {
  185720. if (png_ptr != NULL && info_ptr != NULL)
  185721. #if defined(PNG_oFFs_SUPPORTED)
  185722. if (info_ptr->valid & PNG_INFO_oFFs)
  185723. {
  185724. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185725. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185726. return (0);
  185727. else return (info_ptr->x_offset);
  185728. }
  185729. #else
  185730. return (0);
  185731. #endif
  185732. return (0);
  185733. }
  185734. png_int_32 PNGAPI
  185735. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185736. {
  185737. if (png_ptr != NULL && info_ptr != NULL)
  185738. #if defined(PNG_oFFs_SUPPORTED)
  185739. if (info_ptr->valid & PNG_INFO_oFFs)
  185740. {
  185741. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185742. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185743. return (0);
  185744. else return (info_ptr->y_offset);
  185745. }
  185746. #else
  185747. return (0);
  185748. #endif
  185749. return (0);
  185750. }
  185751. png_int_32 PNGAPI
  185752. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185753. {
  185754. if (png_ptr != NULL && info_ptr != NULL)
  185755. #if defined(PNG_oFFs_SUPPORTED)
  185756. if (info_ptr->valid & PNG_INFO_oFFs)
  185757. {
  185758. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185759. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185760. return (0);
  185761. else return (info_ptr->x_offset);
  185762. }
  185763. #else
  185764. return (0);
  185765. #endif
  185766. return (0);
  185767. }
  185768. png_int_32 PNGAPI
  185769. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185770. {
  185771. if (png_ptr != NULL && info_ptr != NULL)
  185772. #if defined(PNG_oFFs_SUPPORTED)
  185773. if (info_ptr->valid & PNG_INFO_oFFs)
  185774. {
  185775. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185776. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185777. return (0);
  185778. else return (info_ptr->y_offset);
  185779. }
  185780. #else
  185781. return (0);
  185782. #endif
  185783. return (0);
  185784. }
  185785. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185786. png_uint_32 PNGAPI
  185787. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185788. {
  185789. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185790. *.0254 +.5));
  185791. }
  185792. png_uint_32 PNGAPI
  185793. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185794. {
  185795. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185796. *.0254 +.5));
  185797. }
  185798. png_uint_32 PNGAPI
  185799. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185800. {
  185801. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185802. *.0254 +.5));
  185803. }
  185804. float PNGAPI
  185805. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185806. {
  185807. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185808. *.00003937);
  185809. }
  185810. float PNGAPI
  185811. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185812. {
  185813. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185814. *.00003937);
  185815. }
  185816. #if defined(PNG_pHYs_SUPPORTED)
  185817. png_uint_32 PNGAPI
  185818. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185819. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185820. {
  185821. png_uint_32 retval = 0;
  185822. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185823. {
  185824. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185825. if (res_x != NULL)
  185826. {
  185827. *res_x = info_ptr->x_pixels_per_unit;
  185828. retval |= PNG_INFO_pHYs;
  185829. }
  185830. if (res_y != NULL)
  185831. {
  185832. *res_y = info_ptr->y_pixels_per_unit;
  185833. retval |= PNG_INFO_pHYs;
  185834. }
  185835. if (unit_type != NULL)
  185836. {
  185837. *unit_type = (int)info_ptr->phys_unit_type;
  185838. retval |= PNG_INFO_pHYs;
  185839. if(*unit_type == 1)
  185840. {
  185841. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185842. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185843. }
  185844. }
  185845. }
  185846. return (retval);
  185847. }
  185848. #endif /* PNG_pHYs_SUPPORTED */
  185849. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185850. /* png_get_channels really belongs in here, too, but it's been around longer */
  185851. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185852. png_byte PNGAPI
  185853. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185854. {
  185855. if (png_ptr != NULL && info_ptr != NULL)
  185856. return(info_ptr->channels);
  185857. else
  185858. return (0);
  185859. }
  185860. png_bytep PNGAPI
  185861. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185862. {
  185863. if (png_ptr != NULL && info_ptr != NULL)
  185864. return(info_ptr->signature);
  185865. else
  185866. return (NULL);
  185867. }
  185868. #if defined(PNG_bKGD_SUPPORTED)
  185869. png_uint_32 PNGAPI
  185870. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185871. png_color_16p *background)
  185872. {
  185873. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185874. && background != NULL)
  185875. {
  185876. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185877. *background = &(info_ptr->background);
  185878. return (PNG_INFO_bKGD);
  185879. }
  185880. return (0);
  185881. }
  185882. #endif
  185883. #if defined(PNG_cHRM_SUPPORTED)
  185884. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185885. png_uint_32 PNGAPI
  185886. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185887. double *white_x, double *white_y, double *red_x, double *red_y,
  185888. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185889. {
  185890. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185891. {
  185892. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185893. if (white_x != NULL)
  185894. *white_x = (double)info_ptr->x_white;
  185895. if (white_y != NULL)
  185896. *white_y = (double)info_ptr->y_white;
  185897. if (red_x != NULL)
  185898. *red_x = (double)info_ptr->x_red;
  185899. if (red_y != NULL)
  185900. *red_y = (double)info_ptr->y_red;
  185901. if (green_x != NULL)
  185902. *green_x = (double)info_ptr->x_green;
  185903. if (green_y != NULL)
  185904. *green_y = (double)info_ptr->y_green;
  185905. if (blue_x != NULL)
  185906. *blue_x = (double)info_ptr->x_blue;
  185907. if (blue_y != NULL)
  185908. *blue_y = (double)info_ptr->y_blue;
  185909. return (PNG_INFO_cHRM);
  185910. }
  185911. return (0);
  185912. }
  185913. #endif
  185914. #ifdef PNG_FIXED_POINT_SUPPORTED
  185915. png_uint_32 PNGAPI
  185916. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185917. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185918. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185919. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185920. {
  185921. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185922. {
  185923. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185924. if (white_x != NULL)
  185925. *white_x = info_ptr->int_x_white;
  185926. if (white_y != NULL)
  185927. *white_y = info_ptr->int_y_white;
  185928. if (red_x != NULL)
  185929. *red_x = info_ptr->int_x_red;
  185930. if (red_y != NULL)
  185931. *red_y = info_ptr->int_y_red;
  185932. if (green_x != NULL)
  185933. *green_x = info_ptr->int_x_green;
  185934. if (green_y != NULL)
  185935. *green_y = info_ptr->int_y_green;
  185936. if (blue_x != NULL)
  185937. *blue_x = info_ptr->int_x_blue;
  185938. if (blue_y != NULL)
  185939. *blue_y = info_ptr->int_y_blue;
  185940. return (PNG_INFO_cHRM);
  185941. }
  185942. return (0);
  185943. }
  185944. #endif
  185945. #endif
  185946. #if defined(PNG_gAMA_SUPPORTED)
  185947. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185948. png_uint_32 PNGAPI
  185949. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185950. {
  185951. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185952. && file_gamma != NULL)
  185953. {
  185954. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185955. *file_gamma = (double)info_ptr->gamma;
  185956. return (PNG_INFO_gAMA);
  185957. }
  185958. return (0);
  185959. }
  185960. #endif
  185961. #ifdef PNG_FIXED_POINT_SUPPORTED
  185962. png_uint_32 PNGAPI
  185963. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185964. png_fixed_point *int_file_gamma)
  185965. {
  185966. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185967. && int_file_gamma != NULL)
  185968. {
  185969. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185970. *int_file_gamma = info_ptr->int_gamma;
  185971. return (PNG_INFO_gAMA);
  185972. }
  185973. return (0);
  185974. }
  185975. #endif
  185976. #endif
  185977. #if defined(PNG_sRGB_SUPPORTED)
  185978. png_uint_32 PNGAPI
  185979. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185980. {
  185981. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185982. && file_srgb_intent != NULL)
  185983. {
  185984. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185985. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185986. return (PNG_INFO_sRGB);
  185987. }
  185988. return (0);
  185989. }
  185990. #endif
  185991. #if defined(PNG_iCCP_SUPPORTED)
  185992. png_uint_32 PNGAPI
  185993. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185994. png_charpp name, int *compression_type,
  185995. png_charpp profile, png_uint_32 *proflen)
  185996. {
  185997. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185998. && name != NULL && profile != NULL && proflen != NULL)
  185999. {
  186000. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186001. *name = info_ptr->iccp_name;
  186002. *profile = info_ptr->iccp_profile;
  186003. /* compression_type is a dummy so the API won't have to change
  186004. if we introduce multiple compression types later. */
  186005. *proflen = (int)info_ptr->iccp_proflen;
  186006. *compression_type = (int)info_ptr->iccp_compression;
  186007. return (PNG_INFO_iCCP);
  186008. }
  186009. return (0);
  186010. }
  186011. #endif
  186012. #if defined(PNG_sPLT_SUPPORTED)
  186013. png_uint_32 PNGAPI
  186014. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186015. png_sPLT_tpp spalettes)
  186016. {
  186017. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186018. {
  186019. *spalettes = info_ptr->splt_palettes;
  186020. return ((png_uint_32)info_ptr->splt_palettes_num);
  186021. }
  186022. return (0);
  186023. }
  186024. #endif
  186025. #if defined(PNG_hIST_SUPPORTED)
  186026. png_uint_32 PNGAPI
  186027. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186028. {
  186029. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186030. && hist != NULL)
  186031. {
  186032. png_debug1(1, "in %s retrieval function\n", "hIST");
  186033. *hist = info_ptr->hist;
  186034. return (PNG_INFO_hIST);
  186035. }
  186036. return (0);
  186037. }
  186038. #endif
  186039. png_uint_32 PNGAPI
  186040. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186041. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186042. int *color_type, int *interlace_type, int *compression_type,
  186043. int *filter_type)
  186044. {
  186045. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186046. bit_depth != NULL && color_type != NULL)
  186047. {
  186048. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186049. *width = info_ptr->width;
  186050. *height = info_ptr->height;
  186051. *bit_depth = info_ptr->bit_depth;
  186052. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186053. png_error(png_ptr, "Invalid bit depth");
  186054. *color_type = info_ptr->color_type;
  186055. if (info_ptr->color_type > 6)
  186056. png_error(png_ptr, "Invalid color type");
  186057. if (compression_type != NULL)
  186058. *compression_type = info_ptr->compression_type;
  186059. if (filter_type != NULL)
  186060. *filter_type = info_ptr->filter_type;
  186061. if (interlace_type != NULL)
  186062. *interlace_type = info_ptr->interlace_type;
  186063. /* check for potential overflow of rowbytes */
  186064. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186065. png_error(png_ptr, "Invalid image width");
  186066. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186067. png_error(png_ptr, "Invalid image height");
  186068. if (info_ptr->width > (PNG_UINT_32_MAX
  186069. >> 3) /* 8-byte RGBA pixels */
  186070. - 64 /* bigrowbuf hack */
  186071. - 1 /* filter byte */
  186072. - 7*8 /* rounding of width to multiple of 8 pixels */
  186073. - 8) /* extra max_pixel_depth pad */
  186074. {
  186075. png_warning(png_ptr,
  186076. "Width too large for libpng to process image data.");
  186077. }
  186078. return (1);
  186079. }
  186080. return (0);
  186081. }
  186082. #if defined(PNG_oFFs_SUPPORTED)
  186083. png_uint_32 PNGAPI
  186084. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186085. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186086. {
  186087. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186088. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186089. {
  186090. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186091. *offset_x = info_ptr->x_offset;
  186092. *offset_y = info_ptr->y_offset;
  186093. *unit_type = (int)info_ptr->offset_unit_type;
  186094. return (PNG_INFO_oFFs);
  186095. }
  186096. return (0);
  186097. }
  186098. #endif
  186099. #if defined(PNG_pCAL_SUPPORTED)
  186100. png_uint_32 PNGAPI
  186101. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186102. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186103. png_charp *units, png_charpp *params)
  186104. {
  186105. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186106. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186107. nparams != NULL && units != NULL && params != NULL)
  186108. {
  186109. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186110. *purpose = info_ptr->pcal_purpose;
  186111. *X0 = info_ptr->pcal_X0;
  186112. *X1 = info_ptr->pcal_X1;
  186113. *type = (int)info_ptr->pcal_type;
  186114. *nparams = (int)info_ptr->pcal_nparams;
  186115. *units = info_ptr->pcal_units;
  186116. *params = info_ptr->pcal_params;
  186117. return (PNG_INFO_pCAL);
  186118. }
  186119. return (0);
  186120. }
  186121. #endif
  186122. #if defined(PNG_sCAL_SUPPORTED)
  186123. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186124. png_uint_32 PNGAPI
  186125. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186126. int *unit, double *width, double *height)
  186127. {
  186128. if (png_ptr != NULL && info_ptr != NULL &&
  186129. (info_ptr->valid & PNG_INFO_sCAL))
  186130. {
  186131. *unit = info_ptr->scal_unit;
  186132. *width = info_ptr->scal_pixel_width;
  186133. *height = info_ptr->scal_pixel_height;
  186134. return (PNG_INFO_sCAL);
  186135. }
  186136. return(0);
  186137. }
  186138. #else
  186139. #ifdef PNG_FIXED_POINT_SUPPORTED
  186140. png_uint_32 PNGAPI
  186141. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186142. int *unit, png_charpp width, png_charpp height)
  186143. {
  186144. if (png_ptr != NULL && info_ptr != NULL &&
  186145. (info_ptr->valid & PNG_INFO_sCAL))
  186146. {
  186147. *unit = info_ptr->scal_unit;
  186148. *width = info_ptr->scal_s_width;
  186149. *height = info_ptr->scal_s_height;
  186150. return (PNG_INFO_sCAL);
  186151. }
  186152. return(0);
  186153. }
  186154. #endif
  186155. #endif
  186156. #endif
  186157. #if defined(PNG_pHYs_SUPPORTED)
  186158. png_uint_32 PNGAPI
  186159. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186160. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186161. {
  186162. png_uint_32 retval = 0;
  186163. if (png_ptr != NULL && info_ptr != NULL &&
  186164. (info_ptr->valid & PNG_INFO_pHYs))
  186165. {
  186166. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186167. if (res_x != NULL)
  186168. {
  186169. *res_x = info_ptr->x_pixels_per_unit;
  186170. retval |= PNG_INFO_pHYs;
  186171. }
  186172. if (res_y != NULL)
  186173. {
  186174. *res_y = info_ptr->y_pixels_per_unit;
  186175. retval |= PNG_INFO_pHYs;
  186176. }
  186177. if (unit_type != NULL)
  186178. {
  186179. *unit_type = (int)info_ptr->phys_unit_type;
  186180. retval |= PNG_INFO_pHYs;
  186181. }
  186182. }
  186183. return (retval);
  186184. }
  186185. #endif
  186186. png_uint_32 PNGAPI
  186187. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186188. int *num_palette)
  186189. {
  186190. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186191. && palette != NULL)
  186192. {
  186193. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186194. *palette = info_ptr->palette;
  186195. *num_palette = info_ptr->num_palette;
  186196. png_debug1(3, "num_palette = %d\n", *num_palette);
  186197. return (PNG_INFO_PLTE);
  186198. }
  186199. return (0);
  186200. }
  186201. #if defined(PNG_sBIT_SUPPORTED)
  186202. png_uint_32 PNGAPI
  186203. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186204. {
  186205. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186206. && sig_bit != NULL)
  186207. {
  186208. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186209. *sig_bit = &(info_ptr->sig_bit);
  186210. return (PNG_INFO_sBIT);
  186211. }
  186212. return (0);
  186213. }
  186214. #endif
  186215. #if defined(PNG_TEXT_SUPPORTED)
  186216. png_uint_32 PNGAPI
  186217. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186218. int *num_text)
  186219. {
  186220. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186221. {
  186222. png_debug1(1, "in %s retrieval function\n",
  186223. (png_ptr->chunk_name[0] == '\0' ? "text"
  186224. : (png_const_charp)png_ptr->chunk_name));
  186225. if (text_ptr != NULL)
  186226. *text_ptr = info_ptr->text;
  186227. if (num_text != NULL)
  186228. *num_text = info_ptr->num_text;
  186229. return ((png_uint_32)info_ptr->num_text);
  186230. }
  186231. if (num_text != NULL)
  186232. *num_text = 0;
  186233. return(0);
  186234. }
  186235. #endif
  186236. #if defined(PNG_tIME_SUPPORTED)
  186237. png_uint_32 PNGAPI
  186238. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186239. {
  186240. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186241. && mod_time != NULL)
  186242. {
  186243. png_debug1(1, "in %s retrieval function\n", "tIME");
  186244. *mod_time = &(info_ptr->mod_time);
  186245. return (PNG_INFO_tIME);
  186246. }
  186247. return (0);
  186248. }
  186249. #endif
  186250. #if defined(PNG_tRNS_SUPPORTED)
  186251. png_uint_32 PNGAPI
  186252. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186253. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186254. {
  186255. png_uint_32 retval = 0;
  186256. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186257. {
  186258. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186259. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186260. {
  186261. if (trans != NULL)
  186262. {
  186263. *trans = info_ptr->trans;
  186264. retval |= PNG_INFO_tRNS;
  186265. }
  186266. if (trans_values != NULL)
  186267. *trans_values = &(info_ptr->trans_values);
  186268. }
  186269. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186270. {
  186271. if (trans_values != NULL)
  186272. {
  186273. *trans_values = &(info_ptr->trans_values);
  186274. retval |= PNG_INFO_tRNS;
  186275. }
  186276. if(trans != NULL)
  186277. *trans = NULL;
  186278. }
  186279. if(num_trans != NULL)
  186280. {
  186281. *num_trans = info_ptr->num_trans;
  186282. retval |= PNG_INFO_tRNS;
  186283. }
  186284. }
  186285. return (retval);
  186286. }
  186287. #endif
  186288. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186289. png_uint_32 PNGAPI
  186290. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186291. png_unknown_chunkpp unknowns)
  186292. {
  186293. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186294. {
  186295. *unknowns = info_ptr->unknown_chunks;
  186296. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186297. }
  186298. return (0);
  186299. }
  186300. #endif
  186301. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186302. png_byte PNGAPI
  186303. png_get_rgb_to_gray_status (png_structp png_ptr)
  186304. {
  186305. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186306. }
  186307. #endif
  186308. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186309. png_voidp PNGAPI
  186310. png_get_user_chunk_ptr(png_structp png_ptr)
  186311. {
  186312. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186313. }
  186314. #endif
  186315. #ifdef PNG_WRITE_SUPPORTED
  186316. png_uint_32 PNGAPI
  186317. png_get_compression_buffer_size(png_structp png_ptr)
  186318. {
  186319. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186320. }
  186321. #endif
  186322. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186323. #ifndef PNG_1_0_X
  186324. /* this function was added to libpng 1.2.0 and should exist by default */
  186325. png_uint_32 PNGAPI
  186326. png_get_asm_flags (png_structp png_ptr)
  186327. {
  186328. /* obsolete, to be removed from libpng-1.4.0 */
  186329. return (png_ptr? 0L: 0L);
  186330. }
  186331. /* this function was added to libpng 1.2.0 and should exist by default */
  186332. png_uint_32 PNGAPI
  186333. png_get_asm_flagmask (int flag_select)
  186334. {
  186335. /* obsolete, to be removed from libpng-1.4.0 */
  186336. flag_select=flag_select;
  186337. return 0L;
  186338. }
  186339. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186340. /* this function was added to libpng 1.2.0 */
  186341. png_uint_32 PNGAPI
  186342. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186343. {
  186344. /* obsolete, to be removed from libpng-1.4.0 */
  186345. flag_select=flag_select;
  186346. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186347. return 0L;
  186348. }
  186349. /* this function was added to libpng 1.2.0 */
  186350. png_byte PNGAPI
  186351. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186352. {
  186353. /* obsolete, to be removed from libpng-1.4.0 */
  186354. return (png_ptr? 0: 0);
  186355. }
  186356. /* this function was added to libpng 1.2.0 */
  186357. png_uint_32 PNGAPI
  186358. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186359. {
  186360. /* obsolete, to be removed from libpng-1.4.0 */
  186361. return (png_ptr? 0L: 0L);
  186362. }
  186363. #endif /* ?PNG_1_0_X */
  186364. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186365. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186366. /* these functions were added to libpng 1.2.6 */
  186367. png_uint_32 PNGAPI
  186368. png_get_user_width_max (png_structp png_ptr)
  186369. {
  186370. return (png_ptr? png_ptr->user_width_max : 0);
  186371. }
  186372. png_uint_32 PNGAPI
  186373. png_get_user_height_max (png_structp png_ptr)
  186374. {
  186375. return (png_ptr? png_ptr->user_height_max : 0);
  186376. }
  186377. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186378. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186379. /*** End of inlined file: pngget.c ***/
  186380. /*** Start of inlined file: pngmem.c ***/
  186381. /* pngmem.c - stub functions for memory allocation
  186382. *
  186383. * Last changed in libpng 1.2.13 November 13, 2006
  186384. * For conditions of distribution and use, see copyright notice in png.h
  186385. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186386. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186387. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186388. *
  186389. * This file provides a location for all memory allocation. Users who
  186390. * need special memory handling are expected to supply replacement
  186391. * functions for png_malloc() and png_free(), and to use
  186392. * png_create_read_struct_2() and png_create_write_struct_2() to
  186393. * identify the replacement functions.
  186394. */
  186395. #define PNG_INTERNAL
  186396. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186397. /* Borland DOS special memory handler */
  186398. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186399. /* if you change this, be sure to change the one in png.h also */
  186400. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186401. by a single call to calloc() if this is thought to improve performance. */
  186402. png_voidp /* PRIVATE */
  186403. png_create_struct(int type)
  186404. {
  186405. #ifdef PNG_USER_MEM_SUPPORTED
  186406. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186407. }
  186408. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186409. png_voidp /* PRIVATE */
  186410. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186411. {
  186412. #endif /* PNG_USER_MEM_SUPPORTED */
  186413. png_size_t size;
  186414. png_voidp struct_ptr;
  186415. if (type == PNG_STRUCT_INFO)
  186416. size = png_sizeof(png_info);
  186417. else if (type == PNG_STRUCT_PNG)
  186418. size = png_sizeof(png_struct);
  186419. else
  186420. return (png_get_copyright(NULL));
  186421. #ifdef PNG_USER_MEM_SUPPORTED
  186422. if(malloc_fn != NULL)
  186423. {
  186424. png_struct dummy_struct;
  186425. png_structp png_ptr = &dummy_struct;
  186426. png_ptr->mem_ptr=mem_ptr;
  186427. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186428. }
  186429. else
  186430. #endif /* PNG_USER_MEM_SUPPORTED */
  186431. struct_ptr = (png_voidp)farmalloc(size);
  186432. if (struct_ptr != NULL)
  186433. png_memset(struct_ptr, 0, size);
  186434. return (struct_ptr);
  186435. }
  186436. /* Free memory allocated by a png_create_struct() call */
  186437. void /* PRIVATE */
  186438. png_destroy_struct(png_voidp struct_ptr)
  186439. {
  186440. #ifdef PNG_USER_MEM_SUPPORTED
  186441. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186442. }
  186443. /* Free memory allocated by a png_create_struct() call */
  186444. void /* PRIVATE */
  186445. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186446. png_voidp mem_ptr)
  186447. {
  186448. #endif
  186449. if (struct_ptr != NULL)
  186450. {
  186451. #ifdef PNG_USER_MEM_SUPPORTED
  186452. if(free_fn != NULL)
  186453. {
  186454. png_struct dummy_struct;
  186455. png_structp png_ptr = &dummy_struct;
  186456. png_ptr->mem_ptr=mem_ptr;
  186457. (*(free_fn))(png_ptr, struct_ptr);
  186458. return;
  186459. }
  186460. #endif /* PNG_USER_MEM_SUPPORTED */
  186461. farfree (struct_ptr);
  186462. }
  186463. }
  186464. /* Allocate memory. For reasonable files, size should never exceed
  186465. * 64K. However, zlib may allocate more then 64K if you don't tell
  186466. * it not to. See zconf.h and png.h for more information. zlib does
  186467. * need to allocate exactly 64K, so whatever you call here must
  186468. * have the ability to do that.
  186469. *
  186470. * Borland seems to have a problem in DOS mode for exactly 64K.
  186471. * It gives you a segment with an offset of 8 (perhaps to store its
  186472. * memory stuff). zlib doesn't like this at all, so we have to
  186473. * detect and deal with it. This code should not be needed in
  186474. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186475. * been updated by Alexander Lehmann for version 0.89 to waste less
  186476. * memory.
  186477. *
  186478. * Note that we can't use png_size_t for the "size" declaration,
  186479. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186480. * result, we would be truncating potentially larger memory requests
  186481. * (which should cause a fatal error) and introducing major problems.
  186482. */
  186483. png_voidp PNGAPI
  186484. png_malloc(png_structp png_ptr, png_uint_32 size)
  186485. {
  186486. png_voidp ret;
  186487. if (png_ptr == NULL || size == 0)
  186488. return (NULL);
  186489. #ifdef PNG_USER_MEM_SUPPORTED
  186490. if(png_ptr->malloc_fn != NULL)
  186491. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186492. else
  186493. ret = (png_malloc_default(png_ptr, size));
  186494. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186495. png_error(png_ptr, "Out of memory!");
  186496. return (ret);
  186497. }
  186498. png_voidp PNGAPI
  186499. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186500. {
  186501. png_voidp ret;
  186502. #endif /* PNG_USER_MEM_SUPPORTED */
  186503. if (png_ptr == NULL || size == 0)
  186504. return (NULL);
  186505. #ifdef PNG_MAX_MALLOC_64K
  186506. if (size > (png_uint_32)65536L)
  186507. {
  186508. png_warning(png_ptr, "Cannot Allocate > 64K");
  186509. ret = NULL;
  186510. }
  186511. else
  186512. #endif
  186513. if (size != (size_t)size)
  186514. ret = NULL;
  186515. else if (size == (png_uint_32)65536L)
  186516. {
  186517. if (png_ptr->offset_table == NULL)
  186518. {
  186519. /* try to see if we need to do any of this fancy stuff */
  186520. ret = farmalloc(size);
  186521. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186522. {
  186523. int num_blocks;
  186524. png_uint_32 total_size;
  186525. png_bytep table;
  186526. int i;
  186527. png_byte huge * hptr;
  186528. if (ret != NULL)
  186529. {
  186530. farfree(ret);
  186531. ret = NULL;
  186532. }
  186533. if(png_ptr->zlib_window_bits > 14)
  186534. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186535. else
  186536. num_blocks = 1;
  186537. if (png_ptr->zlib_mem_level >= 7)
  186538. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186539. else
  186540. num_blocks++;
  186541. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186542. table = farmalloc(total_size);
  186543. if (table == NULL)
  186544. {
  186545. #ifndef PNG_USER_MEM_SUPPORTED
  186546. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186547. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186548. else
  186549. png_warning(png_ptr, "Out Of Memory.");
  186550. #endif
  186551. return (NULL);
  186552. }
  186553. if ((png_size_t)table & 0xfff0)
  186554. {
  186555. #ifndef PNG_USER_MEM_SUPPORTED
  186556. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186557. png_error(png_ptr,
  186558. "Farmalloc didn't return normalized pointer");
  186559. else
  186560. png_warning(png_ptr,
  186561. "Farmalloc didn't return normalized pointer");
  186562. #endif
  186563. return (NULL);
  186564. }
  186565. png_ptr->offset_table = table;
  186566. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186567. png_sizeof (png_bytep));
  186568. if (png_ptr->offset_table_ptr == NULL)
  186569. {
  186570. #ifndef PNG_USER_MEM_SUPPORTED
  186571. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186572. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186573. else
  186574. png_warning(png_ptr, "Out Of memory.");
  186575. #endif
  186576. return (NULL);
  186577. }
  186578. hptr = (png_byte huge *)table;
  186579. if ((png_size_t)hptr & 0xf)
  186580. {
  186581. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186582. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186583. }
  186584. for (i = 0; i < num_blocks; i++)
  186585. {
  186586. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186587. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186588. }
  186589. png_ptr->offset_table_number = num_blocks;
  186590. png_ptr->offset_table_count = 0;
  186591. png_ptr->offset_table_count_free = 0;
  186592. }
  186593. }
  186594. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186595. {
  186596. #ifndef PNG_USER_MEM_SUPPORTED
  186597. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186598. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186599. else
  186600. png_warning(png_ptr, "Out of Memory.");
  186601. #endif
  186602. return (NULL);
  186603. }
  186604. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186605. }
  186606. else
  186607. ret = farmalloc(size);
  186608. #ifndef PNG_USER_MEM_SUPPORTED
  186609. if (ret == NULL)
  186610. {
  186611. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186612. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186613. else
  186614. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186615. }
  186616. #endif
  186617. return (ret);
  186618. }
  186619. /* free a pointer allocated by png_malloc(). In the default
  186620. configuration, png_ptr is not used, but is passed in case it
  186621. is needed. If ptr is NULL, return without taking any action. */
  186622. void PNGAPI
  186623. png_free(png_structp png_ptr, png_voidp ptr)
  186624. {
  186625. if (png_ptr == NULL || ptr == NULL)
  186626. return;
  186627. #ifdef PNG_USER_MEM_SUPPORTED
  186628. if (png_ptr->free_fn != NULL)
  186629. {
  186630. (*(png_ptr->free_fn))(png_ptr, ptr);
  186631. return;
  186632. }
  186633. else png_free_default(png_ptr, ptr);
  186634. }
  186635. void PNGAPI
  186636. png_free_default(png_structp png_ptr, png_voidp ptr)
  186637. {
  186638. #endif /* PNG_USER_MEM_SUPPORTED */
  186639. if(png_ptr == NULL) return;
  186640. if (png_ptr->offset_table != NULL)
  186641. {
  186642. int i;
  186643. for (i = 0; i < png_ptr->offset_table_count; i++)
  186644. {
  186645. if (ptr == png_ptr->offset_table_ptr[i])
  186646. {
  186647. ptr = NULL;
  186648. png_ptr->offset_table_count_free++;
  186649. break;
  186650. }
  186651. }
  186652. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186653. {
  186654. farfree(png_ptr->offset_table);
  186655. farfree(png_ptr->offset_table_ptr);
  186656. png_ptr->offset_table = NULL;
  186657. png_ptr->offset_table_ptr = NULL;
  186658. }
  186659. }
  186660. if (ptr != NULL)
  186661. {
  186662. farfree(ptr);
  186663. }
  186664. }
  186665. #else /* Not the Borland DOS special memory handler */
  186666. /* Allocate memory for a png_struct or a png_info. The malloc and
  186667. memset can be replaced by a single call to calloc() if this is thought
  186668. to improve performance noticably. */
  186669. png_voidp /* PRIVATE */
  186670. png_create_struct(int type)
  186671. {
  186672. #ifdef PNG_USER_MEM_SUPPORTED
  186673. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186674. }
  186675. /* Allocate memory for a png_struct or a png_info. The malloc and
  186676. memset can be replaced by a single call to calloc() if this is thought
  186677. to improve performance noticably. */
  186678. png_voidp /* PRIVATE */
  186679. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186680. {
  186681. #endif /* PNG_USER_MEM_SUPPORTED */
  186682. png_size_t size;
  186683. png_voidp struct_ptr;
  186684. if (type == PNG_STRUCT_INFO)
  186685. size = png_sizeof(png_info);
  186686. else if (type == PNG_STRUCT_PNG)
  186687. size = png_sizeof(png_struct);
  186688. else
  186689. return (NULL);
  186690. #ifdef PNG_USER_MEM_SUPPORTED
  186691. if(malloc_fn != NULL)
  186692. {
  186693. png_struct dummy_struct;
  186694. png_structp png_ptr = &dummy_struct;
  186695. png_ptr->mem_ptr=mem_ptr;
  186696. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186697. if (struct_ptr != NULL)
  186698. png_memset(struct_ptr, 0, size);
  186699. return (struct_ptr);
  186700. }
  186701. #endif /* PNG_USER_MEM_SUPPORTED */
  186702. #if defined(__TURBOC__) && !defined(__FLAT__)
  186703. struct_ptr = (png_voidp)farmalloc(size);
  186704. #else
  186705. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186706. struct_ptr = (png_voidp)halloc(size,1);
  186707. # else
  186708. struct_ptr = (png_voidp)malloc(size);
  186709. # endif
  186710. #endif
  186711. if (struct_ptr != NULL)
  186712. png_memset(struct_ptr, 0, size);
  186713. return (struct_ptr);
  186714. }
  186715. /* Free memory allocated by a png_create_struct() call */
  186716. void /* PRIVATE */
  186717. png_destroy_struct(png_voidp struct_ptr)
  186718. {
  186719. #ifdef PNG_USER_MEM_SUPPORTED
  186720. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186721. }
  186722. /* Free memory allocated by a png_create_struct() call */
  186723. void /* PRIVATE */
  186724. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186725. png_voidp mem_ptr)
  186726. {
  186727. #endif /* PNG_USER_MEM_SUPPORTED */
  186728. if (struct_ptr != NULL)
  186729. {
  186730. #ifdef PNG_USER_MEM_SUPPORTED
  186731. if(free_fn != NULL)
  186732. {
  186733. png_struct dummy_struct;
  186734. png_structp png_ptr = &dummy_struct;
  186735. png_ptr->mem_ptr=mem_ptr;
  186736. (*(free_fn))(png_ptr, struct_ptr);
  186737. return;
  186738. }
  186739. #endif /* PNG_USER_MEM_SUPPORTED */
  186740. #if defined(__TURBOC__) && !defined(__FLAT__)
  186741. farfree(struct_ptr);
  186742. #else
  186743. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186744. hfree(struct_ptr);
  186745. # else
  186746. free(struct_ptr);
  186747. # endif
  186748. #endif
  186749. }
  186750. }
  186751. /* Allocate memory. For reasonable files, size should never exceed
  186752. 64K. However, zlib may allocate more then 64K if you don't tell
  186753. it not to. See zconf.h and png.h for more information. zlib does
  186754. need to allocate exactly 64K, so whatever you call here must
  186755. have the ability to do that. */
  186756. png_voidp PNGAPI
  186757. png_malloc(png_structp png_ptr, png_uint_32 size)
  186758. {
  186759. png_voidp ret;
  186760. #ifdef PNG_USER_MEM_SUPPORTED
  186761. if (png_ptr == NULL || size == 0)
  186762. return (NULL);
  186763. if(png_ptr->malloc_fn != NULL)
  186764. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186765. else
  186766. ret = (png_malloc_default(png_ptr, size));
  186767. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186768. png_error(png_ptr, "Out of Memory!");
  186769. return (ret);
  186770. }
  186771. png_voidp PNGAPI
  186772. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186773. {
  186774. png_voidp ret;
  186775. #endif /* PNG_USER_MEM_SUPPORTED */
  186776. if (png_ptr == NULL || size == 0)
  186777. return (NULL);
  186778. #ifdef PNG_MAX_MALLOC_64K
  186779. if (size > (png_uint_32)65536L)
  186780. {
  186781. #ifndef PNG_USER_MEM_SUPPORTED
  186782. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186783. png_error(png_ptr, "Cannot Allocate > 64K");
  186784. else
  186785. #endif
  186786. return NULL;
  186787. }
  186788. #endif
  186789. /* Check for overflow */
  186790. #if defined(__TURBOC__) && !defined(__FLAT__)
  186791. if (size != (unsigned long)size)
  186792. ret = NULL;
  186793. else
  186794. ret = farmalloc(size);
  186795. #else
  186796. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186797. if (size != (unsigned long)size)
  186798. ret = NULL;
  186799. else
  186800. ret = halloc(size, 1);
  186801. # else
  186802. if (size != (size_t)size)
  186803. ret = NULL;
  186804. else
  186805. ret = malloc((size_t)size);
  186806. # endif
  186807. #endif
  186808. #ifndef PNG_USER_MEM_SUPPORTED
  186809. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186810. png_error(png_ptr, "Out of Memory");
  186811. #endif
  186812. return (ret);
  186813. }
  186814. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186815. without taking any action. */
  186816. void PNGAPI
  186817. png_free(png_structp png_ptr, png_voidp ptr)
  186818. {
  186819. if (png_ptr == NULL || ptr == NULL)
  186820. return;
  186821. #ifdef PNG_USER_MEM_SUPPORTED
  186822. if (png_ptr->free_fn != NULL)
  186823. {
  186824. (*(png_ptr->free_fn))(png_ptr, ptr);
  186825. return;
  186826. }
  186827. else png_free_default(png_ptr, ptr);
  186828. }
  186829. void PNGAPI
  186830. png_free_default(png_structp png_ptr, png_voidp ptr)
  186831. {
  186832. if (png_ptr == NULL || ptr == NULL)
  186833. return;
  186834. #endif /* PNG_USER_MEM_SUPPORTED */
  186835. #if defined(__TURBOC__) && !defined(__FLAT__)
  186836. farfree(ptr);
  186837. #else
  186838. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186839. hfree(ptr);
  186840. # else
  186841. free(ptr);
  186842. # endif
  186843. #endif
  186844. }
  186845. #endif /* Not Borland DOS special memory handler */
  186846. #if defined(PNG_1_0_X)
  186847. # define png_malloc_warn png_malloc
  186848. #else
  186849. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186850. * function will set up png_malloc() to issue a png_warning and return NULL
  186851. * instead of issuing a png_error, if it fails to allocate the requested
  186852. * memory.
  186853. */
  186854. png_voidp PNGAPI
  186855. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186856. {
  186857. png_voidp ptr;
  186858. png_uint_32 save_flags;
  186859. if(png_ptr == NULL) return (NULL);
  186860. save_flags=png_ptr->flags;
  186861. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186862. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186863. png_ptr->flags=save_flags;
  186864. return(ptr);
  186865. }
  186866. #endif
  186867. png_voidp PNGAPI
  186868. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186869. png_uint_32 length)
  186870. {
  186871. png_size_t size;
  186872. size = (png_size_t)length;
  186873. if ((png_uint_32)size != length)
  186874. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186875. return(png_memcpy (s1, s2, size));
  186876. }
  186877. png_voidp PNGAPI
  186878. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186879. png_uint_32 length)
  186880. {
  186881. png_size_t size;
  186882. size = (png_size_t)length;
  186883. if ((png_uint_32)size != length)
  186884. png_error(png_ptr,"Overflow in png_memset_check.");
  186885. return (png_memset (s1, value, size));
  186886. }
  186887. #ifdef PNG_USER_MEM_SUPPORTED
  186888. /* This function is called when the application wants to use another method
  186889. * of allocating and freeing memory.
  186890. */
  186891. void PNGAPI
  186892. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186893. malloc_fn, png_free_ptr free_fn)
  186894. {
  186895. if(png_ptr != NULL) {
  186896. png_ptr->mem_ptr = mem_ptr;
  186897. png_ptr->malloc_fn = malloc_fn;
  186898. png_ptr->free_fn = free_fn;
  186899. }
  186900. }
  186901. /* This function returns a pointer to the mem_ptr associated with the user
  186902. * functions. The application should free any memory associated with this
  186903. * pointer before png_write_destroy and png_read_destroy are called.
  186904. */
  186905. png_voidp PNGAPI
  186906. png_get_mem_ptr(png_structp png_ptr)
  186907. {
  186908. if(png_ptr == NULL) return (NULL);
  186909. return ((png_voidp)png_ptr->mem_ptr);
  186910. }
  186911. #endif /* PNG_USER_MEM_SUPPORTED */
  186912. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186913. /*** End of inlined file: pngmem.c ***/
  186914. /*** Start of inlined file: pngread.c ***/
  186915. /* pngread.c - read a PNG file
  186916. *
  186917. * Last changed in libpng 1.2.20 September 7, 2007
  186918. * For conditions of distribution and use, see copyright notice in png.h
  186919. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186920. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186921. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186922. *
  186923. * This file contains routines that an application calls directly to
  186924. * read a PNG file or stream.
  186925. */
  186926. #define PNG_INTERNAL
  186927. #if defined(PNG_READ_SUPPORTED)
  186928. /* Create a PNG structure for reading, and allocate any memory needed. */
  186929. png_structp PNGAPI
  186930. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186931. png_error_ptr error_fn, png_error_ptr warn_fn)
  186932. {
  186933. #ifdef PNG_USER_MEM_SUPPORTED
  186934. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186935. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186936. }
  186937. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186938. png_structp PNGAPI
  186939. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186940. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186941. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186942. {
  186943. #endif /* PNG_USER_MEM_SUPPORTED */
  186944. png_structp png_ptr;
  186945. #ifdef PNG_SETJMP_SUPPORTED
  186946. #ifdef USE_FAR_KEYWORD
  186947. jmp_buf jmpbuf;
  186948. #endif
  186949. #endif
  186950. int i;
  186951. png_debug(1, "in png_create_read_struct\n");
  186952. #ifdef PNG_USER_MEM_SUPPORTED
  186953. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186954. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186955. #else
  186956. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186957. #endif
  186958. if (png_ptr == NULL)
  186959. return (NULL);
  186960. /* added at libpng-1.2.6 */
  186961. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186962. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186963. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186964. #endif
  186965. #ifdef PNG_SETJMP_SUPPORTED
  186966. #ifdef USE_FAR_KEYWORD
  186967. if (setjmp(jmpbuf))
  186968. #else
  186969. if (setjmp(png_ptr->jmpbuf))
  186970. #endif
  186971. {
  186972. png_free(png_ptr, png_ptr->zbuf);
  186973. png_ptr->zbuf=NULL;
  186974. #ifdef PNG_USER_MEM_SUPPORTED
  186975. png_destroy_struct_2((png_voidp)png_ptr,
  186976. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186977. #else
  186978. png_destroy_struct((png_voidp)png_ptr);
  186979. #endif
  186980. return (NULL);
  186981. }
  186982. #ifdef USE_FAR_KEYWORD
  186983. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186984. #endif
  186985. #endif
  186986. #ifdef PNG_USER_MEM_SUPPORTED
  186987. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186988. #endif
  186989. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186990. i=0;
  186991. do
  186992. {
  186993. if(user_png_ver[i] != png_libpng_ver[i])
  186994. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186995. } while (png_libpng_ver[i++]);
  186996. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186997. {
  186998. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186999. * we must recompile any applications that use any older library version.
  187000. * For versions after libpng 1.0, we will be compatible, so we need
  187001. * only check the first digit.
  187002. */
  187003. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187004. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187005. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187006. {
  187007. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187008. char msg[80];
  187009. if (user_png_ver)
  187010. {
  187011. png_snprintf(msg, 80,
  187012. "Application was compiled with png.h from libpng-%.20s",
  187013. user_png_ver);
  187014. png_warning(png_ptr, msg);
  187015. }
  187016. png_snprintf(msg, 80,
  187017. "Application is running with png.c from libpng-%.20s",
  187018. png_libpng_ver);
  187019. png_warning(png_ptr, msg);
  187020. #endif
  187021. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187022. png_ptr->flags=0;
  187023. #endif
  187024. png_error(png_ptr,
  187025. "Incompatible libpng version in application and library");
  187026. }
  187027. }
  187028. /* initialize zbuf - compression buffer */
  187029. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187030. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187031. (png_uint_32)png_ptr->zbuf_size);
  187032. png_ptr->zstream.zalloc = png_zalloc;
  187033. png_ptr->zstream.zfree = png_zfree;
  187034. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187035. switch (inflateInit(&png_ptr->zstream))
  187036. {
  187037. case Z_OK: /* Do nothing */ break;
  187038. case Z_MEM_ERROR:
  187039. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187040. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187041. default: png_error(png_ptr, "Unknown zlib error");
  187042. }
  187043. png_ptr->zstream.next_out = png_ptr->zbuf;
  187044. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187045. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187046. #ifdef PNG_SETJMP_SUPPORTED
  187047. /* Applications that neglect to set up their own setjmp() and then encounter
  187048. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187049. abort instead of returning. */
  187050. #ifdef USE_FAR_KEYWORD
  187051. if (setjmp(jmpbuf))
  187052. PNG_ABORT();
  187053. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187054. #else
  187055. if (setjmp(png_ptr->jmpbuf))
  187056. PNG_ABORT();
  187057. #endif
  187058. #endif
  187059. return (png_ptr);
  187060. }
  187061. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187062. /* Initialize PNG structure for reading, and allocate any memory needed.
  187063. This interface is deprecated in favour of the png_create_read_struct(),
  187064. and it will disappear as of libpng-1.3.0. */
  187065. #undef png_read_init
  187066. void PNGAPI
  187067. png_read_init(png_structp png_ptr)
  187068. {
  187069. /* We only come here via pre-1.0.7-compiled applications */
  187070. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187071. }
  187072. void PNGAPI
  187073. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187074. png_size_t png_struct_size, png_size_t png_info_size)
  187075. {
  187076. /* We only come here via pre-1.0.12-compiled applications */
  187077. if(png_ptr == NULL) return;
  187078. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187079. if(png_sizeof(png_struct) > png_struct_size ||
  187080. png_sizeof(png_info) > png_info_size)
  187081. {
  187082. char msg[80];
  187083. png_ptr->warning_fn=NULL;
  187084. if (user_png_ver)
  187085. {
  187086. png_snprintf(msg, 80,
  187087. "Application was compiled with png.h from libpng-%.20s",
  187088. user_png_ver);
  187089. png_warning(png_ptr, msg);
  187090. }
  187091. png_snprintf(msg, 80,
  187092. "Application is running with png.c from libpng-%.20s",
  187093. png_libpng_ver);
  187094. png_warning(png_ptr, msg);
  187095. }
  187096. #endif
  187097. if(png_sizeof(png_struct) > png_struct_size)
  187098. {
  187099. png_ptr->error_fn=NULL;
  187100. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187101. png_ptr->flags=0;
  187102. #endif
  187103. png_error(png_ptr,
  187104. "The png struct allocated by the application for reading is too small.");
  187105. }
  187106. if(png_sizeof(png_info) > png_info_size)
  187107. {
  187108. png_ptr->error_fn=NULL;
  187109. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187110. png_ptr->flags=0;
  187111. #endif
  187112. png_error(png_ptr,
  187113. "The info struct allocated by application for reading is too small.");
  187114. }
  187115. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187116. }
  187117. #endif /* PNG_1_0_X || PNG_1_2_X */
  187118. void PNGAPI
  187119. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187120. png_size_t png_struct_size)
  187121. {
  187122. #ifdef PNG_SETJMP_SUPPORTED
  187123. jmp_buf tmp_jmp; /* to save current jump buffer */
  187124. #endif
  187125. int i=0;
  187126. png_structp png_ptr=*ptr_ptr;
  187127. if(png_ptr == NULL) return;
  187128. do
  187129. {
  187130. if(user_png_ver[i] != png_libpng_ver[i])
  187131. {
  187132. #ifdef PNG_LEGACY_SUPPORTED
  187133. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187134. #else
  187135. png_ptr->warning_fn=NULL;
  187136. png_warning(png_ptr,
  187137. "Application uses deprecated png_read_init() and should be recompiled.");
  187138. break;
  187139. #endif
  187140. }
  187141. } while (png_libpng_ver[i++]);
  187142. png_debug(1, "in png_read_init_3\n");
  187143. #ifdef PNG_SETJMP_SUPPORTED
  187144. /* save jump buffer and error functions */
  187145. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187146. #endif
  187147. if(png_sizeof(png_struct) > png_struct_size)
  187148. {
  187149. png_destroy_struct(png_ptr);
  187150. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187151. png_ptr = *ptr_ptr;
  187152. }
  187153. /* reset all variables to 0 */
  187154. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187155. #ifdef PNG_SETJMP_SUPPORTED
  187156. /* restore jump buffer */
  187157. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187158. #endif
  187159. /* added at libpng-1.2.6 */
  187160. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187161. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187162. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187163. #endif
  187164. /* initialize zbuf - compression buffer */
  187165. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187166. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187167. (png_uint_32)png_ptr->zbuf_size);
  187168. png_ptr->zstream.zalloc = png_zalloc;
  187169. png_ptr->zstream.zfree = png_zfree;
  187170. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187171. switch (inflateInit(&png_ptr->zstream))
  187172. {
  187173. case Z_OK: /* Do nothing */ break;
  187174. case Z_MEM_ERROR:
  187175. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187176. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187177. default: png_error(png_ptr, "Unknown zlib error");
  187178. }
  187179. png_ptr->zstream.next_out = png_ptr->zbuf;
  187180. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187181. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187182. }
  187183. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187184. /* Read the information before the actual image data. This has been
  187185. * changed in v0.90 to allow reading a file that already has the magic
  187186. * bytes read from the stream. You can tell libpng how many bytes have
  187187. * been read from the beginning of the stream (up to the maximum of 8)
  187188. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187189. * here. The application can then have access to the signature bytes we
  187190. * read if it is determined that this isn't a valid PNG file.
  187191. */
  187192. void PNGAPI
  187193. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187194. {
  187195. if(png_ptr == NULL) return;
  187196. png_debug(1, "in png_read_info\n");
  187197. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187198. if (png_ptr->sig_bytes < 8)
  187199. {
  187200. png_size_t num_checked = png_ptr->sig_bytes,
  187201. num_to_check = 8 - num_checked;
  187202. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187203. png_ptr->sig_bytes = 8;
  187204. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187205. {
  187206. if (num_checked < 4 &&
  187207. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187208. png_error(png_ptr, "Not a PNG file");
  187209. else
  187210. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187211. }
  187212. if (num_checked < 3)
  187213. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187214. }
  187215. for(;;)
  187216. {
  187217. #ifdef PNG_USE_LOCAL_ARRAYS
  187218. PNG_CONST PNG_IHDR;
  187219. PNG_CONST PNG_IDAT;
  187220. PNG_CONST PNG_IEND;
  187221. PNG_CONST PNG_PLTE;
  187222. #if defined(PNG_READ_bKGD_SUPPORTED)
  187223. PNG_CONST PNG_bKGD;
  187224. #endif
  187225. #if defined(PNG_READ_cHRM_SUPPORTED)
  187226. PNG_CONST PNG_cHRM;
  187227. #endif
  187228. #if defined(PNG_READ_gAMA_SUPPORTED)
  187229. PNG_CONST PNG_gAMA;
  187230. #endif
  187231. #if defined(PNG_READ_hIST_SUPPORTED)
  187232. PNG_CONST PNG_hIST;
  187233. #endif
  187234. #if defined(PNG_READ_iCCP_SUPPORTED)
  187235. PNG_CONST PNG_iCCP;
  187236. #endif
  187237. #if defined(PNG_READ_iTXt_SUPPORTED)
  187238. PNG_CONST PNG_iTXt;
  187239. #endif
  187240. #if defined(PNG_READ_oFFs_SUPPORTED)
  187241. PNG_CONST PNG_oFFs;
  187242. #endif
  187243. #if defined(PNG_READ_pCAL_SUPPORTED)
  187244. PNG_CONST PNG_pCAL;
  187245. #endif
  187246. #if defined(PNG_READ_pHYs_SUPPORTED)
  187247. PNG_CONST PNG_pHYs;
  187248. #endif
  187249. #if defined(PNG_READ_sBIT_SUPPORTED)
  187250. PNG_CONST PNG_sBIT;
  187251. #endif
  187252. #if defined(PNG_READ_sCAL_SUPPORTED)
  187253. PNG_CONST PNG_sCAL;
  187254. #endif
  187255. #if defined(PNG_READ_sPLT_SUPPORTED)
  187256. PNG_CONST PNG_sPLT;
  187257. #endif
  187258. #if defined(PNG_READ_sRGB_SUPPORTED)
  187259. PNG_CONST PNG_sRGB;
  187260. #endif
  187261. #if defined(PNG_READ_tEXt_SUPPORTED)
  187262. PNG_CONST PNG_tEXt;
  187263. #endif
  187264. #if defined(PNG_READ_tIME_SUPPORTED)
  187265. PNG_CONST PNG_tIME;
  187266. #endif
  187267. #if defined(PNG_READ_tRNS_SUPPORTED)
  187268. PNG_CONST PNG_tRNS;
  187269. #endif
  187270. #if defined(PNG_READ_zTXt_SUPPORTED)
  187271. PNG_CONST PNG_zTXt;
  187272. #endif
  187273. #endif /* PNG_USE_LOCAL_ARRAYS */
  187274. png_byte chunk_length[4];
  187275. png_uint_32 length;
  187276. png_read_data(png_ptr, chunk_length, 4);
  187277. length = png_get_uint_31(png_ptr,chunk_length);
  187278. png_reset_crc(png_ptr);
  187279. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187280. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187281. length);
  187282. /* This should be a binary subdivision search or a hash for
  187283. * matching the chunk name rather than a linear search.
  187284. */
  187285. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187286. if(png_ptr->mode & PNG_AFTER_IDAT)
  187287. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187288. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187289. png_handle_IHDR(png_ptr, info_ptr, length);
  187290. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187291. png_handle_IEND(png_ptr, info_ptr, length);
  187292. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187293. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187294. {
  187295. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187296. png_ptr->mode |= PNG_HAVE_IDAT;
  187297. png_handle_unknown(png_ptr, info_ptr, length);
  187298. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187299. png_ptr->mode |= PNG_HAVE_PLTE;
  187300. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187301. {
  187302. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187303. png_error(png_ptr, "Missing IHDR before IDAT");
  187304. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187305. !(png_ptr->mode & PNG_HAVE_PLTE))
  187306. png_error(png_ptr, "Missing PLTE before IDAT");
  187307. break;
  187308. }
  187309. }
  187310. #endif
  187311. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187312. png_handle_PLTE(png_ptr, info_ptr, length);
  187313. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187314. {
  187315. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187316. png_error(png_ptr, "Missing IHDR before IDAT");
  187317. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187318. !(png_ptr->mode & PNG_HAVE_PLTE))
  187319. png_error(png_ptr, "Missing PLTE before IDAT");
  187320. png_ptr->idat_size = length;
  187321. png_ptr->mode |= PNG_HAVE_IDAT;
  187322. break;
  187323. }
  187324. #if defined(PNG_READ_bKGD_SUPPORTED)
  187325. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187326. png_handle_bKGD(png_ptr, info_ptr, length);
  187327. #endif
  187328. #if defined(PNG_READ_cHRM_SUPPORTED)
  187329. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187330. png_handle_cHRM(png_ptr, info_ptr, length);
  187331. #endif
  187332. #if defined(PNG_READ_gAMA_SUPPORTED)
  187333. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187334. png_handle_gAMA(png_ptr, info_ptr, length);
  187335. #endif
  187336. #if defined(PNG_READ_hIST_SUPPORTED)
  187337. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187338. png_handle_hIST(png_ptr, info_ptr, length);
  187339. #endif
  187340. #if defined(PNG_READ_oFFs_SUPPORTED)
  187341. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187342. png_handle_oFFs(png_ptr, info_ptr, length);
  187343. #endif
  187344. #if defined(PNG_READ_pCAL_SUPPORTED)
  187345. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187346. png_handle_pCAL(png_ptr, info_ptr, length);
  187347. #endif
  187348. #if defined(PNG_READ_sCAL_SUPPORTED)
  187349. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187350. png_handle_sCAL(png_ptr, info_ptr, length);
  187351. #endif
  187352. #if defined(PNG_READ_pHYs_SUPPORTED)
  187353. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187354. png_handle_pHYs(png_ptr, info_ptr, length);
  187355. #endif
  187356. #if defined(PNG_READ_sBIT_SUPPORTED)
  187357. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187358. png_handle_sBIT(png_ptr, info_ptr, length);
  187359. #endif
  187360. #if defined(PNG_READ_sRGB_SUPPORTED)
  187361. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187362. png_handle_sRGB(png_ptr, info_ptr, length);
  187363. #endif
  187364. #if defined(PNG_READ_iCCP_SUPPORTED)
  187365. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187366. png_handle_iCCP(png_ptr, info_ptr, length);
  187367. #endif
  187368. #if defined(PNG_READ_sPLT_SUPPORTED)
  187369. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187370. png_handle_sPLT(png_ptr, info_ptr, length);
  187371. #endif
  187372. #if defined(PNG_READ_tEXt_SUPPORTED)
  187373. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187374. png_handle_tEXt(png_ptr, info_ptr, length);
  187375. #endif
  187376. #if defined(PNG_READ_tIME_SUPPORTED)
  187377. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187378. png_handle_tIME(png_ptr, info_ptr, length);
  187379. #endif
  187380. #if defined(PNG_READ_tRNS_SUPPORTED)
  187381. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187382. png_handle_tRNS(png_ptr, info_ptr, length);
  187383. #endif
  187384. #if defined(PNG_READ_zTXt_SUPPORTED)
  187385. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187386. png_handle_zTXt(png_ptr, info_ptr, length);
  187387. #endif
  187388. #if defined(PNG_READ_iTXt_SUPPORTED)
  187389. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187390. png_handle_iTXt(png_ptr, info_ptr, length);
  187391. #endif
  187392. else
  187393. png_handle_unknown(png_ptr, info_ptr, length);
  187394. }
  187395. }
  187396. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187397. /* optional call to update the users info_ptr structure */
  187398. void PNGAPI
  187399. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187400. {
  187401. png_debug(1, "in png_read_update_info\n");
  187402. if(png_ptr == NULL) return;
  187403. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187404. png_read_start_row(png_ptr);
  187405. else
  187406. png_warning(png_ptr,
  187407. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187408. png_read_transform_info(png_ptr, info_ptr);
  187409. }
  187410. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187411. /* Initialize palette, background, etc, after transformations
  187412. * are set, but before any reading takes place. This allows
  187413. * the user to obtain a gamma-corrected palette, for example.
  187414. * If the user doesn't call this, we will do it ourselves.
  187415. */
  187416. void PNGAPI
  187417. png_start_read_image(png_structp png_ptr)
  187418. {
  187419. png_debug(1, "in png_start_read_image\n");
  187420. if(png_ptr == NULL) return;
  187421. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187422. png_read_start_row(png_ptr);
  187423. }
  187424. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187425. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187426. void PNGAPI
  187427. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187428. {
  187429. #ifdef PNG_USE_LOCAL_ARRAYS
  187430. PNG_CONST PNG_IDAT;
  187431. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187432. 0xff};
  187433. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187434. #endif
  187435. int ret;
  187436. if(png_ptr == NULL) return;
  187437. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187438. png_ptr->row_number, png_ptr->pass);
  187439. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187440. png_read_start_row(png_ptr);
  187441. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187442. {
  187443. /* check for transforms that have been set but were defined out */
  187444. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187445. if (png_ptr->transformations & PNG_INVERT_MONO)
  187446. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187447. #endif
  187448. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187449. if (png_ptr->transformations & PNG_FILLER)
  187450. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187451. #endif
  187452. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187453. if (png_ptr->transformations & PNG_PACKSWAP)
  187454. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187455. #endif
  187456. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187457. if (png_ptr->transformations & PNG_PACK)
  187458. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187459. #endif
  187460. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187461. if (png_ptr->transformations & PNG_SHIFT)
  187462. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187463. #endif
  187464. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187465. if (png_ptr->transformations & PNG_BGR)
  187466. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187467. #endif
  187468. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187469. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187470. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187471. #endif
  187472. }
  187473. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187474. /* if interlaced and we do not need a new row, combine row and return */
  187475. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187476. {
  187477. switch (png_ptr->pass)
  187478. {
  187479. case 0:
  187480. if (png_ptr->row_number & 0x07)
  187481. {
  187482. if (dsp_row != NULL)
  187483. png_combine_row(png_ptr, dsp_row,
  187484. png_pass_dsp_mask[png_ptr->pass]);
  187485. png_read_finish_row(png_ptr);
  187486. return;
  187487. }
  187488. break;
  187489. case 1:
  187490. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187491. {
  187492. if (dsp_row != NULL)
  187493. png_combine_row(png_ptr, dsp_row,
  187494. png_pass_dsp_mask[png_ptr->pass]);
  187495. png_read_finish_row(png_ptr);
  187496. return;
  187497. }
  187498. break;
  187499. case 2:
  187500. if ((png_ptr->row_number & 0x07) != 4)
  187501. {
  187502. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187503. png_combine_row(png_ptr, dsp_row,
  187504. png_pass_dsp_mask[png_ptr->pass]);
  187505. png_read_finish_row(png_ptr);
  187506. return;
  187507. }
  187508. break;
  187509. case 3:
  187510. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187511. {
  187512. if (dsp_row != NULL)
  187513. png_combine_row(png_ptr, dsp_row,
  187514. png_pass_dsp_mask[png_ptr->pass]);
  187515. png_read_finish_row(png_ptr);
  187516. return;
  187517. }
  187518. break;
  187519. case 4:
  187520. if ((png_ptr->row_number & 3) != 2)
  187521. {
  187522. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187523. png_combine_row(png_ptr, dsp_row,
  187524. png_pass_dsp_mask[png_ptr->pass]);
  187525. png_read_finish_row(png_ptr);
  187526. return;
  187527. }
  187528. break;
  187529. case 5:
  187530. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187531. {
  187532. if (dsp_row != NULL)
  187533. png_combine_row(png_ptr, dsp_row,
  187534. png_pass_dsp_mask[png_ptr->pass]);
  187535. png_read_finish_row(png_ptr);
  187536. return;
  187537. }
  187538. break;
  187539. case 6:
  187540. if (!(png_ptr->row_number & 1))
  187541. {
  187542. png_read_finish_row(png_ptr);
  187543. return;
  187544. }
  187545. break;
  187546. }
  187547. }
  187548. #endif
  187549. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187550. png_error(png_ptr, "Invalid attempt to read row data");
  187551. png_ptr->zstream.next_out = png_ptr->row_buf;
  187552. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187553. do
  187554. {
  187555. if (!(png_ptr->zstream.avail_in))
  187556. {
  187557. while (!png_ptr->idat_size)
  187558. {
  187559. png_byte chunk_length[4];
  187560. png_crc_finish(png_ptr, 0);
  187561. png_read_data(png_ptr, chunk_length, 4);
  187562. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187563. png_reset_crc(png_ptr);
  187564. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187565. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187566. png_error(png_ptr, "Not enough image data");
  187567. }
  187568. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187569. png_ptr->zstream.next_in = png_ptr->zbuf;
  187570. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187571. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187572. png_crc_read(png_ptr, png_ptr->zbuf,
  187573. (png_size_t)png_ptr->zstream.avail_in);
  187574. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187575. }
  187576. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187577. if (ret == Z_STREAM_END)
  187578. {
  187579. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187580. png_ptr->idat_size)
  187581. png_error(png_ptr, "Extra compressed data");
  187582. png_ptr->mode |= PNG_AFTER_IDAT;
  187583. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187584. break;
  187585. }
  187586. if (ret != Z_OK)
  187587. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187588. "Decompression error");
  187589. } while (png_ptr->zstream.avail_out);
  187590. png_ptr->row_info.color_type = png_ptr->color_type;
  187591. png_ptr->row_info.width = png_ptr->iwidth;
  187592. png_ptr->row_info.channels = png_ptr->channels;
  187593. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187594. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187595. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187596. png_ptr->row_info.width);
  187597. if(png_ptr->row_buf[0])
  187598. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187599. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187600. (int)(png_ptr->row_buf[0]));
  187601. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187602. png_ptr->rowbytes + 1);
  187603. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187604. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187605. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187606. {
  187607. /* Intrapixel differencing */
  187608. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187609. }
  187610. #endif
  187611. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187612. png_do_read_transformations(png_ptr);
  187613. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187614. /* blow up interlaced rows to full size */
  187615. if (png_ptr->interlaced &&
  187616. (png_ptr->transformations & PNG_INTERLACE))
  187617. {
  187618. if (png_ptr->pass < 6)
  187619. /* old interface (pre-1.0.9):
  187620. png_do_read_interlace(&(png_ptr->row_info),
  187621. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187622. */
  187623. png_do_read_interlace(png_ptr);
  187624. if (dsp_row != NULL)
  187625. png_combine_row(png_ptr, dsp_row,
  187626. png_pass_dsp_mask[png_ptr->pass]);
  187627. if (row != NULL)
  187628. png_combine_row(png_ptr, row,
  187629. png_pass_mask[png_ptr->pass]);
  187630. }
  187631. else
  187632. #endif
  187633. {
  187634. if (row != NULL)
  187635. png_combine_row(png_ptr, row, 0xff);
  187636. if (dsp_row != NULL)
  187637. png_combine_row(png_ptr, dsp_row, 0xff);
  187638. }
  187639. png_read_finish_row(png_ptr);
  187640. if (png_ptr->read_row_fn != NULL)
  187641. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187642. }
  187643. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187644. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187645. /* Read one or more rows of image data. If the image is interlaced,
  187646. * and png_set_interlace_handling() has been called, the rows need to
  187647. * contain the contents of the rows from the previous pass. If the
  187648. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187649. * called, the rows contents must be initialized to the contents of the
  187650. * screen.
  187651. *
  187652. * "row" holds the actual image, and pixels are placed in it
  187653. * as they arrive. If the image is displayed after each pass, it will
  187654. * appear to "sparkle" in. "display_row" can be used to display a
  187655. * "chunky" progressive image, with finer detail added as it becomes
  187656. * available. If you do not want this "chunky" display, you may pass
  187657. * NULL for display_row. If you do not want the sparkle display, and
  187658. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187659. * If you have called png_handle_alpha(), and the image has either an
  187660. * alpha channel or a transparency chunk, you must provide a buffer for
  187661. * rows. In this case, you do not have to provide a display_row buffer
  187662. * also, but you may. If the image is not interlaced, or if you have
  187663. * not called png_set_interlace_handling(), the display_row buffer will
  187664. * be ignored, so pass NULL to it.
  187665. *
  187666. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187667. */
  187668. void PNGAPI
  187669. png_read_rows(png_structp png_ptr, png_bytepp row,
  187670. png_bytepp display_row, png_uint_32 num_rows)
  187671. {
  187672. png_uint_32 i;
  187673. png_bytepp rp;
  187674. png_bytepp dp;
  187675. png_debug(1, "in png_read_rows\n");
  187676. if(png_ptr == NULL) return;
  187677. rp = row;
  187678. dp = display_row;
  187679. if (rp != NULL && dp != NULL)
  187680. for (i = 0; i < num_rows; i++)
  187681. {
  187682. png_bytep rptr = *rp++;
  187683. png_bytep dptr = *dp++;
  187684. png_read_row(png_ptr, rptr, dptr);
  187685. }
  187686. else if(rp != NULL)
  187687. for (i = 0; i < num_rows; i++)
  187688. {
  187689. png_bytep rptr = *rp;
  187690. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187691. rp++;
  187692. }
  187693. else if(dp != NULL)
  187694. for (i = 0; i < num_rows; i++)
  187695. {
  187696. png_bytep dptr = *dp;
  187697. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187698. dp++;
  187699. }
  187700. }
  187701. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187702. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187703. /* Read the entire image. If the image has an alpha channel or a tRNS
  187704. * chunk, and you have called png_handle_alpha()[*], you will need to
  187705. * initialize the image to the current image that PNG will be overlaying.
  187706. * We set the num_rows again here, in case it was incorrectly set in
  187707. * png_read_start_row() by a call to png_read_update_info() or
  187708. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187709. * prior to either of these functions like it should have been. You can
  187710. * only call this function once. If you desire to have an image for
  187711. * each pass of a interlaced image, use png_read_rows() instead.
  187712. *
  187713. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187714. */
  187715. void PNGAPI
  187716. png_read_image(png_structp png_ptr, png_bytepp image)
  187717. {
  187718. png_uint_32 i,image_height;
  187719. int pass, j;
  187720. png_bytepp rp;
  187721. png_debug(1, "in png_read_image\n");
  187722. if(png_ptr == NULL) return;
  187723. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187724. pass = png_set_interlace_handling(png_ptr);
  187725. #else
  187726. if (png_ptr->interlaced)
  187727. png_error(png_ptr,
  187728. "Cannot read interlaced image -- interlace handler disabled.");
  187729. pass = 1;
  187730. #endif
  187731. image_height=png_ptr->height;
  187732. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187733. for (j = 0; j < pass; j++)
  187734. {
  187735. rp = image;
  187736. for (i = 0; i < image_height; i++)
  187737. {
  187738. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187739. rp++;
  187740. }
  187741. }
  187742. }
  187743. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187744. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187745. /* Read the end of the PNG file. Will not read past the end of the
  187746. * file, will verify the end is accurate, and will read any comments
  187747. * or time information at the end of the file, if info is not NULL.
  187748. */
  187749. void PNGAPI
  187750. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187751. {
  187752. png_byte chunk_length[4];
  187753. png_uint_32 length;
  187754. png_debug(1, "in png_read_end\n");
  187755. if(png_ptr == NULL) return;
  187756. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187757. do
  187758. {
  187759. #ifdef PNG_USE_LOCAL_ARRAYS
  187760. PNG_CONST PNG_IHDR;
  187761. PNG_CONST PNG_IDAT;
  187762. PNG_CONST PNG_IEND;
  187763. PNG_CONST PNG_PLTE;
  187764. #if defined(PNG_READ_bKGD_SUPPORTED)
  187765. PNG_CONST PNG_bKGD;
  187766. #endif
  187767. #if defined(PNG_READ_cHRM_SUPPORTED)
  187768. PNG_CONST PNG_cHRM;
  187769. #endif
  187770. #if defined(PNG_READ_gAMA_SUPPORTED)
  187771. PNG_CONST PNG_gAMA;
  187772. #endif
  187773. #if defined(PNG_READ_hIST_SUPPORTED)
  187774. PNG_CONST PNG_hIST;
  187775. #endif
  187776. #if defined(PNG_READ_iCCP_SUPPORTED)
  187777. PNG_CONST PNG_iCCP;
  187778. #endif
  187779. #if defined(PNG_READ_iTXt_SUPPORTED)
  187780. PNG_CONST PNG_iTXt;
  187781. #endif
  187782. #if defined(PNG_READ_oFFs_SUPPORTED)
  187783. PNG_CONST PNG_oFFs;
  187784. #endif
  187785. #if defined(PNG_READ_pCAL_SUPPORTED)
  187786. PNG_CONST PNG_pCAL;
  187787. #endif
  187788. #if defined(PNG_READ_pHYs_SUPPORTED)
  187789. PNG_CONST PNG_pHYs;
  187790. #endif
  187791. #if defined(PNG_READ_sBIT_SUPPORTED)
  187792. PNG_CONST PNG_sBIT;
  187793. #endif
  187794. #if defined(PNG_READ_sCAL_SUPPORTED)
  187795. PNG_CONST PNG_sCAL;
  187796. #endif
  187797. #if defined(PNG_READ_sPLT_SUPPORTED)
  187798. PNG_CONST PNG_sPLT;
  187799. #endif
  187800. #if defined(PNG_READ_sRGB_SUPPORTED)
  187801. PNG_CONST PNG_sRGB;
  187802. #endif
  187803. #if defined(PNG_READ_tEXt_SUPPORTED)
  187804. PNG_CONST PNG_tEXt;
  187805. #endif
  187806. #if defined(PNG_READ_tIME_SUPPORTED)
  187807. PNG_CONST PNG_tIME;
  187808. #endif
  187809. #if defined(PNG_READ_tRNS_SUPPORTED)
  187810. PNG_CONST PNG_tRNS;
  187811. #endif
  187812. #if defined(PNG_READ_zTXt_SUPPORTED)
  187813. PNG_CONST PNG_zTXt;
  187814. #endif
  187815. #endif /* PNG_USE_LOCAL_ARRAYS */
  187816. png_read_data(png_ptr, chunk_length, 4);
  187817. length = png_get_uint_31(png_ptr,chunk_length);
  187818. png_reset_crc(png_ptr);
  187819. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187820. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187821. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187822. png_handle_IHDR(png_ptr, info_ptr, length);
  187823. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187824. png_handle_IEND(png_ptr, info_ptr, length);
  187825. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187826. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187827. {
  187828. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187829. {
  187830. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187831. png_error(png_ptr, "Too many IDAT's found");
  187832. }
  187833. png_handle_unknown(png_ptr, info_ptr, length);
  187834. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187835. png_ptr->mode |= PNG_HAVE_PLTE;
  187836. }
  187837. #endif
  187838. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187839. {
  187840. /* Zero length IDATs are legal after the last IDAT has been
  187841. * read, but not after other chunks have been read.
  187842. */
  187843. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187844. png_error(png_ptr, "Too many IDAT's found");
  187845. png_crc_finish(png_ptr, length);
  187846. }
  187847. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187848. png_handle_PLTE(png_ptr, info_ptr, length);
  187849. #if defined(PNG_READ_bKGD_SUPPORTED)
  187850. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187851. png_handle_bKGD(png_ptr, info_ptr, length);
  187852. #endif
  187853. #if defined(PNG_READ_cHRM_SUPPORTED)
  187854. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187855. png_handle_cHRM(png_ptr, info_ptr, length);
  187856. #endif
  187857. #if defined(PNG_READ_gAMA_SUPPORTED)
  187858. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187859. png_handle_gAMA(png_ptr, info_ptr, length);
  187860. #endif
  187861. #if defined(PNG_READ_hIST_SUPPORTED)
  187862. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187863. png_handle_hIST(png_ptr, info_ptr, length);
  187864. #endif
  187865. #if defined(PNG_READ_oFFs_SUPPORTED)
  187866. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187867. png_handle_oFFs(png_ptr, info_ptr, length);
  187868. #endif
  187869. #if defined(PNG_READ_pCAL_SUPPORTED)
  187870. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187871. png_handle_pCAL(png_ptr, info_ptr, length);
  187872. #endif
  187873. #if defined(PNG_READ_sCAL_SUPPORTED)
  187874. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187875. png_handle_sCAL(png_ptr, info_ptr, length);
  187876. #endif
  187877. #if defined(PNG_READ_pHYs_SUPPORTED)
  187878. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187879. png_handle_pHYs(png_ptr, info_ptr, length);
  187880. #endif
  187881. #if defined(PNG_READ_sBIT_SUPPORTED)
  187882. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187883. png_handle_sBIT(png_ptr, info_ptr, length);
  187884. #endif
  187885. #if defined(PNG_READ_sRGB_SUPPORTED)
  187886. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187887. png_handle_sRGB(png_ptr, info_ptr, length);
  187888. #endif
  187889. #if defined(PNG_READ_iCCP_SUPPORTED)
  187890. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187891. png_handle_iCCP(png_ptr, info_ptr, length);
  187892. #endif
  187893. #if defined(PNG_READ_sPLT_SUPPORTED)
  187894. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187895. png_handle_sPLT(png_ptr, info_ptr, length);
  187896. #endif
  187897. #if defined(PNG_READ_tEXt_SUPPORTED)
  187898. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187899. png_handle_tEXt(png_ptr, info_ptr, length);
  187900. #endif
  187901. #if defined(PNG_READ_tIME_SUPPORTED)
  187902. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187903. png_handle_tIME(png_ptr, info_ptr, length);
  187904. #endif
  187905. #if defined(PNG_READ_tRNS_SUPPORTED)
  187906. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187907. png_handle_tRNS(png_ptr, info_ptr, length);
  187908. #endif
  187909. #if defined(PNG_READ_zTXt_SUPPORTED)
  187910. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187911. png_handle_zTXt(png_ptr, info_ptr, length);
  187912. #endif
  187913. #if defined(PNG_READ_iTXt_SUPPORTED)
  187914. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187915. png_handle_iTXt(png_ptr, info_ptr, length);
  187916. #endif
  187917. else
  187918. png_handle_unknown(png_ptr, info_ptr, length);
  187919. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187920. }
  187921. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187922. /* free all memory used by the read */
  187923. void PNGAPI
  187924. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187925. png_infopp end_info_ptr_ptr)
  187926. {
  187927. png_structp png_ptr = NULL;
  187928. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187929. #ifdef PNG_USER_MEM_SUPPORTED
  187930. png_free_ptr free_fn;
  187931. png_voidp mem_ptr;
  187932. #endif
  187933. png_debug(1, "in png_destroy_read_struct\n");
  187934. if (png_ptr_ptr != NULL)
  187935. png_ptr = *png_ptr_ptr;
  187936. if (info_ptr_ptr != NULL)
  187937. info_ptr = *info_ptr_ptr;
  187938. if (end_info_ptr_ptr != NULL)
  187939. end_info_ptr = *end_info_ptr_ptr;
  187940. #ifdef PNG_USER_MEM_SUPPORTED
  187941. free_fn = png_ptr->free_fn;
  187942. mem_ptr = png_ptr->mem_ptr;
  187943. #endif
  187944. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187945. if (info_ptr != NULL)
  187946. {
  187947. #if defined(PNG_TEXT_SUPPORTED)
  187948. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187949. #endif
  187950. #ifdef PNG_USER_MEM_SUPPORTED
  187951. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187952. (png_voidp)mem_ptr);
  187953. #else
  187954. png_destroy_struct((png_voidp)info_ptr);
  187955. #endif
  187956. *info_ptr_ptr = NULL;
  187957. }
  187958. if (end_info_ptr != NULL)
  187959. {
  187960. #if defined(PNG_READ_TEXT_SUPPORTED)
  187961. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187962. #endif
  187963. #ifdef PNG_USER_MEM_SUPPORTED
  187964. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187965. (png_voidp)mem_ptr);
  187966. #else
  187967. png_destroy_struct((png_voidp)end_info_ptr);
  187968. #endif
  187969. *end_info_ptr_ptr = NULL;
  187970. }
  187971. if (png_ptr != NULL)
  187972. {
  187973. #ifdef PNG_USER_MEM_SUPPORTED
  187974. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187975. (png_voidp)mem_ptr);
  187976. #else
  187977. png_destroy_struct((png_voidp)png_ptr);
  187978. #endif
  187979. *png_ptr_ptr = NULL;
  187980. }
  187981. }
  187982. /* free all memory used by the read (old method) */
  187983. void /* PRIVATE */
  187984. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187985. {
  187986. #ifdef PNG_SETJMP_SUPPORTED
  187987. jmp_buf tmp_jmp;
  187988. #endif
  187989. png_error_ptr error_fn;
  187990. png_error_ptr warning_fn;
  187991. png_voidp error_ptr;
  187992. #ifdef PNG_USER_MEM_SUPPORTED
  187993. png_free_ptr free_fn;
  187994. #endif
  187995. png_debug(1, "in png_read_destroy\n");
  187996. if (info_ptr != NULL)
  187997. png_info_destroy(png_ptr, info_ptr);
  187998. if (end_info_ptr != NULL)
  187999. png_info_destroy(png_ptr, end_info_ptr);
  188000. png_free(png_ptr, png_ptr->zbuf);
  188001. png_free(png_ptr, png_ptr->big_row_buf);
  188002. png_free(png_ptr, png_ptr->prev_row);
  188003. #if defined(PNG_READ_DITHER_SUPPORTED)
  188004. png_free(png_ptr, png_ptr->palette_lookup);
  188005. png_free(png_ptr, png_ptr->dither_index);
  188006. #endif
  188007. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188008. png_free(png_ptr, png_ptr->gamma_table);
  188009. #endif
  188010. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188011. png_free(png_ptr, png_ptr->gamma_from_1);
  188012. png_free(png_ptr, png_ptr->gamma_to_1);
  188013. #endif
  188014. #ifdef PNG_FREE_ME_SUPPORTED
  188015. if (png_ptr->free_me & PNG_FREE_PLTE)
  188016. png_zfree(png_ptr, png_ptr->palette);
  188017. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188018. #else
  188019. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188020. png_zfree(png_ptr, png_ptr->palette);
  188021. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188022. #endif
  188023. #if defined(PNG_tRNS_SUPPORTED) || \
  188024. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188025. #ifdef PNG_FREE_ME_SUPPORTED
  188026. if (png_ptr->free_me & PNG_FREE_TRNS)
  188027. png_free(png_ptr, png_ptr->trans);
  188028. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188029. #else
  188030. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188031. png_free(png_ptr, png_ptr->trans);
  188032. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188033. #endif
  188034. #endif
  188035. #if defined(PNG_READ_hIST_SUPPORTED)
  188036. #ifdef PNG_FREE_ME_SUPPORTED
  188037. if (png_ptr->free_me & PNG_FREE_HIST)
  188038. png_free(png_ptr, png_ptr->hist);
  188039. png_ptr->free_me &= ~PNG_FREE_HIST;
  188040. #else
  188041. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188042. png_free(png_ptr, png_ptr->hist);
  188043. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188044. #endif
  188045. #endif
  188046. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188047. if (png_ptr->gamma_16_table != NULL)
  188048. {
  188049. int i;
  188050. int istop = (1 << (8 - png_ptr->gamma_shift));
  188051. for (i = 0; i < istop; i++)
  188052. {
  188053. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188054. }
  188055. png_free(png_ptr, png_ptr->gamma_16_table);
  188056. }
  188057. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188058. if (png_ptr->gamma_16_from_1 != NULL)
  188059. {
  188060. int i;
  188061. int istop = (1 << (8 - png_ptr->gamma_shift));
  188062. for (i = 0; i < istop; i++)
  188063. {
  188064. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188065. }
  188066. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188067. }
  188068. if (png_ptr->gamma_16_to_1 != NULL)
  188069. {
  188070. int i;
  188071. int istop = (1 << (8 - png_ptr->gamma_shift));
  188072. for (i = 0; i < istop; i++)
  188073. {
  188074. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188075. }
  188076. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188077. }
  188078. #endif
  188079. #endif
  188080. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188081. png_free(png_ptr, png_ptr->time_buffer);
  188082. #endif
  188083. inflateEnd(&png_ptr->zstream);
  188084. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188085. png_free(png_ptr, png_ptr->save_buffer);
  188086. #endif
  188087. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188088. #ifdef PNG_TEXT_SUPPORTED
  188089. png_free(png_ptr, png_ptr->current_text);
  188090. #endif /* PNG_TEXT_SUPPORTED */
  188091. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188092. /* Save the important info out of the png_struct, in case it is
  188093. * being used again.
  188094. */
  188095. #ifdef PNG_SETJMP_SUPPORTED
  188096. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188097. #endif
  188098. error_fn = png_ptr->error_fn;
  188099. warning_fn = png_ptr->warning_fn;
  188100. error_ptr = png_ptr->error_ptr;
  188101. #ifdef PNG_USER_MEM_SUPPORTED
  188102. free_fn = png_ptr->free_fn;
  188103. #endif
  188104. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188105. png_ptr->error_fn = error_fn;
  188106. png_ptr->warning_fn = warning_fn;
  188107. png_ptr->error_ptr = error_ptr;
  188108. #ifdef PNG_USER_MEM_SUPPORTED
  188109. png_ptr->free_fn = free_fn;
  188110. #endif
  188111. #ifdef PNG_SETJMP_SUPPORTED
  188112. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188113. #endif
  188114. }
  188115. void PNGAPI
  188116. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188117. {
  188118. if(png_ptr == NULL) return;
  188119. png_ptr->read_row_fn = read_row_fn;
  188120. }
  188121. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188122. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188123. void PNGAPI
  188124. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188125. int transforms,
  188126. voidp params)
  188127. {
  188128. int row;
  188129. if(png_ptr == NULL) return;
  188130. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188131. /* invert the alpha channel from opacity to transparency
  188132. */
  188133. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188134. png_set_invert_alpha(png_ptr);
  188135. #endif
  188136. /* png_read_info() gives us all of the information from the
  188137. * PNG file before the first IDAT (image data chunk).
  188138. */
  188139. png_read_info(png_ptr, info_ptr);
  188140. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188141. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188142. /* -------------- image transformations start here ------------------- */
  188143. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188144. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188145. */
  188146. if (transforms & PNG_TRANSFORM_STRIP_16)
  188147. png_set_strip_16(png_ptr);
  188148. #endif
  188149. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188150. /* Strip alpha bytes from the input data without combining with
  188151. * the background (not recommended).
  188152. */
  188153. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188154. png_set_strip_alpha(png_ptr);
  188155. #endif
  188156. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188157. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188158. * byte into separate bytes (useful for paletted and grayscale images).
  188159. */
  188160. if (transforms & PNG_TRANSFORM_PACKING)
  188161. png_set_packing(png_ptr);
  188162. #endif
  188163. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188164. /* Change the order of packed pixels to least significant bit first
  188165. * (not useful if you are using png_set_packing).
  188166. */
  188167. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188168. png_set_packswap(png_ptr);
  188169. #endif
  188170. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188171. /* Expand paletted colors into true RGB triplets
  188172. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188173. * Expand paletted or RGB images with transparency to full alpha
  188174. * channels so the data will be available as RGBA quartets.
  188175. */
  188176. if (transforms & PNG_TRANSFORM_EXPAND)
  188177. if ((png_ptr->bit_depth < 8) ||
  188178. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188179. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188180. png_set_expand(png_ptr);
  188181. #endif
  188182. /* We don't handle background color or gamma transformation or dithering.
  188183. */
  188184. #if defined(PNG_READ_INVERT_SUPPORTED)
  188185. /* invert monochrome files to have 0 as white and 1 as black
  188186. */
  188187. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188188. png_set_invert_mono(png_ptr);
  188189. #endif
  188190. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188191. /* If you want to shift the pixel values from the range [0,255] or
  188192. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188193. * colors were originally in:
  188194. */
  188195. if ((transforms & PNG_TRANSFORM_SHIFT)
  188196. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188197. {
  188198. png_color_8p sig_bit;
  188199. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188200. png_set_shift(png_ptr, sig_bit);
  188201. }
  188202. #endif
  188203. #if defined(PNG_READ_BGR_SUPPORTED)
  188204. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188205. */
  188206. if (transforms & PNG_TRANSFORM_BGR)
  188207. png_set_bgr(png_ptr);
  188208. #endif
  188209. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188210. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188211. */
  188212. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188213. png_set_swap_alpha(png_ptr);
  188214. #endif
  188215. #if defined(PNG_READ_SWAP_SUPPORTED)
  188216. /* swap bytes of 16 bit files to least significant byte first
  188217. */
  188218. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188219. png_set_swap(png_ptr);
  188220. #endif
  188221. /* We don't handle adding filler bytes */
  188222. /* Optional call to gamma correct and add the background to the palette
  188223. * and update info structure. REQUIRED if you are expecting libpng to
  188224. * update the palette for you (i.e., you selected such a transform above).
  188225. */
  188226. png_read_update_info(png_ptr, info_ptr);
  188227. /* -------------- image transformations end here ------------------- */
  188228. #ifdef PNG_FREE_ME_SUPPORTED
  188229. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188230. #endif
  188231. if(info_ptr->row_pointers == NULL)
  188232. {
  188233. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188234. info_ptr->height * png_sizeof(png_bytep));
  188235. #ifdef PNG_FREE_ME_SUPPORTED
  188236. info_ptr->free_me |= PNG_FREE_ROWS;
  188237. #endif
  188238. for (row = 0; row < (int)info_ptr->height; row++)
  188239. {
  188240. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188241. png_get_rowbytes(png_ptr, info_ptr));
  188242. }
  188243. }
  188244. png_read_image(png_ptr, info_ptr->row_pointers);
  188245. info_ptr->valid |= PNG_INFO_IDAT;
  188246. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188247. png_read_end(png_ptr, info_ptr);
  188248. transforms = transforms; /* quiet compiler warnings */
  188249. params = params;
  188250. }
  188251. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188252. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188253. #endif /* PNG_READ_SUPPORTED */
  188254. /*** End of inlined file: pngread.c ***/
  188255. /*** Start of inlined file: pngpread.c ***/
  188256. /* pngpread.c - read a png file in push mode
  188257. *
  188258. * Last changed in libpng 1.2.21 October 4, 2007
  188259. * For conditions of distribution and use, see copyright notice in png.h
  188260. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188261. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188262. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188263. */
  188264. #define PNG_INTERNAL
  188265. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188266. /* push model modes */
  188267. #define PNG_READ_SIG_MODE 0
  188268. #define PNG_READ_CHUNK_MODE 1
  188269. #define PNG_READ_IDAT_MODE 2
  188270. #define PNG_SKIP_MODE 3
  188271. #define PNG_READ_tEXt_MODE 4
  188272. #define PNG_READ_zTXt_MODE 5
  188273. #define PNG_READ_DONE_MODE 6
  188274. #define PNG_READ_iTXt_MODE 7
  188275. #define PNG_ERROR_MODE 8
  188276. void PNGAPI
  188277. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188278. png_bytep buffer, png_size_t buffer_size)
  188279. {
  188280. if(png_ptr == NULL) return;
  188281. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188282. while (png_ptr->buffer_size)
  188283. {
  188284. png_process_some_data(png_ptr, info_ptr);
  188285. }
  188286. }
  188287. /* What we do with the incoming data depends on what we were previously
  188288. * doing before we ran out of data...
  188289. */
  188290. void /* PRIVATE */
  188291. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188292. {
  188293. if(png_ptr == NULL) return;
  188294. switch (png_ptr->process_mode)
  188295. {
  188296. case PNG_READ_SIG_MODE:
  188297. {
  188298. png_push_read_sig(png_ptr, info_ptr);
  188299. break;
  188300. }
  188301. case PNG_READ_CHUNK_MODE:
  188302. {
  188303. png_push_read_chunk(png_ptr, info_ptr);
  188304. break;
  188305. }
  188306. case PNG_READ_IDAT_MODE:
  188307. {
  188308. png_push_read_IDAT(png_ptr);
  188309. break;
  188310. }
  188311. #if defined(PNG_READ_tEXt_SUPPORTED)
  188312. case PNG_READ_tEXt_MODE:
  188313. {
  188314. png_push_read_tEXt(png_ptr, info_ptr);
  188315. break;
  188316. }
  188317. #endif
  188318. #if defined(PNG_READ_zTXt_SUPPORTED)
  188319. case PNG_READ_zTXt_MODE:
  188320. {
  188321. png_push_read_zTXt(png_ptr, info_ptr);
  188322. break;
  188323. }
  188324. #endif
  188325. #if defined(PNG_READ_iTXt_SUPPORTED)
  188326. case PNG_READ_iTXt_MODE:
  188327. {
  188328. png_push_read_iTXt(png_ptr, info_ptr);
  188329. break;
  188330. }
  188331. #endif
  188332. case PNG_SKIP_MODE:
  188333. {
  188334. png_push_crc_finish(png_ptr);
  188335. break;
  188336. }
  188337. default:
  188338. {
  188339. png_ptr->buffer_size = 0;
  188340. break;
  188341. }
  188342. }
  188343. }
  188344. /* Read any remaining signature bytes from the stream and compare them with
  188345. * the correct PNG signature. It is possible that this routine is called
  188346. * with bytes already read from the signature, either because they have been
  188347. * checked by the calling application, or because of multiple calls to this
  188348. * routine.
  188349. */
  188350. void /* PRIVATE */
  188351. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188352. {
  188353. png_size_t num_checked = png_ptr->sig_bytes,
  188354. num_to_check = 8 - num_checked;
  188355. if (png_ptr->buffer_size < num_to_check)
  188356. {
  188357. num_to_check = png_ptr->buffer_size;
  188358. }
  188359. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188360. num_to_check);
  188361. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188362. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188363. {
  188364. if (num_checked < 4 &&
  188365. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188366. png_error(png_ptr, "Not a PNG file");
  188367. else
  188368. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188369. }
  188370. else
  188371. {
  188372. if (png_ptr->sig_bytes >= 8)
  188373. {
  188374. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188375. }
  188376. }
  188377. }
  188378. void /* PRIVATE */
  188379. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188380. {
  188381. #ifdef PNG_USE_LOCAL_ARRAYS
  188382. PNG_CONST PNG_IHDR;
  188383. PNG_CONST PNG_IDAT;
  188384. PNG_CONST PNG_IEND;
  188385. PNG_CONST PNG_PLTE;
  188386. #if defined(PNG_READ_bKGD_SUPPORTED)
  188387. PNG_CONST PNG_bKGD;
  188388. #endif
  188389. #if defined(PNG_READ_cHRM_SUPPORTED)
  188390. PNG_CONST PNG_cHRM;
  188391. #endif
  188392. #if defined(PNG_READ_gAMA_SUPPORTED)
  188393. PNG_CONST PNG_gAMA;
  188394. #endif
  188395. #if defined(PNG_READ_hIST_SUPPORTED)
  188396. PNG_CONST PNG_hIST;
  188397. #endif
  188398. #if defined(PNG_READ_iCCP_SUPPORTED)
  188399. PNG_CONST PNG_iCCP;
  188400. #endif
  188401. #if defined(PNG_READ_iTXt_SUPPORTED)
  188402. PNG_CONST PNG_iTXt;
  188403. #endif
  188404. #if defined(PNG_READ_oFFs_SUPPORTED)
  188405. PNG_CONST PNG_oFFs;
  188406. #endif
  188407. #if defined(PNG_READ_pCAL_SUPPORTED)
  188408. PNG_CONST PNG_pCAL;
  188409. #endif
  188410. #if defined(PNG_READ_pHYs_SUPPORTED)
  188411. PNG_CONST PNG_pHYs;
  188412. #endif
  188413. #if defined(PNG_READ_sBIT_SUPPORTED)
  188414. PNG_CONST PNG_sBIT;
  188415. #endif
  188416. #if defined(PNG_READ_sCAL_SUPPORTED)
  188417. PNG_CONST PNG_sCAL;
  188418. #endif
  188419. #if defined(PNG_READ_sRGB_SUPPORTED)
  188420. PNG_CONST PNG_sRGB;
  188421. #endif
  188422. #if defined(PNG_READ_sPLT_SUPPORTED)
  188423. PNG_CONST PNG_sPLT;
  188424. #endif
  188425. #if defined(PNG_READ_tEXt_SUPPORTED)
  188426. PNG_CONST PNG_tEXt;
  188427. #endif
  188428. #if defined(PNG_READ_tIME_SUPPORTED)
  188429. PNG_CONST PNG_tIME;
  188430. #endif
  188431. #if defined(PNG_READ_tRNS_SUPPORTED)
  188432. PNG_CONST PNG_tRNS;
  188433. #endif
  188434. #if defined(PNG_READ_zTXt_SUPPORTED)
  188435. PNG_CONST PNG_zTXt;
  188436. #endif
  188437. #endif /* PNG_USE_LOCAL_ARRAYS */
  188438. /* First we make sure we have enough data for the 4 byte chunk name
  188439. * and the 4 byte chunk length before proceeding with decoding the
  188440. * chunk data. To fully decode each of these chunks, we also make
  188441. * sure we have enough data in the buffer for the 4 byte CRC at the
  188442. * end of every chunk (except IDAT, which is handled separately).
  188443. */
  188444. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188445. {
  188446. png_byte chunk_length[4];
  188447. if (png_ptr->buffer_size < 8)
  188448. {
  188449. png_push_save_buffer(png_ptr);
  188450. return;
  188451. }
  188452. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188453. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188454. png_reset_crc(png_ptr);
  188455. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188456. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188457. }
  188458. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188459. if(png_ptr->mode & PNG_AFTER_IDAT)
  188460. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188461. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188462. {
  188463. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188464. {
  188465. png_push_save_buffer(png_ptr);
  188466. return;
  188467. }
  188468. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188469. }
  188470. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 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_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188478. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188479. png_push_have_end(png_ptr, info_ptr);
  188480. }
  188481. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188482. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188483. {
  188484. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188485. {
  188486. png_push_save_buffer(png_ptr);
  188487. return;
  188488. }
  188489. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188490. png_ptr->mode |= PNG_HAVE_IDAT;
  188491. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188492. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188493. png_ptr->mode |= PNG_HAVE_PLTE;
  188494. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188495. {
  188496. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188497. png_error(png_ptr, "Missing IHDR before IDAT");
  188498. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188499. !(png_ptr->mode & PNG_HAVE_PLTE))
  188500. png_error(png_ptr, "Missing PLTE before IDAT");
  188501. }
  188502. }
  188503. #endif
  188504. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188505. {
  188506. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188507. {
  188508. png_push_save_buffer(png_ptr);
  188509. return;
  188510. }
  188511. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188512. }
  188513. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188514. {
  188515. /* If we reach an IDAT chunk, this means we have read all of the
  188516. * header chunks, and we can start reading the image (or if this
  188517. * is called after the image has been read - we have an error).
  188518. */
  188519. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188520. png_error(png_ptr, "Missing IHDR before IDAT");
  188521. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188522. !(png_ptr->mode & PNG_HAVE_PLTE))
  188523. png_error(png_ptr, "Missing PLTE before IDAT");
  188524. if (png_ptr->mode & PNG_HAVE_IDAT)
  188525. {
  188526. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188527. if (png_ptr->push_length == 0)
  188528. return;
  188529. if (png_ptr->mode & PNG_AFTER_IDAT)
  188530. png_error(png_ptr, "Too many IDAT's found");
  188531. }
  188532. png_ptr->idat_size = png_ptr->push_length;
  188533. png_ptr->mode |= PNG_HAVE_IDAT;
  188534. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188535. png_push_have_info(png_ptr, info_ptr);
  188536. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188537. png_ptr->zstream.next_out = png_ptr->row_buf;
  188538. return;
  188539. }
  188540. #if defined(PNG_READ_gAMA_SUPPORTED)
  188541. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188542. {
  188543. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188544. {
  188545. png_push_save_buffer(png_ptr);
  188546. return;
  188547. }
  188548. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188549. }
  188550. #endif
  188551. #if defined(PNG_READ_sBIT_SUPPORTED)
  188552. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188553. {
  188554. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188555. {
  188556. png_push_save_buffer(png_ptr);
  188557. return;
  188558. }
  188559. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188560. }
  188561. #endif
  188562. #if defined(PNG_READ_cHRM_SUPPORTED)
  188563. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188564. {
  188565. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188566. {
  188567. png_push_save_buffer(png_ptr);
  188568. return;
  188569. }
  188570. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188571. }
  188572. #endif
  188573. #if defined(PNG_READ_sRGB_SUPPORTED)
  188574. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188575. {
  188576. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188577. {
  188578. png_push_save_buffer(png_ptr);
  188579. return;
  188580. }
  188581. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188582. }
  188583. #endif
  188584. #if defined(PNG_READ_iCCP_SUPPORTED)
  188585. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188586. {
  188587. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188588. {
  188589. png_push_save_buffer(png_ptr);
  188590. return;
  188591. }
  188592. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188593. }
  188594. #endif
  188595. #if defined(PNG_READ_sPLT_SUPPORTED)
  188596. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188597. {
  188598. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188599. {
  188600. png_push_save_buffer(png_ptr);
  188601. return;
  188602. }
  188603. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188604. }
  188605. #endif
  188606. #if defined(PNG_READ_tRNS_SUPPORTED)
  188607. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188608. {
  188609. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188610. {
  188611. png_push_save_buffer(png_ptr);
  188612. return;
  188613. }
  188614. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188615. }
  188616. #endif
  188617. #if defined(PNG_READ_bKGD_SUPPORTED)
  188618. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188619. {
  188620. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188621. {
  188622. png_push_save_buffer(png_ptr);
  188623. return;
  188624. }
  188625. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188626. }
  188627. #endif
  188628. #if defined(PNG_READ_hIST_SUPPORTED)
  188629. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188630. {
  188631. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188632. {
  188633. png_push_save_buffer(png_ptr);
  188634. return;
  188635. }
  188636. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188637. }
  188638. #endif
  188639. #if defined(PNG_READ_pHYs_SUPPORTED)
  188640. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188641. {
  188642. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188643. {
  188644. png_push_save_buffer(png_ptr);
  188645. return;
  188646. }
  188647. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188648. }
  188649. #endif
  188650. #if defined(PNG_READ_oFFs_SUPPORTED)
  188651. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188652. {
  188653. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188654. {
  188655. png_push_save_buffer(png_ptr);
  188656. return;
  188657. }
  188658. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188659. }
  188660. #endif
  188661. #if defined(PNG_READ_pCAL_SUPPORTED)
  188662. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188663. {
  188664. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188665. {
  188666. png_push_save_buffer(png_ptr);
  188667. return;
  188668. }
  188669. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188670. }
  188671. #endif
  188672. #if defined(PNG_READ_sCAL_SUPPORTED)
  188673. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188674. {
  188675. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188676. {
  188677. png_push_save_buffer(png_ptr);
  188678. return;
  188679. }
  188680. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188681. }
  188682. #endif
  188683. #if defined(PNG_READ_tIME_SUPPORTED)
  188684. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188685. {
  188686. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188687. {
  188688. png_push_save_buffer(png_ptr);
  188689. return;
  188690. }
  188691. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188692. }
  188693. #endif
  188694. #if defined(PNG_READ_tEXt_SUPPORTED)
  188695. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188696. {
  188697. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188698. {
  188699. png_push_save_buffer(png_ptr);
  188700. return;
  188701. }
  188702. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188703. }
  188704. #endif
  188705. #if defined(PNG_READ_zTXt_SUPPORTED)
  188706. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188707. {
  188708. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188709. {
  188710. png_push_save_buffer(png_ptr);
  188711. return;
  188712. }
  188713. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188714. }
  188715. #endif
  188716. #if defined(PNG_READ_iTXt_SUPPORTED)
  188717. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188718. {
  188719. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188720. {
  188721. png_push_save_buffer(png_ptr);
  188722. return;
  188723. }
  188724. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188725. }
  188726. #endif
  188727. else
  188728. {
  188729. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188730. {
  188731. png_push_save_buffer(png_ptr);
  188732. return;
  188733. }
  188734. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188735. }
  188736. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188737. }
  188738. void /* PRIVATE */
  188739. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188740. {
  188741. png_ptr->process_mode = PNG_SKIP_MODE;
  188742. png_ptr->skip_length = skip;
  188743. }
  188744. void /* PRIVATE */
  188745. png_push_crc_finish(png_structp png_ptr)
  188746. {
  188747. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188748. {
  188749. png_size_t save_size;
  188750. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188751. save_size = (png_size_t)png_ptr->skip_length;
  188752. else
  188753. save_size = png_ptr->save_buffer_size;
  188754. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188755. png_ptr->skip_length -= save_size;
  188756. png_ptr->buffer_size -= save_size;
  188757. png_ptr->save_buffer_size -= save_size;
  188758. png_ptr->save_buffer_ptr += save_size;
  188759. }
  188760. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188761. {
  188762. png_size_t save_size;
  188763. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188764. save_size = (png_size_t)png_ptr->skip_length;
  188765. else
  188766. save_size = png_ptr->current_buffer_size;
  188767. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188768. png_ptr->skip_length -= save_size;
  188769. png_ptr->buffer_size -= save_size;
  188770. png_ptr->current_buffer_size -= save_size;
  188771. png_ptr->current_buffer_ptr += save_size;
  188772. }
  188773. if (!png_ptr->skip_length)
  188774. {
  188775. if (png_ptr->buffer_size < 4)
  188776. {
  188777. png_push_save_buffer(png_ptr);
  188778. return;
  188779. }
  188780. png_crc_finish(png_ptr, 0);
  188781. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188782. }
  188783. }
  188784. void PNGAPI
  188785. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188786. {
  188787. png_bytep ptr;
  188788. if(png_ptr == NULL) return;
  188789. ptr = buffer;
  188790. if (png_ptr->save_buffer_size)
  188791. {
  188792. png_size_t save_size;
  188793. if (length < png_ptr->save_buffer_size)
  188794. save_size = length;
  188795. else
  188796. save_size = png_ptr->save_buffer_size;
  188797. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188798. length -= save_size;
  188799. ptr += save_size;
  188800. png_ptr->buffer_size -= save_size;
  188801. png_ptr->save_buffer_size -= save_size;
  188802. png_ptr->save_buffer_ptr += save_size;
  188803. }
  188804. if (length && png_ptr->current_buffer_size)
  188805. {
  188806. png_size_t save_size;
  188807. if (length < png_ptr->current_buffer_size)
  188808. save_size = length;
  188809. else
  188810. save_size = png_ptr->current_buffer_size;
  188811. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188812. png_ptr->buffer_size -= save_size;
  188813. png_ptr->current_buffer_size -= save_size;
  188814. png_ptr->current_buffer_ptr += save_size;
  188815. }
  188816. }
  188817. void /* PRIVATE */
  188818. png_push_save_buffer(png_structp png_ptr)
  188819. {
  188820. if (png_ptr->save_buffer_size)
  188821. {
  188822. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188823. {
  188824. png_size_t i,istop;
  188825. png_bytep sp;
  188826. png_bytep dp;
  188827. istop = png_ptr->save_buffer_size;
  188828. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188829. i < istop; i++, sp++, dp++)
  188830. {
  188831. *dp = *sp;
  188832. }
  188833. }
  188834. }
  188835. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188836. png_ptr->save_buffer_max)
  188837. {
  188838. png_size_t new_max;
  188839. png_bytep old_buffer;
  188840. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188841. (png_ptr->current_buffer_size + 256))
  188842. {
  188843. png_error(png_ptr, "Potential overflow of save_buffer");
  188844. }
  188845. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188846. old_buffer = png_ptr->save_buffer;
  188847. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188848. (png_uint_32)new_max);
  188849. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188850. png_free(png_ptr, old_buffer);
  188851. png_ptr->save_buffer_max = new_max;
  188852. }
  188853. if (png_ptr->current_buffer_size)
  188854. {
  188855. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188856. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188857. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188858. png_ptr->current_buffer_size = 0;
  188859. }
  188860. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188861. png_ptr->buffer_size = 0;
  188862. }
  188863. void /* PRIVATE */
  188864. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188865. png_size_t buffer_length)
  188866. {
  188867. png_ptr->current_buffer = buffer;
  188868. png_ptr->current_buffer_size = buffer_length;
  188869. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188870. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188871. }
  188872. void /* PRIVATE */
  188873. png_push_read_IDAT(png_structp png_ptr)
  188874. {
  188875. #ifdef PNG_USE_LOCAL_ARRAYS
  188876. PNG_CONST PNG_IDAT;
  188877. #endif
  188878. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188879. {
  188880. png_byte chunk_length[4];
  188881. if (png_ptr->buffer_size < 8)
  188882. {
  188883. png_push_save_buffer(png_ptr);
  188884. return;
  188885. }
  188886. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188887. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188888. png_reset_crc(png_ptr);
  188889. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188890. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188891. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188892. {
  188893. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188894. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188895. png_error(png_ptr, "Not enough compressed data");
  188896. return;
  188897. }
  188898. png_ptr->idat_size = png_ptr->push_length;
  188899. }
  188900. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188901. {
  188902. png_size_t save_size;
  188903. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188904. {
  188905. save_size = (png_size_t)png_ptr->idat_size;
  188906. /* check for overflow */
  188907. if((png_uint_32)save_size != png_ptr->idat_size)
  188908. png_error(png_ptr, "save_size overflowed in pngpread");
  188909. }
  188910. else
  188911. save_size = png_ptr->save_buffer_size;
  188912. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188913. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188914. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188915. png_ptr->idat_size -= save_size;
  188916. png_ptr->buffer_size -= save_size;
  188917. png_ptr->save_buffer_size -= save_size;
  188918. png_ptr->save_buffer_ptr += save_size;
  188919. }
  188920. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188921. {
  188922. png_size_t save_size;
  188923. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188924. {
  188925. save_size = (png_size_t)png_ptr->idat_size;
  188926. /* check for overflow */
  188927. if((png_uint_32)save_size != png_ptr->idat_size)
  188928. png_error(png_ptr, "save_size overflowed in pngpread");
  188929. }
  188930. else
  188931. save_size = png_ptr->current_buffer_size;
  188932. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188933. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188934. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188935. png_ptr->idat_size -= save_size;
  188936. png_ptr->buffer_size -= save_size;
  188937. png_ptr->current_buffer_size -= save_size;
  188938. png_ptr->current_buffer_ptr += save_size;
  188939. }
  188940. if (!png_ptr->idat_size)
  188941. {
  188942. if (png_ptr->buffer_size < 4)
  188943. {
  188944. png_push_save_buffer(png_ptr);
  188945. return;
  188946. }
  188947. png_crc_finish(png_ptr, 0);
  188948. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188949. png_ptr->mode |= PNG_AFTER_IDAT;
  188950. }
  188951. }
  188952. void /* PRIVATE */
  188953. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188954. png_size_t buffer_length)
  188955. {
  188956. int ret;
  188957. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188958. png_error(png_ptr, "Extra compression data");
  188959. png_ptr->zstream.next_in = buffer;
  188960. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188961. for(;;)
  188962. {
  188963. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188964. if (ret != Z_OK)
  188965. {
  188966. if (ret == Z_STREAM_END)
  188967. {
  188968. if (png_ptr->zstream.avail_in)
  188969. png_error(png_ptr, "Extra compressed data");
  188970. if (!(png_ptr->zstream.avail_out))
  188971. {
  188972. png_push_process_row(png_ptr);
  188973. }
  188974. png_ptr->mode |= PNG_AFTER_IDAT;
  188975. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188976. break;
  188977. }
  188978. else if (ret == Z_BUF_ERROR)
  188979. break;
  188980. else
  188981. png_error(png_ptr, "Decompression Error");
  188982. }
  188983. if (!(png_ptr->zstream.avail_out))
  188984. {
  188985. if ((
  188986. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188987. png_ptr->interlaced && png_ptr->pass > 6) ||
  188988. (!png_ptr->interlaced &&
  188989. #endif
  188990. png_ptr->row_number == png_ptr->num_rows))
  188991. {
  188992. if (png_ptr->zstream.avail_in)
  188993. {
  188994. png_warning(png_ptr, "Too much data in IDAT chunks");
  188995. }
  188996. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188997. break;
  188998. }
  188999. png_push_process_row(png_ptr);
  189000. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189001. png_ptr->zstream.next_out = png_ptr->row_buf;
  189002. }
  189003. else
  189004. break;
  189005. }
  189006. }
  189007. void /* PRIVATE */
  189008. png_push_process_row(png_structp png_ptr)
  189009. {
  189010. png_ptr->row_info.color_type = png_ptr->color_type;
  189011. png_ptr->row_info.width = png_ptr->iwidth;
  189012. png_ptr->row_info.channels = png_ptr->channels;
  189013. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189014. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189015. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189016. png_ptr->row_info.width);
  189017. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189018. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189019. (int)(png_ptr->row_buf[0]));
  189020. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189021. png_ptr->rowbytes + 1);
  189022. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189023. png_do_read_transformations(png_ptr);
  189024. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189025. /* blow up interlaced rows to full size */
  189026. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189027. {
  189028. if (png_ptr->pass < 6)
  189029. /* old interface (pre-1.0.9):
  189030. png_do_read_interlace(&(png_ptr->row_info),
  189031. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189032. */
  189033. png_do_read_interlace(png_ptr);
  189034. switch (png_ptr->pass)
  189035. {
  189036. case 0:
  189037. {
  189038. int i;
  189039. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189040. {
  189041. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189042. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189043. }
  189044. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189045. {
  189046. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189047. {
  189048. png_push_have_row(png_ptr, png_bytep_NULL);
  189049. png_read_push_finish_row(png_ptr);
  189050. }
  189051. }
  189052. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189053. {
  189054. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189055. {
  189056. png_push_have_row(png_ptr, png_bytep_NULL);
  189057. png_read_push_finish_row(png_ptr);
  189058. }
  189059. }
  189060. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189061. {
  189062. png_push_have_row(png_ptr, png_bytep_NULL);
  189063. png_read_push_finish_row(png_ptr);
  189064. }
  189065. break;
  189066. }
  189067. case 1:
  189068. {
  189069. int i;
  189070. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189071. {
  189072. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189073. png_read_push_finish_row(png_ptr);
  189074. }
  189075. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189076. {
  189077. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189078. {
  189079. png_push_have_row(png_ptr, png_bytep_NULL);
  189080. png_read_push_finish_row(png_ptr);
  189081. }
  189082. }
  189083. break;
  189084. }
  189085. case 2:
  189086. {
  189087. int i;
  189088. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189089. {
  189090. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189091. png_read_push_finish_row(png_ptr);
  189092. }
  189093. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189094. {
  189095. png_push_have_row(png_ptr, png_bytep_NULL);
  189096. png_read_push_finish_row(png_ptr);
  189097. }
  189098. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189099. {
  189100. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189101. {
  189102. png_push_have_row(png_ptr, png_bytep_NULL);
  189103. png_read_push_finish_row(png_ptr);
  189104. }
  189105. }
  189106. break;
  189107. }
  189108. case 3:
  189109. {
  189110. int i;
  189111. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189112. {
  189113. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189114. png_read_push_finish_row(png_ptr);
  189115. }
  189116. if (png_ptr->pass == 4) /* skip top two generated rows */
  189117. {
  189118. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189119. {
  189120. png_push_have_row(png_ptr, png_bytep_NULL);
  189121. png_read_push_finish_row(png_ptr);
  189122. }
  189123. }
  189124. break;
  189125. }
  189126. case 4:
  189127. {
  189128. int i;
  189129. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189130. {
  189131. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189132. png_read_push_finish_row(png_ptr);
  189133. }
  189134. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189135. {
  189136. png_push_have_row(png_ptr, png_bytep_NULL);
  189137. png_read_push_finish_row(png_ptr);
  189138. }
  189139. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189140. {
  189141. png_push_have_row(png_ptr, png_bytep_NULL);
  189142. png_read_push_finish_row(png_ptr);
  189143. }
  189144. break;
  189145. }
  189146. case 5:
  189147. {
  189148. int i;
  189149. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189150. {
  189151. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189152. png_read_push_finish_row(png_ptr);
  189153. }
  189154. if (png_ptr->pass == 6) /* skip top generated row */
  189155. {
  189156. png_push_have_row(png_ptr, png_bytep_NULL);
  189157. png_read_push_finish_row(png_ptr);
  189158. }
  189159. break;
  189160. }
  189161. case 6:
  189162. {
  189163. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189164. png_read_push_finish_row(png_ptr);
  189165. if (png_ptr->pass != 6)
  189166. break;
  189167. png_push_have_row(png_ptr, png_bytep_NULL);
  189168. png_read_push_finish_row(png_ptr);
  189169. }
  189170. }
  189171. }
  189172. else
  189173. #endif
  189174. {
  189175. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189176. png_read_push_finish_row(png_ptr);
  189177. }
  189178. }
  189179. void /* PRIVATE */
  189180. png_read_push_finish_row(png_structp png_ptr)
  189181. {
  189182. #ifdef PNG_USE_LOCAL_ARRAYS
  189183. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189184. /* start of interlace block */
  189185. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189186. /* offset to next interlace block */
  189187. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189188. /* start of interlace block in the y direction */
  189189. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189190. /* offset to next interlace block in the y direction */
  189191. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189192. /* Height of interlace block. This is not currently used - if you need
  189193. * it, uncomment it here and in png.h
  189194. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189195. */
  189196. #endif
  189197. png_ptr->row_number++;
  189198. if (png_ptr->row_number < png_ptr->num_rows)
  189199. return;
  189200. if (png_ptr->interlaced)
  189201. {
  189202. png_ptr->row_number = 0;
  189203. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189204. png_ptr->rowbytes + 1);
  189205. do
  189206. {
  189207. png_ptr->pass++;
  189208. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189209. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189210. (png_ptr->pass == 5 && png_ptr->width < 2))
  189211. png_ptr->pass++;
  189212. if (png_ptr->pass > 7)
  189213. png_ptr->pass--;
  189214. if (png_ptr->pass >= 7)
  189215. break;
  189216. png_ptr->iwidth = (png_ptr->width +
  189217. png_pass_inc[png_ptr->pass] - 1 -
  189218. png_pass_start[png_ptr->pass]) /
  189219. png_pass_inc[png_ptr->pass];
  189220. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189221. png_ptr->iwidth) + 1;
  189222. if (png_ptr->transformations & PNG_INTERLACE)
  189223. break;
  189224. png_ptr->num_rows = (png_ptr->height +
  189225. png_pass_yinc[png_ptr->pass] - 1 -
  189226. png_pass_ystart[png_ptr->pass]) /
  189227. png_pass_yinc[png_ptr->pass];
  189228. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189229. }
  189230. }
  189231. #if defined(PNG_READ_tEXt_SUPPORTED)
  189232. void /* PRIVATE */
  189233. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189234. length)
  189235. {
  189236. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189237. {
  189238. png_error(png_ptr, "Out of place tEXt");
  189239. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189240. }
  189241. #ifdef PNG_MAX_MALLOC_64K
  189242. png_ptr->skip_length = 0; /* This may not be necessary */
  189243. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189244. {
  189245. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189246. png_ptr->skip_length = length - (png_uint_32)65535L;
  189247. length = (png_uint_32)65535L;
  189248. }
  189249. #endif
  189250. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189251. (png_uint_32)(length+1));
  189252. png_ptr->current_text[length] = '\0';
  189253. png_ptr->current_text_ptr = png_ptr->current_text;
  189254. png_ptr->current_text_size = (png_size_t)length;
  189255. png_ptr->current_text_left = (png_size_t)length;
  189256. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189257. }
  189258. void /* PRIVATE */
  189259. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189260. {
  189261. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189262. {
  189263. png_size_t text_size;
  189264. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189265. text_size = png_ptr->buffer_size;
  189266. else
  189267. text_size = png_ptr->current_text_left;
  189268. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189269. png_ptr->current_text_left -= text_size;
  189270. png_ptr->current_text_ptr += text_size;
  189271. }
  189272. if (!(png_ptr->current_text_left))
  189273. {
  189274. png_textp text_ptr;
  189275. png_charp text;
  189276. png_charp key;
  189277. int ret;
  189278. if (png_ptr->buffer_size < 4)
  189279. {
  189280. png_push_save_buffer(png_ptr);
  189281. return;
  189282. }
  189283. png_push_crc_finish(png_ptr);
  189284. #if defined(PNG_MAX_MALLOC_64K)
  189285. if (png_ptr->skip_length)
  189286. return;
  189287. #endif
  189288. key = png_ptr->current_text;
  189289. for (text = key; *text; text++)
  189290. /* empty loop */ ;
  189291. if (text < key + png_ptr->current_text_size)
  189292. text++;
  189293. text_ptr = (png_textp)png_malloc(png_ptr,
  189294. (png_uint_32)png_sizeof(png_text));
  189295. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189296. text_ptr->key = key;
  189297. #ifdef PNG_iTXt_SUPPORTED
  189298. text_ptr->lang = NULL;
  189299. text_ptr->lang_key = NULL;
  189300. #endif
  189301. text_ptr->text = text;
  189302. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189303. png_free(png_ptr, key);
  189304. png_free(png_ptr, text_ptr);
  189305. png_ptr->current_text = NULL;
  189306. if (ret)
  189307. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189308. }
  189309. }
  189310. #endif
  189311. #if defined(PNG_READ_zTXt_SUPPORTED)
  189312. void /* PRIVATE */
  189313. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189314. length)
  189315. {
  189316. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189317. {
  189318. png_error(png_ptr, "Out of place zTXt");
  189319. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189320. }
  189321. #ifdef PNG_MAX_MALLOC_64K
  189322. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189323. * to be able to store the uncompressed data. Actually, the threshold
  189324. * is probably around 32K, but it isn't as definite as 64K is.
  189325. */
  189326. if (length > (png_uint_32)65535L)
  189327. {
  189328. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189329. png_push_crc_skip(png_ptr, length);
  189330. return;
  189331. }
  189332. #endif
  189333. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189334. (png_uint_32)(length+1));
  189335. png_ptr->current_text[length] = '\0';
  189336. png_ptr->current_text_ptr = png_ptr->current_text;
  189337. png_ptr->current_text_size = (png_size_t)length;
  189338. png_ptr->current_text_left = (png_size_t)length;
  189339. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189340. }
  189341. void /* PRIVATE */
  189342. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189343. {
  189344. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189345. {
  189346. png_size_t text_size;
  189347. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189348. text_size = png_ptr->buffer_size;
  189349. else
  189350. text_size = png_ptr->current_text_left;
  189351. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189352. png_ptr->current_text_left -= text_size;
  189353. png_ptr->current_text_ptr += text_size;
  189354. }
  189355. if (!(png_ptr->current_text_left))
  189356. {
  189357. png_textp text_ptr;
  189358. png_charp text;
  189359. png_charp key;
  189360. int ret;
  189361. png_size_t text_size, key_size;
  189362. if (png_ptr->buffer_size < 4)
  189363. {
  189364. png_push_save_buffer(png_ptr);
  189365. return;
  189366. }
  189367. png_push_crc_finish(png_ptr);
  189368. key = png_ptr->current_text;
  189369. for (text = key; *text; text++)
  189370. /* empty loop */ ;
  189371. /* zTXt can't have zero text */
  189372. if (text >= key + png_ptr->current_text_size)
  189373. {
  189374. png_ptr->current_text = NULL;
  189375. png_free(png_ptr, key);
  189376. return;
  189377. }
  189378. text++;
  189379. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189380. {
  189381. png_ptr->current_text = NULL;
  189382. png_free(png_ptr, key);
  189383. return;
  189384. }
  189385. text++;
  189386. png_ptr->zstream.next_in = (png_bytep )text;
  189387. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189388. (text - key));
  189389. png_ptr->zstream.next_out = png_ptr->zbuf;
  189390. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189391. key_size = text - key;
  189392. text_size = 0;
  189393. text = NULL;
  189394. ret = Z_STREAM_END;
  189395. while (png_ptr->zstream.avail_in)
  189396. {
  189397. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189398. if (ret != Z_OK && ret != Z_STREAM_END)
  189399. {
  189400. inflateReset(&png_ptr->zstream);
  189401. png_ptr->zstream.avail_in = 0;
  189402. png_ptr->current_text = NULL;
  189403. png_free(png_ptr, key);
  189404. png_free(png_ptr, text);
  189405. return;
  189406. }
  189407. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189408. {
  189409. if (text == NULL)
  189410. {
  189411. text = (png_charp)png_malloc(png_ptr,
  189412. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189413. + key_size + 1));
  189414. png_memcpy(text + key_size, png_ptr->zbuf,
  189415. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189416. png_memcpy(text, key, key_size);
  189417. text_size = key_size + png_ptr->zbuf_size -
  189418. png_ptr->zstream.avail_out;
  189419. *(text + text_size) = '\0';
  189420. }
  189421. else
  189422. {
  189423. png_charp tmp;
  189424. tmp = text;
  189425. text = (png_charp)png_malloc(png_ptr, text_size +
  189426. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189427. + 1));
  189428. png_memcpy(text, tmp, text_size);
  189429. png_free(png_ptr, tmp);
  189430. png_memcpy(text + text_size, png_ptr->zbuf,
  189431. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189432. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189433. *(text + text_size) = '\0';
  189434. }
  189435. if (ret != Z_STREAM_END)
  189436. {
  189437. png_ptr->zstream.next_out = png_ptr->zbuf;
  189438. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189439. }
  189440. }
  189441. else
  189442. {
  189443. break;
  189444. }
  189445. if (ret == Z_STREAM_END)
  189446. break;
  189447. }
  189448. inflateReset(&png_ptr->zstream);
  189449. png_ptr->zstream.avail_in = 0;
  189450. if (ret != Z_STREAM_END)
  189451. {
  189452. png_ptr->current_text = NULL;
  189453. png_free(png_ptr, key);
  189454. png_free(png_ptr, text);
  189455. return;
  189456. }
  189457. png_ptr->current_text = NULL;
  189458. png_free(png_ptr, key);
  189459. key = text;
  189460. text += key_size;
  189461. text_ptr = (png_textp)png_malloc(png_ptr,
  189462. (png_uint_32)png_sizeof(png_text));
  189463. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189464. text_ptr->key = key;
  189465. #ifdef PNG_iTXt_SUPPORTED
  189466. text_ptr->lang = NULL;
  189467. text_ptr->lang_key = NULL;
  189468. #endif
  189469. text_ptr->text = text;
  189470. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189471. png_free(png_ptr, key);
  189472. png_free(png_ptr, text_ptr);
  189473. if (ret)
  189474. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189475. }
  189476. }
  189477. #endif
  189478. #if defined(PNG_READ_iTXt_SUPPORTED)
  189479. void /* PRIVATE */
  189480. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189481. length)
  189482. {
  189483. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189484. {
  189485. png_error(png_ptr, "Out of place iTXt");
  189486. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189487. }
  189488. #ifdef PNG_MAX_MALLOC_64K
  189489. png_ptr->skip_length = 0; /* This may not be necessary */
  189490. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189491. {
  189492. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189493. png_ptr->skip_length = length - (png_uint_32)65535L;
  189494. length = (png_uint_32)65535L;
  189495. }
  189496. #endif
  189497. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189498. (png_uint_32)(length+1));
  189499. png_ptr->current_text[length] = '\0';
  189500. png_ptr->current_text_ptr = png_ptr->current_text;
  189501. png_ptr->current_text_size = (png_size_t)length;
  189502. png_ptr->current_text_left = (png_size_t)length;
  189503. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189504. }
  189505. void /* PRIVATE */
  189506. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189507. {
  189508. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189509. {
  189510. png_size_t text_size;
  189511. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189512. text_size = png_ptr->buffer_size;
  189513. else
  189514. text_size = png_ptr->current_text_left;
  189515. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189516. png_ptr->current_text_left -= text_size;
  189517. png_ptr->current_text_ptr += text_size;
  189518. }
  189519. if (!(png_ptr->current_text_left))
  189520. {
  189521. png_textp text_ptr;
  189522. png_charp key;
  189523. int comp_flag;
  189524. png_charp lang;
  189525. png_charp lang_key;
  189526. png_charp text;
  189527. int ret;
  189528. if (png_ptr->buffer_size < 4)
  189529. {
  189530. png_push_save_buffer(png_ptr);
  189531. return;
  189532. }
  189533. png_push_crc_finish(png_ptr);
  189534. #if defined(PNG_MAX_MALLOC_64K)
  189535. if (png_ptr->skip_length)
  189536. return;
  189537. #endif
  189538. key = png_ptr->current_text;
  189539. for (lang = key; *lang; lang++)
  189540. /* empty loop */ ;
  189541. if (lang < key + png_ptr->current_text_size - 3)
  189542. lang++;
  189543. comp_flag = *lang++;
  189544. lang++; /* skip comp_type, always zero */
  189545. for (lang_key = lang; *lang_key; lang_key++)
  189546. /* empty loop */ ;
  189547. lang_key++; /* skip NUL separator */
  189548. text=lang_key;
  189549. if (lang_key < key + png_ptr->current_text_size - 1)
  189550. {
  189551. for (; *text; text++)
  189552. /* empty loop */ ;
  189553. }
  189554. if (text < key + png_ptr->current_text_size)
  189555. text++;
  189556. text_ptr = (png_textp)png_malloc(png_ptr,
  189557. (png_uint_32)png_sizeof(png_text));
  189558. text_ptr->compression = comp_flag + 2;
  189559. text_ptr->key = key;
  189560. text_ptr->lang = lang;
  189561. text_ptr->lang_key = lang_key;
  189562. text_ptr->text = text;
  189563. text_ptr->text_length = 0;
  189564. text_ptr->itxt_length = png_strlen(text);
  189565. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189566. png_ptr->current_text = NULL;
  189567. png_free(png_ptr, text_ptr);
  189568. if (ret)
  189569. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189570. }
  189571. }
  189572. #endif
  189573. /* This function is called when we haven't found a handler for this
  189574. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189575. * name or a critical chunk), the chunk is (currently) silently ignored.
  189576. */
  189577. void /* PRIVATE */
  189578. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189579. length)
  189580. {
  189581. png_uint_32 skip=0;
  189582. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189583. if (!(png_ptr->chunk_name[0] & 0x20))
  189584. {
  189585. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189586. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189587. PNG_HANDLE_CHUNK_ALWAYS
  189588. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189589. && png_ptr->read_user_chunk_fn == NULL
  189590. #endif
  189591. )
  189592. #endif
  189593. png_chunk_error(png_ptr, "unknown critical chunk");
  189594. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189595. }
  189596. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189597. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189598. {
  189599. #ifdef PNG_MAX_MALLOC_64K
  189600. if (length > (png_uint_32)65535L)
  189601. {
  189602. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189603. skip = length - (png_uint_32)65535L;
  189604. length = (png_uint_32)65535L;
  189605. }
  189606. #endif
  189607. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189608. (png_charp)png_ptr->chunk_name, 5);
  189609. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189610. png_ptr->unknown_chunk.size = (png_size_t)length;
  189611. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189612. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189613. if(png_ptr->read_user_chunk_fn != NULL)
  189614. {
  189615. /* callback to user unknown chunk handler */
  189616. int ret;
  189617. ret = (*(png_ptr->read_user_chunk_fn))
  189618. (png_ptr, &png_ptr->unknown_chunk);
  189619. if (ret < 0)
  189620. png_chunk_error(png_ptr, "error in user chunk");
  189621. if (ret == 0)
  189622. {
  189623. if (!(png_ptr->chunk_name[0] & 0x20))
  189624. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189625. PNG_HANDLE_CHUNK_ALWAYS)
  189626. png_chunk_error(png_ptr, "unknown critical chunk");
  189627. png_set_unknown_chunks(png_ptr, info_ptr,
  189628. &png_ptr->unknown_chunk, 1);
  189629. }
  189630. }
  189631. #else
  189632. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189633. #endif
  189634. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189635. png_ptr->unknown_chunk.data = NULL;
  189636. }
  189637. else
  189638. #endif
  189639. skip=length;
  189640. png_push_crc_skip(png_ptr, skip);
  189641. }
  189642. void /* PRIVATE */
  189643. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189644. {
  189645. if (png_ptr->info_fn != NULL)
  189646. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189647. }
  189648. void /* PRIVATE */
  189649. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189650. {
  189651. if (png_ptr->end_fn != NULL)
  189652. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189653. }
  189654. void /* PRIVATE */
  189655. png_push_have_row(png_structp png_ptr, png_bytep row)
  189656. {
  189657. if (png_ptr->row_fn != NULL)
  189658. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189659. (int)png_ptr->pass);
  189660. }
  189661. void PNGAPI
  189662. png_progressive_combine_row (png_structp png_ptr,
  189663. png_bytep old_row, png_bytep new_row)
  189664. {
  189665. #ifdef PNG_USE_LOCAL_ARRAYS
  189666. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189667. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189668. #endif
  189669. if(png_ptr == NULL) return;
  189670. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189671. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189672. }
  189673. void PNGAPI
  189674. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189675. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189676. png_progressive_end_ptr end_fn)
  189677. {
  189678. if(png_ptr == NULL) return;
  189679. png_ptr->info_fn = info_fn;
  189680. png_ptr->row_fn = row_fn;
  189681. png_ptr->end_fn = end_fn;
  189682. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189683. }
  189684. png_voidp PNGAPI
  189685. png_get_progressive_ptr(png_structp png_ptr)
  189686. {
  189687. if(png_ptr == NULL) return (NULL);
  189688. return png_ptr->io_ptr;
  189689. }
  189690. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189691. /*** End of inlined file: pngpread.c ***/
  189692. /*** Start of inlined file: pngrio.c ***/
  189693. /* pngrio.c - functions for data input
  189694. *
  189695. * Last changed in libpng 1.2.13 November 13, 2006
  189696. * For conditions of distribution and use, see copyright notice in png.h
  189697. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189698. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189699. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189700. *
  189701. * This file provides a location for all input. Users who need
  189702. * special handling are expected to write a function that has the same
  189703. * arguments as this and performs a similar function, but that possibly
  189704. * has a different input method. Note that you shouldn't change this
  189705. * function, but rather write a replacement function and then make
  189706. * libpng use it at run time with png_set_read_fn(...).
  189707. */
  189708. #define PNG_INTERNAL
  189709. #if defined(PNG_READ_SUPPORTED)
  189710. /* Read the data from whatever input you are using. The default routine
  189711. reads from a file pointer. Note that this routine sometimes gets called
  189712. with very small lengths, so you should implement some kind of simple
  189713. buffering if you are using unbuffered reads. This should never be asked
  189714. to read more then 64K on a 16 bit machine. */
  189715. void /* PRIVATE */
  189716. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189717. {
  189718. png_debug1(4,"reading %d bytes\n", (int)length);
  189719. if (png_ptr->read_data_fn != NULL)
  189720. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189721. else
  189722. png_error(png_ptr, "Call to NULL read function");
  189723. }
  189724. #if !defined(PNG_NO_STDIO)
  189725. /* This is the function that does the actual reading of data. If you are
  189726. not reading from a standard C stream, you should create a replacement
  189727. read_data function and use it at run time with png_set_read_fn(), rather
  189728. than changing the library. */
  189729. #ifndef USE_FAR_KEYWORD
  189730. void PNGAPI
  189731. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189732. {
  189733. png_size_t check;
  189734. if(png_ptr == NULL) return;
  189735. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189736. * instead of an int, which is what fread() actually returns.
  189737. */
  189738. #if defined(_WIN32_WCE)
  189739. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189740. check = 0;
  189741. #else
  189742. check = (png_size_t)fread(data, (png_size_t)1, length,
  189743. (png_FILE_p)png_ptr->io_ptr);
  189744. #endif
  189745. if (check != length)
  189746. png_error(png_ptr, "Read Error");
  189747. }
  189748. #else
  189749. /* this is the model-independent version. Since the standard I/O library
  189750. can't handle far buffers in the medium and small models, we have to copy
  189751. the data.
  189752. */
  189753. #define NEAR_BUF_SIZE 1024
  189754. #define MIN(a,b) (a <= b ? a : b)
  189755. static void PNGAPI
  189756. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189757. {
  189758. int check;
  189759. png_byte *n_data;
  189760. png_FILE_p io_ptr;
  189761. if(png_ptr == NULL) return;
  189762. /* Check if data really is near. If so, use usual code. */
  189763. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189764. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189765. if ((png_bytep)n_data == data)
  189766. {
  189767. #if defined(_WIN32_WCE)
  189768. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189769. check = 0;
  189770. #else
  189771. check = fread(n_data, 1, length, io_ptr);
  189772. #endif
  189773. }
  189774. else
  189775. {
  189776. png_byte buf[NEAR_BUF_SIZE];
  189777. png_size_t read, remaining, err;
  189778. check = 0;
  189779. remaining = length;
  189780. do
  189781. {
  189782. read = MIN(NEAR_BUF_SIZE, remaining);
  189783. #if defined(_WIN32_WCE)
  189784. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189785. err = 0;
  189786. #else
  189787. err = fread(buf, (png_size_t)1, read, io_ptr);
  189788. #endif
  189789. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189790. if(err != read)
  189791. break;
  189792. else
  189793. check += err;
  189794. data += read;
  189795. remaining -= read;
  189796. }
  189797. while (remaining != 0);
  189798. }
  189799. if ((png_uint_32)check != (png_uint_32)length)
  189800. png_error(png_ptr, "read Error");
  189801. }
  189802. #endif
  189803. #endif
  189804. /* This function allows the application to supply a new input function
  189805. for libpng if standard C streams aren't being used.
  189806. This function takes as its arguments:
  189807. png_ptr - pointer to a png input data structure
  189808. io_ptr - pointer to user supplied structure containing info about
  189809. the input functions. May be NULL.
  189810. read_data_fn - pointer to a new input function that takes as its
  189811. arguments a pointer to a png_struct, a pointer to
  189812. a location where input data can be stored, and a 32-bit
  189813. unsigned int that is the number of bytes to be read.
  189814. To exit and output any fatal error messages the new write
  189815. function should call png_error(png_ptr, "Error msg"). */
  189816. void PNGAPI
  189817. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189818. png_rw_ptr read_data_fn)
  189819. {
  189820. if(png_ptr == NULL) return;
  189821. png_ptr->io_ptr = io_ptr;
  189822. #if !defined(PNG_NO_STDIO)
  189823. if (read_data_fn != NULL)
  189824. png_ptr->read_data_fn = read_data_fn;
  189825. else
  189826. png_ptr->read_data_fn = png_default_read_data;
  189827. #else
  189828. png_ptr->read_data_fn = read_data_fn;
  189829. #endif
  189830. /* It is an error to write to a read device */
  189831. if (png_ptr->write_data_fn != NULL)
  189832. {
  189833. png_ptr->write_data_fn = NULL;
  189834. png_warning(png_ptr,
  189835. "It's an error to set both read_data_fn and write_data_fn in the ");
  189836. png_warning(png_ptr,
  189837. "same structure. Resetting write_data_fn to NULL.");
  189838. }
  189839. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189840. png_ptr->output_flush_fn = NULL;
  189841. #endif
  189842. }
  189843. #endif /* PNG_READ_SUPPORTED */
  189844. /*** End of inlined file: pngrio.c ***/
  189845. /*** Start of inlined file: pngrtran.c ***/
  189846. /* pngrtran.c - transforms the data in a row for PNG readers
  189847. *
  189848. * Last changed in libpng 1.2.21 [October 4, 2007]
  189849. * For conditions of distribution and use, see copyright notice in png.h
  189850. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189851. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189852. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189853. *
  189854. * This file contains functions optionally called by an application
  189855. * in order to tell libpng how to handle data when reading a PNG.
  189856. * Transformations that are used in both reading and writing are
  189857. * in pngtrans.c.
  189858. */
  189859. #define PNG_INTERNAL
  189860. #if defined(PNG_READ_SUPPORTED)
  189861. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189862. void PNGAPI
  189863. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189864. {
  189865. png_debug(1, "in png_set_crc_action\n");
  189866. /* Tell libpng how we react to CRC errors in critical chunks */
  189867. if(png_ptr == NULL) return;
  189868. switch (crit_action)
  189869. {
  189870. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189871. break;
  189872. case PNG_CRC_WARN_USE: /* warn/use data */
  189873. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189874. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189875. break;
  189876. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189877. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189878. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189879. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189880. break;
  189881. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189882. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189883. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189884. case PNG_CRC_DEFAULT:
  189885. default:
  189886. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189887. break;
  189888. }
  189889. switch (ancil_action)
  189890. {
  189891. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189892. break;
  189893. case PNG_CRC_WARN_USE: /* warn/use data */
  189894. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189895. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189896. break;
  189897. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189898. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189899. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189900. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189901. break;
  189902. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189903. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189904. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189905. break;
  189906. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189907. case PNG_CRC_DEFAULT:
  189908. default:
  189909. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189910. break;
  189911. }
  189912. }
  189913. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189914. defined(PNG_FLOATING_POINT_SUPPORTED)
  189915. /* handle alpha and tRNS via a background color */
  189916. void PNGAPI
  189917. png_set_background(png_structp png_ptr,
  189918. png_color_16p background_color, int background_gamma_code,
  189919. int need_expand, double background_gamma)
  189920. {
  189921. png_debug(1, "in png_set_background\n");
  189922. if(png_ptr == NULL) return;
  189923. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189924. {
  189925. png_warning(png_ptr, "Application must supply a known background gamma");
  189926. return;
  189927. }
  189928. png_ptr->transformations |= PNG_BACKGROUND;
  189929. png_memcpy(&(png_ptr->background), background_color,
  189930. png_sizeof(png_color_16));
  189931. png_ptr->background_gamma = (float)background_gamma;
  189932. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189933. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189934. }
  189935. #endif
  189936. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189937. /* strip 16 bit depth files to 8 bit depth */
  189938. void PNGAPI
  189939. png_set_strip_16(png_structp png_ptr)
  189940. {
  189941. png_debug(1, "in png_set_strip_16\n");
  189942. if(png_ptr == NULL) return;
  189943. png_ptr->transformations |= PNG_16_TO_8;
  189944. }
  189945. #endif
  189946. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189947. void PNGAPI
  189948. png_set_strip_alpha(png_structp png_ptr)
  189949. {
  189950. png_debug(1, "in png_set_strip_alpha\n");
  189951. if(png_ptr == NULL) return;
  189952. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189953. }
  189954. #endif
  189955. #if defined(PNG_READ_DITHER_SUPPORTED)
  189956. /* Dither file to 8 bit. Supply a palette, the current number
  189957. * of elements in the palette, the maximum number of elements
  189958. * allowed, and a histogram if possible. If the current number
  189959. * of colors is greater then the maximum number, the palette will be
  189960. * modified to fit in the maximum number. "full_dither" indicates
  189961. * whether we need a dithering cube set up for RGB images, or if we
  189962. * simply are reducing the number of colors in a paletted image.
  189963. */
  189964. typedef struct png_dsort_struct
  189965. {
  189966. struct png_dsort_struct FAR * next;
  189967. png_byte left;
  189968. png_byte right;
  189969. } png_dsort;
  189970. typedef png_dsort FAR * png_dsortp;
  189971. typedef png_dsort FAR * FAR * png_dsortpp;
  189972. void PNGAPI
  189973. png_set_dither(png_structp png_ptr, png_colorp palette,
  189974. int num_palette, int maximum_colors, png_uint_16p histogram,
  189975. int full_dither)
  189976. {
  189977. png_debug(1, "in png_set_dither\n");
  189978. if(png_ptr == NULL) return;
  189979. png_ptr->transformations |= PNG_DITHER;
  189980. if (!full_dither)
  189981. {
  189982. int i;
  189983. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189984. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189985. for (i = 0; i < num_palette; i++)
  189986. png_ptr->dither_index[i] = (png_byte)i;
  189987. }
  189988. if (num_palette > maximum_colors)
  189989. {
  189990. if (histogram != NULL)
  189991. {
  189992. /* This is easy enough, just throw out the least used colors.
  189993. Perhaps not the best solution, but good enough. */
  189994. int i;
  189995. /* initialize an array to sort colors */
  189996. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189997. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189998. /* initialize the dither_sort array */
  189999. for (i = 0; i < num_palette; i++)
  190000. png_ptr->dither_sort[i] = (png_byte)i;
  190001. /* Find the least used palette entries by starting a
  190002. bubble sort, and running it until we have sorted
  190003. out enough colors. Note that we don't care about
  190004. sorting all the colors, just finding which are
  190005. least used. */
  190006. for (i = num_palette - 1; i >= maximum_colors; i--)
  190007. {
  190008. int done; /* to stop early if the list is pre-sorted */
  190009. int j;
  190010. done = 1;
  190011. for (j = 0; j < i; j++)
  190012. {
  190013. if (histogram[png_ptr->dither_sort[j]]
  190014. < histogram[png_ptr->dither_sort[j + 1]])
  190015. {
  190016. png_byte t;
  190017. t = png_ptr->dither_sort[j];
  190018. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190019. png_ptr->dither_sort[j + 1] = t;
  190020. done = 0;
  190021. }
  190022. }
  190023. if (done)
  190024. break;
  190025. }
  190026. /* swap the palette around, and set up a table, if necessary */
  190027. if (full_dither)
  190028. {
  190029. int j = num_palette;
  190030. /* put all the useful colors within the max, but don't
  190031. move the others */
  190032. for (i = 0; i < maximum_colors; i++)
  190033. {
  190034. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190035. {
  190036. do
  190037. j--;
  190038. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190039. palette[i] = palette[j];
  190040. }
  190041. }
  190042. }
  190043. else
  190044. {
  190045. int j = num_palette;
  190046. /* move all the used colors inside the max limit, and
  190047. develop a translation table */
  190048. for (i = 0; i < maximum_colors; i++)
  190049. {
  190050. /* only move the colors we need to */
  190051. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190052. {
  190053. png_color tmp_color;
  190054. do
  190055. j--;
  190056. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190057. tmp_color = palette[j];
  190058. palette[j] = palette[i];
  190059. palette[i] = tmp_color;
  190060. /* indicate where the color went */
  190061. png_ptr->dither_index[j] = (png_byte)i;
  190062. png_ptr->dither_index[i] = (png_byte)j;
  190063. }
  190064. }
  190065. /* find closest color for those colors we are not using */
  190066. for (i = 0; i < num_palette; i++)
  190067. {
  190068. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190069. {
  190070. int min_d, k, min_k, d_index;
  190071. /* find the closest color to one we threw out */
  190072. d_index = png_ptr->dither_index[i];
  190073. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190074. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190075. {
  190076. int d;
  190077. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190078. if (d < min_d)
  190079. {
  190080. min_d = d;
  190081. min_k = k;
  190082. }
  190083. }
  190084. /* point to closest color */
  190085. png_ptr->dither_index[i] = (png_byte)min_k;
  190086. }
  190087. }
  190088. }
  190089. png_free(png_ptr, png_ptr->dither_sort);
  190090. png_ptr->dither_sort=NULL;
  190091. }
  190092. else
  190093. {
  190094. /* This is much harder to do simply (and quickly). Perhaps
  190095. we need to go through a median cut routine, but those
  190096. don't always behave themselves with only a few colors
  190097. as input. So we will just find the closest two colors,
  190098. and throw out one of them (chosen somewhat randomly).
  190099. [We don't understand this at all, so if someone wants to
  190100. work on improving it, be our guest - AED, GRP]
  190101. */
  190102. int i;
  190103. int max_d;
  190104. int num_new_palette;
  190105. png_dsortp t;
  190106. png_dsortpp hash;
  190107. t=NULL;
  190108. /* initialize palette index arrays */
  190109. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190110. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190111. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190112. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190113. /* initialize the sort array */
  190114. for (i = 0; i < num_palette; i++)
  190115. {
  190116. png_ptr->index_to_palette[i] = (png_byte)i;
  190117. png_ptr->palette_to_index[i] = (png_byte)i;
  190118. }
  190119. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190120. png_sizeof (png_dsortp)));
  190121. for (i = 0; i < 769; i++)
  190122. hash[i] = NULL;
  190123. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190124. num_new_palette = num_palette;
  190125. /* initial wild guess at how far apart the farthest pixel
  190126. pair we will be eliminating will be. Larger
  190127. numbers mean more areas will be allocated, Smaller
  190128. numbers run the risk of not saving enough data, and
  190129. having to do this all over again.
  190130. I have not done extensive checking on this number.
  190131. */
  190132. max_d = 96;
  190133. while (num_new_palette > maximum_colors)
  190134. {
  190135. for (i = 0; i < num_new_palette - 1; i++)
  190136. {
  190137. int j;
  190138. for (j = i + 1; j < num_new_palette; j++)
  190139. {
  190140. int d;
  190141. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190142. if (d <= max_d)
  190143. {
  190144. t = (png_dsortp)png_malloc_warn(png_ptr,
  190145. (png_uint_32)(png_sizeof(png_dsort)));
  190146. if (t == NULL)
  190147. break;
  190148. t->next = hash[d];
  190149. t->left = (png_byte)i;
  190150. t->right = (png_byte)j;
  190151. hash[d] = t;
  190152. }
  190153. }
  190154. if (t == NULL)
  190155. break;
  190156. }
  190157. if (t != NULL)
  190158. for (i = 0; i <= max_d; i++)
  190159. {
  190160. if (hash[i] != NULL)
  190161. {
  190162. png_dsortp p;
  190163. for (p = hash[i]; p; p = p->next)
  190164. {
  190165. if ((int)png_ptr->index_to_palette[p->left]
  190166. < num_new_palette &&
  190167. (int)png_ptr->index_to_palette[p->right]
  190168. < num_new_palette)
  190169. {
  190170. int j, next_j;
  190171. if (num_new_palette & 0x01)
  190172. {
  190173. j = p->left;
  190174. next_j = p->right;
  190175. }
  190176. else
  190177. {
  190178. j = p->right;
  190179. next_j = p->left;
  190180. }
  190181. num_new_palette--;
  190182. palette[png_ptr->index_to_palette[j]]
  190183. = palette[num_new_palette];
  190184. if (!full_dither)
  190185. {
  190186. int k;
  190187. for (k = 0; k < num_palette; k++)
  190188. {
  190189. if (png_ptr->dither_index[k] ==
  190190. png_ptr->index_to_palette[j])
  190191. png_ptr->dither_index[k] =
  190192. png_ptr->index_to_palette[next_j];
  190193. if ((int)png_ptr->dither_index[k] ==
  190194. num_new_palette)
  190195. png_ptr->dither_index[k] =
  190196. png_ptr->index_to_palette[j];
  190197. }
  190198. }
  190199. png_ptr->index_to_palette[png_ptr->palette_to_index
  190200. [num_new_palette]] = png_ptr->index_to_palette[j];
  190201. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190202. = png_ptr->palette_to_index[num_new_palette];
  190203. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190204. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190205. }
  190206. if (num_new_palette <= maximum_colors)
  190207. break;
  190208. }
  190209. if (num_new_palette <= maximum_colors)
  190210. break;
  190211. }
  190212. }
  190213. for (i = 0; i < 769; i++)
  190214. {
  190215. if (hash[i] != NULL)
  190216. {
  190217. png_dsortp p = hash[i];
  190218. while (p)
  190219. {
  190220. t = p->next;
  190221. png_free(png_ptr, p);
  190222. p = t;
  190223. }
  190224. }
  190225. hash[i] = 0;
  190226. }
  190227. max_d += 96;
  190228. }
  190229. png_free(png_ptr, hash);
  190230. png_free(png_ptr, png_ptr->palette_to_index);
  190231. png_free(png_ptr, png_ptr->index_to_palette);
  190232. png_ptr->palette_to_index=NULL;
  190233. png_ptr->index_to_palette=NULL;
  190234. }
  190235. num_palette = maximum_colors;
  190236. }
  190237. if (png_ptr->palette == NULL)
  190238. {
  190239. png_ptr->palette = palette;
  190240. }
  190241. png_ptr->num_palette = (png_uint_16)num_palette;
  190242. if (full_dither)
  190243. {
  190244. int i;
  190245. png_bytep distance;
  190246. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190247. PNG_DITHER_BLUE_BITS;
  190248. int num_red = (1 << PNG_DITHER_RED_BITS);
  190249. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190250. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190251. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190252. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190253. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190254. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190255. png_sizeof (png_byte));
  190256. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190257. png_sizeof(png_byte)));
  190258. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190259. for (i = 0; i < num_palette; i++)
  190260. {
  190261. int ir, ig, ib;
  190262. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190263. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190264. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190265. for (ir = 0; ir < num_red; ir++)
  190266. {
  190267. /* int dr = abs(ir - r); */
  190268. int dr = ((ir > r) ? ir - r : r - ir);
  190269. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190270. for (ig = 0; ig < num_green; ig++)
  190271. {
  190272. /* int dg = abs(ig - g); */
  190273. int dg = ((ig > g) ? ig - g : g - ig);
  190274. int dt = dr + dg;
  190275. int dm = ((dr > dg) ? dr : dg);
  190276. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190277. for (ib = 0; ib < num_blue; ib++)
  190278. {
  190279. int d_index = index_g | ib;
  190280. /* int db = abs(ib - b); */
  190281. int db = ((ib > b) ? ib - b : b - ib);
  190282. int dmax = ((dm > db) ? dm : db);
  190283. int d = dmax + dt + db;
  190284. if (d < (int)distance[d_index])
  190285. {
  190286. distance[d_index] = (png_byte)d;
  190287. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190288. }
  190289. }
  190290. }
  190291. }
  190292. }
  190293. png_free(png_ptr, distance);
  190294. }
  190295. }
  190296. #endif
  190297. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190298. /* Transform the image from the file_gamma to the screen_gamma. We
  190299. * only do transformations on images where the file_gamma and screen_gamma
  190300. * are not close reciprocals, otherwise it slows things down slightly, and
  190301. * also needlessly introduces small errors.
  190302. *
  190303. * We will turn off gamma transformation later if no semitransparent entries
  190304. * are present in the tRNS array for palette images. We can't do it here
  190305. * because we don't necessarily have the tRNS chunk yet.
  190306. */
  190307. void PNGAPI
  190308. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190309. {
  190310. png_debug(1, "in png_set_gamma\n");
  190311. if(png_ptr == NULL) return;
  190312. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190313. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190314. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190315. png_ptr->transformations |= PNG_GAMMA;
  190316. png_ptr->gamma = (float)file_gamma;
  190317. png_ptr->screen_gamma = (float)scrn_gamma;
  190318. }
  190319. #endif
  190320. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190321. /* Expand paletted images to RGB, expand grayscale images of
  190322. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190323. * to alpha channels.
  190324. */
  190325. void PNGAPI
  190326. png_set_expand(png_structp png_ptr)
  190327. {
  190328. png_debug(1, "in png_set_expand\n");
  190329. if(png_ptr == NULL) return;
  190330. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190331. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190332. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190333. #endif
  190334. }
  190335. /* GRR 19990627: the following three functions currently are identical
  190336. * to png_set_expand(). However, it is entirely reasonable that someone
  190337. * might wish to expand an indexed image to RGB but *not* expand a single,
  190338. * fully transparent palette entry to a full alpha channel--perhaps instead
  190339. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190340. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190341. * IOW, a future version of the library may make the transformations flag
  190342. * a bit more fine-grained, with separate bits for each of these three
  190343. * functions.
  190344. *
  190345. * More to the point, these functions make it obvious what libpng will be
  190346. * doing, whereas "expand" can (and does) mean any number of things.
  190347. *
  190348. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190349. * to expand only the sample depth but not to expand the tRNS to alpha.
  190350. */
  190351. /* Expand paletted images to RGB. */
  190352. void PNGAPI
  190353. png_set_palette_to_rgb(png_structp png_ptr)
  190354. {
  190355. png_debug(1, "in png_set_palette_to_rgb\n");
  190356. if(png_ptr == NULL) return;
  190357. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190358. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190359. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190360. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190361. #endif
  190362. }
  190363. #if !defined(PNG_1_0_X)
  190364. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190365. void PNGAPI
  190366. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190367. {
  190368. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190369. if(png_ptr == NULL) return;
  190370. png_ptr->transformations |= PNG_EXPAND;
  190371. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190372. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190373. #endif
  190374. }
  190375. #endif
  190376. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190377. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190378. /* Deprecated as of libpng-1.2.9 */
  190379. void PNGAPI
  190380. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190381. {
  190382. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190383. if(png_ptr == NULL) return;
  190384. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190385. }
  190386. #endif
  190387. /* Expand tRNS chunks to alpha channels. */
  190388. void PNGAPI
  190389. png_set_tRNS_to_alpha(png_structp png_ptr)
  190390. {
  190391. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190392. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190393. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190394. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190395. #endif
  190396. }
  190397. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190398. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190399. void PNGAPI
  190400. png_set_gray_to_rgb(png_structp png_ptr)
  190401. {
  190402. png_debug(1, "in png_set_gray_to_rgb\n");
  190403. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190404. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190405. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190406. #endif
  190407. }
  190408. #endif
  190409. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190410. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190411. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190412. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190413. */
  190414. void PNGAPI
  190415. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190416. double green)
  190417. {
  190418. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190419. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190420. if(png_ptr == NULL) return;
  190421. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190422. }
  190423. #endif
  190424. void PNGAPI
  190425. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190426. png_fixed_point red, png_fixed_point green)
  190427. {
  190428. png_debug(1, "in png_set_rgb_to_gray\n");
  190429. if(png_ptr == NULL) return;
  190430. switch(error_action)
  190431. {
  190432. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190433. break;
  190434. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190435. break;
  190436. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190437. }
  190438. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190439. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190440. png_ptr->transformations |= PNG_EXPAND;
  190441. #else
  190442. {
  190443. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190444. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190445. }
  190446. #endif
  190447. {
  190448. png_uint_16 red_int, green_int;
  190449. if(red < 0 || green < 0)
  190450. {
  190451. red_int = 6968; /* .212671 * 32768 + .5 */
  190452. green_int = 23434; /* .715160 * 32768 + .5 */
  190453. }
  190454. else if(red + green < 100000L)
  190455. {
  190456. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190457. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190458. }
  190459. else
  190460. {
  190461. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190462. red_int = 6968;
  190463. green_int = 23434;
  190464. }
  190465. png_ptr->rgb_to_gray_red_coeff = red_int;
  190466. png_ptr->rgb_to_gray_green_coeff = green_int;
  190467. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190468. }
  190469. }
  190470. #endif
  190471. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190472. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190473. defined(PNG_LEGACY_SUPPORTED)
  190474. void PNGAPI
  190475. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190476. read_user_transform_fn)
  190477. {
  190478. png_debug(1, "in png_set_read_user_transform_fn\n");
  190479. if(png_ptr == NULL) return;
  190480. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190481. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190482. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190483. #endif
  190484. #ifdef PNG_LEGACY_SUPPORTED
  190485. if(read_user_transform_fn)
  190486. png_warning(png_ptr,
  190487. "This version of libpng does not support user transforms");
  190488. #endif
  190489. }
  190490. #endif
  190491. /* Initialize everything needed for the read. This includes modifying
  190492. * the palette.
  190493. */
  190494. void /* PRIVATE */
  190495. png_init_read_transformations(png_structp png_ptr)
  190496. {
  190497. png_debug(1, "in png_init_read_transformations\n");
  190498. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190499. if(png_ptr != NULL)
  190500. #endif
  190501. {
  190502. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190503. || defined(PNG_READ_GAMMA_SUPPORTED)
  190504. int color_type = png_ptr->color_type;
  190505. #endif
  190506. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190507. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190508. /* Detect gray background and attempt to enable optimization
  190509. * for gray --> RGB case */
  190510. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190511. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190512. * background color might actually be gray yet not be flagged as such.
  190513. * This is not a problem for the current code, which uses
  190514. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190515. * png_do_gray_to_rgb() transformation.
  190516. */
  190517. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190518. !(color_type & PNG_COLOR_MASK_COLOR))
  190519. {
  190520. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190521. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190522. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190523. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190524. png_ptr->background.red == png_ptr->background.green &&
  190525. png_ptr->background.red == png_ptr->background.blue)
  190526. {
  190527. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190528. png_ptr->background.gray = png_ptr->background.red;
  190529. }
  190530. #endif
  190531. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190532. (png_ptr->transformations & PNG_EXPAND))
  190533. {
  190534. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190535. {
  190536. /* expand background and tRNS chunks */
  190537. switch (png_ptr->bit_depth)
  190538. {
  190539. case 1:
  190540. png_ptr->background.gray *= (png_uint_16)0xff;
  190541. png_ptr->background.red = png_ptr->background.green
  190542. = png_ptr->background.blue = png_ptr->background.gray;
  190543. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190544. {
  190545. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190546. png_ptr->trans_values.red = png_ptr->trans_values.green
  190547. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190548. }
  190549. break;
  190550. case 2:
  190551. png_ptr->background.gray *= (png_uint_16)0x55;
  190552. png_ptr->background.red = png_ptr->background.green
  190553. = png_ptr->background.blue = png_ptr->background.gray;
  190554. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190555. {
  190556. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190557. png_ptr->trans_values.red = png_ptr->trans_values.green
  190558. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190559. }
  190560. break;
  190561. case 4:
  190562. png_ptr->background.gray *= (png_uint_16)0x11;
  190563. png_ptr->background.red = png_ptr->background.green
  190564. = png_ptr->background.blue = png_ptr->background.gray;
  190565. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190566. {
  190567. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190568. png_ptr->trans_values.red = png_ptr->trans_values.green
  190569. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190570. }
  190571. break;
  190572. case 8:
  190573. case 16:
  190574. png_ptr->background.red = png_ptr->background.green
  190575. = png_ptr->background.blue = png_ptr->background.gray;
  190576. break;
  190577. }
  190578. }
  190579. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190580. {
  190581. png_ptr->background.red =
  190582. png_ptr->palette[png_ptr->background.index].red;
  190583. png_ptr->background.green =
  190584. png_ptr->palette[png_ptr->background.index].green;
  190585. png_ptr->background.blue =
  190586. png_ptr->palette[png_ptr->background.index].blue;
  190587. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190588. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190589. {
  190590. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190591. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190592. #endif
  190593. {
  190594. /* invert the alpha channel (in tRNS) unless the pixels are
  190595. going to be expanded, in which case leave it for later */
  190596. int i,istop;
  190597. istop=(int)png_ptr->num_trans;
  190598. for (i=0; i<istop; i++)
  190599. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190600. }
  190601. }
  190602. #endif
  190603. }
  190604. }
  190605. #endif
  190606. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190607. png_ptr->background_1 = png_ptr->background;
  190608. #endif
  190609. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190610. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190611. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190612. < PNG_GAMMA_THRESHOLD))
  190613. {
  190614. int i,k;
  190615. k=0;
  190616. for (i=0; i<png_ptr->num_trans; i++)
  190617. {
  190618. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190619. k=1; /* partial transparency is present */
  190620. }
  190621. if (k == 0)
  190622. png_ptr->transformations &= (~PNG_GAMMA);
  190623. }
  190624. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190625. png_ptr->gamma != 0.0)
  190626. {
  190627. png_build_gamma_table(png_ptr);
  190628. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190629. if (png_ptr->transformations & PNG_BACKGROUND)
  190630. {
  190631. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190632. {
  190633. /* could skip if no transparency and
  190634. */
  190635. png_color back, back_1;
  190636. png_colorp palette = png_ptr->palette;
  190637. int num_palette = png_ptr->num_palette;
  190638. int i;
  190639. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190640. {
  190641. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190642. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190643. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190644. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190645. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190646. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190647. }
  190648. else
  190649. {
  190650. double g, gs;
  190651. switch (png_ptr->background_gamma_type)
  190652. {
  190653. case PNG_BACKGROUND_GAMMA_SCREEN:
  190654. g = (png_ptr->screen_gamma);
  190655. gs = 1.0;
  190656. break;
  190657. case PNG_BACKGROUND_GAMMA_FILE:
  190658. g = 1.0 / (png_ptr->gamma);
  190659. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190660. break;
  190661. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190662. g = 1.0 / (png_ptr->background_gamma);
  190663. gs = 1.0 / (png_ptr->background_gamma *
  190664. png_ptr->screen_gamma);
  190665. break;
  190666. default:
  190667. g = 1.0; /* back_1 */
  190668. gs = 1.0; /* back */
  190669. }
  190670. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190671. {
  190672. back.red = (png_byte)png_ptr->background.red;
  190673. back.green = (png_byte)png_ptr->background.green;
  190674. back.blue = (png_byte)png_ptr->background.blue;
  190675. }
  190676. else
  190677. {
  190678. back.red = (png_byte)(pow(
  190679. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190680. back.green = (png_byte)(pow(
  190681. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190682. back.blue = (png_byte)(pow(
  190683. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190684. }
  190685. back_1.red = (png_byte)(pow(
  190686. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190687. back_1.green = (png_byte)(pow(
  190688. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190689. back_1.blue = (png_byte)(pow(
  190690. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190691. }
  190692. for (i = 0; i < num_palette; i++)
  190693. {
  190694. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190695. {
  190696. if (png_ptr->trans[i] == 0)
  190697. {
  190698. palette[i] = back;
  190699. }
  190700. else /* if (png_ptr->trans[i] != 0xff) */
  190701. {
  190702. png_byte v, w;
  190703. v = png_ptr->gamma_to_1[palette[i].red];
  190704. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190705. palette[i].red = png_ptr->gamma_from_1[w];
  190706. v = png_ptr->gamma_to_1[palette[i].green];
  190707. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190708. palette[i].green = png_ptr->gamma_from_1[w];
  190709. v = png_ptr->gamma_to_1[palette[i].blue];
  190710. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190711. palette[i].blue = png_ptr->gamma_from_1[w];
  190712. }
  190713. }
  190714. else
  190715. {
  190716. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190717. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190718. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190719. }
  190720. }
  190721. }
  190722. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190723. else
  190724. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190725. {
  190726. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190727. double g = 1.0;
  190728. double gs = 1.0;
  190729. switch (png_ptr->background_gamma_type)
  190730. {
  190731. case PNG_BACKGROUND_GAMMA_SCREEN:
  190732. g = (png_ptr->screen_gamma);
  190733. gs = 1.0;
  190734. break;
  190735. case PNG_BACKGROUND_GAMMA_FILE:
  190736. g = 1.0 / (png_ptr->gamma);
  190737. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190738. break;
  190739. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190740. g = 1.0 / (png_ptr->background_gamma);
  190741. gs = 1.0 / (png_ptr->background_gamma *
  190742. png_ptr->screen_gamma);
  190743. break;
  190744. }
  190745. png_ptr->background_1.gray = (png_uint_16)(pow(
  190746. (double)png_ptr->background.gray / m, g) * m + .5);
  190747. png_ptr->background.gray = (png_uint_16)(pow(
  190748. (double)png_ptr->background.gray / m, gs) * m + .5);
  190749. if ((png_ptr->background.red != png_ptr->background.green) ||
  190750. (png_ptr->background.red != png_ptr->background.blue) ||
  190751. (png_ptr->background.red != png_ptr->background.gray))
  190752. {
  190753. /* RGB or RGBA with color background */
  190754. png_ptr->background_1.red = (png_uint_16)(pow(
  190755. (double)png_ptr->background.red / m, g) * m + .5);
  190756. png_ptr->background_1.green = (png_uint_16)(pow(
  190757. (double)png_ptr->background.green / m, g) * m + .5);
  190758. png_ptr->background_1.blue = (png_uint_16)(pow(
  190759. (double)png_ptr->background.blue / m, g) * m + .5);
  190760. png_ptr->background.red = (png_uint_16)(pow(
  190761. (double)png_ptr->background.red / m, gs) * m + .5);
  190762. png_ptr->background.green = (png_uint_16)(pow(
  190763. (double)png_ptr->background.green / m, gs) * m + .5);
  190764. png_ptr->background.blue = (png_uint_16)(pow(
  190765. (double)png_ptr->background.blue / m, gs) * m + .5);
  190766. }
  190767. else
  190768. {
  190769. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190770. png_ptr->background_1.red = png_ptr->background_1.green
  190771. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190772. png_ptr->background.red = png_ptr->background.green
  190773. = png_ptr->background.blue = png_ptr->background.gray;
  190774. }
  190775. }
  190776. }
  190777. else
  190778. /* transformation does not include PNG_BACKGROUND */
  190779. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190780. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190781. {
  190782. png_colorp palette = png_ptr->palette;
  190783. int num_palette = png_ptr->num_palette;
  190784. int i;
  190785. for (i = 0; i < num_palette; i++)
  190786. {
  190787. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190788. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190789. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190790. }
  190791. }
  190792. }
  190793. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190794. else
  190795. #endif
  190796. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190797. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190798. /* No GAMMA transformation */
  190799. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190800. (color_type == PNG_COLOR_TYPE_PALETTE))
  190801. {
  190802. int i;
  190803. int istop = (int)png_ptr->num_trans;
  190804. png_color back;
  190805. png_colorp palette = png_ptr->palette;
  190806. back.red = (png_byte)png_ptr->background.red;
  190807. back.green = (png_byte)png_ptr->background.green;
  190808. back.blue = (png_byte)png_ptr->background.blue;
  190809. for (i = 0; i < istop; i++)
  190810. {
  190811. if (png_ptr->trans[i] == 0)
  190812. {
  190813. palette[i] = back;
  190814. }
  190815. else if (png_ptr->trans[i] != 0xff)
  190816. {
  190817. /* The png_composite() macro is defined in png.h */
  190818. png_composite(palette[i].red, palette[i].red,
  190819. png_ptr->trans[i], back.red);
  190820. png_composite(palette[i].green, palette[i].green,
  190821. png_ptr->trans[i], back.green);
  190822. png_composite(palette[i].blue, palette[i].blue,
  190823. png_ptr->trans[i], back.blue);
  190824. }
  190825. }
  190826. }
  190827. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190828. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190829. if ((png_ptr->transformations & PNG_SHIFT) &&
  190830. (color_type == PNG_COLOR_TYPE_PALETTE))
  190831. {
  190832. png_uint_16 i;
  190833. png_uint_16 istop = png_ptr->num_palette;
  190834. int sr = 8 - png_ptr->sig_bit.red;
  190835. int sg = 8 - png_ptr->sig_bit.green;
  190836. int sb = 8 - png_ptr->sig_bit.blue;
  190837. if (sr < 0 || sr > 8)
  190838. sr = 0;
  190839. if (sg < 0 || sg > 8)
  190840. sg = 0;
  190841. if (sb < 0 || sb > 8)
  190842. sb = 0;
  190843. for (i = 0; i < istop; i++)
  190844. {
  190845. png_ptr->palette[i].red >>= sr;
  190846. png_ptr->palette[i].green >>= sg;
  190847. png_ptr->palette[i].blue >>= sb;
  190848. }
  190849. }
  190850. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190851. }
  190852. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190853. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190854. if(png_ptr)
  190855. return;
  190856. #endif
  190857. }
  190858. /* Modify the info structure to reflect the transformations. The
  190859. * info should be updated so a PNG file could be written with it,
  190860. * assuming the transformations result in valid PNG data.
  190861. */
  190862. void /* PRIVATE */
  190863. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190864. {
  190865. png_debug(1, "in png_read_transform_info\n");
  190866. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190867. if (png_ptr->transformations & PNG_EXPAND)
  190868. {
  190869. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190870. {
  190871. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190872. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190873. else
  190874. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190875. info_ptr->bit_depth = 8;
  190876. info_ptr->num_trans = 0;
  190877. }
  190878. else
  190879. {
  190880. if (png_ptr->num_trans)
  190881. {
  190882. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190883. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190884. else
  190885. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190886. }
  190887. if (info_ptr->bit_depth < 8)
  190888. info_ptr->bit_depth = 8;
  190889. info_ptr->num_trans = 0;
  190890. }
  190891. }
  190892. #endif
  190893. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190894. if (png_ptr->transformations & PNG_BACKGROUND)
  190895. {
  190896. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190897. info_ptr->num_trans = 0;
  190898. info_ptr->background = png_ptr->background;
  190899. }
  190900. #endif
  190901. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190902. if (png_ptr->transformations & PNG_GAMMA)
  190903. {
  190904. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190905. info_ptr->gamma = png_ptr->gamma;
  190906. #endif
  190907. #ifdef PNG_FIXED_POINT_SUPPORTED
  190908. info_ptr->int_gamma = png_ptr->int_gamma;
  190909. #endif
  190910. }
  190911. #endif
  190912. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190913. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190914. info_ptr->bit_depth = 8;
  190915. #endif
  190916. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190917. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190918. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190919. #endif
  190920. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190921. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190922. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190923. #endif
  190924. #if defined(PNG_READ_DITHER_SUPPORTED)
  190925. if (png_ptr->transformations & PNG_DITHER)
  190926. {
  190927. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190928. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190929. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190930. {
  190931. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190932. }
  190933. }
  190934. #endif
  190935. #if defined(PNG_READ_PACK_SUPPORTED)
  190936. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190937. info_ptr->bit_depth = 8;
  190938. #endif
  190939. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190940. info_ptr->channels = 1;
  190941. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190942. info_ptr->channels = 3;
  190943. else
  190944. info_ptr->channels = 1;
  190945. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190946. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190947. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190948. #endif
  190949. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190950. info_ptr->channels++;
  190951. #if defined(PNG_READ_FILLER_SUPPORTED)
  190952. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190953. if ((png_ptr->transformations & PNG_FILLER) &&
  190954. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190955. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190956. {
  190957. info_ptr->channels++;
  190958. /* if adding a true alpha channel not just filler */
  190959. #if !defined(PNG_1_0_X)
  190960. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190961. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190962. #endif
  190963. }
  190964. #endif
  190965. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190966. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190967. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190968. {
  190969. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190970. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190971. if(info_ptr->channels < png_ptr->user_transform_channels)
  190972. info_ptr->channels = png_ptr->user_transform_channels;
  190973. }
  190974. #endif
  190975. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190976. info_ptr->bit_depth);
  190977. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190978. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190979. if(png_ptr)
  190980. return;
  190981. #endif
  190982. }
  190983. /* Transform the row. The order of transformations is significant,
  190984. * and is very touchy. If you add a transformation, take care to
  190985. * decide how it fits in with the other transformations here.
  190986. */
  190987. void /* PRIVATE */
  190988. png_do_read_transformations(png_structp png_ptr)
  190989. {
  190990. png_debug(1, "in png_do_read_transformations\n");
  190991. if (png_ptr->row_buf == NULL)
  190992. {
  190993. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190994. char msg[50];
  190995. png_snprintf2(msg, 50,
  190996. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190997. png_ptr->pass);
  190998. png_error(png_ptr, msg);
  190999. #else
  191000. png_error(png_ptr, "NULL row buffer");
  191001. #endif
  191002. }
  191003. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191004. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191005. /* Application has failed to call either png_read_start_image()
  191006. * or png_read_update_info() after setting transforms that expand
  191007. * pixels. This check added to libpng-1.2.19 */
  191008. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191009. png_error(png_ptr, "Uninitialized row");
  191010. #else
  191011. png_warning(png_ptr, "Uninitialized row");
  191012. #endif
  191013. #endif
  191014. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191015. if (png_ptr->transformations & PNG_EXPAND)
  191016. {
  191017. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191018. {
  191019. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191020. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191021. }
  191022. else
  191023. {
  191024. if (png_ptr->num_trans &&
  191025. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191026. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191027. &(png_ptr->trans_values));
  191028. else
  191029. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191030. NULL);
  191031. }
  191032. }
  191033. #endif
  191034. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191035. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191036. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191037. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191038. #endif
  191039. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191040. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191041. {
  191042. int rgb_error =
  191043. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191044. if(rgb_error)
  191045. {
  191046. png_ptr->rgb_to_gray_status=1;
  191047. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191048. PNG_RGB_TO_GRAY_WARN)
  191049. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191050. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191051. PNG_RGB_TO_GRAY_ERR)
  191052. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191053. }
  191054. }
  191055. #endif
  191056. /*
  191057. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191058. In most cases, the "simple transparency" should be done prior to doing
  191059. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191060. pixel is transparent. You would also need to make sure that the
  191061. transparency information is upgraded to RGB.
  191062. To summarize, the current flow is:
  191063. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191064. with background "in place" if transparent,
  191065. convert to RGB if necessary
  191066. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191067. convert to RGB if necessary
  191068. To support RGB backgrounds for gray images we need:
  191069. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191070. 3 or 6 bytes and composite with background
  191071. "in place" if transparent (3x compare/pixel
  191072. compared to doing composite with gray bkgrnd)
  191073. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191074. remove alpha bytes (3x float operations/pixel
  191075. compared with composite on gray background)
  191076. Greg's change will do this. The reason it wasn't done before is for
  191077. performance, as this increases the per-pixel operations. If we would check
  191078. in advance if the background was gray or RGB, and position the gray-to-RGB
  191079. transform appropriately, then it would save a lot of work/time.
  191080. */
  191081. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191082. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191083. * for performance reasons */
  191084. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191085. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191086. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191087. #endif
  191088. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191089. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191090. ((png_ptr->num_trans != 0 ) ||
  191091. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191092. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191093. &(png_ptr->trans_values), &(png_ptr->background)
  191094. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191095. , &(png_ptr->background_1),
  191096. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191097. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191098. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191099. png_ptr->gamma_shift
  191100. #endif
  191101. );
  191102. #endif
  191103. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191104. if ((png_ptr->transformations & PNG_GAMMA) &&
  191105. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191106. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191107. ((png_ptr->num_trans != 0) ||
  191108. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191109. #endif
  191110. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191111. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191112. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191113. png_ptr->gamma_shift);
  191114. #endif
  191115. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191116. if (png_ptr->transformations & PNG_16_TO_8)
  191117. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191118. #endif
  191119. #if defined(PNG_READ_DITHER_SUPPORTED)
  191120. if (png_ptr->transformations & PNG_DITHER)
  191121. {
  191122. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191123. png_ptr->palette_lookup, png_ptr->dither_index);
  191124. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191125. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191126. }
  191127. #endif
  191128. #if defined(PNG_READ_INVERT_SUPPORTED)
  191129. if (png_ptr->transformations & PNG_INVERT_MONO)
  191130. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191131. #endif
  191132. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191133. if (png_ptr->transformations & PNG_SHIFT)
  191134. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191135. &(png_ptr->shift));
  191136. #endif
  191137. #if defined(PNG_READ_PACK_SUPPORTED)
  191138. if (png_ptr->transformations & PNG_PACK)
  191139. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191140. #endif
  191141. #if defined(PNG_READ_BGR_SUPPORTED)
  191142. if (png_ptr->transformations & PNG_BGR)
  191143. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191144. #endif
  191145. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191146. if (png_ptr->transformations & PNG_PACKSWAP)
  191147. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191148. #endif
  191149. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191150. /* if gray -> RGB, do so now only if we did not do so above */
  191151. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191152. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191153. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191154. #endif
  191155. #if defined(PNG_READ_FILLER_SUPPORTED)
  191156. if (png_ptr->transformations & PNG_FILLER)
  191157. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191158. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191159. #endif
  191160. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191161. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191162. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191163. #endif
  191164. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191165. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191166. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191167. #endif
  191168. #if defined(PNG_READ_SWAP_SUPPORTED)
  191169. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191170. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191171. #endif
  191172. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191173. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191174. {
  191175. if(png_ptr->read_user_transform_fn != NULL)
  191176. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191177. (png_ptr, /* png_ptr */
  191178. &(png_ptr->row_info), /* row_info: */
  191179. /* png_uint_32 width; width of row */
  191180. /* png_uint_32 rowbytes; number of bytes in row */
  191181. /* png_byte color_type; color type of pixels */
  191182. /* png_byte bit_depth; bit depth of samples */
  191183. /* png_byte channels; number of channels (1-4) */
  191184. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191185. png_ptr->row_buf + 1); /* start of pixel data for row */
  191186. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191187. if(png_ptr->user_transform_depth)
  191188. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191189. if(png_ptr->user_transform_channels)
  191190. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191191. #endif
  191192. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191193. png_ptr->row_info.channels);
  191194. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191195. png_ptr->row_info.width);
  191196. }
  191197. #endif
  191198. }
  191199. #if defined(PNG_READ_PACK_SUPPORTED)
  191200. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191201. * without changing the actual values. Thus, if you had a row with
  191202. * a bit depth of 1, you would end up with bytes that only contained
  191203. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191204. * png_do_shift() after this.
  191205. */
  191206. void /* PRIVATE */
  191207. png_do_unpack(png_row_infop row_info, png_bytep row)
  191208. {
  191209. png_debug(1, "in png_do_unpack\n");
  191210. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191211. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191212. #else
  191213. if (row_info->bit_depth < 8)
  191214. #endif
  191215. {
  191216. png_uint_32 i;
  191217. png_uint_32 row_width=row_info->width;
  191218. switch (row_info->bit_depth)
  191219. {
  191220. case 1:
  191221. {
  191222. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191223. png_bytep dp = row + (png_size_t)row_width - 1;
  191224. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191225. for (i = 0; i < row_width; i++)
  191226. {
  191227. *dp = (png_byte)((*sp >> shift) & 0x01);
  191228. if (shift == 7)
  191229. {
  191230. shift = 0;
  191231. sp--;
  191232. }
  191233. else
  191234. shift++;
  191235. dp--;
  191236. }
  191237. break;
  191238. }
  191239. case 2:
  191240. {
  191241. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191242. png_bytep dp = row + (png_size_t)row_width - 1;
  191243. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191244. for (i = 0; i < row_width; i++)
  191245. {
  191246. *dp = (png_byte)((*sp >> shift) & 0x03);
  191247. if (shift == 6)
  191248. {
  191249. shift = 0;
  191250. sp--;
  191251. }
  191252. else
  191253. shift += 2;
  191254. dp--;
  191255. }
  191256. break;
  191257. }
  191258. case 4:
  191259. {
  191260. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191261. png_bytep dp = row + (png_size_t)row_width - 1;
  191262. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191263. for (i = 0; i < row_width; i++)
  191264. {
  191265. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191266. if (shift == 4)
  191267. {
  191268. shift = 0;
  191269. sp--;
  191270. }
  191271. else
  191272. shift = 4;
  191273. dp--;
  191274. }
  191275. break;
  191276. }
  191277. }
  191278. row_info->bit_depth = 8;
  191279. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191280. row_info->rowbytes = row_width * row_info->channels;
  191281. }
  191282. }
  191283. #endif
  191284. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191285. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191286. * pixels back to their significant bits values. Thus, if you have
  191287. * a row of bit depth 8, but only 5 are significant, this will shift
  191288. * the values back to 0 through 31.
  191289. */
  191290. void /* PRIVATE */
  191291. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191292. {
  191293. png_debug(1, "in png_do_unshift\n");
  191294. if (
  191295. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191296. row != NULL && row_info != NULL && sig_bits != NULL &&
  191297. #endif
  191298. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191299. {
  191300. int shift[4];
  191301. int channels = 0;
  191302. int c;
  191303. png_uint_16 value = 0;
  191304. png_uint_32 row_width = row_info->width;
  191305. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191306. {
  191307. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191308. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191309. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191310. }
  191311. else
  191312. {
  191313. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191314. }
  191315. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191316. {
  191317. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191318. }
  191319. for (c = 0; c < channels; c++)
  191320. {
  191321. if (shift[c] <= 0)
  191322. shift[c] = 0;
  191323. else
  191324. value = 1;
  191325. }
  191326. if (!value)
  191327. return;
  191328. switch (row_info->bit_depth)
  191329. {
  191330. case 2:
  191331. {
  191332. png_bytep bp;
  191333. png_uint_32 i;
  191334. png_uint_32 istop = row_info->rowbytes;
  191335. for (bp = row, i = 0; i < istop; i++)
  191336. {
  191337. *bp >>= 1;
  191338. *bp++ &= 0x55;
  191339. }
  191340. break;
  191341. }
  191342. case 4:
  191343. {
  191344. png_bytep bp = row;
  191345. png_uint_32 i;
  191346. png_uint_32 istop = row_info->rowbytes;
  191347. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191348. (png_byte)((int)0xf >> shift[0]));
  191349. for (i = 0; i < istop; i++)
  191350. {
  191351. *bp >>= shift[0];
  191352. *bp++ &= mask;
  191353. }
  191354. break;
  191355. }
  191356. case 8:
  191357. {
  191358. png_bytep bp = row;
  191359. png_uint_32 i;
  191360. png_uint_32 istop = row_width * channels;
  191361. for (i = 0; i < istop; i++)
  191362. {
  191363. *bp++ >>= shift[i%channels];
  191364. }
  191365. break;
  191366. }
  191367. case 16:
  191368. {
  191369. png_bytep bp = row;
  191370. png_uint_32 i;
  191371. png_uint_32 istop = channels * row_width;
  191372. for (i = 0; i < istop; i++)
  191373. {
  191374. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191375. value >>= shift[i%channels];
  191376. *bp++ = (png_byte)(value >> 8);
  191377. *bp++ = (png_byte)(value & 0xff);
  191378. }
  191379. break;
  191380. }
  191381. }
  191382. }
  191383. }
  191384. #endif
  191385. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191386. /* chop rows of bit depth 16 down to 8 */
  191387. void /* PRIVATE */
  191388. png_do_chop(png_row_infop row_info, png_bytep row)
  191389. {
  191390. png_debug(1, "in png_do_chop\n");
  191391. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191392. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191393. #else
  191394. if (row_info->bit_depth == 16)
  191395. #endif
  191396. {
  191397. png_bytep sp = row;
  191398. png_bytep dp = row;
  191399. png_uint_32 i;
  191400. png_uint_32 istop = row_info->width * row_info->channels;
  191401. for (i = 0; i<istop; i++, sp += 2, dp++)
  191402. {
  191403. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191404. /* This does a more accurate scaling of the 16-bit color
  191405. * value, rather than a simple low-byte truncation.
  191406. *
  191407. * What the ideal calculation should be:
  191408. * *dp = (((((png_uint_32)(*sp) << 8) |
  191409. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191410. *
  191411. * GRR: no, I think this is what it really should be:
  191412. * *dp = (((((png_uint_32)(*sp) << 8) |
  191413. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191414. *
  191415. * GRR: here's the exact calculation with shifts:
  191416. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191417. * *dp = (temp - (temp >> 8)) >> 8;
  191418. *
  191419. * Approximate calculation with shift/add instead of multiply/divide:
  191420. * *dp = ((((png_uint_32)(*sp) << 8) |
  191421. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191422. *
  191423. * What we actually do to avoid extra shifting and conversion:
  191424. */
  191425. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191426. #else
  191427. /* Simply discard the low order byte */
  191428. *dp = *sp;
  191429. #endif
  191430. }
  191431. row_info->bit_depth = 8;
  191432. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191433. row_info->rowbytes = row_info->width * row_info->channels;
  191434. }
  191435. }
  191436. #endif
  191437. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191438. void /* PRIVATE */
  191439. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191440. {
  191441. png_debug(1, "in png_do_read_swap_alpha\n");
  191442. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191443. if (row != NULL && row_info != NULL)
  191444. #endif
  191445. {
  191446. png_uint_32 row_width = row_info->width;
  191447. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191448. {
  191449. /* This converts from RGBA to ARGB */
  191450. if (row_info->bit_depth == 8)
  191451. {
  191452. png_bytep sp = row + row_info->rowbytes;
  191453. png_bytep dp = sp;
  191454. png_byte save;
  191455. png_uint_32 i;
  191456. for (i = 0; i < row_width; i++)
  191457. {
  191458. save = *(--sp);
  191459. *(--dp) = *(--sp);
  191460. *(--dp) = *(--sp);
  191461. *(--dp) = *(--sp);
  191462. *(--dp) = save;
  191463. }
  191464. }
  191465. /* This converts from RRGGBBAA to AARRGGBB */
  191466. else
  191467. {
  191468. png_bytep sp = row + row_info->rowbytes;
  191469. png_bytep dp = sp;
  191470. png_byte save[2];
  191471. png_uint_32 i;
  191472. for (i = 0; i < row_width; i++)
  191473. {
  191474. save[0] = *(--sp);
  191475. save[1] = *(--sp);
  191476. *(--dp) = *(--sp);
  191477. *(--dp) = *(--sp);
  191478. *(--dp) = *(--sp);
  191479. *(--dp) = *(--sp);
  191480. *(--dp) = *(--sp);
  191481. *(--dp) = *(--sp);
  191482. *(--dp) = save[0];
  191483. *(--dp) = save[1];
  191484. }
  191485. }
  191486. }
  191487. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191488. {
  191489. /* This converts from GA to AG */
  191490. if (row_info->bit_depth == 8)
  191491. {
  191492. png_bytep sp = row + row_info->rowbytes;
  191493. png_bytep dp = sp;
  191494. png_byte save;
  191495. png_uint_32 i;
  191496. for (i = 0; i < row_width; i++)
  191497. {
  191498. save = *(--sp);
  191499. *(--dp) = *(--sp);
  191500. *(--dp) = save;
  191501. }
  191502. }
  191503. /* This converts from GGAA to AAGG */
  191504. else
  191505. {
  191506. png_bytep sp = row + row_info->rowbytes;
  191507. png_bytep dp = sp;
  191508. png_byte save[2];
  191509. png_uint_32 i;
  191510. for (i = 0; i < row_width; i++)
  191511. {
  191512. save[0] = *(--sp);
  191513. save[1] = *(--sp);
  191514. *(--dp) = *(--sp);
  191515. *(--dp) = *(--sp);
  191516. *(--dp) = save[0];
  191517. *(--dp) = save[1];
  191518. }
  191519. }
  191520. }
  191521. }
  191522. }
  191523. #endif
  191524. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191525. void /* PRIVATE */
  191526. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191527. {
  191528. png_debug(1, "in png_do_read_invert_alpha\n");
  191529. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191530. if (row != NULL && row_info != NULL)
  191531. #endif
  191532. {
  191533. png_uint_32 row_width = row_info->width;
  191534. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191535. {
  191536. /* This inverts the alpha channel in RGBA */
  191537. if (row_info->bit_depth == 8)
  191538. {
  191539. png_bytep sp = row + row_info->rowbytes;
  191540. png_bytep dp = sp;
  191541. png_uint_32 i;
  191542. for (i = 0; i < row_width; i++)
  191543. {
  191544. *(--dp) = (png_byte)(255 - *(--sp));
  191545. /* This does nothing:
  191546. *(--dp) = *(--sp);
  191547. *(--dp) = *(--sp);
  191548. *(--dp) = *(--sp);
  191549. We can replace it with:
  191550. */
  191551. sp-=3;
  191552. dp=sp;
  191553. }
  191554. }
  191555. /* This inverts the alpha channel in RRGGBBAA */
  191556. else
  191557. {
  191558. png_bytep sp = row + row_info->rowbytes;
  191559. png_bytep dp = sp;
  191560. png_uint_32 i;
  191561. for (i = 0; i < row_width; i++)
  191562. {
  191563. *(--dp) = (png_byte)(255 - *(--sp));
  191564. *(--dp) = (png_byte)(255 - *(--sp));
  191565. /* This does nothing:
  191566. *(--dp) = *(--sp);
  191567. *(--dp) = *(--sp);
  191568. *(--dp) = *(--sp);
  191569. *(--dp) = *(--sp);
  191570. *(--dp) = *(--sp);
  191571. *(--dp) = *(--sp);
  191572. We can replace it with:
  191573. */
  191574. sp-=6;
  191575. dp=sp;
  191576. }
  191577. }
  191578. }
  191579. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191580. {
  191581. /* This inverts the alpha channel in GA */
  191582. if (row_info->bit_depth == 8)
  191583. {
  191584. png_bytep sp = row + row_info->rowbytes;
  191585. png_bytep dp = sp;
  191586. png_uint_32 i;
  191587. for (i = 0; i < row_width; i++)
  191588. {
  191589. *(--dp) = (png_byte)(255 - *(--sp));
  191590. *(--dp) = *(--sp);
  191591. }
  191592. }
  191593. /* This inverts the alpha channel in GGAA */
  191594. else
  191595. {
  191596. png_bytep sp = row + row_info->rowbytes;
  191597. png_bytep dp = sp;
  191598. png_uint_32 i;
  191599. for (i = 0; i < row_width; i++)
  191600. {
  191601. *(--dp) = (png_byte)(255 - *(--sp));
  191602. *(--dp) = (png_byte)(255 - *(--sp));
  191603. /*
  191604. *(--dp) = *(--sp);
  191605. *(--dp) = *(--sp);
  191606. */
  191607. sp-=2;
  191608. dp=sp;
  191609. }
  191610. }
  191611. }
  191612. }
  191613. }
  191614. #endif
  191615. #if defined(PNG_READ_FILLER_SUPPORTED)
  191616. /* Add filler channel if we have RGB color */
  191617. void /* PRIVATE */
  191618. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191619. png_uint_32 filler, png_uint_32 flags)
  191620. {
  191621. png_uint_32 i;
  191622. png_uint_32 row_width = row_info->width;
  191623. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191624. png_byte lo_filler = (png_byte)(filler & 0xff);
  191625. png_debug(1, "in png_do_read_filler\n");
  191626. if (
  191627. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191628. row != NULL && row_info != NULL &&
  191629. #endif
  191630. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191631. {
  191632. if(row_info->bit_depth == 8)
  191633. {
  191634. /* This changes the data from G to GX */
  191635. if (flags & PNG_FLAG_FILLER_AFTER)
  191636. {
  191637. png_bytep sp = row + (png_size_t)row_width;
  191638. png_bytep dp = sp + (png_size_t)row_width;
  191639. for (i = 1; i < row_width; i++)
  191640. {
  191641. *(--dp) = lo_filler;
  191642. *(--dp) = *(--sp);
  191643. }
  191644. *(--dp) = lo_filler;
  191645. row_info->channels = 2;
  191646. row_info->pixel_depth = 16;
  191647. row_info->rowbytes = row_width * 2;
  191648. }
  191649. /* This changes the data from G to XG */
  191650. else
  191651. {
  191652. png_bytep sp = row + (png_size_t)row_width;
  191653. png_bytep dp = sp + (png_size_t)row_width;
  191654. for (i = 0; i < row_width; i++)
  191655. {
  191656. *(--dp) = *(--sp);
  191657. *(--dp) = lo_filler;
  191658. }
  191659. row_info->channels = 2;
  191660. row_info->pixel_depth = 16;
  191661. row_info->rowbytes = row_width * 2;
  191662. }
  191663. }
  191664. else if(row_info->bit_depth == 16)
  191665. {
  191666. /* This changes the data from GG to GGXX */
  191667. if (flags & PNG_FLAG_FILLER_AFTER)
  191668. {
  191669. png_bytep sp = row + (png_size_t)row_width * 2;
  191670. png_bytep dp = sp + (png_size_t)row_width * 2;
  191671. for (i = 1; i < row_width; i++)
  191672. {
  191673. *(--dp) = hi_filler;
  191674. *(--dp) = lo_filler;
  191675. *(--dp) = *(--sp);
  191676. *(--dp) = *(--sp);
  191677. }
  191678. *(--dp) = hi_filler;
  191679. *(--dp) = lo_filler;
  191680. row_info->channels = 2;
  191681. row_info->pixel_depth = 32;
  191682. row_info->rowbytes = row_width * 4;
  191683. }
  191684. /* This changes the data from GG to XXGG */
  191685. else
  191686. {
  191687. png_bytep sp = row + (png_size_t)row_width * 2;
  191688. png_bytep dp = sp + (png_size_t)row_width * 2;
  191689. for (i = 0; i < row_width; i++)
  191690. {
  191691. *(--dp) = *(--sp);
  191692. *(--dp) = *(--sp);
  191693. *(--dp) = hi_filler;
  191694. *(--dp) = lo_filler;
  191695. }
  191696. row_info->channels = 2;
  191697. row_info->pixel_depth = 32;
  191698. row_info->rowbytes = row_width * 4;
  191699. }
  191700. }
  191701. } /* COLOR_TYPE == GRAY */
  191702. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191703. {
  191704. if(row_info->bit_depth == 8)
  191705. {
  191706. /* This changes the data from RGB to RGBX */
  191707. if (flags & PNG_FLAG_FILLER_AFTER)
  191708. {
  191709. png_bytep sp = row + (png_size_t)row_width * 3;
  191710. png_bytep dp = sp + (png_size_t)row_width;
  191711. for (i = 1; i < row_width; i++)
  191712. {
  191713. *(--dp) = lo_filler;
  191714. *(--dp) = *(--sp);
  191715. *(--dp) = *(--sp);
  191716. *(--dp) = *(--sp);
  191717. }
  191718. *(--dp) = lo_filler;
  191719. row_info->channels = 4;
  191720. row_info->pixel_depth = 32;
  191721. row_info->rowbytes = row_width * 4;
  191722. }
  191723. /* This changes the data from RGB to XRGB */
  191724. else
  191725. {
  191726. png_bytep sp = row + (png_size_t)row_width * 3;
  191727. png_bytep dp = sp + (png_size_t)row_width;
  191728. for (i = 0; i < row_width; i++)
  191729. {
  191730. *(--dp) = *(--sp);
  191731. *(--dp) = *(--sp);
  191732. *(--dp) = *(--sp);
  191733. *(--dp) = lo_filler;
  191734. }
  191735. row_info->channels = 4;
  191736. row_info->pixel_depth = 32;
  191737. row_info->rowbytes = row_width * 4;
  191738. }
  191739. }
  191740. else if(row_info->bit_depth == 16)
  191741. {
  191742. /* This changes the data from RRGGBB to RRGGBBXX */
  191743. if (flags & PNG_FLAG_FILLER_AFTER)
  191744. {
  191745. png_bytep sp = row + (png_size_t)row_width * 6;
  191746. png_bytep dp = sp + (png_size_t)row_width * 2;
  191747. for (i = 1; i < row_width; i++)
  191748. {
  191749. *(--dp) = hi_filler;
  191750. *(--dp) = lo_filler;
  191751. *(--dp) = *(--sp);
  191752. *(--dp) = *(--sp);
  191753. *(--dp) = *(--sp);
  191754. *(--dp) = *(--sp);
  191755. *(--dp) = *(--sp);
  191756. *(--dp) = *(--sp);
  191757. }
  191758. *(--dp) = hi_filler;
  191759. *(--dp) = lo_filler;
  191760. row_info->channels = 4;
  191761. row_info->pixel_depth = 64;
  191762. row_info->rowbytes = row_width * 8;
  191763. }
  191764. /* This changes the data from RRGGBB to XXRRGGBB */
  191765. else
  191766. {
  191767. png_bytep sp = row + (png_size_t)row_width * 6;
  191768. png_bytep dp = sp + (png_size_t)row_width * 2;
  191769. for (i = 0; i < row_width; i++)
  191770. {
  191771. *(--dp) = *(--sp);
  191772. *(--dp) = *(--sp);
  191773. *(--dp) = *(--sp);
  191774. *(--dp) = *(--sp);
  191775. *(--dp) = *(--sp);
  191776. *(--dp) = *(--sp);
  191777. *(--dp) = hi_filler;
  191778. *(--dp) = lo_filler;
  191779. }
  191780. row_info->channels = 4;
  191781. row_info->pixel_depth = 64;
  191782. row_info->rowbytes = row_width * 8;
  191783. }
  191784. }
  191785. } /* COLOR_TYPE == RGB */
  191786. }
  191787. #endif
  191788. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191789. /* expand grayscale files to RGB, with or without alpha */
  191790. void /* PRIVATE */
  191791. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191792. {
  191793. png_uint_32 i;
  191794. png_uint_32 row_width = row_info->width;
  191795. png_debug(1, "in png_do_gray_to_rgb\n");
  191796. if (row_info->bit_depth >= 8 &&
  191797. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191798. row != NULL && row_info != NULL &&
  191799. #endif
  191800. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191801. {
  191802. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191803. {
  191804. if (row_info->bit_depth == 8)
  191805. {
  191806. png_bytep sp = row + (png_size_t)row_width - 1;
  191807. png_bytep dp = sp + (png_size_t)row_width * 2;
  191808. for (i = 0; i < row_width; i++)
  191809. {
  191810. *(dp--) = *sp;
  191811. *(dp--) = *sp;
  191812. *(dp--) = *(sp--);
  191813. }
  191814. }
  191815. else
  191816. {
  191817. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191818. png_bytep dp = sp + (png_size_t)row_width * 4;
  191819. for (i = 0; i < row_width; i++)
  191820. {
  191821. *(dp--) = *sp;
  191822. *(dp--) = *(sp - 1);
  191823. *(dp--) = *sp;
  191824. *(dp--) = *(sp - 1);
  191825. *(dp--) = *(sp--);
  191826. *(dp--) = *(sp--);
  191827. }
  191828. }
  191829. }
  191830. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191831. {
  191832. if (row_info->bit_depth == 8)
  191833. {
  191834. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191835. png_bytep dp = sp + (png_size_t)row_width * 2;
  191836. for (i = 0; i < row_width; i++)
  191837. {
  191838. *(dp--) = *(sp--);
  191839. *(dp--) = *sp;
  191840. *(dp--) = *sp;
  191841. *(dp--) = *(sp--);
  191842. }
  191843. }
  191844. else
  191845. {
  191846. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191847. png_bytep dp = sp + (png_size_t)row_width * 4;
  191848. for (i = 0; i < row_width; i++)
  191849. {
  191850. *(dp--) = *(sp--);
  191851. *(dp--) = *(sp--);
  191852. *(dp--) = *sp;
  191853. *(dp--) = *(sp - 1);
  191854. *(dp--) = *sp;
  191855. *(dp--) = *(sp - 1);
  191856. *(dp--) = *(sp--);
  191857. *(dp--) = *(sp--);
  191858. }
  191859. }
  191860. }
  191861. row_info->channels += (png_byte)2;
  191862. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191863. row_info->pixel_depth = (png_byte)(row_info->channels *
  191864. row_info->bit_depth);
  191865. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191866. }
  191867. }
  191868. #endif
  191869. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191870. /* reduce RGB files to grayscale, with or without alpha
  191871. * using the equation given in Poynton's ColorFAQ at
  191872. * <http://www.inforamp.net/~poynton/>
  191873. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191874. *
  191875. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191876. *
  191877. * We approximate this with
  191878. *
  191879. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191880. *
  191881. * which can be expressed with integers as
  191882. *
  191883. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191884. *
  191885. * The calculation is to be done in a linear colorspace.
  191886. *
  191887. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191888. */
  191889. int /* PRIVATE */
  191890. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191891. {
  191892. png_uint_32 i;
  191893. png_uint_32 row_width = row_info->width;
  191894. int rgb_error = 0;
  191895. png_debug(1, "in png_do_rgb_to_gray\n");
  191896. if (
  191897. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191898. row != NULL && row_info != NULL &&
  191899. #endif
  191900. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191901. {
  191902. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191903. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191904. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191905. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191906. {
  191907. if (row_info->bit_depth == 8)
  191908. {
  191909. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191910. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191911. {
  191912. png_bytep sp = row;
  191913. png_bytep dp = row;
  191914. for (i = 0; i < row_width; i++)
  191915. {
  191916. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191917. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191918. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191919. if(red != green || red != blue)
  191920. {
  191921. rgb_error |= 1;
  191922. *(dp++) = png_ptr->gamma_from_1[
  191923. (rc*red+gc*green+bc*blue)>>15];
  191924. }
  191925. else
  191926. *(dp++) = *(sp-1);
  191927. }
  191928. }
  191929. else
  191930. #endif
  191931. {
  191932. png_bytep sp = row;
  191933. png_bytep dp = row;
  191934. for (i = 0; i < row_width; i++)
  191935. {
  191936. png_byte red = *(sp++);
  191937. png_byte green = *(sp++);
  191938. png_byte blue = *(sp++);
  191939. if(red != green || red != blue)
  191940. {
  191941. rgb_error |= 1;
  191942. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191943. }
  191944. else
  191945. *(dp++) = *(sp-1);
  191946. }
  191947. }
  191948. }
  191949. else /* RGB bit_depth == 16 */
  191950. {
  191951. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191952. if (png_ptr->gamma_16_to_1 != NULL &&
  191953. png_ptr->gamma_16_from_1 != NULL)
  191954. {
  191955. png_bytep sp = row;
  191956. png_bytep dp = row;
  191957. for (i = 0; i < row_width; i++)
  191958. {
  191959. png_uint_16 red, green, blue, w;
  191960. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191961. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191962. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191963. if(red == green && red == blue)
  191964. w = red;
  191965. else
  191966. {
  191967. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191968. png_ptr->gamma_shift][red>>8];
  191969. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191970. png_ptr->gamma_shift][green>>8];
  191971. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191972. png_ptr->gamma_shift][blue>>8];
  191973. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191974. + bc*blue_1)>>15);
  191975. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191976. png_ptr->gamma_shift][gray16 >> 8];
  191977. rgb_error |= 1;
  191978. }
  191979. *(dp++) = (png_byte)((w>>8) & 0xff);
  191980. *(dp++) = (png_byte)(w & 0xff);
  191981. }
  191982. }
  191983. else
  191984. #endif
  191985. {
  191986. png_bytep sp = row;
  191987. png_bytep dp = row;
  191988. for (i = 0; i < row_width; i++)
  191989. {
  191990. png_uint_16 red, green, blue, gray16;
  191991. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191992. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191993. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191994. if(red != green || red != blue)
  191995. rgb_error |= 1;
  191996. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191997. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191998. *(dp++) = (png_byte)(gray16 & 0xff);
  191999. }
  192000. }
  192001. }
  192002. }
  192003. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192004. {
  192005. if (row_info->bit_depth == 8)
  192006. {
  192007. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192008. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192009. {
  192010. png_bytep sp = row;
  192011. png_bytep dp = row;
  192012. for (i = 0; i < row_width; i++)
  192013. {
  192014. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192015. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192016. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192017. if(red != green || red != blue)
  192018. rgb_error |= 1;
  192019. *(dp++) = png_ptr->gamma_from_1
  192020. [(rc*red + gc*green + bc*blue)>>15];
  192021. *(dp++) = *(sp++); /* alpha */
  192022. }
  192023. }
  192024. else
  192025. #endif
  192026. {
  192027. png_bytep sp = row;
  192028. png_bytep dp = row;
  192029. for (i = 0; i < row_width; i++)
  192030. {
  192031. png_byte red = *(sp++);
  192032. png_byte green = *(sp++);
  192033. png_byte blue = *(sp++);
  192034. if(red != green || red != blue)
  192035. rgb_error |= 1;
  192036. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192037. *(dp++) = *(sp++); /* alpha */
  192038. }
  192039. }
  192040. }
  192041. else /* RGBA bit_depth == 16 */
  192042. {
  192043. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192044. if (png_ptr->gamma_16_to_1 != NULL &&
  192045. png_ptr->gamma_16_from_1 != NULL)
  192046. {
  192047. png_bytep sp = row;
  192048. png_bytep dp = row;
  192049. for (i = 0; i < row_width; i++)
  192050. {
  192051. png_uint_16 red, green, blue, w;
  192052. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192053. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192054. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192055. if(red == green && red == blue)
  192056. w = red;
  192057. else
  192058. {
  192059. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192060. png_ptr->gamma_shift][red>>8];
  192061. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192062. png_ptr->gamma_shift][green>>8];
  192063. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192064. png_ptr->gamma_shift][blue>>8];
  192065. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192066. + gc * green_1 + bc * blue_1)>>15);
  192067. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192068. png_ptr->gamma_shift][gray16 >> 8];
  192069. rgb_error |= 1;
  192070. }
  192071. *(dp++) = (png_byte)((w>>8) & 0xff);
  192072. *(dp++) = (png_byte)(w & 0xff);
  192073. *(dp++) = *(sp++); /* alpha */
  192074. *(dp++) = *(sp++);
  192075. }
  192076. }
  192077. else
  192078. #endif
  192079. {
  192080. png_bytep sp = row;
  192081. png_bytep dp = row;
  192082. for (i = 0; i < row_width; i++)
  192083. {
  192084. png_uint_16 red, green, blue, gray16;
  192085. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192086. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192087. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192088. if(red != green || red != blue)
  192089. rgb_error |= 1;
  192090. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192091. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192092. *(dp++) = (png_byte)(gray16 & 0xff);
  192093. *(dp++) = *(sp++); /* alpha */
  192094. *(dp++) = *(sp++);
  192095. }
  192096. }
  192097. }
  192098. }
  192099. row_info->channels -= (png_byte)2;
  192100. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192101. row_info->pixel_depth = (png_byte)(row_info->channels *
  192102. row_info->bit_depth);
  192103. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192104. }
  192105. return rgb_error;
  192106. }
  192107. #endif
  192108. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192109. * large of png_color. This lets grayscale images be treated as
  192110. * paletted. Most useful for gamma correction and simplification
  192111. * of code.
  192112. */
  192113. void PNGAPI
  192114. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192115. {
  192116. int num_palette;
  192117. int color_inc;
  192118. int i;
  192119. int v;
  192120. png_debug(1, "in png_do_build_grayscale_palette\n");
  192121. if (palette == NULL)
  192122. return;
  192123. switch (bit_depth)
  192124. {
  192125. case 1:
  192126. num_palette = 2;
  192127. color_inc = 0xff;
  192128. break;
  192129. case 2:
  192130. num_palette = 4;
  192131. color_inc = 0x55;
  192132. break;
  192133. case 4:
  192134. num_palette = 16;
  192135. color_inc = 0x11;
  192136. break;
  192137. case 8:
  192138. num_palette = 256;
  192139. color_inc = 1;
  192140. break;
  192141. default:
  192142. num_palette = 0;
  192143. color_inc = 0;
  192144. break;
  192145. }
  192146. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192147. {
  192148. palette[i].red = (png_byte)v;
  192149. palette[i].green = (png_byte)v;
  192150. palette[i].blue = (png_byte)v;
  192151. }
  192152. }
  192153. /* This function is currently unused. Do we really need it? */
  192154. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192155. void /* PRIVATE */
  192156. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192157. int num_palette)
  192158. {
  192159. png_debug(1, "in png_correct_palette\n");
  192160. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192161. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192162. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192163. {
  192164. png_color back, back_1;
  192165. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192166. {
  192167. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192168. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192169. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192170. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192171. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192172. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192173. }
  192174. else
  192175. {
  192176. double g;
  192177. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192178. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192179. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192180. {
  192181. back.red = png_ptr->background.red;
  192182. back.green = png_ptr->background.green;
  192183. back.blue = png_ptr->background.blue;
  192184. }
  192185. else
  192186. {
  192187. back.red =
  192188. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192189. 255.0 + 0.5);
  192190. back.green =
  192191. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192192. 255.0 + 0.5);
  192193. back.blue =
  192194. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192195. 255.0 + 0.5);
  192196. }
  192197. g = 1.0 / png_ptr->background_gamma;
  192198. back_1.red =
  192199. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192200. 255.0 + 0.5);
  192201. back_1.green =
  192202. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192203. 255.0 + 0.5);
  192204. back_1.blue =
  192205. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192206. 255.0 + 0.5);
  192207. }
  192208. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192209. {
  192210. png_uint_32 i;
  192211. for (i = 0; i < (png_uint_32)num_palette; i++)
  192212. {
  192213. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192214. {
  192215. palette[i] = back;
  192216. }
  192217. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192218. {
  192219. png_byte v, w;
  192220. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192221. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192222. palette[i].red = png_ptr->gamma_from_1[w];
  192223. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192224. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192225. palette[i].green = png_ptr->gamma_from_1[w];
  192226. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192227. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192228. palette[i].blue = png_ptr->gamma_from_1[w];
  192229. }
  192230. else
  192231. {
  192232. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192233. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192234. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192235. }
  192236. }
  192237. }
  192238. else
  192239. {
  192240. int i;
  192241. for (i = 0; i < num_palette; i++)
  192242. {
  192243. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192244. {
  192245. palette[i] = back;
  192246. }
  192247. else
  192248. {
  192249. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192250. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192251. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192252. }
  192253. }
  192254. }
  192255. }
  192256. else
  192257. #endif
  192258. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192259. if (png_ptr->transformations & PNG_GAMMA)
  192260. {
  192261. int i;
  192262. for (i = 0; i < num_palette; i++)
  192263. {
  192264. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192265. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192266. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192267. }
  192268. }
  192269. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192270. else
  192271. #endif
  192272. #endif
  192273. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192274. if (png_ptr->transformations & PNG_BACKGROUND)
  192275. {
  192276. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192277. {
  192278. png_color back;
  192279. back.red = (png_byte)png_ptr->background.red;
  192280. back.green = (png_byte)png_ptr->background.green;
  192281. back.blue = (png_byte)png_ptr->background.blue;
  192282. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192283. {
  192284. if (png_ptr->trans[i] == 0)
  192285. {
  192286. palette[i].red = back.red;
  192287. palette[i].green = back.green;
  192288. palette[i].blue = back.blue;
  192289. }
  192290. else if (png_ptr->trans[i] != 0xff)
  192291. {
  192292. png_composite(palette[i].red, png_ptr->palette[i].red,
  192293. png_ptr->trans[i], back.red);
  192294. png_composite(palette[i].green, png_ptr->palette[i].green,
  192295. png_ptr->trans[i], back.green);
  192296. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192297. png_ptr->trans[i], back.blue);
  192298. }
  192299. }
  192300. }
  192301. else /* assume grayscale palette (what else could it be?) */
  192302. {
  192303. int i;
  192304. for (i = 0; i < num_palette; i++)
  192305. {
  192306. if (i == (png_byte)png_ptr->trans_values.gray)
  192307. {
  192308. palette[i].red = (png_byte)png_ptr->background.red;
  192309. palette[i].green = (png_byte)png_ptr->background.green;
  192310. palette[i].blue = (png_byte)png_ptr->background.blue;
  192311. }
  192312. }
  192313. }
  192314. }
  192315. #endif
  192316. }
  192317. #endif
  192318. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192319. /* Replace any alpha or transparency with the supplied background color.
  192320. * "background" is already in the screen gamma, while "background_1" is
  192321. * at a gamma of 1.0. Paletted files have already been taken care of.
  192322. */
  192323. void /* PRIVATE */
  192324. png_do_background(png_row_infop row_info, png_bytep row,
  192325. png_color_16p trans_values, png_color_16p background
  192326. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192327. , png_color_16p background_1,
  192328. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192329. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192330. png_uint_16pp gamma_16_to_1, int gamma_shift
  192331. #endif
  192332. )
  192333. {
  192334. png_bytep sp, dp;
  192335. png_uint_32 i;
  192336. png_uint_32 row_width=row_info->width;
  192337. int shift;
  192338. png_debug(1, "in png_do_background\n");
  192339. if (background != NULL &&
  192340. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192341. row != NULL && row_info != NULL &&
  192342. #endif
  192343. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192344. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192345. {
  192346. switch (row_info->color_type)
  192347. {
  192348. case PNG_COLOR_TYPE_GRAY:
  192349. {
  192350. switch (row_info->bit_depth)
  192351. {
  192352. case 1:
  192353. {
  192354. sp = row;
  192355. shift = 7;
  192356. for (i = 0; i < row_width; i++)
  192357. {
  192358. if ((png_uint_16)((*sp >> shift) & 0x01)
  192359. == trans_values->gray)
  192360. {
  192361. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192362. *sp |= (png_byte)(background->gray << shift);
  192363. }
  192364. if (!shift)
  192365. {
  192366. shift = 7;
  192367. sp++;
  192368. }
  192369. else
  192370. shift--;
  192371. }
  192372. break;
  192373. }
  192374. case 2:
  192375. {
  192376. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192377. if (gamma_table != NULL)
  192378. {
  192379. sp = row;
  192380. shift = 6;
  192381. for (i = 0; i < row_width; i++)
  192382. {
  192383. if ((png_uint_16)((*sp >> shift) & 0x03)
  192384. == trans_values->gray)
  192385. {
  192386. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192387. *sp |= (png_byte)(background->gray << shift);
  192388. }
  192389. else
  192390. {
  192391. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192392. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192393. (p << 4) | (p << 6)] >> 6) & 0x03);
  192394. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192395. *sp |= (png_byte)(g << shift);
  192396. }
  192397. if (!shift)
  192398. {
  192399. shift = 6;
  192400. sp++;
  192401. }
  192402. else
  192403. shift -= 2;
  192404. }
  192405. }
  192406. else
  192407. #endif
  192408. {
  192409. sp = row;
  192410. shift = 6;
  192411. for (i = 0; i < row_width; i++)
  192412. {
  192413. if ((png_uint_16)((*sp >> shift) & 0x03)
  192414. == trans_values->gray)
  192415. {
  192416. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192417. *sp |= (png_byte)(background->gray << shift);
  192418. }
  192419. if (!shift)
  192420. {
  192421. shift = 6;
  192422. sp++;
  192423. }
  192424. else
  192425. shift -= 2;
  192426. }
  192427. }
  192428. break;
  192429. }
  192430. case 4:
  192431. {
  192432. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192433. if (gamma_table != NULL)
  192434. {
  192435. sp = row;
  192436. shift = 4;
  192437. for (i = 0; i < row_width; i++)
  192438. {
  192439. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192440. == trans_values->gray)
  192441. {
  192442. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192443. *sp |= (png_byte)(background->gray << shift);
  192444. }
  192445. else
  192446. {
  192447. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192448. png_byte g = (png_byte)((gamma_table[p |
  192449. (p << 4)] >> 4) & 0x0f);
  192450. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192451. *sp |= (png_byte)(g << shift);
  192452. }
  192453. if (!shift)
  192454. {
  192455. shift = 4;
  192456. sp++;
  192457. }
  192458. else
  192459. shift -= 4;
  192460. }
  192461. }
  192462. else
  192463. #endif
  192464. {
  192465. sp = row;
  192466. shift = 4;
  192467. for (i = 0; i < row_width; i++)
  192468. {
  192469. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192470. == trans_values->gray)
  192471. {
  192472. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192473. *sp |= (png_byte)(background->gray << shift);
  192474. }
  192475. if (!shift)
  192476. {
  192477. shift = 4;
  192478. sp++;
  192479. }
  192480. else
  192481. shift -= 4;
  192482. }
  192483. }
  192484. break;
  192485. }
  192486. case 8:
  192487. {
  192488. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192489. if (gamma_table != NULL)
  192490. {
  192491. sp = row;
  192492. for (i = 0; i < row_width; i++, sp++)
  192493. {
  192494. if (*sp == trans_values->gray)
  192495. {
  192496. *sp = (png_byte)background->gray;
  192497. }
  192498. else
  192499. {
  192500. *sp = gamma_table[*sp];
  192501. }
  192502. }
  192503. }
  192504. else
  192505. #endif
  192506. {
  192507. sp = row;
  192508. for (i = 0; i < row_width; i++, sp++)
  192509. {
  192510. if (*sp == trans_values->gray)
  192511. {
  192512. *sp = (png_byte)background->gray;
  192513. }
  192514. }
  192515. }
  192516. break;
  192517. }
  192518. case 16:
  192519. {
  192520. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192521. if (gamma_16 != NULL)
  192522. {
  192523. sp = row;
  192524. for (i = 0; i < row_width; i++, sp += 2)
  192525. {
  192526. png_uint_16 v;
  192527. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192528. if (v == trans_values->gray)
  192529. {
  192530. /* background is already in screen gamma */
  192531. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192532. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192533. }
  192534. else
  192535. {
  192536. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192537. *sp = (png_byte)((v >> 8) & 0xff);
  192538. *(sp + 1) = (png_byte)(v & 0xff);
  192539. }
  192540. }
  192541. }
  192542. else
  192543. #endif
  192544. {
  192545. sp = row;
  192546. for (i = 0; i < row_width; i++, sp += 2)
  192547. {
  192548. png_uint_16 v;
  192549. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192550. if (v == trans_values->gray)
  192551. {
  192552. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192553. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192554. }
  192555. }
  192556. }
  192557. break;
  192558. }
  192559. }
  192560. break;
  192561. }
  192562. case PNG_COLOR_TYPE_RGB:
  192563. {
  192564. if (row_info->bit_depth == 8)
  192565. {
  192566. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192567. if (gamma_table != NULL)
  192568. {
  192569. sp = row;
  192570. for (i = 0; i < row_width; i++, sp += 3)
  192571. {
  192572. if (*sp == trans_values->red &&
  192573. *(sp + 1) == trans_values->green &&
  192574. *(sp + 2) == trans_values->blue)
  192575. {
  192576. *sp = (png_byte)background->red;
  192577. *(sp + 1) = (png_byte)background->green;
  192578. *(sp + 2) = (png_byte)background->blue;
  192579. }
  192580. else
  192581. {
  192582. *sp = gamma_table[*sp];
  192583. *(sp + 1) = gamma_table[*(sp + 1)];
  192584. *(sp + 2) = gamma_table[*(sp + 2)];
  192585. }
  192586. }
  192587. }
  192588. else
  192589. #endif
  192590. {
  192591. sp = row;
  192592. for (i = 0; i < row_width; i++, sp += 3)
  192593. {
  192594. if (*sp == trans_values->red &&
  192595. *(sp + 1) == trans_values->green &&
  192596. *(sp + 2) == trans_values->blue)
  192597. {
  192598. *sp = (png_byte)background->red;
  192599. *(sp + 1) = (png_byte)background->green;
  192600. *(sp + 2) = (png_byte)background->blue;
  192601. }
  192602. }
  192603. }
  192604. }
  192605. else /* if (row_info->bit_depth == 16) */
  192606. {
  192607. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192608. if (gamma_16 != NULL)
  192609. {
  192610. sp = row;
  192611. for (i = 0; i < row_width; i++, sp += 6)
  192612. {
  192613. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192614. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192615. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192616. if (r == trans_values->red && g == trans_values->green &&
  192617. b == trans_values->blue)
  192618. {
  192619. /* background is already in screen gamma */
  192620. *sp = (png_byte)((background->red >> 8) & 0xff);
  192621. *(sp + 1) = (png_byte)(background->red & 0xff);
  192622. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192623. *(sp + 3) = (png_byte)(background->green & 0xff);
  192624. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192625. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192626. }
  192627. else
  192628. {
  192629. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192630. *sp = (png_byte)((v >> 8) & 0xff);
  192631. *(sp + 1) = (png_byte)(v & 0xff);
  192632. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192633. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192634. *(sp + 3) = (png_byte)(v & 0xff);
  192635. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192636. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192637. *(sp + 5) = (png_byte)(v & 0xff);
  192638. }
  192639. }
  192640. }
  192641. else
  192642. #endif
  192643. {
  192644. sp = row;
  192645. for (i = 0; i < row_width; i++, sp += 6)
  192646. {
  192647. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192648. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192649. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192650. if (r == trans_values->red && g == trans_values->green &&
  192651. b == trans_values->blue)
  192652. {
  192653. *sp = (png_byte)((background->red >> 8) & 0xff);
  192654. *(sp + 1) = (png_byte)(background->red & 0xff);
  192655. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192656. *(sp + 3) = (png_byte)(background->green & 0xff);
  192657. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192658. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192659. }
  192660. }
  192661. }
  192662. }
  192663. break;
  192664. }
  192665. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192666. {
  192667. if (row_info->bit_depth == 8)
  192668. {
  192669. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192670. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192671. gamma_table != NULL)
  192672. {
  192673. sp = row;
  192674. dp = row;
  192675. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192676. {
  192677. png_uint_16 a = *(sp + 1);
  192678. if (a == 0xff)
  192679. {
  192680. *dp = gamma_table[*sp];
  192681. }
  192682. else if (a == 0)
  192683. {
  192684. /* background is already in screen gamma */
  192685. *dp = (png_byte)background->gray;
  192686. }
  192687. else
  192688. {
  192689. png_byte v, w;
  192690. v = gamma_to_1[*sp];
  192691. png_composite(w, v, a, background_1->gray);
  192692. *dp = gamma_from_1[w];
  192693. }
  192694. }
  192695. }
  192696. else
  192697. #endif
  192698. {
  192699. sp = row;
  192700. dp = row;
  192701. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192702. {
  192703. png_byte a = *(sp + 1);
  192704. if (a == 0xff)
  192705. {
  192706. *dp = *sp;
  192707. }
  192708. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192709. else if (a == 0)
  192710. {
  192711. *dp = (png_byte)background->gray;
  192712. }
  192713. else
  192714. {
  192715. png_composite(*dp, *sp, a, background_1->gray);
  192716. }
  192717. #else
  192718. *dp = (png_byte)background->gray;
  192719. #endif
  192720. }
  192721. }
  192722. }
  192723. else /* if (png_ptr->bit_depth == 16) */
  192724. {
  192725. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192726. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192727. gamma_16_to_1 != NULL)
  192728. {
  192729. sp = row;
  192730. dp = row;
  192731. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192732. {
  192733. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192734. if (a == (png_uint_16)0xffff)
  192735. {
  192736. png_uint_16 v;
  192737. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192738. *dp = (png_byte)((v >> 8) & 0xff);
  192739. *(dp + 1) = (png_byte)(v & 0xff);
  192740. }
  192741. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192742. else if (a == 0)
  192743. #else
  192744. else
  192745. #endif
  192746. {
  192747. /* background is already in screen gamma */
  192748. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192749. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192750. }
  192751. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192752. else
  192753. {
  192754. png_uint_16 g, v, w;
  192755. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192756. png_composite_16(v, g, a, background_1->gray);
  192757. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192758. *dp = (png_byte)((w >> 8) & 0xff);
  192759. *(dp + 1) = (png_byte)(w & 0xff);
  192760. }
  192761. #endif
  192762. }
  192763. }
  192764. else
  192765. #endif
  192766. {
  192767. sp = row;
  192768. dp = row;
  192769. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192770. {
  192771. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192772. if (a == (png_uint_16)0xffff)
  192773. {
  192774. png_memcpy(dp, sp, 2);
  192775. }
  192776. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192777. else if (a == 0)
  192778. #else
  192779. else
  192780. #endif
  192781. {
  192782. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192783. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192784. }
  192785. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192786. else
  192787. {
  192788. png_uint_16 g, v;
  192789. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192790. png_composite_16(v, g, a, background_1->gray);
  192791. *dp = (png_byte)((v >> 8) & 0xff);
  192792. *(dp + 1) = (png_byte)(v & 0xff);
  192793. }
  192794. #endif
  192795. }
  192796. }
  192797. }
  192798. break;
  192799. }
  192800. case PNG_COLOR_TYPE_RGB_ALPHA:
  192801. {
  192802. if (row_info->bit_depth == 8)
  192803. {
  192804. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192805. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192806. gamma_table != NULL)
  192807. {
  192808. sp = row;
  192809. dp = row;
  192810. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192811. {
  192812. png_byte a = *(sp + 3);
  192813. if (a == 0xff)
  192814. {
  192815. *dp = gamma_table[*sp];
  192816. *(dp + 1) = gamma_table[*(sp + 1)];
  192817. *(dp + 2) = gamma_table[*(sp + 2)];
  192818. }
  192819. else if (a == 0)
  192820. {
  192821. /* background is already in screen gamma */
  192822. *dp = (png_byte)background->red;
  192823. *(dp + 1) = (png_byte)background->green;
  192824. *(dp + 2) = (png_byte)background->blue;
  192825. }
  192826. else
  192827. {
  192828. png_byte v, w;
  192829. v = gamma_to_1[*sp];
  192830. png_composite(w, v, a, background_1->red);
  192831. *dp = gamma_from_1[w];
  192832. v = gamma_to_1[*(sp + 1)];
  192833. png_composite(w, v, a, background_1->green);
  192834. *(dp + 1) = gamma_from_1[w];
  192835. v = gamma_to_1[*(sp + 2)];
  192836. png_composite(w, v, a, background_1->blue);
  192837. *(dp + 2) = gamma_from_1[w];
  192838. }
  192839. }
  192840. }
  192841. else
  192842. #endif
  192843. {
  192844. sp = row;
  192845. dp = row;
  192846. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192847. {
  192848. png_byte a = *(sp + 3);
  192849. if (a == 0xff)
  192850. {
  192851. *dp = *sp;
  192852. *(dp + 1) = *(sp + 1);
  192853. *(dp + 2) = *(sp + 2);
  192854. }
  192855. else if (a == 0)
  192856. {
  192857. *dp = (png_byte)background->red;
  192858. *(dp + 1) = (png_byte)background->green;
  192859. *(dp + 2) = (png_byte)background->blue;
  192860. }
  192861. else
  192862. {
  192863. png_composite(*dp, *sp, a, background->red);
  192864. png_composite(*(dp + 1), *(sp + 1), a,
  192865. background->green);
  192866. png_composite(*(dp + 2), *(sp + 2), a,
  192867. background->blue);
  192868. }
  192869. }
  192870. }
  192871. }
  192872. else /* if (row_info->bit_depth == 16) */
  192873. {
  192874. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192875. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192876. gamma_16_to_1 != NULL)
  192877. {
  192878. sp = row;
  192879. dp = row;
  192880. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192881. {
  192882. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192883. << 8) + (png_uint_16)(*(sp + 7)));
  192884. if (a == (png_uint_16)0xffff)
  192885. {
  192886. png_uint_16 v;
  192887. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192888. *dp = (png_byte)((v >> 8) & 0xff);
  192889. *(dp + 1) = (png_byte)(v & 0xff);
  192890. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192891. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192892. *(dp + 3) = (png_byte)(v & 0xff);
  192893. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192894. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192895. *(dp + 5) = (png_byte)(v & 0xff);
  192896. }
  192897. else if (a == 0)
  192898. {
  192899. /* background is already in screen gamma */
  192900. *dp = (png_byte)((background->red >> 8) & 0xff);
  192901. *(dp + 1) = (png_byte)(background->red & 0xff);
  192902. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192903. *(dp + 3) = (png_byte)(background->green & 0xff);
  192904. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192905. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192906. }
  192907. else
  192908. {
  192909. png_uint_16 v, w, x;
  192910. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192911. png_composite_16(w, v, a, background_1->red);
  192912. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192913. *dp = (png_byte)((x >> 8) & 0xff);
  192914. *(dp + 1) = (png_byte)(x & 0xff);
  192915. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192916. png_composite_16(w, v, a, background_1->green);
  192917. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192918. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192919. *(dp + 3) = (png_byte)(x & 0xff);
  192920. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192921. png_composite_16(w, v, a, background_1->blue);
  192922. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192923. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192924. *(dp + 5) = (png_byte)(x & 0xff);
  192925. }
  192926. }
  192927. }
  192928. else
  192929. #endif
  192930. {
  192931. sp = row;
  192932. dp = row;
  192933. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192934. {
  192935. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192936. << 8) + (png_uint_16)(*(sp + 7)));
  192937. if (a == (png_uint_16)0xffff)
  192938. {
  192939. png_memcpy(dp, sp, 6);
  192940. }
  192941. else if (a == 0)
  192942. {
  192943. *dp = (png_byte)((background->red >> 8) & 0xff);
  192944. *(dp + 1) = (png_byte)(background->red & 0xff);
  192945. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192946. *(dp + 3) = (png_byte)(background->green & 0xff);
  192947. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192948. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192949. }
  192950. else
  192951. {
  192952. png_uint_16 v;
  192953. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192954. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192955. + *(sp + 3));
  192956. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192957. + *(sp + 5));
  192958. png_composite_16(v, r, a, background->red);
  192959. *dp = (png_byte)((v >> 8) & 0xff);
  192960. *(dp + 1) = (png_byte)(v & 0xff);
  192961. png_composite_16(v, g, a, background->green);
  192962. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192963. *(dp + 3) = (png_byte)(v & 0xff);
  192964. png_composite_16(v, b, a, background->blue);
  192965. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192966. *(dp + 5) = (png_byte)(v & 0xff);
  192967. }
  192968. }
  192969. }
  192970. }
  192971. break;
  192972. }
  192973. }
  192974. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192975. {
  192976. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192977. row_info->channels--;
  192978. row_info->pixel_depth = (png_byte)(row_info->channels *
  192979. row_info->bit_depth);
  192980. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192981. }
  192982. }
  192983. }
  192984. #endif
  192985. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192986. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192987. * you do this after you deal with the transparency issue on grayscale
  192988. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192989. * is 16, use gamma_16_table and gamma_shift. Build these with
  192990. * build_gamma_table().
  192991. */
  192992. void /* PRIVATE */
  192993. png_do_gamma(png_row_infop row_info, png_bytep row,
  192994. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192995. int gamma_shift)
  192996. {
  192997. png_bytep sp;
  192998. png_uint_32 i;
  192999. png_uint_32 row_width=row_info->width;
  193000. png_debug(1, "in png_do_gamma\n");
  193001. if (
  193002. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193003. row != NULL && row_info != NULL &&
  193004. #endif
  193005. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193006. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193007. {
  193008. switch (row_info->color_type)
  193009. {
  193010. case PNG_COLOR_TYPE_RGB:
  193011. {
  193012. if (row_info->bit_depth == 8)
  193013. {
  193014. sp = row;
  193015. for (i = 0; i < row_width; i++)
  193016. {
  193017. *sp = gamma_table[*sp];
  193018. sp++;
  193019. *sp = gamma_table[*sp];
  193020. sp++;
  193021. *sp = gamma_table[*sp];
  193022. sp++;
  193023. }
  193024. }
  193025. else /* if (row_info->bit_depth == 16) */
  193026. {
  193027. sp = row;
  193028. for (i = 0; i < row_width; i++)
  193029. {
  193030. png_uint_16 v;
  193031. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193032. *sp = (png_byte)((v >> 8) & 0xff);
  193033. *(sp + 1) = (png_byte)(v & 0xff);
  193034. sp += 2;
  193035. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193036. *sp = (png_byte)((v >> 8) & 0xff);
  193037. *(sp + 1) = (png_byte)(v & 0xff);
  193038. sp += 2;
  193039. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193040. *sp = (png_byte)((v >> 8) & 0xff);
  193041. *(sp + 1) = (png_byte)(v & 0xff);
  193042. sp += 2;
  193043. }
  193044. }
  193045. break;
  193046. }
  193047. case PNG_COLOR_TYPE_RGB_ALPHA:
  193048. {
  193049. if (row_info->bit_depth == 8)
  193050. {
  193051. sp = row;
  193052. for (i = 0; i < row_width; i++)
  193053. {
  193054. *sp = gamma_table[*sp];
  193055. sp++;
  193056. *sp = gamma_table[*sp];
  193057. sp++;
  193058. *sp = gamma_table[*sp];
  193059. sp++;
  193060. sp++;
  193061. }
  193062. }
  193063. else /* if (row_info->bit_depth == 16) */
  193064. {
  193065. sp = row;
  193066. for (i = 0; i < row_width; i++)
  193067. {
  193068. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193069. *sp = (png_byte)((v >> 8) & 0xff);
  193070. *(sp + 1) = (png_byte)(v & 0xff);
  193071. sp += 2;
  193072. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193073. *sp = (png_byte)((v >> 8) & 0xff);
  193074. *(sp + 1) = (png_byte)(v & 0xff);
  193075. sp += 2;
  193076. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193077. *sp = (png_byte)((v >> 8) & 0xff);
  193078. *(sp + 1) = (png_byte)(v & 0xff);
  193079. sp += 4;
  193080. }
  193081. }
  193082. break;
  193083. }
  193084. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193085. {
  193086. if (row_info->bit_depth == 8)
  193087. {
  193088. sp = row;
  193089. for (i = 0; i < row_width; i++)
  193090. {
  193091. *sp = gamma_table[*sp];
  193092. sp += 2;
  193093. }
  193094. }
  193095. else /* if (row_info->bit_depth == 16) */
  193096. {
  193097. sp = row;
  193098. for (i = 0; i < row_width; i++)
  193099. {
  193100. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193101. *sp = (png_byte)((v >> 8) & 0xff);
  193102. *(sp + 1) = (png_byte)(v & 0xff);
  193103. sp += 4;
  193104. }
  193105. }
  193106. break;
  193107. }
  193108. case PNG_COLOR_TYPE_GRAY:
  193109. {
  193110. if (row_info->bit_depth == 2)
  193111. {
  193112. sp = row;
  193113. for (i = 0; i < row_width; i += 4)
  193114. {
  193115. int a = *sp & 0xc0;
  193116. int b = *sp & 0x30;
  193117. int c = *sp & 0x0c;
  193118. int d = *sp & 0x03;
  193119. *sp = (png_byte)(
  193120. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193121. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193122. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193123. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193124. sp++;
  193125. }
  193126. }
  193127. if (row_info->bit_depth == 4)
  193128. {
  193129. sp = row;
  193130. for (i = 0; i < row_width; i += 2)
  193131. {
  193132. int msb = *sp & 0xf0;
  193133. int lsb = *sp & 0x0f;
  193134. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193135. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193136. sp++;
  193137. }
  193138. }
  193139. else if (row_info->bit_depth == 8)
  193140. {
  193141. sp = row;
  193142. for (i = 0; i < row_width; i++)
  193143. {
  193144. *sp = gamma_table[*sp];
  193145. sp++;
  193146. }
  193147. }
  193148. else if (row_info->bit_depth == 16)
  193149. {
  193150. sp = row;
  193151. for (i = 0; i < row_width; i++)
  193152. {
  193153. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193154. *sp = (png_byte)((v >> 8) & 0xff);
  193155. *(sp + 1) = (png_byte)(v & 0xff);
  193156. sp += 2;
  193157. }
  193158. }
  193159. break;
  193160. }
  193161. }
  193162. }
  193163. }
  193164. #endif
  193165. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193166. /* Expands a palette row to an RGB or RGBA row depending
  193167. * upon whether you supply trans and num_trans.
  193168. */
  193169. void /* PRIVATE */
  193170. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193171. png_colorp palette, png_bytep trans, int num_trans)
  193172. {
  193173. int shift, value;
  193174. png_bytep sp, dp;
  193175. png_uint_32 i;
  193176. png_uint_32 row_width=row_info->width;
  193177. png_debug(1, "in png_do_expand_palette\n");
  193178. if (
  193179. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193180. row != NULL && row_info != NULL &&
  193181. #endif
  193182. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193183. {
  193184. if (row_info->bit_depth < 8)
  193185. {
  193186. switch (row_info->bit_depth)
  193187. {
  193188. case 1:
  193189. {
  193190. sp = row + (png_size_t)((row_width - 1) >> 3);
  193191. dp = row + (png_size_t)row_width - 1;
  193192. shift = 7 - (int)((row_width + 7) & 0x07);
  193193. for (i = 0; i < row_width; i++)
  193194. {
  193195. if ((*sp >> shift) & 0x01)
  193196. *dp = 1;
  193197. else
  193198. *dp = 0;
  193199. if (shift == 7)
  193200. {
  193201. shift = 0;
  193202. sp--;
  193203. }
  193204. else
  193205. shift++;
  193206. dp--;
  193207. }
  193208. break;
  193209. }
  193210. case 2:
  193211. {
  193212. sp = row + (png_size_t)((row_width - 1) >> 2);
  193213. dp = row + (png_size_t)row_width - 1;
  193214. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193215. for (i = 0; i < row_width; i++)
  193216. {
  193217. value = (*sp >> shift) & 0x03;
  193218. *dp = (png_byte)value;
  193219. if (shift == 6)
  193220. {
  193221. shift = 0;
  193222. sp--;
  193223. }
  193224. else
  193225. shift += 2;
  193226. dp--;
  193227. }
  193228. break;
  193229. }
  193230. case 4:
  193231. {
  193232. sp = row + (png_size_t)((row_width - 1) >> 1);
  193233. dp = row + (png_size_t)row_width - 1;
  193234. shift = (int)((row_width & 0x01) << 2);
  193235. for (i = 0; i < row_width; i++)
  193236. {
  193237. value = (*sp >> shift) & 0x0f;
  193238. *dp = (png_byte)value;
  193239. if (shift == 4)
  193240. {
  193241. shift = 0;
  193242. sp--;
  193243. }
  193244. else
  193245. shift += 4;
  193246. dp--;
  193247. }
  193248. break;
  193249. }
  193250. }
  193251. row_info->bit_depth = 8;
  193252. row_info->pixel_depth = 8;
  193253. row_info->rowbytes = row_width;
  193254. }
  193255. switch (row_info->bit_depth)
  193256. {
  193257. case 8:
  193258. {
  193259. if (trans != NULL)
  193260. {
  193261. sp = row + (png_size_t)row_width - 1;
  193262. dp = row + (png_size_t)(row_width << 2) - 1;
  193263. for (i = 0; i < row_width; i++)
  193264. {
  193265. if ((int)(*sp) >= num_trans)
  193266. *dp-- = 0xff;
  193267. else
  193268. *dp-- = trans[*sp];
  193269. *dp-- = palette[*sp].blue;
  193270. *dp-- = palette[*sp].green;
  193271. *dp-- = palette[*sp].red;
  193272. sp--;
  193273. }
  193274. row_info->bit_depth = 8;
  193275. row_info->pixel_depth = 32;
  193276. row_info->rowbytes = row_width * 4;
  193277. row_info->color_type = 6;
  193278. row_info->channels = 4;
  193279. }
  193280. else
  193281. {
  193282. sp = row + (png_size_t)row_width - 1;
  193283. dp = row + (png_size_t)(row_width * 3) - 1;
  193284. for (i = 0; i < row_width; i++)
  193285. {
  193286. *dp-- = palette[*sp].blue;
  193287. *dp-- = palette[*sp].green;
  193288. *dp-- = palette[*sp].red;
  193289. sp--;
  193290. }
  193291. row_info->bit_depth = 8;
  193292. row_info->pixel_depth = 24;
  193293. row_info->rowbytes = row_width * 3;
  193294. row_info->color_type = 2;
  193295. row_info->channels = 3;
  193296. }
  193297. break;
  193298. }
  193299. }
  193300. }
  193301. }
  193302. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193303. * expanded transparency value is supplied, an alpha channel is built.
  193304. */
  193305. void /* PRIVATE */
  193306. png_do_expand(png_row_infop row_info, png_bytep row,
  193307. png_color_16p trans_value)
  193308. {
  193309. int shift, value;
  193310. png_bytep sp, dp;
  193311. png_uint_32 i;
  193312. png_uint_32 row_width=row_info->width;
  193313. png_debug(1, "in png_do_expand\n");
  193314. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193315. if (row != NULL && row_info != NULL)
  193316. #endif
  193317. {
  193318. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193319. {
  193320. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193321. if (row_info->bit_depth < 8)
  193322. {
  193323. switch (row_info->bit_depth)
  193324. {
  193325. case 1:
  193326. {
  193327. gray = (png_uint_16)((gray&0x01)*0xff);
  193328. sp = row + (png_size_t)((row_width - 1) >> 3);
  193329. dp = row + (png_size_t)row_width - 1;
  193330. shift = 7 - (int)((row_width + 7) & 0x07);
  193331. for (i = 0; i < row_width; i++)
  193332. {
  193333. if ((*sp >> shift) & 0x01)
  193334. *dp = 0xff;
  193335. else
  193336. *dp = 0;
  193337. if (shift == 7)
  193338. {
  193339. shift = 0;
  193340. sp--;
  193341. }
  193342. else
  193343. shift++;
  193344. dp--;
  193345. }
  193346. break;
  193347. }
  193348. case 2:
  193349. {
  193350. gray = (png_uint_16)((gray&0x03)*0x55);
  193351. sp = row + (png_size_t)((row_width - 1) >> 2);
  193352. dp = row + (png_size_t)row_width - 1;
  193353. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193354. for (i = 0; i < row_width; i++)
  193355. {
  193356. value = (*sp >> shift) & 0x03;
  193357. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193358. (value << 6));
  193359. if (shift == 6)
  193360. {
  193361. shift = 0;
  193362. sp--;
  193363. }
  193364. else
  193365. shift += 2;
  193366. dp--;
  193367. }
  193368. break;
  193369. }
  193370. case 4:
  193371. {
  193372. gray = (png_uint_16)((gray&0x0f)*0x11);
  193373. sp = row + (png_size_t)((row_width - 1) >> 1);
  193374. dp = row + (png_size_t)row_width - 1;
  193375. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193376. for (i = 0; i < row_width; i++)
  193377. {
  193378. value = (*sp >> shift) & 0x0f;
  193379. *dp = (png_byte)(value | (value << 4));
  193380. if (shift == 4)
  193381. {
  193382. shift = 0;
  193383. sp--;
  193384. }
  193385. else
  193386. shift = 4;
  193387. dp--;
  193388. }
  193389. break;
  193390. }
  193391. }
  193392. row_info->bit_depth = 8;
  193393. row_info->pixel_depth = 8;
  193394. row_info->rowbytes = row_width;
  193395. }
  193396. if (trans_value != NULL)
  193397. {
  193398. if (row_info->bit_depth == 8)
  193399. {
  193400. gray = gray & 0xff;
  193401. sp = row + (png_size_t)row_width - 1;
  193402. dp = row + (png_size_t)(row_width << 1) - 1;
  193403. for (i = 0; i < row_width; i++)
  193404. {
  193405. if (*sp == gray)
  193406. *dp-- = 0;
  193407. else
  193408. *dp-- = 0xff;
  193409. *dp-- = *sp--;
  193410. }
  193411. }
  193412. else if (row_info->bit_depth == 16)
  193413. {
  193414. png_byte gray_high = (gray >> 8) & 0xff;
  193415. png_byte gray_low = gray & 0xff;
  193416. sp = row + row_info->rowbytes - 1;
  193417. dp = row + (row_info->rowbytes << 1) - 1;
  193418. for (i = 0; i < row_width; i++)
  193419. {
  193420. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193421. {
  193422. *dp-- = 0;
  193423. *dp-- = 0;
  193424. }
  193425. else
  193426. {
  193427. *dp-- = 0xff;
  193428. *dp-- = 0xff;
  193429. }
  193430. *dp-- = *sp--;
  193431. *dp-- = *sp--;
  193432. }
  193433. }
  193434. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193435. row_info->channels = 2;
  193436. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193437. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193438. row_width);
  193439. }
  193440. }
  193441. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193442. {
  193443. if (row_info->bit_depth == 8)
  193444. {
  193445. png_byte red = trans_value->red & 0xff;
  193446. png_byte green = trans_value->green & 0xff;
  193447. png_byte blue = trans_value->blue & 0xff;
  193448. sp = row + (png_size_t)row_info->rowbytes - 1;
  193449. dp = row + (png_size_t)(row_width << 2) - 1;
  193450. for (i = 0; i < row_width; i++)
  193451. {
  193452. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193453. *dp-- = 0;
  193454. else
  193455. *dp-- = 0xff;
  193456. *dp-- = *sp--;
  193457. *dp-- = *sp--;
  193458. *dp-- = *sp--;
  193459. }
  193460. }
  193461. else if (row_info->bit_depth == 16)
  193462. {
  193463. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193464. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193465. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193466. png_byte red_low = trans_value->red & 0xff;
  193467. png_byte green_low = trans_value->green & 0xff;
  193468. png_byte blue_low = trans_value->blue & 0xff;
  193469. sp = row + row_info->rowbytes - 1;
  193470. dp = row + (png_size_t)(row_width << 3) - 1;
  193471. for (i = 0; i < row_width; i++)
  193472. {
  193473. if (*(sp - 5) == red_high &&
  193474. *(sp - 4) == red_low &&
  193475. *(sp - 3) == green_high &&
  193476. *(sp - 2) == green_low &&
  193477. *(sp - 1) == blue_high &&
  193478. *(sp ) == blue_low)
  193479. {
  193480. *dp-- = 0;
  193481. *dp-- = 0;
  193482. }
  193483. else
  193484. {
  193485. *dp-- = 0xff;
  193486. *dp-- = 0xff;
  193487. }
  193488. *dp-- = *sp--;
  193489. *dp-- = *sp--;
  193490. *dp-- = *sp--;
  193491. *dp-- = *sp--;
  193492. *dp-- = *sp--;
  193493. *dp-- = *sp--;
  193494. }
  193495. }
  193496. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193497. row_info->channels = 4;
  193498. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193499. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193500. }
  193501. }
  193502. }
  193503. #endif
  193504. #if defined(PNG_READ_DITHER_SUPPORTED)
  193505. void /* PRIVATE */
  193506. png_do_dither(png_row_infop row_info, png_bytep row,
  193507. png_bytep palette_lookup, png_bytep dither_lookup)
  193508. {
  193509. png_bytep sp, dp;
  193510. png_uint_32 i;
  193511. png_uint_32 row_width=row_info->width;
  193512. png_debug(1, "in png_do_dither\n");
  193513. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193514. if (row != NULL && row_info != NULL)
  193515. #endif
  193516. {
  193517. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193518. palette_lookup && row_info->bit_depth == 8)
  193519. {
  193520. int r, g, b, p;
  193521. sp = row;
  193522. dp = row;
  193523. for (i = 0; i < row_width; i++)
  193524. {
  193525. r = *sp++;
  193526. g = *sp++;
  193527. b = *sp++;
  193528. /* this looks real messy, but the compiler will reduce
  193529. it down to a reasonable formula. For example, with
  193530. 5 bits per color, we get:
  193531. p = (((r >> 3) & 0x1f) << 10) |
  193532. (((g >> 3) & 0x1f) << 5) |
  193533. ((b >> 3) & 0x1f);
  193534. */
  193535. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193536. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193537. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193538. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193539. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193540. (PNG_DITHER_BLUE_BITS)) |
  193541. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193542. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193543. *dp++ = palette_lookup[p];
  193544. }
  193545. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193546. row_info->channels = 1;
  193547. row_info->pixel_depth = row_info->bit_depth;
  193548. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193549. }
  193550. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193551. palette_lookup != NULL && row_info->bit_depth == 8)
  193552. {
  193553. int r, g, b, p;
  193554. sp = row;
  193555. dp = row;
  193556. for (i = 0; i < row_width; i++)
  193557. {
  193558. r = *sp++;
  193559. g = *sp++;
  193560. b = *sp++;
  193561. sp++;
  193562. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193563. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193564. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193565. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193566. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193567. (PNG_DITHER_BLUE_BITS)) |
  193568. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193569. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193570. *dp++ = palette_lookup[p];
  193571. }
  193572. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193573. row_info->channels = 1;
  193574. row_info->pixel_depth = row_info->bit_depth;
  193575. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193576. }
  193577. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193578. dither_lookup && row_info->bit_depth == 8)
  193579. {
  193580. sp = row;
  193581. for (i = 0; i < row_width; i++, sp++)
  193582. {
  193583. *sp = dither_lookup[*sp];
  193584. }
  193585. }
  193586. }
  193587. }
  193588. #endif
  193589. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193590. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193591. static PNG_CONST int png_gamma_shift[] =
  193592. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193593. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193594. * tables, we don't make a full table if we are reducing to 8-bit in
  193595. * the future. Note also how the gamma_16 tables are segmented so that
  193596. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193597. */
  193598. void /* PRIVATE */
  193599. png_build_gamma_table(png_structp png_ptr)
  193600. {
  193601. png_debug(1, "in png_build_gamma_table\n");
  193602. if (png_ptr->bit_depth <= 8)
  193603. {
  193604. int i;
  193605. double g;
  193606. if (png_ptr->screen_gamma > .000001)
  193607. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193608. else
  193609. g = 1.0;
  193610. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193611. (png_uint_32)256);
  193612. for (i = 0; i < 256; i++)
  193613. {
  193614. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193615. g) * 255.0 + .5);
  193616. }
  193617. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193618. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193619. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193620. {
  193621. g = 1.0 / (png_ptr->gamma);
  193622. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193623. (png_uint_32)256);
  193624. for (i = 0; i < 256; i++)
  193625. {
  193626. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193627. g) * 255.0 + .5);
  193628. }
  193629. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193630. (png_uint_32)256);
  193631. if(png_ptr->screen_gamma > 0.000001)
  193632. g = 1.0 / png_ptr->screen_gamma;
  193633. else
  193634. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193635. for (i = 0; i < 256; i++)
  193636. {
  193637. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193638. g) * 255.0 + .5);
  193639. }
  193640. }
  193641. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193642. }
  193643. else
  193644. {
  193645. double g;
  193646. int i, j, shift, num;
  193647. int sig_bit;
  193648. png_uint_32 ig;
  193649. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193650. {
  193651. sig_bit = (int)png_ptr->sig_bit.red;
  193652. if ((int)png_ptr->sig_bit.green > sig_bit)
  193653. sig_bit = png_ptr->sig_bit.green;
  193654. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193655. sig_bit = png_ptr->sig_bit.blue;
  193656. }
  193657. else
  193658. {
  193659. sig_bit = (int)png_ptr->sig_bit.gray;
  193660. }
  193661. if (sig_bit > 0)
  193662. shift = 16 - sig_bit;
  193663. else
  193664. shift = 0;
  193665. if (png_ptr->transformations & PNG_16_TO_8)
  193666. {
  193667. if (shift < (16 - PNG_MAX_GAMMA_8))
  193668. shift = (16 - PNG_MAX_GAMMA_8);
  193669. }
  193670. if (shift > 8)
  193671. shift = 8;
  193672. if (shift < 0)
  193673. shift = 0;
  193674. png_ptr->gamma_shift = (png_byte)shift;
  193675. num = (1 << (8 - shift));
  193676. if (png_ptr->screen_gamma > .000001)
  193677. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193678. else
  193679. g = 1.0;
  193680. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193681. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193682. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193683. {
  193684. double fin, fout;
  193685. png_uint_32 last, max;
  193686. for (i = 0; i < num; i++)
  193687. {
  193688. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193689. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193690. }
  193691. g = 1.0 / g;
  193692. last = 0;
  193693. for (i = 0; i < 256; i++)
  193694. {
  193695. fout = ((double)i + 0.5) / 256.0;
  193696. fin = pow(fout, g);
  193697. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193698. while (last <= max)
  193699. {
  193700. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193701. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193702. (png_uint_16)i | ((png_uint_16)i << 8));
  193703. last++;
  193704. }
  193705. }
  193706. while (last < ((png_uint_32)num << 8))
  193707. {
  193708. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193709. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193710. last++;
  193711. }
  193712. }
  193713. else
  193714. {
  193715. for (i = 0; i < num; i++)
  193716. {
  193717. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193718. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193719. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193720. for (j = 0; j < 256; j++)
  193721. {
  193722. png_ptr->gamma_16_table[i][j] =
  193723. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193724. 65535.0, g) * 65535.0 + .5);
  193725. }
  193726. }
  193727. }
  193728. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193729. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193730. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193731. {
  193732. g = 1.0 / (png_ptr->gamma);
  193733. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193734. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193735. for (i = 0; i < num; i++)
  193736. {
  193737. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193738. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193739. ig = (((png_uint_32)i *
  193740. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193741. for (j = 0; j < 256; j++)
  193742. {
  193743. png_ptr->gamma_16_to_1[i][j] =
  193744. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193745. 65535.0, g) * 65535.0 + .5);
  193746. }
  193747. }
  193748. if(png_ptr->screen_gamma > 0.000001)
  193749. g = 1.0 / png_ptr->screen_gamma;
  193750. else
  193751. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193752. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193753. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193754. for (i = 0; i < num; i++)
  193755. {
  193756. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193757. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193758. ig = (((png_uint_32)i *
  193759. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193760. for (j = 0; j < 256; j++)
  193761. {
  193762. png_ptr->gamma_16_from_1[i][j] =
  193763. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193764. 65535.0, g) * 65535.0 + .5);
  193765. }
  193766. }
  193767. }
  193768. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193769. }
  193770. }
  193771. #endif
  193772. /* To do: install integer version of png_build_gamma_table here */
  193773. #endif
  193774. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193775. /* undoes intrapixel differencing */
  193776. void /* PRIVATE */
  193777. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193778. {
  193779. png_debug(1, "in png_do_read_intrapixel\n");
  193780. if (
  193781. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193782. row != NULL && row_info != NULL &&
  193783. #endif
  193784. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193785. {
  193786. int bytes_per_pixel;
  193787. png_uint_32 row_width = row_info->width;
  193788. if (row_info->bit_depth == 8)
  193789. {
  193790. png_bytep rp;
  193791. png_uint_32 i;
  193792. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193793. bytes_per_pixel = 3;
  193794. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193795. bytes_per_pixel = 4;
  193796. else
  193797. return;
  193798. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193799. {
  193800. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193801. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193802. }
  193803. }
  193804. else if (row_info->bit_depth == 16)
  193805. {
  193806. png_bytep rp;
  193807. png_uint_32 i;
  193808. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193809. bytes_per_pixel = 6;
  193810. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193811. bytes_per_pixel = 8;
  193812. else
  193813. return;
  193814. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193815. {
  193816. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193817. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193818. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193819. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193820. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193821. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193822. *(rp+1) = (png_byte)(red & 0xff);
  193823. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193824. *(rp+5) = (png_byte)(blue & 0xff);
  193825. }
  193826. }
  193827. }
  193828. }
  193829. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193830. #endif /* PNG_READ_SUPPORTED */
  193831. /*** End of inlined file: pngrtran.c ***/
  193832. /*** Start of inlined file: pngrutil.c ***/
  193833. /* pngrutil.c - utilities to read a PNG file
  193834. *
  193835. * Last changed in libpng 1.2.21 [October 4, 2007]
  193836. * For conditions of distribution and use, see copyright notice in png.h
  193837. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193838. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193839. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193840. *
  193841. * This file contains routines that are only called from within
  193842. * libpng itself during the course of reading an image.
  193843. */
  193844. #define PNG_INTERNAL
  193845. #if defined(PNG_READ_SUPPORTED)
  193846. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193847. # define WIN32_WCE_OLD
  193848. #endif
  193849. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193850. # if defined(WIN32_WCE_OLD)
  193851. /* strtod() function is not supported on WindowsCE */
  193852. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193853. {
  193854. double result = 0;
  193855. int len;
  193856. wchar_t *str, *end;
  193857. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193858. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193859. if ( NULL != str )
  193860. {
  193861. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193862. result = wcstod(str, &end);
  193863. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193864. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193865. png_free(png_ptr, str);
  193866. }
  193867. return result;
  193868. }
  193869. # else
  193870. # define png_strtod(p,a,b) strtod(a,b)
  193871. # endif
  193872. #endif
  193873. png_uint_32 PNGAPI
  193874. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193875. {
  193876. png_uint_32 i = png_get_uint_32(buf);
  193877. if (i > PNG_UINT_31_MAX)
  193878. png_error(png_ptr, "PNG unsigned integer out of range.");
  193879. return (i);
  193880. }
  193881. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193882. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193883. png_uint_32 PNGAPI
  193884. png_get_uint_32(png_bytep buf)
  193885. {
  193886. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193887. ((png_uint_32)(*(buf + 1)) << 16) +
  193888. ((png_uint_32)(*(buf + 2)) << 8) +
  193889. (png_uint_32)(*(buf + 3));
  193890. return (i);
  193891. }
  193892. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193893. * data is stored in the PNG file in two's complement format, and it is
  193894. * assumed that the machine format for signed integers is the same. */
  193895. png_int_32 PNGAPI
  193896. png_get_int_32(png_bytep buf)
  193897. {
  193898. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193899. ((png_int_32)(*(buf + 1)) << 16) +
  193900. ((png_int_32)(*(buf + 2)) << 8) +
  193901. (png_int_32)(*(buf + 3));
  193902. return (i);
  193903. }
  193904. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193905. png_uint_16 PNGAPI
  193906. png_get_uint_16(png_bytep buf)
  193907. {
  193908. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193909. (png_uint_16)(*(buf + 1)));
  193910. return (i);
  193911. }
  193912. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193913. /* Read data, and (optionally) run it through the CRC. */
  193914. void /* PRIVATE */
  193915. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193916. {
  193917. if(png_ptr == NULL) return;
  193918. png_read_data(png_ptr, buf, length);
  193919. png_calculate_crc(png_ptr, buf, length);
  193920. }
  193921. /* Optionally skip data and then check the CRC. Depending on whether we
  193922. are reading a ancillary or critical chunk, and how the program has set
  193923. things up, we may calculate the CRC on the data and print a message.
  193924. Returns '1' if there was a CRC error, '0' otherwise. */
  193925. int /* PRIVATE */
  193926. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193927. {
  193928. png_size_t i;
  193929. png_size_t istop = png_ptr->zbuf_size;
  193930. for (i = (png_size_t)skip; i > istop; i -= istop)
  193931. {
  193932. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193933. }
  193934. if (i)
  193935. {
  193936. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193937. }
  193938. if (png_crc_error(png_ptr))
  193939. {
  193940. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193941. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193942. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193943. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193944. {
  193945. png_chunk_warning(png_ptr, "CRC error");
  193946. }
  193947. else
  193948. {
  193949. png_chunk_error(png_ptr, "CRC error");
  193950. }
  193951. return (1);
  193952. }
  193953. return (0);
  193954. }
  193955. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193956. the data it has read thus far. */
  193957. int /* PRIVATE */
  193958. png_crc_error(png_structp png_ptr)
  193959. {
  193960. png_byte crc_bytes[4];
  193961. png_uint_32 crc;
  193962. int need_crc = 1;
  193963. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193964. {
  193965. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193966. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193967. need_crc = 0;
  193968. }
  193969. else /* critical */
  193970. {
  193971. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193972. need_crc = 0;
  193973. }
  193974. png_read_data(png_ptr, crc_bytes, 4);
  193975. if (need_crc)
  193976. {
  193977. crc = png_get_uint_32(crc_bytes);
  193978. return ((int)(crc != png_ptr->crc));
  193979. }
  193980. else
  193981. return (0);
  193982. }
  193983. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193984. defined(PNG_READ_iCCP_SUPPORTED)
  193985. /*
  193986. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193987. * points at an allocated area holding the contents of a chunk with a
  193988. * trailing compressed part. What we get back is an allocated area
  193989. * holding the original prefix part and an uncompressed version of the
  193990. * trailing part (the malloc area passed in is freed).
  193991. */
  193992. png_charp /* PRIVATE */
  193993. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193994. png_charp chunkdata, png_size_t chunklength,
  193995. png_size_t prefix_size, png_size_t *newlength)
  193996. {
  193997. static PNG_CONST char msg[] = "Error decoding compressed text";
  193998. png_charp text;
  193999. png_size_t text_size;
  194000. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194001. {
  194002. int ret = Z_OK;
  194003. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194004. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194005. png_ptr->zstream.next_out = png_ptr->zbuf;
  194006. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194007. text_size = 0;
  194008. text = NULL;
  194009. while (png_ptr->zstream.avail_in)
  194010. {
  194011. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194012. if (ret != Z_OK && ret != Z_STREAM_END)
  194013. {
  194014. if (png_ptr->zstream.msg != NULL)
  194015. png_warning(png_ptr, png_ptr->zstream.msg);
  194016. else
  194017. png_warning(png_ptr, msg);
  194018. inflateReset(&png_ptr->zstream);
  194019. png_ptr->zstream.avail_in = 0;
  194020. if (text == NULL)
  194021. {
  194022. text_size = prefix_size + png_sizeof(msg) + 1;
  194023. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194024. if (text == NULL)
  194025. {
  194026. png_free(png_ptr,chunkdata);
  194027. png_error(png_ptr,"Not enough memory to decompress chunk");
  194028. }
  194029. png_memcpy(text, chunkdata, prefix_size);
  194030. }
  194031. text[text_size - 1] = 0x00;
  194032. /* Copy what we can of the error message into the text chunk */
  194033. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194034. text_size = png_sizeof(msg) > text_size ? text_size :
  194035. png_sizeof(msg);
  194036. png_memcpy(text + prefix_size, msg, text_size + 1);
  194037. break;
  194038. }
  194039. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194040. {
  194041. if (text == NULL)
  194042. {
  194043. text_size = prefix_size +
  194044. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194045. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194046. if (text == NULL)
  194047. {
  194048. png_free(png_ptr,chunkdata);
  194049. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194050. }
  194051. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194052. text_size - prefix_size);
  194053. png_memcpy(text, chunkdata, prefix_size);
  194054. *(text + text_size) = 0x00;
  194055. }
  194056. else
  194057. {
  194058. png_charp tmp;
  194059. tmp = text;
  194060. text = (png_charp)png_malloc_warn(png_ptr,
  194061. (png_uint_32)(text_size +
  194062. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194063. if (text == NULL)
  194064. {
  194065. png_free(png_ptr, tmp);
  194066. png_free(png_ptr, chunkdata);
  194067. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194068. }
  194069. png_memcpy(text, tmp, text_size);
  194070. png_free(png_ptr, tmp);
  194071. png_memcpy(text + text_size, png_ptr->zbuf,
  194072. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194073. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194074. *(text + text_size) = 0x00;
  194075. }
  194076. if (ret == Z_STREAM_END)
  194077. break;
  194078. else
  194079. {
  194080. png_ptr->zstream.next_out = png_ptr->zbuf;
  194081. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194082. }
  194083. }
  194084. }
  194085. if (ret != Z_STREAM_END)
  194086. {
  194087. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194088. char umsg[52];
  194089. if (ret == Z_BUF_ERROR)
  194090. png_snprintf(umsg, 52,
  194091. "Buffer error in compressed datastream in %s chunk",
  194092. png_ptr->chunk_name);
  194093. else if (ret == Z_DATA_ERROR)
  194094. png_snprintf(umsg, 52,
  194095. "Data error in compressed datastream in %s chunk",
  194096. png_ptr->chunk_name);
  194097. else
  194098. png_snprintf(umsg, 52,
  194099. "Incomplete compressed datastream in %s chunk",
  194100. png_ptr->chunk_name);
  194101. png_warning(png_ptr, umsg);
  194102. #else
  194103. png_warning(png_ptr,
  194104. "Incomplete compressed datastream in chunk other than IDAT");
  194105. #endif
  194106. text_size=prefix_size;
  194107. if (text == NULL)
  194108. {
  194109. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194110. if (text == NULL)
  194111. {
  194112. png_free(png_ptr, chunkdata);
  194113. png_error(png_ptr,"Not enough memory for text.");
  194114. }
  194115. png_memcpy(text, chunkdata, prefix_size);
  194116. }
  194117. *(text + text_size) = 0x00;
  194118. }
  194119. inflateReset(&png_ptr->zstream);
  194120. png_ptr->zstream.avail_in = 0;
  194121. png_free(png_ptr, chunkdata);
  194122. chunkdata = text;
  194123. *newlength=text_size;
  194124. }
  194125. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194126. {
  194127. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194128. char umsg[50];
  194129. png_snprintf(umsg, 50,
  194130. "Unknown zTXt compression type %d", comp_type);
  194131. png_warning(png_ptr, umsg);
  194132. #else
  194133. png_warning(png_ptr, "Unknown zTXt compression type");
  194134. #endif
  194135. *(chunkdata + prefix_size) = 0x00;
  194136. *newlength=prefix_size;
  194137. }
  194138. return chunkdata;
  194139. }
  194140. #endif
  194141. /* read and check the IDHR chunk */
  194142. void /* PRIVATE */
  194143. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194144. {
  194145. png_byte buf[13];
  194146. png_uint_32 width, height;
  194147. int bit_depth, color_type, compression_type, filter_type;
  194148. int interlace_type;
  194149. png_debug(1, "in png_handle_IHDR\n");
  194150. if (png_ptr->mode & PNG_HAVE_IHDR)
  194151. png_error(png_ptr, "Out of place IHDR");
  194152. /* check the length */
  194153. if (length != 13)
  194154. png_error(png_ptr, "Invalid IHDR chunk");
  194155. png_ptr->mode |= PNG_HAVE_IHDR;
  194156. png_crc_read(png_ptr, buf, 13);
  194157. png_crc_finish(png_ptr, 0);
  194158. width = png_get_uint_31(png_ptr, buf);
  194159. height = png_get_uint_31(png_ptr, buf + 4);
  194160. bit_depth = buf[8];
  194161. color_type = buf[9];
  194162. compression_type = buf[10];
  194163. filter_type = buf[11];
  194164. interlace_type = buf[12];
  194165. /* set internal variables */
  194166. png_ptr->width = width;
  194167. png_ptr->height = height;
  194168. png_ptr->bit_depth = (png_byte)bit_depth;
  194169. png_ptr->interlaced = (png_byte)interlace_type;
  194170. png_ptr->color_type = (png_byte)color_type;
  194171. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194172. png_ptr->filter_type = (png_byte)filter_type;
  194173. #endif
  194174. png_ptr->compression_type = (png_byte)compression_type;
  194175. /* find number of channels */
  194176. switch (png_ptr->color_type)
  194177. {
  194178. case PNG_COLOR_TYPE_GRAY:
  194179. case PNG_COLOR_TYPE_PALETTE:
  194180. png_ptr->channels = 1;
  194181. break;
  194182. case PNG_COLOR_TYPE_RGB:
  194183. png_ptr->channels = 3;
  194184. break;
  194185. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194186. png_ptr->channels = 2;
  194187. break;
  194188. case PNG_COLOR_TYPE_RGB_ALPHA:
  194189. png_ptr->channels = 4;
  194190. break;
  194191. }
  194192. /* set up other useful info */
  194193. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194194. png_ptr->channels);
  194195. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194196. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194197. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194198. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194199. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194200. color_type, interlace_type, compression_type, filter_type);
  194201. }
  194202. /* read and check the palette */
  194203. void /* PRIVATE */
  194204. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194205. {
  194206. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194207. int num, i;
  194208. #ifndef PNG_NO_POINTER_INDEXING
  194209. png_colorp pal_ptr;
  194210. #endif
  194211. png_debug(1, "in png_handle_PLTE\n");
  194212. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194213. png_error(png_ptr, "Missing IHDR before PLTE");
  194214. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194215. {
  194216. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194217. png_crc_finish(png_ptr, length);
  194218. return;
  194219. }
  194220. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194221. png_error(png_ptr, "Duplicate PLTE chunk");
  194222. png_ptr->mode |= PNG_HAVE_PLTE;
  194223. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194224. {
  194225. png_warning(png_ptr,
  194226. "Ignoring PLTE chunk in grayscale PNG");
  194227. png_crc_finish(png_ptr, length);
  194228. return;
  194229. }
  194230. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194231. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194232. {
  194233. png_crc_finish(png_ptr, length);
  194234. return;
  194235. }
  194236. #endif
  194237. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194238. {
  194239. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194240. {
  194241. png_warning(png_ptr, "Invalid palette chunk");
  194242. png_crc_finish(png_ptr, length);
  194243. return;
  194244. }
  194245. else
  194246. {
  194247. png_error(png_ptr, "Invalid palette chunk");
  194248. }
  194249. }
  194250. num = (int)length / 3;
  194251. #ifndef PNG_NO_POINTER_INDEXING
  194252. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194253. {
  194254. png_byte buf[3];
  194255. png_crc_read(png_ptr, buf, 3);
  194256. pal_ptr->red = buf[0];
  194257. pal_ptr->green = buf[1];
  194258. pal_ptr->blue = buf[2];
  194259. }
  194260. #else
  194261. for (i = 0; i < num; i++)
  194262. {
  194263. png_byte buf[3];
  194264. png_crc_read(png_ptr, buf, 3);
  194265. /* don't depend upon png_color being any order */
  194266. palette[i].red = buf[0];
  194267. palette[i].green = buf[1];
  194268. palette[i].blue = buf[2];
  194269. }
  194270. #endif
  194271. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194272. whatever the normal CRC configuration tells us. However, if we
  194273. have an RGB image, the PLTE can be considered ancillary, so
  194274. we will act as though it is. */
  194275. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194276. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194277. #endif
  194278. {
  194279. png_crc_finish(png_ptr, 0);
  194280. }
  194281. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194282. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194283. {
  194284. /* If we don't want to use the data from an ancillary chunk,
  194285. we have two options: an error abort, or a warning and we
  194286. ignore the data in this chunk (which should be OK, since
  194287. it's considered ancillary for a RGB or RGBA image). */
  194288. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194289. {
  194290. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194291. {
  194292. png_chunk_error(png_ptr, "CRC error");
  194293. }
  194294. else
  194295. {
  194296. png_chunk_warning(png_ptr, "CRC error");
  194297. return;
  194298. }
  194299. }
  194300. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194301. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194302. {
  194303. png_chunk_warning(png_ptr, "CRC error");
  194304. }
  194305. }
  194306. #endif
  194307. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194308. #if defined(PNG_READ_tRNS_SUPPORTED)
  194309. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194310. {
  194311. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194312. {
  194313. if (png_ptr->num_trans > (png_uint_16)num)
  194314. {
  194315. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194316. png_ptr->num_trans = (png_uint_16)num;
  194317. }
  194318. if (info_ptr->num_trans > (png_uint_16)num)
  194319. {
  194320. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194321. info_ptr->num_trans = (png_uint_16)num;
  194322. }
  194323. }
  194324. }
  194325. #endif
  194326. }
  194327. void /* PRIVATE */
  194328. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194329. {
  194330. png_debug(1, "in png_handle_IEND\n");
  194331. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194332. {
  194333. png_error(png_ptr, "No image in file");
  194334. }
  194335. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194336. if (length != 0)
  194337. {
  194338. png_warning(png_ptr, "Incorrect IEND chunk length");
  194339. }
  194340. png_crc_finish(png_ptr, length);
  194341. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194342. }
  194343. #if defined(PNG_READ_gAMA_SUPPORTED)
  194344. void /* PRIVATE */
  194345. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194346. {
  194347. png_fixed_point igamma;
  194348. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194349. float file_gamma;
  194350. #endif
  194351. png_byte buf[4];
  194352. png_debug(1, "in png_handle_gAMA\n");
  194353. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194354. png_error(png_ptr, "Missing IHDR before gAMA");
  194355. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194356. {
  194357. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194358. png_crc_finish(png_ptr, length);
  194359. return;
  194360. }
  194361. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194362. /* Should be an error, but we can cope with it */
  194363. png_warning(png_ptr, "Out of place gAMA chunk");
  194364. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194365. #if defined(PNG_READ_sRGB_SUPPORTED)
  194366. && !(info_ptr->valid & PNG_INFO_sRGB)
  194367. #endif
  194368. )
  194369. {
  194370. png_warning(png_ptr, "Duplicate gAMA chunk");
  194371. png_crc_finish(png_ptr, length);
  194372. return;
  194373. }
  194374. if (length != 4)
  194375. {
  194376. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194377. png_crc_finish(png_ptr, length);
  194378. return;
  194379. }
  194380. png_crc_read(png_ptr, buf, 4);
  194381. if (png_crc_finish(png_ptr, 0))
  194382. return;
  194383. igamma = (png_fixed_point)png_get_uint_32(buf);
  194384. /* check for zero gamma */
  194385. if (igamma == 0)
  194386. {
  194387. png_warning(png_ptr,
  194388. "Ignoring gAMA chunk with gamma=0");
  194389. return;
  194390. }
  194391. #if defined(PNG_READ_sRGB_SUPPORTED)
  194392. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194393. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194394. {
  194395. png_warning(png_ptr,
  194396. "Ignoring incorrect gAMA value when sRGB is also present");
  194397. #ifndef PNG_NO_CONSOLE_IO
  194398. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194399. #endif
  194400. return;
  194401. }
  194402. #endif /* PNG_READ_sRGB_SUPPORTED */
  194403. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194404. file_gamma = (float)igamma / (float)100000.0;
  194405. # ifdef PNG_READ_GAMMA_SUPPORTED
  194406. png_ptr->gamma = file_gamma;
  194407. # endif
  194408. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194409. #endif
  194410. #ifdef PNG_FIXED_POINT_SUPPORTED
  194411. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194412. #endif
  194413. }
  194414. #endif
  194415. #if defined(PNG_READ_sBIT_SUPPORTED)
  194416. void /* PRIVATE */
  194417. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194418. {
  194419. png_size_t truelen;
  194420. png_byte buf[4];
  194421. png_debug(1, "in png_handle_sBIT\n");
  194422. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194423. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194424. png_error(png_ptr, "Missing IHDR before sBIT");
  194425. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194426. {
  194427. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194428. png_crc_finish(png_ptr, length);
  194429. return;
  194430. }
  194431. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194432. {
  194433. /* Should be an error, but we can cope with it */
  194434. png_warning(png_ptr, "Out of place sBIT chunk");
  194435. }
  194436. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194437. {
  194438. png_warning(png_ptr, "Duplicate sBIT chunk");
  194439. png_crc_finish(png_ptr, length);
  194440. return;
  194441. }
  194442. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194443. truelen = 3;
  194444. else
  194445. truelen = (png_size_t)png_ptr->channels;
  194446. if (length != truelen || length > 4)
  194447. {
  194448. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194449. png_crc_finish(png_ptr, length);
  194450. return;
  194451. }
  194452. png_crc_read(png_ptr, buf, truelen);
  194453. if (png_crc_finish(png_ptr, 0))
  194454. return;
  194455. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194456. {
  194457. png_ptr->sig_bit.red = buf[0];
  194458. png_ptr->sig_bit.green = buf[1];
  194459. png_ptr->sig_bit.blue = buf[2];
  194460. png_ptr->sig_bit.alpha = buf[3];
  194461. }
  194462. else
  194463. {
  194464. png_ptr->sig_bit.gray = buf[0];
  194465. png_ptr->sig_bit.red = buf[0];
  194466. png_ptr->sig_bit.green = buf[0];
  194467. png_ptr->sig_bit.blue = buf[0];
  194468. png_ptr->sig_bit.alpha = buf[1];
  194469. }
  194470. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194471. }
  194472. #endif
  194473. #if defined(PNG_READ_cHRM_SUPPORTED)
  194474. void /* PRIVATE */
  194475. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194476. {
  194477. png_byte buf[4];
  194478. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194479. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194480. #endif
  194481. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194482. int_y_green, int_x_blue, int_y_blue;
  194483. png_uint_32 uint_x, uint_y;
  194484. png_debug(1, "in png_handle_cHRM\n");
  194485. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194486. png_error(png_ptr, "Missing IHDR before cHRM");
  194487. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194488. {
  194489. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194490. png_crc_finish(png_ptr, length);
  194491. return;
  194492. }
  194493. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194494. /* Should be an error, but we can cope with it */
  194495. png_warning(png_ptr, "Missing PLTE before cHRM");
  194496. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194497. #if defined(PNG_READ_sRGB_SUPPORTED)
  194498. && !(info_ptr->valid & PNG_INFO_sRGB)
  194499. #endif
  194500. )
  194501. {
  194502. png_warning(png_ptr, "Duplicate cHRM chunk");
  194503. png_crc_finish(png_ptr, length);
  194504. return;
  194505. }
  194506. if (length != 32)
  194507. {
  194508. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194509. png_crc_finish(png_ptr, length);
  194510. return;
  194511. }
  194512. png_crc_read(png_ptr, buf, 4);
  194513. uint_x = png_get_uint_32(buf);
  194514. png_crc_read(png_ptr, buf, 4);
  194515. uint_y = png_get_uint_32(buf);
  194516. if (uint_x > 80000L || uint_y > 80000L ||
  194517. uint_x + uint_y > 100000L)
  194518. {
  194519. png_warning(png_ptr, "Invalid cHRM white point");
  194520. png_crc_finish(png_ptr, 24);
  194521. return;
  194522. }
  194523. int_x_white = (png_fixed_point)uint_x;
  194524. int_y_white = (png_fixed_point)uint_y;
  194525. png_crc_read(png_ptr, buf, 4);
  194526. uint_x = png_get_uint_32(buf);
  194527. png_crc_read(png_ptr, buf, 4);
  194528. uint_y = png_get_uint_32(buf);
  194529. if (uint_x + uint_y > 100000L)
  194530. {
  194531. png_warning(png_ptr, "Invalid cHRM red point");
  194532. png_crc_finish(png_ptr, 16);
  194533. return;
  194534. }
  194535. int_x_red = (png_fixed_point)uint_x;
  194536. int_y_red = (png_fixed_point)uint_y;
  194537. png_crc_read(png_ptr, buf, 4);
  194538. uint_x = png_get_uint_32(buf);
  194539. png_crc_read(png_ptr, buf, 4);
  194540. uint_y = png_get_uint_32(buf);
  194541. if (uint_x + uint_y > 100000L)
  194542. {
  194543. png_warning(png_ptr, "Invalid cHRM green point");
  194544. png_crc_finish(png_ptr, 8);
  194545. return;
  194546. }
  194547. int_x_green = (png_fixed_point)uint_x;
  194548. int_y_green = (png_fixed_point)uint_y;
  194549. png_crc_read(png_ptr, buf, 4);
  194550. uint_x = png_get_uint_32(buf);
  194551. png_crc_read(png_ptr, buf, 4);
  194552. uint_y = png_get_uint_32(buf);
  194553. if (uint_x + uint_y > 100000L)
  194554. {
  194555. png_warning(png_ptr, "Invalid cHRM blue point");
  194556. png_crc_finish(png_ptr, 0);
  194557. return;
  194558. }
  194559. int_x_blue = (png_fixed_point)uint_x;
  194560. int_y_blue = (png_fixed_point)uint_y;
  194561. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194562. white_x = (float)int_x_white / (float)100000.0;
  194563. white_y = (float)int_y_white / (float)100000.0;
  194564. red_x = (float)int_x_red / (float)100000.0;
  194565. red_y = (float)int_y_red / (float)100000.0;
  194566. green_x = (float)int_x_green / (float)100000.0;
  194567. green_y = (float)int_y_green / (float)100000.0;
  194568. blue_x = (float)int_x_blue / (float)100000.0;
  194569. blue_y = (float)int_y_blue / (float)100000.0;
  194570. #endif
  194571. #if defined(PNG_READ_sRGB_SUPPORTED)
  194572. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194573. {
  194574. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194575. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194576. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194577. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194578. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194579. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194580. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194581. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194582. {
  194583. png_warning(png_ptr,
  194584. "Ignoring incorrect cHRM value when sRGB is also present");
  194585. #ifndef PNG_NO_CONSOLE_IO
  194586. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194587. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194588. white_x, white_y, red_x, red_y);
  194589. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194590. green_x, green_y, blue_x, blue_y);
  194591. #else
  194592. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194593. int_x_white, int_y_white, int_x_red, int_y_red);
  194594. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194595. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194596. #endif
  194597. #endif /* PNG_NO_CONSOLE_IO */
  194598. }
  194599. png_crc_finish(png_ptr, 0);
  194600. return;
  194601. }
  194602. #endif /* PNG_READ_sRGB_SUPPORTED */
  194603. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194604. png_set_cHRM(png_ptr, info_ptr,
  194605. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194606. #endif
  194607. #ifdef PNG_FIXED_POINT_SUPPORTED
  194608. png_set_cHRM_fixed(png_ptr, info_ptr,
  194609. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194610. int_y_green, int_x_blue, int_y_blue);
  194611. #endif
  194612. if (png_crc_finish(png_ptr, 0))
  194613. return;
  194614. }
  194615. #endif
  194616. #if defined(PNG_READ_sRGB_SUPPORTED)
  194617. void /* PRIVATE */
  194618. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194619. {
  194620. int intent;
  194621. png_byte buf[1];
  194622. png_debug(1, "in png_handle_sRGB\n");
  194623. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194624. png_error(png_ptr, "Missing IHDR before sRGB");
  194625. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194626. {
  194627. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194628. png_crc_finish(png_ptr, length);
  194629. return;
  194630. }
  194631. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194632. /* Should be an error, but we can cope with it */
  194633. png_warning(png_ptr, "Out of place sRGB chunk");
  194634. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194635. {
  194636. png_warning(png_ptr, "Duplicate sRGB chunk");
  194637. png_crc_finish(png_ptr, length);
  194638. return;
  194639. }
  194640. if (length != 1)
  194641. {
  194642. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194643. png_crc_finish(png_ptr, length);
  194644. return;
  194645. }
  194646. png_crc_read(png_ptr, buf, 1);
  194647. if (png_crc_finish(png_ptr, 0))
  194648. return;
  194649. intent = buf[0];
  194650. /* check for bad intent */
  194651. if (intent >= PNG_sRGB_INTENT_LAST)
  194652. {
  194653. png_warning(png_ptr, "Unknown sRGB intent");
  194654. return;
  194655. }
  194656. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194657. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194658. {
  194659. png_fixed_point igamma;
  194660. #ifdef PNG_FIXED_POINT_SUPPORTED
  194661. igamma=info_ptr->int_gamma;
  194662. #else
  194663. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194664. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194665. # endif
  194666. #endif
  194667. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194668. {
  194669. png_warning(png_ptr,
  194670. "Ignoring incorrect gAMA value when sRGB is also present");
  194671. #ifndef PNG_NO_CONSOLE_IO
  194672. # ifdef PNG_FIXED_POINT_SUPPORTED
  194673. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194674. # else
  194675. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194676. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194677. # endif
  194678. # endif
  194679. #endif
  194680. }
  194681. }
  194682. #endif /* PNG_READ_gAMA_SUPPORTED */
  194683. #ifdef PNG_READ_cHRM_SUPPORTED
  194684. #ifdef PNG_FIXED_POINT_SUPPORTED
  194685. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194686. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194687. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194688. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194689. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194690. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194691. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194692. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194693. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194694. {
  194695. png_warning(png_ptr,
  194696. "Ignoring incorrect cHRM value when sRGB is also present");
  194697. }
  194698. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194699. #endif /* PNG_READ_cHRM_SUPPORTED */
  194700. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194701. }
  194702. #endif /* PNG_READ_sRGB_SUPPORTED */
  194703. #if defined(PNG_READ_iCCP_SUPPORTED)
  194704. void /* PRIVATE */
  194705. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194706. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194707. {
  194708. png_charp chunkdata;
  194709. png_byte compression_type;
  194710. png_bytep pC;
  194711. png_charp profile;
  194712. png_uint_32 skip = 0;
  194713. png_uint_32 profile_size, profile_length;
  194714. png_size_t slength, prefix_length, data_length;
  194715. png_debug(1, "in png_handle_iCCP\n");
  194716. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194717. png_error(png_ptr, "Missing IHDR before iCCP");
  194718. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194719. {
  194720. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194721. png_crc_finish(png_ptr, length);
  194722. return;
  194723. }
  194724. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194725. /* Should be an error, but we can cope with it */
  194726. png_warning(png_ptr, "Out of place iCCP chunk");
  194727. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194728. {
  194729. png_warning(png_ptr, "Duplicate iCCP chunk");
  194730. png_crc_finish(png_ptr, length);
  194731. return;
  194732. }
  194733. #ifdef PNG_MAX_MALLOC_64K
  194734. if (length > (png_uint_32)65535L)
  194735. {
  194736. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194737. skip = length - (png_uint_32)65535L;
  194738. length = (png_uint_32)65535L;
  194739. }
  194740. #endif
  194741. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194742. slength = (png_size_t)length;
  194743. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194744. if (png_crc_finish(png_ptr, skip))
  194745. {
  194746. png_free(png_ptr, chunkdata);
  194747. return;
  194748. }
  194749. chunkdata[slength] = 0x00;
  194750. for (profile = chunkdata; *profile; profile++)
  194751. /* empty loop to find end of name */ ;
  194752. ++profile;
  194753. /* there should be at least one zero (the compression type byte)
  194754. following the separator, and we should be on it */
  194755. if ( profile >= chunkdata + slength - 1)
  194756. {
  194757. png_free(png_ptr, chunkdata);
  194758. png_warning(png_ptr, "Malformed iCCP chunk");
  194759. return;
  194760. }
  194761. /* compression_type should always be zero */
  194762. compression_type = *profile++;
  194763. if (compression_type)
  194764. {
  194765. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194766. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194767. wrote nonzero) */
  194768. }
  194769. prefix_length = profile - chunkdata;
  194770. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194771. slength, prefix_length, &data_length);
  194772. profile_length = data_length - prefix_length;
  194773. if ( prefix_length > data_length || profile_length < 4)
  194774. {
  194775. png_free(png_ptr, chunkdata);
  194776. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194777. return;
  194778. }
  194779. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194780. pC = (png_bytep)(chunkdata+prefix_length);
  194781. profile_size = ((*(pC ))<<24) |
  194782. ((*(pC+1))<<16) |
  194783. ((*(pC+2))<< 8) |
  194784. ((*(pC+3)) );
  194785. if(profile_size < profile_length)
  194786. profile_length = profile_size;
  194787. if(profile_size > profile_length)
  194788. {
  194789. png_free(png_ptr, chunkdata);
  194790. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194791. return;
  194792. }
  194793. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194794. chunkdata + prefix_length, profile_length);
  194795. png_free(png_ptr, chunkdata);
  194796. }
  194797. #endif /* PNG_READ_iCCP_SUPPORTED */
  194798. #if defined(PNG_READ_sPLT_SUPPORTED)
  194799. void /* PRIVATE */
  194800. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194801. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194802. {
  194803. png_bytep chunkdata;
  194804. png_bytep entry_start;
  194805. png_sPLT_t new_palette;
  194806. #ifdef PNG_NO_POINTER_INDEXING
  194807. png_sPLT_entryp pp;
  194808. #endif
  194809. int data_length, entry_size, i;
  194810. png_uint_32 skip = 0;
  194811. png_size_t slength;
  194812. png_debug(1, "in png_handle_sPLT\n");
  194813. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194814. png_error(png_ptr, "Missing IHDR before sPLT");
  194815. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194816. {
  194817. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194818. png_crc_finish(png_ptr, length);
  194819. return;
  194820. }
  194821. #ifdef PNG_MAX_MALLOC_64K
  194822. if (length > (png_uint_32)65535L)
  194823. {
  194824. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194825. skip = length - (png_uint_32)65535L;
  194826. length = (png_uint_32)65535L;
  194827. }
  194828. #endif
  194829. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194830. slength = (png_size_t)length;
  194831. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194832. if (png_crc_finish(png_ptr, skip))
  194833. {
  194834. png_free(png_ptr, chunkdata);
  194835. return;
  194836. }
  194837. chunkdata[slength] = 0x00;
  194838. for (entry_start = chunkdata; *entry_start; entry_start++)
  194839. /* empty loop to find end of name */ ;
  194840. ++entry_start;
  194841. /* a sample depth should follow the separator, and we should be on it */
  194842. if (entry_start > chunkdata + slength - 2)
  194843. {
  194844. png_free(png_ptr, chunkdata);
  194845. png_warning(png_ptr, "malformed sPLT chunk");
  194846. return;
  194847. }
  194848. new_palette.depth = *entry_start++;
  194849. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194850. data_length = (slength - (entry_start - chunkdata));
  194851. /* integrity-check the data length */
  194852. if (data_length % entry_size)
  194853. {
  194854. png_free(png_ptr, chunkdata);
  194855. png_warning(png_ptr, "sPLT chunk has bad length");
  194856. return;
  194857. }
  194858. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194859. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194860. png_sizeof(png_sPLT_entry)))
  194861. {
  194862. png_warning(png_ptr, "sPLT chunk too long");
  194863. return;
  194864. }
  194865. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194866. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194867. if (new_palette.entries == NULL)
  194868. {
  194869. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194870. return;
  194871. }
  194872. #ifndef PNG_NO_POINTER_INDEXING
  194873. for (i = 0; i < new_palette.nentries; i++)
  194874. {
  194875. png_sPLT_entryp pp = new_palette.entries + i;
  194876. if (new_palette.depth == 8)
  194877. {
  194878. pp->red = *entry_start++;
  194879. pp->green = *entry_start++;
  194880. pp->blue = *entry_start++;
  194881. pp->alpha = *entry_start++;
  194882. }
  194883. else
  194884. {
  194885. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194886. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194887. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194888. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194889. }
  194890. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194891. }
  194892. #else
  194893. pp = new_palette.entries;
  194894. for (i = 0; i < new_palette.nentries; i++)
  194895. {
  194896. if (new_palette.depth == 8)
  194897. {
  194898. pp[i].red = *entry_start++;
  194899. pp[i].green = *entry_start++;
  194900. pp[i].blue = *entry_start++;
  194901. pp[i].alpha = *entry_start++;
  194902. }
  194903. else
  194904. {
  194905. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194906. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194907. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194908. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194909. }
  194910. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194911. }
  194912. #endif
  194913. /* discard all chunk data except the name and stash that */
  194914. new_palette.name = (png_charp)chunkdata;
  194915. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194916. png_free(png_ptr, chunkdata);
  194917. png_free(png_ptr, new_palette.entries);
  194918. }
  194919. #endif /* PNG_READ_sPLT_SUPPORTED */
  194920. #if defined(PNG_READ_tRNS_SUPPORTED)
  194921. void /* PRIVATE */
  194922. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194923. {
  194924. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194925. int bit_mask;
  194926. png_debug(1, "in png_handle_tRNS\n");
  194927. /* For non-indexed color, mask off any bits in the tRNS value that
  194928. * exceed the bit depth. Some creators were writing extra bits there.
  194929. * This is not needed for indexed color. */
  194930. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194931. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194932. png_error(png_ptr, "Missing IHDR before tRNS");
  194933. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194934. {
  194935. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194936. png_crc_finish(png_ptr, length);
  194937. return;
  194938. }
  194939. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194940. {
  194941. png_warning(png_ptr, "Duplicate tRNS chunk");
  194942. png_crc_finish(png_ptr, length);
  194943. return;
  194944. }
  194945. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194946. {
  194947. png_byte buf[2];
  194948. if (length != 2)
  194949. {
  194950. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194951. png_crc_finish(png_ptr, length);
  194952. return;
  194953. }
  194954. png_crc_read(png_ptr, buf, 2);
  194955. png_ptr->num_trans = 1;
  194956. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194957. }
  194958. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194959. {
  194960. png_byte buf[6];
  194961. if (length != 6)
  194962. {
  194963. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194964. png_crc_finish(png_ptr, length);
  194965. return;
  194966. }
  194967. png_crc_read(png_ptr, buf, (png_size_t)length);
  194968. png_ptr->num_trans = 1;
  194969. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194970. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194971. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194972. }
  194973. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194974. {
  194975. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194976. {
  194977. /* Should be an error, but we can cope with it. */
  194978. png_warning(png_ptr, "Missing PLTE before tRNS");
  194979. }
  194980. if (length > (png_uint_32)png_ptr->num_palette ||
  194981. length > PNG_MAX_PALETTE_LENGTH)
  194982. {
  194983. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194984. png_crc_finish(png_ptr, length);
  194985. return;
  194986. }
  194987. if (length == 0)
  194988. {
  194989. png_warning(png_ptr, "Zero length tRNS chunk");
  194990. png_crc_finish(png_ptr, length);
  194991. return;
  194992. }
  194993. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194994. png_ptr->num_trans = (png_uint_16)length;
  194995. }
  194996. else
  194997. {
  194998. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194999. png_crc_finish(png_ptr, length);
  195000. return;
  195001. }
  195002. if (png_crc_finish(png_ptr, 0))
  195003. {
  195004. png_ptr->num_trans = 0;
  195005. return;
  195006. }
  195007. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195008. &(png_ptr->trans_values));
  195009. }
  195010. #endif
  195011. #if defined(PNG_READ_bKGD_SUPPORTED)
  195012. void /* PRIVATE */
  195013. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195014. {
  195015. png_size_t truelen;
  195016. png_byte buf[6];
  195017. png_debug(1, "in png_handle_bKGD\n");
  195018. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195019. png_error(png_ptr, "Missing IHDR before bKGD");
  195020. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195021. {
  195022. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195023. png_crc_finish(png_ptr, length);
  195024. return;
  195025. }
  195026. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195027. !(png_ptr->mode & PNG_HAVE_PLTE))
  195028. {
  195029. png_warning(png_ptr, "Missing PLTE before bKGD");
  195030. png_crc_finish(png_ptr, length);
  195031. return;
  195032. }
  195033. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195034. {
  195035. png_warning(png_ptr, "Duplicate bKGD chunk");
  195036. png_crc_finish(png_ptr, length);
  195037. return;
  195038. }
  195039. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195040. truelen = 1;
  195041. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195042. truelen = 6;
  195043. else
  195044. truelen = 2;
  195045. if (length != truelen)
  195046. {
  195047. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195048. png_crc_finish(png_ptr, length);
  195049. return;
  195050. }
  195051. png_crc_read(png_ptr, buf, truelen);
  195052. if (png_crc_finish(png_ptr, 0))
  195053. return;
  195054. /* We convert the index value into RGB components so that we can allow
  195055. * arbitrary RGB values for background when we have transparency, and
  195056. * so it is easy to determine the RGB values of the background color
  195057. * from the info_ptr struct. */
  195058. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195059. {
  195060. png_ptr->background.index = buf[0];
  195061. if(info_ptr->num_palette)
  195062. {
  195063. if(buf[0] > info_ptr->num_palette)
  195064. {
  195065. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195066. return;
  195067. }
  195068. png_ptr->background.red =
  195069. (png_uint_16)png_ptr->palette[buf[0]].red;
  195070. png_ptr->background.green =
  195071. (png_uint_16)png_ptr->palette[buf[0]].green;
  195072. png_ptr->background.blue =
  195073. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195074. }
  195075. }
  195076. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195077. {
  195078. png_ptr->background.red =
  195079. png_ptr->background.green =
  195080. png_ptr->background.blue =
  195081. png_ptr->background.gray = png_get_uint_16(buf);
  195082. }
  195083. else
  195084. {
  195085. png_ptr->background.red = png_get_uint_16(buf);
  195086. png_ptr->background.green = png_get_uint_16(buf + 2);
  195087. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195088. }
  195089. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195090. }
  195091. #endif
  195092. #if defined(PNG_READ_hIST_SUPPORTED)
  195093. void /* PRIVATE */
  195094. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195095. {
  195096. unsigned int num, i;
  195097. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195098. png_debug(1, "in png_handle_hIST\n");
  195099. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195100. png_error(png_ptr, "Missing IHDR before hIST");
  195101. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195102. {
  195103. png_warning(png_ptr, "Invalid hIST after IDAT");
  195104. png_crc_finish(png_ptr, length);
  195105. return;
  195106. }
  195107. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195108. {
  195109. png_warning(png_ptr, "Missing PLTE before hIST");
  195110. png_crc_finish(png_ptr, length);
  195111. return;
  195112. }
  195113. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195114. {
  195115. png_warning(png_ptr, "Duplicate hIST chunk");
  195116. png_crc_finish(png_ptr, length);
  195117. return;
  195118. }
  195119. num = length / 2 ;
  195120. if (num != (unsigned int) png_ptr->num_palette || num >
  195121. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195122. {
  195123. png_warning(png_ptr, "Incorrect hIST chunk length");
  195124. png_crc_finish(png_ptr, length);
  195125. return;
  195126. }
  195127. for (i = 0; i < num; i++)
  195128. {
  195129. png_byte buf[2];
  195130. png_crc_read(png_ptr, buf, 2);
  195131. readbuf[i] = png_get_uint_16(buf);
  195132. }
  195133. if (png_crc_finish(png_ptr, 0))
  195134. return;
  195135. png_set_hIST(png_ptr, info_ptr, readbuf);
  195136. }
  195137. #endif
  195138. #if defined(PNG_READ_pHYs_SUPPORTED)
  195139. void /* PRIVATE */
  195140. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195141. {
  195142. png_byte buf[9];
  195143. png_uint_32 res_x, res_y;
  195144. int unit_type;
  195145. png_debug(1, "in png_handle_pHYs\n");
  195146. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195147. png_error(png_ptr, "Missing IHDR before pHYs");
  195148. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195149. {
  195150. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195151. png_crc_finish(png_ptr, length);
  195152. return;
  195153. }
  195154. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195155. {
  195156. png_warning(png_ptr, "Duplicate pHYs chunk");
  195157. png_crc_finish(png_ptr, length);
  195158. return;
  195159. }
  195160. if (length != 9)
  195161. {
  195162. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195163. png_crc_finish(png_ptr, length);
  195164. return;
  195165. }
  195166. png_crc_read(png_ptr, buf, 9);
  195167. if (png_crc_finish(png_ptr, 0))
  195168. return;
  195169. res_x = png_get_uint_32(buf);
  195170. res_y = png_get_uint_32(buf + 4);
  195171. unit_type = buf[8];
  195172. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195173. }
  195174. #endif
  195175. #if defined(PNG_READ_oFFs_SUPPORTED)
  195176. void /* PRIVATE */
  195177. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195178. {
  195179. png_byte buf[9];
  195180. png_int_32 offset_x, offset_y;
  195181. int unit_type;
  195182. png_debug(1, "in png_handle_oFFs\n");
  195183. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195184. png_error(png_ptr, "Missing IHDR before oFFs");
  195185. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195186. {
  195187. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195188. png_crc_finish(png_ptr, length);
  195189. return;
  195190. }
  195191. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195192. {
  195193. png_warning(png_ptr, "Duplicate oFFs chunk");
  195194. png_crc_finish(png_ptr, length);
  195195. return;
  195196. }
  195197. if (length != 9)
  195198. {
  195199. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195200. png_crc_finish(png_ptr, length);
  195201. return;
  195202. }
  195203. png_crc_read(png_ptr, buf, 9);
  195204. if (png_crc_finish(png_ptr, 0))
  195205. return;
  195206. offset_x = png_get_int_32(buf);
  195207. offset_y = png_get_int_32(buf + 4);
  195208. unit_type = buf[8];
  195209. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195210. }
  195211. #endif
  195212. #if defined(PNG_READ_pCAL_SUPPORTED)
  195213. /* read the pCAL chunk (described in the PNG Extensions document) */
  195214. void /* PRIVATE */
  195215. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195216. {
  195217. png_charp purpose;
  195218. png_int_32 X0, X1;
  195219. png_byte type, nparams;
  195220. png_charp buf, units, endptr;
  195221. png_charpp params;
  195222. png_size_t slength;
  195223. int i;
  195224. png_debug(1, "in png_handle_pCAL\n");
  195225. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195226. png_error(png_ptr, "Missing IHDR before pCAL");
  195227. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195228. {
  195229. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195230. png_crc_finish(png_ptr, length);
  195231. return;
  195232. }
  195233. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195234. {
  195235. png_warning(png_ptr, "Duplicate pCAL chunk");
  195236. png_crc_finish(png_ptr, length);
  195237. return;
  195238. }
  195239. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195240. length + 1);
  195241. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195242. if (purpose == NULL)
  195243. {
  195244. png_warning(png_ptr, "No memory for pCAL purpose.");
  195245. return;
  195246. }
  195247. slength = (png_size_t)length;
  195248. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195249. if (png_crc_finish(png_ptr, 0))
  195250. {
  195251. png_free(png_ptr, purpose);
  195252. return;
  195253. }
  195254. purpose[slength] = 0x00; /* null terminate the last string */
  195255. png_debug(3, "Finding end of pCAL purpose string\n");
  195256. for (buf = purpose; *buf; buf++)
  195257. /* empty loop */ ;
  195258. endptr = purpose + slength;
  195259. /* We need to have at least 12 bytes after the purpose string
  195260. in order to get the parameter information. */
  195261. if (endptr <= buf + 12)
  195262. {
  195263. png_warning(png_ptr, "Invalid pCAL data");
  195264. png_free(png_ptr, purpose);
  195265. return;
  195266. }
  195267. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195268. X0 = png_get_int_32((png_bytep)buf+1);
  195269. X1 = png_get_int_32((png_bytep)buf+5);
  195270. type = buf[9];
  195271. nparams = buf[10];
  195272. units = buf + 11;
  195273. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195274. /* Check that we have the right number of parameters for known
  195275. equation types. */
  195276. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195277. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195278. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195279. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195280. {
  195281. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195282. png_free(png_ptr, purpose);
  195283. return;
  195284. }
  195285. else if (type >= PNG_EQUATION_LAST)
  195286. {
  195287. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195288. }
  195289. for (buf = units; *buf; buf++)
  195290. /* Empty loop to move past the units string. */ ;
  195291. png_debug(3, "Allocating pCAL parameters array\n");
  195292. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195293. *png_sizeof(png_charp))) ;
  195294. if (params == NULL)
  195295. {
  195296. png_free(png_ptr, purpose);
  195297. png_warning(png_ptr, "No memory for pCAL params.");
  195298. return;
  195299. }
  195300. /* Get pointers to the start of each parameter string. */
  195301. for (i = 0; i < (int)nparams; i++)
  195302. {
  195303. buf++; /* Skip the null string terminator from previous parameter. */
  195304. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195305. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195306. /* Empty loop to move past each parameter string */ ;
  195307. /* Make sure we haven't run out of data yet */
  195308. if (buf > endptr)
  195309. {
  195310. png_warning(png_ptr, "Invalid pCAL data");
  195311. png_free(png_ptr, purpose);
  195312. png_free(png_ptr, params);
  195313. return;
  195314. }
  195315. }
  195316. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195317. units, params);
  195318. png_free(png_ptr, purpose);
  195319. png_free(png_ptr, params);
  195320. }
  195321. #endif
  195322. #if defined(PNG_READ_sCAL_SUPPORTED)
  195323. /* read the sCAL chunk */
  195324. void /* PRIVATE */
  195325. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195326. {
  195327. png_charp buffer, ep;
  195328. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195329. double width, height;
  195330. png_charp vp;
  195331. #else
  195332. #ifdef PNG_FIXED_POINT_SUPPORTED
  195333. png_charp swidth, sheight;
  195334. #endif
  195335. #endif
  195336. png_size_t slength;
  195337. png_debug(1, "in png_handle_sCAL\n");
  195338. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195339. png_error(png_ptr, "Missing IHDR before sCAL");
  195340. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195341. {
  195342. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195343. png_crc_finish(png_ptr, length);
  195344. return;
  195345. }
  195346. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195347. {
  195348. png_warning(png_ptr, "Duplicate sCAL chunk");
  195349. png_crc_finish(png_ptr, length);
  195350. return;
  195351. }
  195352. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195353. length + 1);
  195354. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195355. if (buffer == NULL)
  195356. {
  195357. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195358. return;
  195359. }
  195360. slength = (png_size_t)length;
  195361. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195362. if (png_crc_finish(png_ptr, 0))
  195363. {
  195364. png_free(png_ptr, buffer);
  195365. return;
  195366. }
  195367. buffer[slength] = 0x00; /* null terminate the last string */
  195368. ep = buffer + 1; /* skip unit byte */
  195369. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195370. width = png_strtod(png_ptr, ep, &vp);
  195371. if (*vp)
  195372. {
  195373. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195374. return;
  195375. }
  195376. #else
  195377. #ifdef PNG_FIXED_POINT_SUPPORTED
  195378. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195379. if (swidth == NULL)
  195380. {
  195381. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195382. return;
  195383. }
  195384. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195385. #endif
  195386. #endif
  195387. for (ep = buffer; *ep; ep++)
  195388. /* empty loop */ ;
  195389. ep++;
  195390. if (buffer + slength < ep)
  195391. {
  195392. png_warning(png_ptr, "Truncated sCAL chunk");
  195393. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195394. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195395. png_free(png_ptr, swidth);
  195396. #endif
  195397. png_free(png_ptr, buffer);
  195398. return;
  195399. }
  195400. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195401. height = png_strtod(png_ptr, ep, &vp);
  195402. if (*vp)
  195403. {
  195404. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195405. return;
  195406. }
  195407. #else
  195408. #ifdef PNG_FIXED_POINT_SUPPORTED
  195409. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195410. if (swidth == NULL)
  195411. {
  195412. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195413. return;
  195414. }
  195415. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195416. #endif
  195417. #endif
  195418. if (buffer + slength < ep
  195419. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195420. || width <= 0. || height <= 0.
  195421. #endif
  195422. )
  195423. {
  195424. png_warning(png_ptr, "Invalid sCAL data");
  195425. png_free(png_ptr, buffer);
  195426. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195427. png_free(png_ptr, swidth);
  195428. png_free(png_ptr, sheight);
  195429. #endif
  195430. return;
  195431. }
  195432. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195433. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195434. #else
  195435. #ifdef PNG_FIXED_POINT_SUPPORTED
  195436. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195437. #endif
  195438. #endif
  195439. png_free(png_ptr, buffer);
  195440. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195441. png_free(png_ptr, swidth);
  195442. png_free(png_ptr, sheight);
  195443. #endif
  195444. }
  195445. #endif
  195446. #if defined(PNG_READ_tIME_SUPPORTED)
  195447. void /* PRIVATE */
  195448. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195449. {
  195450. png_byte buf[7];
  195451. png_time mod_time;
  195452. png_debug(1, "in png_handle_tIME\n");
  195453. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195454. png_error(png_ptr, "Out of place tIME chunk");
  195455. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195456. {
  195457. png_warning(png_ptr, "Duplicate tIME chunk");
  195458. png_crc_finish(png_ptr, length);
  195459. return;
  195460. }
  195461. if (png_ptr->mode & PNG_HAVE_IDAT)
  195462. png_ptr->mode |= PNG_AFTER_IDAT;
  195463. if (length != 7)
  195464. {
  195465. png_warning(png_ptr, "Incorrect tIME chunk length");
  195466. png_crc_finish(png_ptr, length);
  195467. return;
  195468. }
  195469. png_crc_read(png_ptr, buf, 7);
  195470. if (png_crc_finish(png_ptr, 0))
  195471. return;
  195472. mod_time.second = buf[6];
  195473. mod_time.minute = buf[5];
  195474. mod_time.hour = buf[4];
  195475. mod_time.day = buf[3];
  195476. mod_time.month = buf[2];
  195477. mod_time.year = png_get_uint_16(buf);
  195478. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195479. }
  195480. #endif
  195481. #if defined(PNG_READ_tEXt_SUPPORTED)
  195482. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195483. void /* PRIVATE */
  195484. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195485. {
  195486. png_textp text_ptr;
  195487. png_charp key;
  195488. png_charp text;
  195489. png_uint_32 skip = 0;
  195490. png_size_t slength;
  195491. int ret;
  195492. png_debug(1, "in png_handle_tEXt\n");
  195493. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195494. png_error(png_ptr, "Missing IHDR before tEXt");
  195495. if (png_ptr->mode & PNG_HAVE_IDAT)
  195496. png_ptr->mode |= PNG_AFTER_IDAT;
  195497. #ifdef PNG_MAX_MALLOC_64K
  195498. if (length > (png_uint_32)65535L)
  195499. {
  195500. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195501. skip = length - (png_uint_32)65535L;
  195502. length = (png_uint_32)65535L;
  195503. }
  195504. #endif
  195505. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195506. if (key == NULL)
  195507. {
  195508. png_warning(png_ptr, "No memory to process text chunk.");
  195509. return;
  195510. }
  195511. slength = (png_size_t)length;
  195512. png_crc_read(png_ptr, (png_bytep)key, slength);
  195513. if (png_crc_finish(png_ptr, skip))
  195514. {
  195515. png_free(png_ptr, key);
  195516. return;
  195517. }
  195518. key[slength] = 0x00;
  195519. for (text = key; *text; text++)
  195520. /* empty loop to find end of key */ ;
  195521. if (text != key + slength)
  195522. text++;
  195523. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195524. (png_uint_32)png_sizeof(png_text));
  195525. if (text_ptr == NULL)
  195526. {
  195527. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195528. png_free(png_ptr, key);
  195529. return;
  195530. }
  195531. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195532. text_ptr->key = key;
  195533. #ifdef PNG_iTXt_SUPPORTED
  195534. text_ptr->lang = NULL;
  195535. text_ptr->lang_key = NULL;
  195536. text_ptr->itxt_length = 0;
  195537. #endif
  195538. text_ptr->text = text;
  195539. text_ptr->text_length = png_strlen(text);
  195540. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195541. png_free(png_ptr, key);
  195542. png_free(png_ptr, text_ptr);
  195543. if (ret)
  195544. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195545. }
  195546. #endif
  195547. #if defined(PNG_READ_zTXt_SUPPORTED)
  195548. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195549. void /* PRIVATE */
  195550. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195551. {
  195552. png_textp text_ptr;
  195553. png_charp chunkdata;
  195554. png_charp text;
  195555. int comp_type;
  195556. int ret;
  195557. png_size_t slength, prefix_len, data_len;
  195558. png_debug(1, "in png_handle_zTXt\n");
  195559. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195560. png_error(png_ptr, "Missing IHDR before zTXt");
  195561. if (png_ptr->mode & PNG_HAVE_IDAT)
  195562. png_ptr->mode |= PNG_AFTER_IDAT;
  195563. #ifdef PNG_MAX_MALLOC_64K
  195564. /* We will no doubt have problems with chunks even half this size, but
  195565. there is no hard and fast rule to tell us where to stop. */
  195566. if (length > (png_uint_32)65535L)
  195567. {
  195568. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195569. png_crc_finish(png_ptr, length);
  195570. return;
  195571. }
  195572. #endif
  195573. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195574. if (chunkdata == NULL)
  195575. {
  195576. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195577. return;
  195578. }
  195579. slength = (png_size_t)length;
  195580. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195581. if (png_crc_finish(png_ptr, 0))
  195582. {
  195583. png_free(png_ptr, chunkdata);
  195584. return;
  195585. }
  195586. chunkdata[slength] = 0x00;
  195587. for (text = chunkdata; *text; text++)
  195588. /* empty loop */ ;
  195589. /* zTXt must have some text after the chunkdataword */
  195590. if (text >= chunkdata + slength - 2)
  195591. {
  195592. png_warning(png_ptr, "Truncated zTXt chunk");
  195593. png_free(png_ptr, chunkdata);
  195594. return;
  195595. }
  195596. else
  195597. {
  195598. comp_type = *(++text);
  195599. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195600. {
  195601. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195602. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195603. }
  195604. text++; /* skip the compression_method byte */
  195605. }
  195606. prefix_len = text - chunkdata;
  195607. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195608. (png_size_t)length, prefix_len, &data_len);
  195609. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195610. (png_uint_32)png_sizeof(png_text));
  195611. if (text_ptr == NULL)
  195612. {
  195613. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195614. png_free(png_ptr, chunkdata);
  195615. return;
  195616. }
  195617. text_ptr->compression = comp_type;
  195618. text_ptr->key = chunkdata;
  195619. #ifdef PNG_iTXt_SUPPORTED
  195620. text_ptr->lang = NULL;
  195621. text_ptr->lang_key = NULL;
  195622. text_ptr->itxt_length = 0;
  195623. #endif
  195624. text_ptr->text = chunkdata + prefix_len;
  195625. text_ptr->text_length = data_len;
  195626. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195627. png_free(png_ptr, text_ptr);
  195628. png_free(png_ptr, chunkdata);
  195629. if (ret)
  195630. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195631. }
  195632. #endif
  195633. #if defined(PNG_READ_iTXt_SUPPORTED)
  195634. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195635. void /* PRIVATE */
  195636. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195637. {
  195638. png_textp text_ptr;
  195639. png_charp chunkdata;
  195640. png_charp key, lang, text, lang_key;
  195641. int comp_flag;
  195642. int comp_type = 0;
  195643. int ret;
  195644. png_size_t slength, prefix_len, data_len;
  195645. png_debug(1, "in png_handle_iTXt\n");
  195646. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195647. png_error(png_ptr, "Missing IHDR before iTXt");
  195648. if (png_ptr->mode & PNG_HAVE_IDAT)
  195649. png_ptr->mode |= PNG_AFTER_IDAT;
  195650. #ifdef PNG_MAX_MALLOC_64K
  195651. /* We will no doubt have problems with chunks even half this size, but
  195652. there is no hard and fast rule to tell us where to stop. */
  195653. if (length > (png_uint_32)65535L)
  195654. {
  195655. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195656. png_crc_finish(png_ptr, length);
  195657. return;
  195658. }
  195659. #endif
  195660. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195661. if (chunkdata == NULL)
  195662. {
  195663. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195664. return;
  195665. }
  195666. slength = (png_size_t)length;
  195667. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195668. if (png_crc_finish(png_ptr, 0))
  195669. {
  195670. png_free(png_ptr, chunkdata);
  195671. return;
  195672. }
  195673. chunkdata[slength] = 0x00;
  195674. for (lang = chunkdata; *lang; lang++)
  195675. /* empty loop */ ;
  195676. lang++; /* skip NUL separator */
  195677. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195678. translated keyword (possibly empty), and possibly some text after the
  195679. keyword */
  195680. if (lang >= chunkdata + slength - 3)
  195681. {
  195682. png_warning(png_ptr, "Truncated iTXt chunk");
  195683. png_free(png_ptr, chunkdata);
  195684. return;
  195685. }
  195686. else
  195687. {
  195688. comp_flag = *lang++;
  195689. comp_type = *lang++;
  195690. }
  195691. for (lang_key = lang; *lang_key; lang_key++)
  195692. /* empty loop */ ;
  195693. lang_key++; /* skip NUL separator */
  195694. if (lang_key >= chunkdata + slength)
  195695. {
  195696. png_warning(png_ptr, "Truncated iTXt chunk");
  195697. png_free(png_ptr, chunkdata);
  195698. return;
  195699. }
  195700. for (text = lang_key; *text; text++)
  195701. /* empty loop */ ;
  195702. text++; /* skip NUL separator */
  195703. if (text >= chunkdata + slength)
  195704. {
  195705. png_warning(png_ptr, "Malformed iTXt chunk");
  195706. png_free(png_ptr, chunkdata);
  195707. return;
  195708. }
  195709. prefix_len = text - chunkdata;
  195710. key=chunkdata;
  195711. if (comp_flag)
  195712. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195713. (size_t)length, prefix_len, &data_len);
  195714. else
  195715. data_len=png_strlen(chunkdata + prefix_len);
  195716. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195717. (png_uint_32)png_sizeof(png_text));
  195718. if (text_ptr == NULL)
  195719. {
  195720. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195721. png_free(png_ptr, chunkdata);
  195722. return;
  195723. }
  195724. text_ptr->compression = (int)comp_flag + 1;
  195725. text_ptr->lang_key = chunkdata+(lang_key-key);
  195726. text_ptr->lang = chunkdata+(lang-key);
  195727. text_ptr->itxt_length = data_len;
  195728. text_ptr->text_length = 0;
  195729. text_ptr->key = chunkdata;
  195730. text_ptr->text = chunkdata + prefix_len;
  195731. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195732. png_free(png_ptr, text_ptr);
  195733. png_free(png_ptr, chunkdata);
  195734. if (ret)
  195735. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195736. }
  195737. #endif
  195738. /* This function is called when we haven't found a handler for a
  195739. chunk. If there isn't a problem with the chunk itself (ie bad
  195740. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195741. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195742. case it will be saved away to be written out later. */
  195743. void /* PRIVATE */
  195744. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195745. {
  195746. png_uint_32 skip = 0;
  195747. png_debug(1, "in png_handle_unknown\n");
  195748. if (png_ptr->mode & PNG_HAVE_IDAT)
  195749. {
  195750. #ifdef PNG_USE_LOCAL_ARRAYS
  195751. PNG_CONST PNG_IDAT;
  195752. #endif
  195753. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195754. png_ptr->mode |= PNG_AFTER_IDAT;
  195755. }
  195756. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195757. if (!(png_ptr->chunk_name[0] & 0x20))
  195758. {
  195759. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195760. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195761. PNG_HANDLE_CHUNK_ALWAYS
  195762. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195763. && png_ptr->read_user_chunk_fn == NULL
  195764. #endif
  195765. )
  195766. #endif
  195767. png_chunk_error(png_ptr, "unknown critical chunk");
  195768. }
  195769. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195770. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195771. (png_ptr->read_user_chunk_fn != NULL))
  195772. {
  195773. #ifdef PNG_MAX_MALLOC_64K
  195774. if (length > (png_uint_32)65535L)
  195775. {
  195776. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195777. skip = length - (png_uint_32)65535L;
  195778. length = (png_uint_32)65535L;
  195779. }
  195780. #endif
  195781. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195782. (png_charp)png_ptr->chunk_name, 5);
  195783. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195784. png_ptr->unknown_chunk.size = (png_size_t)length;
  195785. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195786. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195787. if(png_ptr->read_user_chunk_fn != NULL)
  195788. {
  195789. /* callback to user unknown chunk handler */
  195790. int ret;
  195791. ret = (*(png_ptr->read_user_chunk_fn))
  195792. (png_ptr, &png_ptr->unknown_chunk);
  195793. if (ret < 0)
  195794. png_chunk_error(png_ptr, "error in user chunk");
  195795. if (ret == 0)
  195796. {
  195797. if (!(png_ptr->chunk_name[0] & 0x20))
  195798. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195799. PNG_HANDLE_CHUNK_ALWAYS)
  195800. png_chunk_error(png_ptr, "unknown critical chunk");
  195801. png_set_unknown_chunks(png_ptr, info_ptr,
  195802. &png_ptr->unknown_chunk, 1);
  195803. }
  195804. }
  195805. #else
  195806. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195807. #endif
  195808. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195809. png_ptr->unknown_chunk.data = NULL;
  195810. }
  195811. else
  195812. #endif
  195813. skip = length;
  195814. png_crc_finish(png_ptr, skip);
  195815. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195816. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195817. #endif
  195818. }
  195819. /* This function is called to verify that a chunk name is valid.
  195820. This function can't have the "critical chunk check" incorporated
  195821. into it, since in the future we will need to be able to call user
  195822. functions to handle unknown critical chunks after we check that
  195823. the chunk name itself is valid. */
  195824. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195825. void /* PRIVATE */
  195826. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195827. {
  195828. png_debug(1, "in png_check_chunk_name\n");
  195829. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195830. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195831. {
  195832. png_chunk_error(png_ptr, "invalid chunk type");
  195833. }
  195834. }
  195835. /* Combines the row recently read in with the existing pixels in the
  195836. row. This routine takes care of alpha and transparency if requested.
  195837. This routine also handles the two methods of progressive display
  195838. of interlaced images, depending on the mask value.
  195839. The mask value describes which pixels are to be combined with
  195840. the row. The pattern always repeats every 8 pixels, so just 8
  195841. bits are needed. A one indicates the pixel is to be combined,
  195842. a zero indicates the pixel is to be skipped. This is in addition
  195843. to any alpha or transparency value associated with the pixel. If
  195844. you want all pixels to be combined, pass 0xff (255) in mask. */
  195845. void /* PRIVATE */
  195846. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195847. {
  195848. png_debug(1,"in png_combine_row\n");
  195849. if (mask == 0xff)
  195850. {
  195851. png_memcpy(row, png_ptr->row_buf + 1,
  195852. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195853. }
  195854. else
  195855. {
  195856. switch (png_ptr->row_info.pixel_depth)
  195857. {
  195858. case 1:
  195859. {
  195860. png_bytep sp = png_ptr->row_buf + 1;
  195861. png_bytep dp = row;
  195862. int s_inc, s_start, s_end;
  195863. int m = 0x80;
  195864. int shift;
  195865. png_uint_32 i;
  195866. png_uint_32 row_width = png_ptr->width;
  195867. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195868. if (png_ptr->transformations & PNG_PACKSWAP)
  195869. {
  195870. s_start = 0;
  195871. s_end = 7;
  195872. s_inc = 1;
  195873. }
  195874. else
  195875. #endif
  195876. {
  195877. s_start = 7;
  195878. s_end = 0;
  195879. s_inc = -1;
  195880. }
  195881. shift = s_start;
  195882. for (i = 0; i < row_width; i++)
  195883. {
  195884. if (m & mask)
  195885. {
  195886. int value;
  195887. value = (*sp >> shift) & 0x01;
  195888. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195889. *dp |= (png_byte)(value << shift);
  195890. }
  195891. if (shift == s_end)
  195892. {
  195893. shift = s_start;
  195894. sp++;
  195895. dp++;
  195896. }
  195897. else
  195898. shift += s_inc;
  195899. if (m == 1)
  195900. m = 0x80;
  195901. else
  195902. m >>= 1;
  195903. }
  195904. break;
  195905. }
  195906. case 2:
  195907. {
  195908. png_bytep sp = png_ptr->row_buf + 1;
  195909. png_bytep dp = row;
  195910. int s_start, s_end, s_inc;
  195911. int m = 0x80;
  195912. int shift;
  195913. png_uint_32 i;
  195914. png_uint_32 row_width = png_ptr->width;
  195915. int value;
  195916. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195917. if (png_ptr->transformations & PNG_PACKSWAP)
  195918. {
  195919. s_start = 0;
  195920. s_end = 6;
  195921. s_inc = 2;
  195922. }
  195923. else
  195924. #endif
  195925. {
  195926. s_start = 6;
  195927. s_end = 0;
  195928. s_inc = -2;
  195929. }
  195930. shift = s_start;
  195931. for (i = 0; i < row_width; i++)
  195932. {
  195933. if (m & mask)
  195934. {
  195935. value = (*sp >> shift) & 0x03;
  195936. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195937. *dp |= (png_byte)(value << shift);
  195938. }
  195939. if (shift == s_end)
  195940. {
  195941. shift = s_start;
  195942. sp++;
  195943. dp++;
  195944. }
  195945. else
  195946. shift += s_inc;
  195947. if (m == 1)
  195948. m = 0x80;
  195949. else
  195950. m >>= 1;
  195951. }
  195952. break;
  195953. }
  195954. case 4:
  195955. {
  195956. png_bytep sp = png_ptr->row_buf + 1;
  195957. png_bytep dp = row;
  195958. int s_start, s_end, s_inc;
  195959. int m = 0x80;
  195960. int shift;
  195961. png_uint_32 i;
  195962. png_uint_32 row_width = png_ptr->width;
  195963. int value;
  195964. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195965. if (png_ptr->transformations & PNG_PACKSWAP)
  195966. {
  195967. s_start = 0;
  195968. s_end = 4;
  195969. s_inc = 4;
  195970. }
  195971. else
  195972. #endif
  195973. {
  195974. s_start = 4;
  195975. s_end = 0;
  195976. s_inc = -4;
  195977. }
  195978. shift = s_start;
  195979. for (i = 0; i < row_width; i++)
  195980. {
  195981. if (m & mask)
  195982. {
  195983. value = (*sp >> shift) & 0xf;
  195984. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195985. *dp |= (png_byte)(value << shift);
  195986. }
  195987. if (shift == s_end)
  195988. {
  195989. shift = s_start;
  195990. sp++;
  195991. dp++;
  195992. }
  195993. else
  195994. shift += s_inc;
  195995. if (m == 1)
  195996. m = 0x80;
  195997. else
  195998. m >>= 1;
  195999. }
  196000. break;
  196001. }
  196002. default:
  196003. {
  196004. png_bytep sp = png_ptr->row_buf + 1;
  196005. png_bytep dp = row;
  196006. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196007. png_uint_32 i;
  196008. png_uint_32 row_width = png_ptr->width;
  196009. png_byte m = 0x80;
  196010. for (i = 0; i < row_width; i++)
  196011. {
  196012. if (m & mask)
  196013. {
  196014. png_memcpy(dp, sp, pixel_bytes);
  196015. }
  196016. sp += pixel_bytes;
  196017. dp += pixel_bytes;
  196018. if (m == 1)
  196019. m = 0x80;
  196020. else
  196021. m >>= 1;
  196022. }
  196023. break;
  196024. }
  196025. }
  196026. }
  196027. }
  196028. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196029. /* OLD pre-1.0.9 interface:
  196030. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196031. png_uint_32 transformations)
  196032. */
  196033. void /* PRIVATE */
  196034. png_do_read_interlace(png_structp png_ptr)
  196035. {
  196036. png_row_infop row_info = &(png_ptr->row_info);
  196037. png_bytep row = png_ptr->row_buf + 1;
  196038. int pass = png_ptr->pass;
  196039. png_uint_32 transformations = png_ptr->transformations;
  196040. #ifdef PNG_USE_LOCAL_ARRAYS
  196041. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196042. /* offset to next interlace block */
  196043. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196044. #endif
  196045. png_debug(1,"in png_do_read_interlace\n");
  196046. if (row != NULL && row_info != NULL)
  196047. {
  196048. png_uint_32 final_width;
  196049. final_width = row_info->width * png_pass_inc[pass];
  196050. switch (row_info->pixel_depth)
  196051. {
  196052. case 1:
  196053. {
  196054. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196055. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196056. int sshift, dshift;
  196057. int s_start, s_end, s_inc;
  196058. int jstop = png_pass_inc[pass];
  196059. png_byte v;
  196060. png_uint_32 i;
  196061. int j;
  196062. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196063. if (transformations & PNG_PACKSWAP)
  196064. {
  196065. sshift = (int)((row_info->width + 7) & 0x07);
  196066. dshift = (int)((final_width + 7) & 0x07);
  196067. s_start = 7;
  196068. s_end = 0;
  196069. s_inc = -1;
  196070. }
  196071. else
  196072. #endif
  196073. {
  196074. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196075. dshift = 7 - (int)((final_width + 7) & 0x07);
  196076. s_start = 0;
  196077. s_end = 7;
  196078. s_inc = 1;
  196079. }
  196080. for (i = 0; i < row_info->width; i++)
  196081. {
  196082. v = (png_byte)((*sp >> sshift) & 0x01);
  196083. for (j = 0; j < jstop; j++)
  196084. {
  196085. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196086. *dp |= (png_byte)(v << dshift);
  196087. if (dshift == s_end)
  196088. {
  196089. dshift = s_start;
  196090. dp--;
  196091. }
  196092. else
  196093. dshift += s_inc;
  196094. }
  196095. if (sshift == s_end)
  196096. {
  196097. sshift = s_start;
  196098. sp--;
  196099. }
  196100. else
  196101. sshift += s_inc;
  196102. }
  196103. break;
  196104. }
  196105. case 2:
  196106. {
  196107. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196108. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196109. int sshift, dshift;
  196110. int s_start, s_end, s_inc;
  196111. int jstop = png_pass_inc[pass];
  196112. png_uint_32 i;
  196113. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196114. if (transformations & PNG_PACKSWAP)
  196115. {
  196116. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196117. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196118. s_start = 6;
  196119. s_end = 0;
  196120. s_inc = -2;
  196121. }
  196122. else
  196123. #endif
  196124. {
  196125. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196126. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196127. s_start = 0;
  196128. s_end = 6;
  196129. s_inc = 2;
  196130. }
  196131. for (i = 0; i < row_info->width; i++)
  196132. {
  196133. png_byte v;
  196134. int j;
  196135. v = (png_byte)((*sp >> sshift) & 0x03);
  196136. for (j = 0; j < jstop; j++)
  196137. {
  196138. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196139. *dp |= (png_byte)(v << dshift);
  196140. if (dshift == s_end)
  196141. {
  196142. dshift = s_start;
  196143. dp--;
  196144. }
  196145. else
  196146. dshift += s_inc;
  196147. }
  196148. if (sshift == s_end)
  196149. {
  196150. sshift = s_start;
  196151. sp--;
  196152. }
  196153. else
  196154. sshift += s_inc;
  196155. }
  196156. break;
  196157. }
  196158. case 4:
  196159. {
  196160. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196161. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196162. int sshift, dshift;
  196163. int s_start, s_end, s_inc;
  196164. png_uint_32 i;
  196165. int jstop = png_pass_inc[pass];
  196166. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196167. if (transformations & PNG_PACKSWAP)
  196168. {
  196169. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196170. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196171. s_start = 4;
  196172. s_end = 0;
  196173. s_inc = -4;
  196174. }
  196175. else
  196176. #endif
  196177. {
  196178. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196179. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196180. s_start = 0;
  196181. s_end = 4;
  196182. s_inc = 4;
  196183. }
  196184. for (i = 0; i < row_info->width; i++)
  196185. {
  196186. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196187. int j;
  196188. for (j = 0; j < jstop; j++)
  196189. {
  196190. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196191. *dp |= (png_byte)(v << dshift);
  196192. if (dshift == s_end)
  196193. {
  196194. dshift = s_start;
  196195. dp--;
  196196. }
  196197. else
  196198. dshift += s_inc;
  196199. }
  196200. if (sshift == s_end)
  196201. {
  196202. sshift = s_start;
  196203. sp--;
  196204. }
  196205. else
  196206. sshift += s_inc;
  196207. }
  196208. break;
  196209. }
  196210. default:
  196211. {
  196212. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196213. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196214. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196215. int jstop = png_pass_inc[pass];
  196216. png_uint_32 i;
  196217. for (i = 0; i < row_info->width; i++)
  196218. {
  196219. png_byte v[8];
  196220. int j;
  196221. png_memcpy(v, sp, pixel_bytes);
  196222. for (j = 0; j < jstop; j++)
  196223. {
  196224. png_memcpy(dp, v, pixel_bytes);
  196225. dp -= pixel_bytes;
  196226. }
  196227. sp -= pixel_bytes;
  196228. }
  196229. break;
  196230. }
  196231. }
  196232. row_info->width = final_width;
  196233. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196234. }
  196235. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196236. transformations = transformations; /* silence compiler warning */
  196237. #endif
  196238. }
  196239. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196240. void /* PRIVATE */
  196241. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196242. png_bytep prev_row, int filter)
  196243. {
  196244. png_debug(1, "in png_read_filter_row\n");
  196245. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196246. switch (filter)
  196247. {
  196248. case PNG_FILTER_VALUE_NONE:
  196249. break;
  196250. case PNG_FILTER_VALUE_SUB:
  196251. {
  196252. png_uint_32 i;
  196253. png_uint_32 istop = row_info->rowbytes;
  196254. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196255. png_bytep rp = row + bpp;
  196256. png_bytep lp = row;
  196257. for (i = bpp; i < istop; i++)
  196258. {
  196259. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196260. rp++;
  196261. }
  196262. break;
  196263. }
  196264. case PNG_FILTER_VALUE_UP:
  196265. {
  196266. png_uint_32 i;
  196267. png_uint_32 istop = row_info->rowbytes;
  196268. png_bytep rp = row;
  196269. png_bytep pp = prev_row;
  196270. for (i = 0; i < istop; i++)
  196271. {
  196272. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196273. rp++;
  196274. }
  196275. break;
  196276. }
  196277. case PNG_FILTER_VALUE_AVG:
  196278. {
  196279. png_uint_32 i;
  196280. png_bytep rp = row;
  196281. png_bytep pp = prev_row;
  196282. png_bytep lp = row;
  196283. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196284. png_uint_32 istop = row_info->rowbytes - bpp;
  196285. for (i = 0; i < bpp; i++)
  196286. {
  196287. *rp = (png_byte)(((int)(*rp) +
  196288. ((int)(*pp++) / 2 )) & 0xff);
  196289. rp++;
  196290. }
  196291. for (i = 0; i < istop; i++)
  196292. {
  196293. *rp = (png_byte)(((int)(*rp) +
  196294. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196295. rp++;
  196296. }
  196297. break;
  196298. }
  196299. case PNG_FILTER_VALUE_PAETH:
  196300. {
  196301. png_uint_32 i;
  196302. png_bytep rp = row;
  196303. png_bytep pp = prev_row;
  196304. png_bytep lp = row;
  196305. png_bytep cp = prev_row;
  196306. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196307. png_uint_32 istop=row_info->rowbytes - bpp;
  196308. for (i = 0; i < bpp; i++)
  196309. {
  196310. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196311. rp++;
  196312. }
  196313. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196314. {
  196315. int a, b, c, pa, pb, pc, p;
  196316. a = *lp++;
  196317. b = *pp++;
  196318. c = *cp++;
  196319. p = b - c;
  196320. pc = a - c;
  196321. #ifdef PNG_USE_ABS
  196322. pa = abs(p);
  196323. pb = abs(pc);
  196324. pc = abs(p + pc);
  196325. #else
  196326. pa = p < 0 ? -p : p;
  196327. pb = pc < 0 ? -pc : pc;
  196328. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196329. #endif
  196330. /*
  196331. if (pa <= pb && pa <= pc)
  196332. p = a;
  196333. else if (pb <= pc)
  196334. p = b;
  196335. else
  196336. p = c;
  196337. */
  196338. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196339. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196340. rp++;
  196341. }
  196342. break;
  196343. }
  196344. default:
  196345. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196346. *row=0;
  196347. break;
  196348. }
  196349. }
  196350. void /* PRIVATE */
  196351. png_read_finish_row(png_structp png_ptr)
  196352. {
  196353. #ifdef PNG_USE_LOCAL_ARRAYS
  196354. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196355. /* start of interlace block */
  196356. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196357. /* offset to next interlace block */
  196358. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196359. /* start of interlace block in the y direction */
  196360. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196361. /* offset to next interlace block in the y direction */
  196362. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196363. #endif
  196364. png_debug(1, "in png_read_finish_row\n");
  196365. png_ptr->row_number++;
  196366. if (png_ptr->row_number < png_ptr->num_rows)
  196367. return;
  196368. if (png_ptr->interlaced)
  196369. {
  196370. png_ptr->row_number = 0;
  196371. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196372. png_ptr->rowbytes + 1);
  196373. do
  196374. {
  196375. png_ptr->pass++;
  196376. if (png_ptr->pass >= 7)
  196377. break;
  196378. png_ptr->iwidth = (png_ptr->width +
  196379. png_pass_inc[png_ptr->pass] - 1 -
  196380. png_pass_start[png_ptr->pass]) /
  196381. png_pass_inc[png_ptr->pass];
  196382. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196383. png_ptr->iwidth) + 1;
  196384. if (!(png_ptr->transformations & PNG_INTERLACE))
  196385. {
  196386. png_ptr->num_rows = (png_ptr->height +
  196387. png_pass_yinc[png_ptr->pass] - 1 -
  196388. png_pass_ystart[png_ptr->pass]) /
  196389. png_pass_yinc[png_ptr->pass];
  196390. if (!(png_ptr->num_rows))
  196391. continue;
  196392. }
  196393. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196394. break;
  196395. } while (png_ptr->iwidth == 0);
  196396. if (png_ptr->pass < 7)
  196397. return;
  196398. }
  196399. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196400. {
  196401. #ifdef PNG_USE_LOCAL_ARRAYS
  196402. PNG_CONST PNG_IDAT;
  196403. #endif
  196404. char extra;
  196405. int ret;
  196406. png_ptr->zstream.next_out = (Bytef *)&extra;
  196407. png_ptr->zstream.avail_out = (uInt)1;
  196408. for(;;)
  196409. {
  196410. if (!(png_ptr->zstream.avail_in))
  196411. {
  196412. while (!png_ptr->idat_size)
  196413. {
  196414. png_byte chunk_length[4];
  196415. png_crc_finish(png_ptr, 0);
  196416. png_read_data(png_ptr, chunk_length, 4);
  196417. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196418. png_reset_crc(png_ptr);
  196419. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196420. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196421. png_error(png_ptr, "Not enough image data");
  196422. }
  196423. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196424. png_ptr->zstream.next_in = png_ptr->zbuf;
  196425. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196426. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196427. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196428. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196429. }
  196430. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196431. if (ret == Z_STREAM_END)
  196432. {
  196433. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196434. png_ptr->idat_size)
  196435. png_warning(png_ptr, "Extra compressed data");
  196436. png_ptr->mode |= PNG_AFTER_IDAT;
  196437. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196438. break;
  196439. }
  196440. if (ret != Z_OK)
  196441. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196442. "Decompression Error");
  196443. if (!(png_ptr->zstream.avail_out))
  196444. {
  196445. png_warning(png_ptr, "Extra compressed data.");
  196446. png_ptr->mode |= PNG_AFTER_IDAT;
  196447. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196448. break;
  196449. }
  196450. }
  196451. png_ptr->zstream.avail_out = 0;
  196452. }
  196453. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196454. png_warning(png_ptr, "Extra compression data");
  196455. inflateReset(&png_ptr->zstream);
  196456. png_ptr->mode |= PNG_AFTER_IDAT;
  196457. }
  196458. void /* PRIVATE */
  196459. png_read_start_row(png_structp png_ptr)
  196460. {
  196461. #ifdef PNG_USE_LOCAL_ARRAYS
  196462. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196463. /* start of interlace block */
  196464. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196465. /* offset to next interlace block */
  196466. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196467. /* start of interlace block in the y direction */
  196468. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196469. /* offset to next interlace block in the y direction */
  196470. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196471. #endif
  196472. int max_pixel_depth;
  196473. png_uint_32 row_bytes;
  196474. png_debug(1, "in png_read_start_row\n");
  196475. png_ptr->zstream.avail_in = 0;
  196476. png_init_read_transformations(png_ptr);
  196477. if (png_ptr->interlaced)
  196478. {
  196479. if (!(png_ptr->transformations & PNG_INTERLACE))
  196480. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196481. png_pass_ystart[0]) / png_pass_yinc[0];
  196482. else
  196483. png_ptr->num_rows = png_ptr->height;
  196484. png_ptr->iwidth = (png_ptr->width +
  196485. png_pass_inc[png_ptr->pass] - 1 -
  196486. png_pass_start[png_ptr->pass]) /
  196487. png_pass_inc[png_ptr->pass];
  196488. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196489. png_ptr->irowbytes = (png_size_t)row_bytes;
  196490. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196491. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196492. }
  196493. else
  196494. {
  196495. png_ptr->num_rows = png_ptr->height;
  196496. png_ptr->iwidth = png_ptr->width;
  196497. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196498. }
  196499. max_pixel_depth = png_ptr->pixel_depth;
  196500. #if defined(PNG_READ_PACK_SUPPORTED)
  196501. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196502. max_pixel_depth = 8;
  196503. #endif
  196504. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196505. if (png_ptr->transformations & PNG_EXPAND)
  196506. {
  196507. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196508. {
  196509. if (png_ptr->num_trans)
  196510. max_pixel_depth = 32;
  196511. else
  196512. max_pixel_depth = 24;
  196513. }
  196514. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196515. {
  196516. if (max_pixel_depth < 8)
  196517. max_pixel_depth = 8;
  196518. if (png_ptr->num_trans)
  196519. max_pixel_depth *= 2;
  196520. }
  196521. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196522. {
  196523. if (png_ptr->num_trans)
  196524. {
  196525. max_pixel_depth *= 4;
  196526. max_pixel_depth /= 3;
  196527. }
  196528. }
  196529. }
  196530. #endif
  196531. #if defined(PNG_READ_FILLER_SUPPORTED)
  196532. if (png_ptr->transformations & (PNG_FILLER))
  196533. {
  196534. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196535. max_pixel_depth = 32;
  196536. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196537. {
  196538. if (max_pixel_depth <= 8)
  196539. max_pixel_depth = 16;
  196540. else
  196541. max_pixel_depth = 32;
  196542. }
  196543. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196544. {
  196545. if (max_pixel_depth <= 32)
  196546. max_pixel_depth = 32;
  196547. else
  196548. max_pixel_depth = 64;
  196549. }
  196550. }
  196551. #endif
  196552. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196553. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196554. {
  196555. if (
  196556. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196557. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196558. #endif
  196559. #if defined(PNG_READ_FILLER_SUPPORTED)
  196560. (png_ptr->transformations & (PNG_FILLER)) ||
  196561. #endif
  196562. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196563. {
  196564. if (max_pixel_depth <= 16)
  196565. max_pixel_depth = 32;
  196566. else
  196567. max_pixel_depth = 64;
  196568. }
  196569. else
  196570. {
  196571. if (max_pixel_depth <= 8)
  196572. {
  196573. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196574. max_pixel_depth = 32;
  196575. else
  196576. max_pixel_depth = 24;
  196577. }
  196578. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196579. max_pixel_depth = 64;
  196580. else
  196581. max_pixel_depth = 48;
  196582. }
  196583. }
  196584. #endif
  196585. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196586. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196587. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196588. {
  196589. int user_pixel_depth=png_ptr->user_transform_depth*
  196590. png_ptr->user_transform_channels;
  196591. if(user_pixel_depth > max_pixel_depth)
  196592. max_pixel_depth=user_pixel_depth;
  196593. }
  196594. #endif
  196595. /* align the width on the next larger 8 pixels. Mainly used
  196596. for interlacing */
  196597. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196598. /* calculate the maximum bytes needed, adding a byte and a pixel
  196599. for safety's sake */
  196600. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196601. 1 + ((max_pixel_depth + 7) >> 3);
  196602. #ifdef PNG_MAX_MALLOC_64K
  196603. if (row_bytes > (png_uint_32)65536L)
  196604. png_error(png_ptr, "This image requires a row greater than 64KB");
  196605. #endif
  196606. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196607. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196608. #ifdef PNG_MAX_MALLOC_64K
  196609. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196610. png_error(png_ptr, "This image requires a row greater than 64KB");
  196611. #endif
  196612. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196613. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196614. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196615. png_ptr->rowbytes + 1));
  196616. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196617. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196618. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196619. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196620. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196621. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196622. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196623. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196624. }
  196625. #endif /* PNG_READ_SUPPORTED */
  196626. /*** End of inlined file: pngrutil.c ***/
  196627. /*** Start of inlined file: pngset.c ***/
  196628. /* pngset.c - storage of image information into info struct
  196629. *
  196630. * Last changed in libpng 1.2.21 [October 4, 2007]
  196631. * For conditions of distribution and use, see copyright notice in png.h
  196632. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196633. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196634. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196635. *
  196636. * The functions here are used during reads to store data from the file
  196637. * into the info struct, and during writes to store application data
  196638. * into the info struct for writing into the file. This abstracts the
  196639. * info struct and allows us to change the structure in the future.
  196640. */
  196641. #define PNG_INTERNAL
  196642. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196643. #if defined(PNG_bKGD_SUPPORTED)
  196644. void PNGAPI
  196645. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196646. {
  196647. png_debug1(1, "in %s storage function\n", "bKGD");
  196648. if (png_ptr == NULL || info_ptr == NULL)
  196649. return;
  196650. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196651. info_ptr->valid |= PNG_INFO_bKGD;
  196652. }
  196653. #endif
  196654. #if defined(PNG_cHRM_SUPPORTED)
  196655. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196656. void PNGAPI
  196657. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196658. double white_x, double white_y, double red_x, double red_y,
  196659. double green_x, double green_y, double blue_x, double blue_y)
  196660. {
  196661. png_debug1(1, "in %s storage function\n", "cHRM");
  196662. if (png_ptr == NULL || info_ptr == NULL)
  196663. return;
  196664. if (white_x < 0.0 || white_y < 0.0 ||
  196665. red_x < 0.0 || red_y < 0.0 ||
  196666. green_x < 0.0 || green_y < 0.0 ||
  196667. blue_x < 0.0 || blue_y < 0.0)
  196668. {
  196669. png_warning(png_ptr,
  196670. "Ignoring attempt to set negative chromaticity value");
  196671. return;
  196672. }
  196673. if (white_x > 21474.83 || white_y > 21474.83 ||
  196674. red_x > 21474.83 || red_y > 21474.83 ||
  196675. green_x > 21474.83 || green_y > 21474.83 ||
  196676. blue_x > 21474.83 || blue_y > 21474.83)
  196677. {
  196678. png_warning(png_ptr,
  196679. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196680. return;
  196681. }
  196682. info_ptr->x_white = (float)white_x;
  196683. info_ptr->y_white = (float)white_y;
  196684. info_ptr->x_red = (float)red_x;
  196685. info_ptr->y_red = (float)red_y;
  196686. info_ptr->x_green = (float)green_x;
  196687. info_ptr->y_green = (float)green_y;
  196688. info_ptr->x_blue = (float)blue_x;
  196689. info_ptr->y_blue = (float)blue_y;
  196690. #ifdef PNG_FIXED_POINT_SUPPORTED
  196691. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196692. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196693. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196694. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196695. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196696. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196697. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196698. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196699. #endif
  196700. info_ptr->valid |= PNG_INFO_cHRM;
  196701. }
  196702. #endif
  196703. #ifdef PNG_FIXED_POINT_SUPPORTED
  196704. void PNGAPI
  196705. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196706. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196707. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196708. png_fixed_point blue_x, png_fixed_point blue_y)
  196709. {
  196710. png_debug1(1, "in %s storage function\n", "cHRM");
  196711. if (png_ptr == NULL || info_ptr == NULL)
  196712. return;
  196713. if (white_x < 0 || white_y < 0 ||
  196714. red_x < 0 || red_y < 0 ||
  196715. green_x < 0 || green_y < 0 ||
  196716. blue_x < 0 || blue_y < 0)
  196717. {
  196718. png_warning(png_ptr,
  196719. "Ignoring attempt to set negative chromaticity value");
  196720. return;
  196721. }
  196722. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196723. if (white_x > (double) PNG_UINT_31_MAX ||
  196724. white_y > (double) PNG_UINT_31_MAX ||
  196725. red_x > (double) PNG_UINT_31_MAX ||
  196726. red_y > (double) PNG_UINT_31_MAX ||
  196727. green_x > (double) PNG_UINT_31_MAX ||
  196728. green_y > (double) PNG_UINT_31_MAX ||
  196729. blue_x > (double) PNG_UINT_31_MAX ||
  196730. blue_y > (double) PNG_UINT_31_MAX)
  196731. #else
  196732. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196733. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196734. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196735. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196736. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196737. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196738. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196739. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196740. #endif
  196741. {
  196742. png_warning(png_ptr,
  196743. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196744. return;
  196745. }
  196746. info_ptr->int_x_white = white_x;
  196747. info_ptr->int_y_white = white_y;
  196748. info_ptr->int_x_red = red_x;
  196749. info_ptr->int_y_red = red_y;
  196750. info_ptr->int_x_green = green_x;
  196751. info_ptr->int_y_green = green_y;
  196752. info_ptr->int_x_blue = blue_x;
  196753. info_ptr->int_y_blue = blue_y;
  196754. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196755. info_ptr->x_white = (float)(white_x/100000.);
  196756. info_ptr->y_white = (float)(white_y/100000.);
  196757. info_ptr->x_red = (float)( red_x/100000.);
  196758. info_ptr->y_red = (float)( red_y/100000.);
  196759. info_ptr->x_green = (float)(green_x/100000.);
  196760. info_ptr->y_green = (float)(green_y/100000.);
  196761. info_ptr->x_blue = (float)( blue_x/100000.);
  196762. info_ptr->y_blue = (float)( blue_y/100000.);
  196763. #endif
  196764. info_ptr->valid |= PNG_INFO_cHRM;
  196765. }
  196766. #endif
  196767. #endif
  196768. #if defined(PNG_gAMA_SUPPORTED)
  196769. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196770. void PNGAPI
  196771. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196772. {
  196773. double gamma;
  196774. png_debug1(1, "in %s storage function\n", "gAMA");
  196775. if (png_ptr == NULL || info_ptr == NULL)
  196776. return;
  196777. /* Check for overflow */
  196778. if (file_gamma > 21474.83)
  196779. {
  196780. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196781. gamma=21474.83;
  196782. }
  196783. else
  196784. gamma=file_gamma;
  196785. info_ptr->gamma = (float)gamma;
  196786. #ifdef PNG_FIXED_POINT_SUPPORTED
  196787. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196788. #endif
  196789. info_ptr->valid |= PNG_INFO_gAMA;
  196790. if(gamma == 0.0)
  196791. png_warning(png_ptr, "Setting gamma=0");
  196792. }
  196793. #endif
  196794. void PNGAPI
  196795. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196796. int_gamma)
  196797. {
  196798. png_fixed_point gamma;
  196799. png_debug1(1, "in %s storage function\n", "gAMA");
  196800. if (png_ptr == NULL || info_ptr == NULL)
  196801. return;
  196802. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196803. {
  196804. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196805. gamma=PNG_UINT_31_MAX;
  196806. }
  196807. else
  196808. {
  196809. if (int_gamma < 0)
  196810. {
  196811. png_warning(png_ptr, "Setting negative gamma to zero");
  196812. gamma=0;
  196813. }
  196814. else
  196815. gamma=int_gamma;
  196816. }
  196817. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196818. info_ptr->gamma = (float)(gamma/100000.);
  196819. #endif
  196820. #ifdef PNG_FIXED_POINT_SUPPORTED
  196821. info_ptr->int_gamma = gamma;
  196822. #endif
  196823. info_ptr->valid |= PNG_INFO_gAMA;
  196824. if(gamma == 0)
  196825. png_warning(png_ptr, "Setting gamma=0");
  196826. }
  196827. #endif
  196828. #if defined(PNG_hIST_SUPPORTED)
  196829. void PNGAPI
  196830. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196831. {
  196832. int i;
  196833. png_debug1(1, "in %s storage function\n", "hIST");
  196834. if (png_ptr == NULL || info_ptr == NULL)
  196835. return;
  196836. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196837. > PNG_MAX_PALETTE_LENGTH)
  196838. {
  196839. png_warning(png_ptr,
  196840. "Invalid palette size, hIST allocation skipped.");
  196841. return;
  196842. }
  196843. #ifdef PNG_FREE_ME_SUPPORTED
  196844. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196845. #endif
  196846. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196847. 1.2.1 */
  196848. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196849. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196850. if (png_ptr->hist == NULL)
  196851. {
  196852. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196853. return;
  196854. }
  196855. for (i = 0; i < info_ptr->num_palette; i++)
  196856. png_ptr->hist[i] = hist[i];
  196857. info_ptr->hist = png_ptr->hist;
  196858. info_ptr->valid |= PNG_INFO_hIST;
  196859. #ifdef PNG_FREE_ME_SUPPORTED
  196860. info_ptr->free_me |= PNG_FREE_HIST;
  196861. #else
  196862. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196863. #endif
  196864. }
  196865. #endif
  196866. void PNGAPI
  196867. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196868. png_uint_32 width, png_uint_32 height, int bit_depth,
  196869. int color_type, int interlace_type, int compression_type,
  196870. int filter_type)
  196871. {
  196872. png_debug1(1, "in %s storage function\n", "IHDR");
  196873. if (png_ptr == NULL || info_ptr == NULL)
  196874. return;
  196875. /* check for width and height valid values */
  196876. if (width == 0 || height == 0)
  196877. png_error(png_ptr, "Image width or height is zero in IHDR");
  196878. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196879. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196880. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196881. #else
  196882. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196883. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196884. #endif
  196885. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196886. png_error(png_ptr, "Invalid image size in IHDR");
  196887. if ( width > (PNG_UINT_32_MAX
  196888. >> 3) /* 8-byte RGBA pixels */
  196889. - 64 /* bigrowbuf hack */
  196890. - 1 /* filter byte */
  196891. - 7*8 /* rounding of width to multiple of 8 pixels */
  196892. - 8) /* extra max_pixel_depth pad */
  196893. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196894. /* check other values */
  196895. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196896. bit_depth != 8 && bit_depth != 16)
  196897. png_error(png_ptr, "Invalid bit depth in IHDR");
  196898. if (color_type < 0 || color_type == 1 ||
  196899. color_type == 5 || color_type > 6)
  196900. png_error(png_ptr, "Invalid color type in IHDR");
  196901. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196902. ((color_type == PNG_COLOR_TYPE_RGB ||
  196903. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196904. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196905. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196906. if (interlace_type >= PNG_INTERLACE_LAST)
  196907. png_error(png_ptr, "Unknown interlace method in IHDR");
  196908. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196909. png_error(png_ptr, "Unknown compression method in IHDR");
  196910. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196911. /* Accept filter_method 64 (intrapixel differencing) only if
  196912. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196913. * 2. Libpng did not read a PNG signature (this filter_method is only
  196914. * used in PNG datastreams that are embedded in MNG datastreams) and
  196915. * 3. The application called png_permit_mng_features with a mask that
  196916. * included PNG_FLAG_MNG_FILTER_64 and
  196917. * 4. The filter_method is 64 and
  196918. * 5. The color_type is RGB or RGBA
  196919. */
  196920. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196921. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196922. if(filter_type != PNG_FILTER_TYPE_BASE)
  196923. {
  196924. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196925. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196926. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196927. (color_type == PNG_COLOR_TYPE_RGB ||
  196928. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196929. png_error(png_ptr, "Unknown filter method in IHDR");
  196930. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196931. png_warning(png_ptr, "Invalid filter method in IHDR");
  196932. }
  196933. #else
  196934. if(filter_type != PNG_FILTER_TYPE_BASE)
  196935. png_error(png_ptr, "Unknown filter method in IHDR");
  196936. #endif
  196937. info_ptr->width = width;
  196938. info_ptr->height = height;
  196939. info_ptr->bit_depth = (png_byte)bit_depth;
  196940. info_ptr->color_type =(png_byte) color_type;
  196941. info_ptr->compression_type = (png_byte)compression_type;
  196942. info_ptr->filter_type = (png_byte)filter_type;
  196943. info_ptr->interlace_type = (png_byte)interlace_type;
  196944. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196945. info_ptr->channels = 1;
  196946. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196947. info_ptr->channels = 3;
  196948. else
  196949. info_ptr->channels = 1;
  196950. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196951. info_ptr->channels++;
  196952. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196953. /* check for potential overflow */
  196954. if (width > (PNG_UINT_32_MAX
  196955. >> 3) /* 8-byte RGBA pixels */
  196956. - 64 /* bigrowbuf hack */
  196957. - 1 /* filter byte */
  196958. - 7*8 /* rounding of width to multiple of 8 pixels */
  196959. - 8) /* extra max_pixel_depth pad */
  196960. info_ptr->rowbytes = (png_size_t)0;
  196961. else
  196962. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196963. }
  196964. #if defined(PNG_oFFs_SUPPORTED)
  196965. void PNGAPI
  196966. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196967. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196968. {
  196969. png_debug1(1, "in %s storage function\n", "oFFs");
  196970. if (png_ptr == NULL || info_ptr == NULL)
  196971. return;
  196972. info_ptr->x_offset = offset_x;
  196973. info_ptr->y_offset = offset_y;
  196974. info_ptr->offset_unit_type = (png_byte)unit_type;
  196975. info_ptr->valid |= PNG_INFO_oFFs;
  196976. }
  196977. #endif
  196978. #if defined(PNG_pCAL_SUPPORTED)
  196979. void PNGAPI
  196980. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196981. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196982. png_charp units, png_charpp params)
  196983. {
  196984. png_uint_32 length;
  196985. int i;
  196986. png_debug1(1, "in %s storage function\n", "pCAL");
  196987. if (png_ptr == NULL || info_ptr == NULL)
  196988. return;
  196989. length = png_strlen(purpose) + 1;
  196990. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196991. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196992. if (info_ptr->pcal_purpose == NULL)
  196993. {
  196994. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196995. return;
  196996. }
  196997. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196998. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196999. info_ptr->pcal_X0 = X0;
  197000. info_ptr->pcal_X1 = X1;
  197001. info_ptr->pcal_type = (png_byte)type;
  197002. info_ptr->pcal_nparams = (png_byte)nparams;
  197003. length = png_strlen(units) + 1;
  197004. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197005. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197006. if (info_ptr->pcal_units == NULL)
  197007. {
  197008. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197009. return;
  197010. }
  197011. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197012. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197013. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197014. if (info_ptr->pcal_params == NULL)
  197015. {
  197016. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197017. return;
  197018. }
  197019. info_ptr->pcal_params[nparams] = NULL;
  197020. for (i = 0; i < nparams; i++)
  197021. {
  197022. length = png_strlen(params[i]) + 1;
  197023. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197024. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197025. if (info_ptr->pcal_params[i] == NULL)
  197026. {
  197027. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197028. return;
  197029. }
  197030. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197031. }
  197032. info_ptr->valid |= PNG_INFO_pCAL;
  197033. #ifdef PNG_FREE_ME_SUPPORTED
  197034. info_ptr->free_me |= PNG_FREE_PCAL;
  197035. #endif
  197036. }
  197037. #endif
  197038. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197039. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197040. void PNGAPI
  197041. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197042. int unit, double width, double height)
  197043. {
  197044. png_debug1(1, "in %s storage function\n", "sCAL");
  197045. if (png_ptr == NULL || info_ptr == NULL)
  197046. return;
  197047. info_ptr->scal_unit = (png_byte)unit;
  197048. info_ptr->scal_pixel_width = width;
  197049. info_ptr->scal_pixel_height = height;
  197050. info_ptr->valid |= PNG_INFO_sCAL;
  197051. }
  197052. #else
  197053. #ifdef PNG_FIXED_POINT_SUPPORTED
  197054. void PNGAPI
  197055. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197056. int unit, png_charp swidth, png_charp sheight)
  197057. {
  197058. png_uint_32 length;
  197059. png_debug1(1, "in %s storage function\n", "sCAL");
  197060. if (png_ptr == NULL || info_ptr == NULL)
  197061. return;
  197062. info_ptr->scal_unit = (png_byte)unit;
  197063. length = png_strlen(swidth) + 1;
  197064. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197065. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197066. if (info_ptr->scal_s_width == NULL)
  197067. {
  197068. png_warning(png_ptr,
  197069. "Memory allocation failed while processing sCAL.");
  197070. }
  197071. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197072. length = png_strlen(sheight) + 1;
  197073. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197074. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197075. if (info_ptr->scal_s_height == NULL)
  197076. {
  197077. png_free (png_ptr, info_ptr->scal_s_width);
  197078. png_warning(png_ptr,
  197079. "Memory allocation failed while processing sCAL.");
  197080. }
  197081. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197082. info_ptr->valid |= PNG_INFO_sCAL;
  197083. #ifdef PNG_FREE_ME_SUPPORTED
  197084. info_ptr->free_me |= PNG_FREE_SCAL;
  197085. #endif
  197086. }
  197087. #endif
  197088. #endif
  197089. #endif
  197090. #if defined(PNG_pHYs_SUPPORTED)
  197091. void PNGAPI
  197092. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197093. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197094. {
  197095. png_debug1(1, "in %s storage function\n", "pHYs");
  197096. if (png_ptr == NULL || info_ptr == NULL)
  197097. return;
  197098. info_ptr->x_pixels_per_unit = res_x;
  197099. info_ptr->y_pixels_per_unit = res_y;
  197100. info_ptr->phys_unit_type = (png_byte)unit_type;
  197101. info_ptr->valid |= PNG_INFO_pHYs;
  197102. }
  197103. #endif
  197104. void PNGAPI
  197105. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197106. png_colorp palette, int num_palette)
  197107. {
  197108. png_debug1(1, "in %s storage function\n", "PLTE");
  197109. if (png_ptr == NULL || info_ptr == NULL)
  197110. return;
  197111. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197112. {
  197113. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197114. png_error(png_ptr, "Invalid palette length");
  197115. else
  197116. {
  197117. png_warning(png_ptr, "Invalid palette length");
  197118. return;
  197119. }
  197120. }
  197121. /*
  197122. * It may not actually be necessary to set png_ptr->palette here;
  197123. * we do it for backward compatibility with the way the png_handle_tRNS
  197124. * function used to do the allocation.
  197125. */
  197126. #ifdef PNG_FREE_ME_SUPPORTED
  197127. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197128. #endif
  197129. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197130. of num_palette entries,
  197131. in case of an invalid PNG file that has too-large sample values. */
  197132. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197133. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197134. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197135. png_sizeof(png_color));
  197136. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197137. info_ptr->palette = png_ptr->palette;
  197138. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197139. #ifdef PNG_FREE_ME_SUPPORTED
  197140. info_ptr->free_me |= PNG_FREE_PLTE;
  197141. #else
  197142. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197143. #endif
  197144. info_ptr->valid |= PNG_INFO_PLTE;
  197145. }
  197146. #if defined(PNG_sBIT_SUPPORTED)
  197147. void PNGAPI
  197148. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197149. png_color_8p sig_bit)
  197150. {
  197151. png_debug1(1, "in %s storage function\n", "sBIT");
  197152. if (png_ptr == NULL || info_ptr == NULL)
  197153. return;
  197154. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197155. info_ptr->valid |= PNG_INFO_sBIT;
  197156. }
  197157. #endif
  197158. #if defined(PNG_sRGB_SUPPORTED)
  197159. void PNGAPI
  197160. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197161. {
  197162. png_debug1(1, "in %s storage function\n", "sRGB");
  197163. if (png_ptr == NULL || info_ptr == NULL)
  197164. return;
  197165. info_ptr->srgb_intent = (png_byte)intent;
  197166. info_ptr->valid |= PNG_INFO_sRGB;
  197167. }
  197168. void PNGAPI
  197169. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197170. int intent)
  197171. {
  197172. #if defined(PNG_gAMA_SUPPORTED)
  197173. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197174. float file_gamma;
  197175. #endif
  197176. #ifdef PNG_FIXED_POINT_SUPPORTED
  197177. png_fixed_point int_file_gamma;
  197178. #endif
  197179. #endif
  197180. #if defined(PNG_cHRM_SUPPORTED)
  197181. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197182. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197183. #endif
  197184. #ifdef PNG_FIXED_POINT_SUPPORTED
  197185. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197186. int_green_y, int_blue_x, int_blue_y;
  197187. #endif
  197188. #endif
  197189. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197190. if (png_ptr == NULL || info_ptr == NULL)
  197191. return;
  197192. png_set_sRGB(png_ptr, info_ptr, intent);
  197193. #if defined(PNG_gAMA_SUPPORTED)
  197194. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197195. file_gamma = (float).45455;
  197196. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197197. #endif
  197198. #ifdef PNG_FIXED_POINT_SUPPORTED
  197199. int_file_gamma = 45455L;
  197200. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197201. #endif
  197202. #endif
  197203. #if defined(PNG_cHRM_SUPPORTED)
  197204. #ifdef PNG_FIXED_POINT_SUPPORTED
  197205. int_white_x = 31270L;
  197206. int_white_y = 32900L;
  197207. int_red_x = 64000L;
  197208. int_red_y = 33000L;
  197209. int_green_x = 30000L;
  197210. int_green_y = 60000L;
  197211. int_blue_x = 15000L;
  197212. int_blue_y = 6000L;
  197213. png_set_cHRM_fixed(png_ptr, info_ptr,
  197214. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197215. int_blue_x, int_blue_y);
  197216. #endif
  197217. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197218. white_x = (float).3127;
  197219. white_y = (float).3290;
  197220. red_x = (float).64;
  197221. red_y = (float).33;
  197222. green_x = (float).30;
  197223. green_y = (float).60;
  197224. blue_x = (float).15;
  197225. blue_y = (float).06;
  197226. png_set_cHRM(png_ptr, info_ptr,
  197227. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197228. #endif
  197229. #endif
  197230. }
  197231. #endif
  197232. #if defined(PNG_iCCP_SUPPORTED)
  197233. void PNGAPI
  197234. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197235. png_charp name, int compression_type,
  197236. png_charp profile, png_uint_32 proflen)
  197237. {
  197238. png_charp new_iccp_name;
  197239. png_charp new_iccp_profile;
  197240. png_debug1(1, "in %s storage function\n", "iCCP");
  197241. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197242. return;
  197243. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197244. if (new_iccp_name == NULL)
  197245. {
  197246. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197247. return;
  197248. }
  197249. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197250. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197251. if (new_iccp_profile == NULL)
  197252. {
  197253. png_free (png_ptr, new_iccp_name);
  197254. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197255. return;
  197256. }
  197257. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197258. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197259. info_ptr->iccp_proflen = proflen;
  197260. info_ptr->iccp_name = new_iccp_name;
  197261. info_ptr->iccp_profile = new_iccp_profile;
  197262. /* Compression is always zero but is here so the API and info structure
  197263. * does not have to change if we introduce multiple compression types */
  197264. info_ptr->iccp_compression = (png_byte)compression_type;
  197265. #ifdef PNG_FREE_ME_SUPPORTED
  197266. info_ptr->free_me |= PNG_FREE_ICCP;
  197267. #endif
  197268. info_ptr->valid |= PNG_INFO_iCCP;
  197269. }
  197270. #endif
  197271. #if defined(PNG_TEXT_SUPPORTED)
  197272. void PNGAPI
  197273. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197274. int num_text)
  197275. {
  197276. int ret;
  197277. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197278. if (ret)
  197279. png_error(png_ptr, "Insufficient memory to store text");
  197280. }
  197281. int /* PRIVATE */
  197282. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197283. int num_text)
  197284. {
  197285. int i;
  197286. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197287. "text" : (png_const_charp)png_ptr->chunk_name));
  197288. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197289. return(0);
  197290. /* Make sure we have enough space in the "text" array in info_struct
  197291. * to hold all of the incoming text_ptr objects.
  197292. */
  197293. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197294. {
  197295. if (info_ptr->text != NULL)
  197296. {
  197297. png_textp old_text;
  197298. int old_max;
  197299. old_max = info_ptr->max_text;
  197300. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197301. old_text = info_ptr->text;
  197302. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197303. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197304. if (info_ptr->text == NULL)
  197305. {
  197306. png_free(png_ptr, old_text);
  197307. return(1);
  197308. }
  197309. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197310. png_sizeof(png_text)));
  197311. png_free(png_ptr, old_text);
  197312. }
  197313. else
  197314. {
  197315. info_ptr->max_text = num_text + 8;
  197316. info_ptr->num_text = 0;
  197317. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197318. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197319. if (info_ptr->text == NULL)
  197320. return(1);
  197321. #ifdef PNG_FREE_ME_SUPPORTED
  197322. info_ptr->free_me |= PNG_FREE_TEXT;
  197323. #endif
  197324. }
  197325. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197326. info_ptr->max_text);
  197327. }
  197328. for (i = 0; i < num_text; i++)
  197329. {
  197330. png_size_t text_length,key_len;
  197331. png_size_t lang_len,lang_key_len;
  197332. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197333. if (text_ptr[i].key == NULL)
  197334. continue;
  197335. key_len = png_strlen(text_ptr[i].key);
  197336. if(text_ptr[i].compression <= 0)
  197337. {
  197338. lang_len = 0;
  197339. lang_key_len = 0;
  197340. }
  197341. else
  197342. #ifdef PNG_iTXt_SUPPORTED
  197343. {
  197344. /* set iTXt data */
  197345. if (text_ptr[i].lang != NULL)
  197346. lang_len = png_strlen(text_ptr[i].lang);
  197347. else
  197348. lang_len = 0;
  197349. if (text_ptr[i].lang_key != NULL)
  197350. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197351. else
  197352. lang_key_len = 0;
  197353. }
  197354. #else
  197355. {
  197356. png_warning(png_ptr, "iTXt chunk not supported.");
  197357. continue;
  197358. }
  197359. #endif
  197360. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197361. {
  197362. text_length = 0;
  197363. #ifdef PNG_iTXt_SUPPORTED
  197364. if(text_ptr[i].compression > 0)
  197365. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197366. else
  197367. #endif
  197368. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197369. }
  197370. else
  197371. {
  197372. text_length = png_strlen(text_ptr[i].text);
  197373. textp->compression = text_ptr[i].compression;
  197374. }
  197375. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197376. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197377. if (textp->key == NULL)
  197378. return(1);
  197379. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197380. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197381. (int)textp->key);
  197382. png_memcpy(textp->key, text_ptr[i].key,
  197383. (png_size_t)(key_len));
  197384. *(textp->key+key_len) = '\0';
  197385. #ifdef PNG_iTXt_SUPPORTED
  197386. if (text_ptr[i].compression > 0)
  197387. {
  197388. textp->lang=textp->key + key_len + 1;
  197389. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197390. *(textp->lang+lang_len) = '\0';
  197391. textp->lang_key=textp->lang + lang_len + 1;
  197392. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197393. *(textp->lang_key+lang_key_len) = '\0';
  197394. textp->text=textp->lang_key + lang_key_len + 1;
  197395. }
  197396. else
  197397. #endif
  197398. {
  197399. #ifdef PNG_iTXt_SUPPORTED
  197400. textp->lang=NULL;
  197401. textp->lang_key=NULL;
  197402. #endif
  197403. textp->text=textp->key + key_len + 1;
  197404. }
  197405. if(text_length)
  197406. png_memcpy(textp->text, text_ptr[i].text,
  197407. (png_size_t)(text_length));
  197408. *(textp->text+text_length) = '\0';
  197409. #ifdef PNG_iTXt_SUPPORTED
  197410. if(textp->compression > 0)
  197411. {
  197412. textp->text_length = 0;
  197413. textp->itxt_length = text_length;
  197414. }
  197415. else
  197416. #endif
  197417. {
  197418. textp->text_length = text_length;
  197419. #ifdef PNG_iTXt_SUPPORTED
  197420. textp->itxt_length = 0;
  197421. #endif
  197422. }
  197423. info_ptr->num_text++;
  197424. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197425. }
  197426. return(0);
  197427. }
  197428. #endif
  197429. #if defined(PNG_tIME_SUPPORTED)
  197430. void PNGAPI
  197431. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197432. {
  197433. png_debug1(1, "in %s storage function\n", "tIME");
  197434. if (png_ptr == NULL || info_ptr == NULL ||
  197435. (png_ptr->mode & PNG_WROTE_tIME))
  197436. return;
  197437. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197438. info_ptr->valid |= PNG_INFO_tIME;
  197439. }
  197440. #endif
  197441. #if defined(PNG_tRNS_SUPPORTED)
  197442. void PNGAPI
  197443. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197444. png_bytep trans, int num_trans, png_color_16p trans_values)
  197445. {
  197446. png_debug1(1, "in %s storage function\n", "tRNS");
  197447. if (png_ptr == NULL || info_ptr == NULL)
  197448. return;
  197449. if (trans != NULL)
  197450. {
  197451. /*
  197452. * It may not actually be necessary to set png_ptr->trans here;
  197453. * we do it for backward compatibility with the way the png_handle_tRNS
  197454. * function used to do the allocation.
  197455. */
  197456. #ifdef PNG_FREE_ME_SUPPORTED
  197457. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197458. #endif
  197459. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197460. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197461. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197462. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197463. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197464. #ifdef PNG_FREE_ME_SUPPORTED
  197465. info_ptr->free_me |= PNG_FREE_TRNS;
  197466. #else
  197467. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197468. #endif
  197469. }
  197470. if (trans_values != NULL)
  197471. {
  197472. png_memcpy(&(info_ptr->trans_values), trans_values,
  197473. png_sizeof(png_color_16));
  197474. if (num_trans == 0)
  197475. num_trans = 1;
  197476. }
  197477. info_ptr->num_trans = (png_uint_16)num_trans;
  197478. info_ptr->valid |= PNG_INFO_tRNS;
  197479. }
  197480. #endif
  197481. #if defined(PNG_sPLT_SUPPORTED)
  197482. void PNGAPI
  197483. png_set_sPLT(png_structp png_ptr,
  197484. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197485. {
  197486. png_sPLT_tp np;
  197487. int i;
  197488. if (png_ptr == NULL || info_ptr == NULL)
  197489. return;
  197490. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197491. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197492. if (np == NULL)
  197493. {
  197494. png_warning(png_ptr, "No memory for sPLT palettes.");
  197495. return;
  197496. }
  197497. png_memcpy(np, info_ptr->splt_palettes,
  197498. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197499. png_free(png_ptr, info_ptr->splt_palettes);
  197500. info_ptr->splt_palettes=NULL;
  197501. for (i = 0; i < nentries; i++)
  197502. {
  197503. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197504. png_sPLT_tp from = entries + i;
  197505. to->name = (png_charp)png_malloc_warn(png_ptr,
  197506. png_strlen(from->name) + 1);
  197507. if (to->name == NULL)
  197508. {
  197509. png_warning(png_ptr,
  197510. "Out of memory while processing sPLT chunk");
  197511. }
  197512. /* TODO: use png_malloc_warn */
  197513. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197514. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197515. from->nentries * png_sizeof(png_sPLT_entry));
  197516. /* TODO: use png_malloc_warn */
  197517. png_memcpy(to->entries, from->entries,
  197518. from->nentries * png_sizeof(png_sPLT_entry));
  197519. if (to->entries == NULL)
  197520. {
  197521. png_warning(png_ptr,
  197522. "Out of memory while processing sPLT chunk");
  197523. png_free(png_ptr,to->name);
  197524. to->name = NULL;
  197525. }
  197526. to->nentries = from->nentries;
  197527. to->depth = from->depth;
  197528. }
  197529. info_ptr->splt_palettes = np;
  197530. info_ptr->splt_palettes_num += nentries;
  197531. info_ptr->valid |= PNG_INFO_sPLT;
  197532. #ifdef PNG_FREE_ME_SUPPORTED
  197533. info_ptr->free_me |= PNG_FREE_SPLT;
  197534. #endif
  197535. }
  197536. #endif /* PNG_sPLT_SUPPORTED */
  197537. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197538. void PNGAPI
  197539. png_set_unknown_chunks(png_structp png_ptr,
  197540. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197541. {
  197542. png_unknown_chunkp np;
  197543. int i;
  197544. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197545. return;
  197546. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197547. (info_ptr->unknown_chunks_num + num_unknowns) *
  197548. png_sizeof(png_unknown_chunk));
  197549. if (np == NULL)
  197550. {
  197551. png_warning(png_ptr,
  197552. "Out of memory while processing unknown chunk.");
  197553. return;
  197554. }
  197555. png_memcpy(np, info_ptr->unknown_chunks,
  197556. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197557. png_free(png_ptr, info_ptr->unknown_chunks);
  197558. info_ptr->unknown_chunks=NULL;
  197559. for (i = 0; i < num_unknowns; i++)
  197560. {
  197561. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197562. png_unknown_chunkp from = unknowns + i;
  197563. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197564. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197565. if (to->data == NULL)
  197566. {
  197567. png_warning(png_ptr,
  197568. "Out of memory while processing unknown chunk.");
  197569. }
  197570. else
  197571. {
  197572. png_memcpy(to->data, from->data, from->size);
  197573. to->size = from->size;
  197574. /* note our location in the read or write sequence */
  197575. to->location = (png_byte)(png_ptr->mode & 0xff);
  197576. }
  197577. }
  197578. info_ptr->unknown_chunks = np;
  197579. info_ptr->unknown_chunks_num += num_unknowns;
  197580. #ifdef PNG_FREE_ME_SUPPORTED
  197581. info_ptr->free_me |= PNG_FREE_UNKN;
  197582. #endif
  197583. }
  197584. void PNGAPI
  197585. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197586. int chunk, int location)
  197587. {
  197588. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197589. (int)info_ptr->unknown_chunks_num)
  197590. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197591. }
  197592. #endif
  197593. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197594. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197595. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197596. void PNGAPI
  197597. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197598. {
  197599. /* This function is deprecated in favor of png_permit_mng_features()
  197600. and will be removed from libpng-1.3.0 */
  197601. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197602. if (png_ptr == NULL)
  197603. return;
  197604. png_ptr->mng_features_permitted = (png_byte)
  197605. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197606. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197607. }
  197608. #endif
  197609. #endif
  197610. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197611. png_uint_32 PNGAPI
  197612. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197613. {
  197614. png_debug(1, "in png_permit_mng_features\n");
  197615. if (png_ptr == NULL)
  197616. return (png_uint_32)0;
  197617. png_ptr->mng_features_permitted =
  197618. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197619. return (png_uint_32)png_ptr->mng_features_permitted;
  197620. }
  197621. #endif
  197622. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197623. void PNGAPI
  197624. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197625. chunk_list, int num_chunks)
  197626. {
  197627. png_bytep new_list, p;
  197628. int i, old_num_chunks;
  197629. if (png_ptr == NULL)
  197630. return;
  197631. if (num_chunks == 0)
  197632. {
  197633. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197634. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197635. else
  197636. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197637. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197638. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197639. else
  197640. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197641. return;
  197642. }
  197643. if (chunk_list == NULL)
  197644. return;
  197645. old_num_chunks=png_ptr->num_chunk_list;
  197646. new_list=(png_bytep)png_malloc(png_ptr,
  197647. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197648. if(png_ptr->chunk_list != NULL)
  197649. {
  197650. png_memcpy(new_list, png_ptr->chunk_list,
  197651. (png_size_t)(5*old_num_chunks));
  197652. png_free(png_ptr, png_ptr->chunk_list);
  197653. png_ptr->chunk_list=NULL;
  197654. }
  197655. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197656. (png_size_t)(5*num_chunks));
  197657. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197658. *p=(png_byte)keep;
  197659. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197660. png_ptr->chunk_list=new_list;
  197661. #ifdef PNG_FREE_ME_SUPPORTED
  197662. png_ptr->free_me |= PNG_FREE_LIST;
  197663. #endif
  197664. }
  197665. #endif
  197666. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197667. void PNGAPI
  197668. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197669. png_user_chunk_ptr read_user_chunk_fn)
  197670. {
  197671. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197672. if (png_ptr == NULL)
  197673. return;
  197674. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197675. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197676. }
  197677. #endif
  197678. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197679. void PNGAPI
  197680. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197681. {
  197682. png_debug1(1, "in %s storage function\n", "rows");
  197683. if (png_ptr == NULL || info_ptr == NULL)
  197684. return;
  197685. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197686. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197687. info_ptr->row_pointers = row_pointers;
  197688. if(row_pointers)
  197689. info_ptr->valid |= PNG_INFO_IDAT;
  197690. }
  197691. #endif
  197692. #ifdef PNG_WRITE_SUPPORTED
  197693. void PNGAPI
  197694. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197695. {
  197696. if (png_ptr == NULL)
  197697. return;
  197698. if(png_ptr->zbuf)
  197699. png_free(png_ptr, png_ptr->zbuf);
  197700. png_ptr->zbuf_size = (png_size_t)size;
  197701. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197702. png_ptr->zstream.next_out = png_ptr->zbuf;
  197703. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197704. }
  197705. #endif
  197706. void PNGAPI
  197707. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197708. {
  197709. if (png_ptr && info_ptr)
  197710. info_ptr->valid &= ~(mask);
  197711. }
  197712. #ifndef PNG_1_0_X
  197713. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197714. /* function was added to libpng 1.2.0 and should always exist by default */
  197715. void PNGAPI
  197716. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197717. {
  197718. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197719. if (png_ptr != NULL)
  197720. png_ptr->asm_flags = 0;
  197721. }
  197722. /* this function was added to libpng 1.2.0 */
  197723. void PNGAPI
  197724. png_set_mmx_thresholds (png_structp png_ptr,
  197725. png_byte,
  197726. png_uint_32)
  197727. {
  197728. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197729. if (png_ptr == NULL)
  197730. return;
  197731. }
  197732. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197733. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197734. /* this function was added to libpng 1.2.6 */
  197735. void PNGAPI
  197736. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197737. png_uint_32 user_height_max)
  197738. {
  197739. /* Images with dimensions larger than these limits will be
  197740. * rejected by png_set_IHDR(). To accept any PNG datastream
  197741. * regardless of dimensions, set both limits to 0x7ffffffL.
  197742. */
  197743. if(png_ptr == NULL) return;
  197744. png_ptr->user_width_max = user_width_max;
  197745. png_ptr->user_height_max = user_height_max;
  197746. }
  197747. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197748. #endif /* ?PNG_1_0_X */
  197749. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197750. /*** End of inlined file: pngset.c ***/
  197751. /*** Start of inlined file: pngtrans.c ***/
  197752. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197753. *
  197754. * Last changed in libpng 1.2.17 May 15, 2007
  197755. * For conditions of distribution and use, see copyright notice in png.h
  197756. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197757. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197758. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197759. */
  197760. #define PNG_INTERNAL
  197761. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197762. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197763. /* turn on BGR-to-RGB mapping */
  197764. void PNGAPI
  197765. png_set_bgr(png_structp png_ptr)
  197766. {
  197767. png_debug(1, "in png_set_bgr\n");
  197768. if(png_ptr == NULL) return;
  197769. png_ptr->transformations |= PNG_BGR;
  197770. }
  197771. #endif
  197772. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197773. /* turn on 16 bit byte swapping */
  197774. void PNGAPI
  197775. png_set_swap(png_structp png_ptr)
  197776. {
  197777. png_debug(1, "in png_set_swap\n");
  197778. if(png_ptr == NULL) return;
  197779. if (png_ptr->bit_depth == 16)
  197780. png_ptr->transformations |= PNG_SWAP_BYTES;
  197781. }
  197782. #endif
  197783. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197784. /* turn on pixel packing */
  197785. void PNGAPI
  197786. png_set_packing(png_structp png_ptr)
  197787. {
  197788. png_debug(1, "in png_set_packing\n");
  197789. if(png_ptr == NULL) return;
  197790. if (png_ptr->bit_depth < 8)
  197791. {
  197792. png_ptr->transformations |= PNG_PACK;
  197793. png_ptr->usr_bit_depth = 8;
  197794. }
  197795. }
  197796. #endif
  197797. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197798. /* turn on packed pixel swapping */
  197799. void PNGAPI
  197800. png_set_packswap(png_structp png_ptr)
  197801. {
  197802. png_debug(1, "in png_set_packswap\n");
  197803. if(png_ptr == NULL) return;
  197804. if (png_ptr->bit_depth < 8)
  197805. png_ptr->transformations |= PNG_PACKSWAP;
  197806. }
  197807. #endif
  197808. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197809. void PNGAPI
  197810. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197811. {
  197812. png_debug(1, "in png_set_shift\n");
  197813. if(png_ptr == NULL) return;
  197814. png_ptr->transformations |= PNG_SHIFT;
  197815. png_ptr->shift = *true_bits;
  197816. }
  197817. #endif
  197818. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197819. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197820. int PNGAPI
  197821. png_set_interlace_handling(png_structp png_ptr)
  197822. {
  197823. png_debug(1, "in png_set_interlace handling\n");
  197824. if (png_ptr && png_ptr->interlaced)
  197825. {
  197826. png_ptr->transformations |= PNG_INTERLACE;
  197827. return (7);
  197828. }
  197829. return (1);
  197830. }
  197831. #endif
  197832. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197833. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197834. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197835. * for 48-bit input data, as well as to avoid problems with some compilers
  197836. * that don't like bytes as parameters.
  197837. */
  197838. void PNGAPI
  197839. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197840. {
  197841. png_debug(1, "in png_set_filler\n");
  197842. if(png_ptr == NULL) return;
  197843. png_ptr->transformations |= PNG_FILLER;
  197844. png_ptr->filler = (png_byte)filler;
  197845. if (filler_loc == PNG_FILLER_AFTER)
  197846. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197847. else
  197848. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197849. /* This should probably go in the "do_read_filler" routine.
  197850. * I attempted to do that in libpng-1.0.1a but that caused problems
  197851. * so I restored it in libpng-1.0.2a
  197852. */
  197853. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197854. {
  197855. png_ptr->usr_channels = 4;
  197856. }
  197857. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197858. * a less-than-8-bit grayscale to GA? */
  197859. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197860. {
  197861. png_ptr->usr_channels = 2;
  197862. }
  197863. }
  197864. #if !defined(PNG_1_0_X)
  197865. /* Added to libpng-1.2.7 */
  197866. void PNGAPI
  197867. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197868. {
  197869. png_debug(1, "in png_set_add_alpha\n");
  197870. if(png_ptr == NULL) return;
  197871. png_set_filler(png_ptr, filler, filler_loc);
  197872. png_ptr->transformations |= PNG_ADD_ALPHA;
  197873. }
  197874. #endif
  197875. #endif
  197876. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197877. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197878. void PNGAPI
  197879. png_set_swap_alpha(png_structp png_ptr)
  197880. {
  197881. png_debug(1, "in png_set_swap_alpha\n");
  197882. if(png_ptr == NULL) return;
  197883. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197884. }
  197885. #endif
  197886. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197887. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197888. void PNGAPI
  197889. png_set_invert_alpha(png_structp png_ptr)
  197890. {
  197891. png_debug(1, "in png_set_invert_alpha\n");
  197892. if(png_ptr == NULL) return;
  197893. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197894. }
  197895. #endif
  197896. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197897. void PNGAPI
  197898. png_set_invert_mono(png_structp png_ptr)
  197899. {
  197900. png_debug(1, "in png_set_invert_mono\n");
  197901. if(png_ptr == NULL) return;
  197902. png_ptr->transformations |= PNG_INVERT_MONO;
  197903. }
  197904. /* invert monochrome grayscale data */
  197905. void /* PRIVATE */
  197906. png_do_invert(png_row_infop row_info, png_bytep row)
  197907. {
  197908. png_debug(1, "in png_do_invert\n");
  197909. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197910. * if (row_info->bit_depth == 1 &&
  197911. */
  197912. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197913. if (row == NULL || row_info == NULL)
  197914. return;
  197915. #endif
  197916. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197917. {
  197918. png_bytep rp = row;
  197919. png_uint_32 i;
  197920. png_uint_32 istop = row_info->rowbytes;
  197921. for (i = 0; i < istop; i++)
  197922. {
  197923. *rp = (png_byte)(~(*rp));
  197924. rp++;
  197925. }
  197926. }
  197927. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197928. row_info->bit_depth == 8)
  197929. {
  197930. png_bytep rp = row;
  197931. png_uint_32 i;
  197932. png_uint_32 istop = row_info->rowbytes;
  197933. for (i = 0; i < istop; i+=2)
  197934. {
  197935. *rp = (png_byte)(~(*rp));
  197936. rp+=2;
  197937. }
  197938. }
  197939. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197940. row_info->bit_depth == 16)
  197941. {
  197942. png_bytep rp = row;
  197943. png_uint_32 i;
  197944. png_uint_32 istop = row_info->rowbytes;
  197945. for (i = 0; i < istop; i+=4)
  197946. {
  197947. *rp = (png_byte)(~(*rp));
  197948. *(rp+1) = (png_byte)(~(*(rp+1)));
  197949. rp+=4;
  197950. }
  197951. }
  197952. }
  197953. #endif
  197954. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197955. /* swaps byte order on 16 bit depth images */
  197956. void /* PRIVATE */
  197957. png_do_swap(png_row_infop row_info, png_bytep row)
  197958. {
  197959. png_debug(1, "in png_do_swap\n");
  197960. if (
  197961. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197962. row != NULL && row_info != NULL &&
  197963. #endif
  197964. row_info->bit_depth == 16)
  197965. {
  197966. png_bytep rp = row;
  197967. png_uint_32 i;
  197968. png_uint_32 istop= row_info->width * row_info->channels;
  197969. for (i = 0; i < istop; i++, rp += 2)
  197970. {
  197971. png_byte t = *rp;
  197972. *rp = *(rp + 1);
  197973. *(rp + 1) = t;
  197974. }
  197975. }
  197976. }
  197977. #endif
  197978. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197979. static PNG_CONST png_byte onebppswaptable[256] = {
  197980. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197981. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197982. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197983. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197984. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197985. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197986. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197987. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197988. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197989. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197990. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197991. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197992. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197993. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197994. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197995. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197996. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197997. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197998. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197999. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198000. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198001. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198002. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198003. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198004. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198005. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198006. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198007. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198008. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198009. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198010. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198011. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198012. };
  198013. static PNG_CONST png_byte twobppswaptable[256] = {
  198014. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198015. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198016. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198017. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198018. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198019. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198020. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198021. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198022. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198023. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198024. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198025. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198026. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198027. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198028. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198029. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198030. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198031. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198032. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198033. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198034. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198035. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198036. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198037. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198038. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198039. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198040. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198041. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198042. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198043. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198044. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198045. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198046. };
  198047. static PNG_CONST png_byte fourbppswaptable[256] = {
  198048. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198049. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198050. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198051. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198052. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198053. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198054. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198055. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198056. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198057. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198058. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198059. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198060. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198061. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198062. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198063. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198064. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198065. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198066. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198067. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198068. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198069. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198070. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198071. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198072. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198073. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198074. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198075. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198076. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198077. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198078. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198079. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198080. };
  198081. /* swaps pixel packing order within bytes */
  198082. void /* PRIVATE */
  198083. png_do_packswap(png_row_infop row_info, png_bytep row)
  198084. {
  198085. png_debug(1, "in png_do_packswap\n");
  198086. if (
  198087. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198088. row != NULL && row_info != NULL &&
  198089. #endif
  198090. row_info->bit_depth < 8)
  198091. {
  198092. png_bytep rp, end, table;
  198093. end = row + row_info->rowbytes;
  198094. if (row_info->bit_depth == 1)
  198095. table = (png_bytep)onebppswaptable;
  198096. else if (row_info->bit_depth == 2)
  198097. table = (png_bytep)twobppswaptable;
  198098. else if (row_info->bit_depth == 4)
  198099. table = (png_bytep)fourbppswaptable;
  198100. else
  198101. return;
  198102. for (rp = row; rp < end; rp++)
  198103. *rp = table[*rp];
  198104. }
  198105. }
  198106. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198107. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198108. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198109. /* remove filler or alpha byte(s) */
  198110. void /* PRIVATE */
  198111. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198112. {
  198113. png_debug(1, "in png_do_strip_filler\n");
  198114. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198115. if (row != NULL && row_info != NULL)
  198116. #endif
  198117. {
  198118. png_bytep sp=row;
  198119. png_bytep dp=row;
  198120. png_uint_32 row_width=row_info->width;
  198121. png_uint_32 i;
  198122. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198123. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198124. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198125. row_info->channels == 4)
  198126. {
  198127. if (row_info->bit_depth == 8)
  198128. {
  198129. /* This converts from RGBX or RGBA to RGB */
  198130. if (flags & PNG_FLAG_FILLER_AFTER)
  198131. {
  198132. dp+=3; sp+=4;
  198133. for (i = 1; i < row_width; i++)
  198134. {
  198135. *dp++ = *sp++;
  198136. *dp++ = *sp++;
  198137. *dp++ = *sp++;
  198138. sp++;
  198139. }
  198140. }
  198141. /* This converts from XRGB or ARGB to RGB */
  198142. else
  198143. {
  198144. for (i = 0; i < row_width; i++)
  198145. {
  198146. sp++;
  198147. *dp++ = *sp++;
  198148. *dp++ = *sp++;
  198149. *dp++ = *sp++;
  198150. }
  198151. }
  198152. row_info->pixel_depth = 24;
  198153. row_info->rowbytes = row_width * 3;
  198154. }
  198155. else /* if (row_info->bit_depth == 16) */
  198156. {
  198157. if (flags & PNG_FLAG_FILLER_AFTER)
  198158. {
  198159. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198160. sp += 8; dp += 6;
  198161. for (i = 1; i < row_width; i++)
  198162. {
  198163. /* This could be (although png_memcpy is probably slower):
  198164. png_memcpy(dp, sp, 6);
  198165. sp += 8;
  198166. dp += 6;
  198167. */
  198168. *dp++ = *sp++;
  198169. *dp++ = *sp++;
  198170. *dp++ = *sp++;
  198171. *dp++ = *sp++;
  198172. *dp++ = *sp++;
  198173. *dp++ = *sp++;
  198174. sp += 2;
  198175. }
  198176. }
  198177. else
  198178. {
  198179. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198180. for (i = 0; i < row_width; i++)
  198181. {
  198182. /* This could be (although png_memcpy is probably slower):
  198183. png_memcpy(dp, sp, 6);
  198184. sp += 8;
  198185. dp += 6;
  198186. */
  198187. sp+=2;
  198188. *dp++ = *sp++;
  198189. *dp++ = *sp++;
  198190. *dp++ = *sp++;
  198191. *dp++ = *sp++;
  198192. *dp++ = *sp++;
  198193. *dp++ = *sp++;
  198194. }
  198195. }
  198196. row_info->pixel_depth = 48;
  198197. row_info->rowbytes = row_width * 6;
  198198. }
  198199. row_info->channels = 3;
  198200. }
  198201. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198202. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198203. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198204. row_info->channels == 2)
  198205. {
  198206. if (row_info->bit_depth == 8)
  198207. {
  198208. /* This converts from GX or GA to G */
  198209. if (flags & PNG_FLAG_FILLER_AFTER)
  198210. {
  198211. for (i = 0; i < row_width; i++)
  198212. {
  198213. *dp++ = *sp++;
  198214. sp++;
  198215. }
  198216. }
  198217. /* This converts from XG or AG to G */
  198218. else
  198219. {
  198220. for (i = 0; i < row_width; i++)
  198221. {
  198222. sp++;
  198223. *dp++ = *sp++;
  198224. }
  198225. }
  198226. row_info->pixel_depth = 8;
  198227. row_info->rowbytes = row_width;
  198228. }
  198229. else /* if (row_info->bit_depth == 16) */
  198230. {
  198231. if (flags & PNG_FLAG_FILLER_AFTER)
  198232. {
  198233. /* This converts from GGXX or GGAA to GG */
  198234. sp += 4; dp += 2;
  198235. for (i = 1; i < row_width; i++)
  198236. {
  198237. *dp++ = *sp++;
  198238. *dp++ = *sp++;
  198239. sp += 2;
  198240. }
  198241. }
  198242. else
  198243. {
  198244. /* This converts from XXGG or AAGG to GG */
  198245. for (i = 0; i < row_width; i++)
  198246. {
  198247. sp += 2;
  198248. *dp++ = *sp++;
  198249. *dp++ = *sp++;
  198250. }
  198251. }
  198252. row_info->pixel_depth = 16;
  198253. row_info->rowbytes = row_width * 2;
  198254. }
  198255. row_info->channels = 1;
  198256. }
  198257. if (flags & PNG_FLAG_STRIP_ALPHA)
  198258. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198259. }
  198260. }
  198261. #endif
  198262. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198263. /* swaps red and blue bytes within a pixel */
  198264. void /* PRIVATE */
  198265. png_do_bgr(png_row_infop row_info, png_bytep row)
  198266. {
  198267. png_debug(1, "in png_do_bgr\n");
  198268. if (
  198269. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198270. row != NULL && row_info != NULL &&
  198271. #endif
  198272. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198273. {
  198274. png_uint_32 row_width = row_info->width;
  198275. if (row_info->bit_depth == 8)
  198276. {
  198277. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198278. {
  198279. png_bytep rp;
  198280. png_uint_32 i;
  198281. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198282. {
  198283. png_byte save = *rp;
  198284. *rp = *(rp + 2);
  198285. *(rp + 2) = save;
  198286. }
  198287. }
  198288. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198289. {
  198290. png_bytep rp;
  198291. png_uint_32 i;
  198292. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198293. {
  198294. png_byte save = *rp;
  198295. *rp = *(rp + 2);
  198296. *(rp + 2) = save;
  198297. }
  198298. }
  198299. }
  198300. else if (row_info->bit_depth == 16)
  198301. {
  198302. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198303. {
  198304. png_bytep rp;
  198305. png_uint_32 i;
  198306. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198307. {
  198308. png_byte save = *rp;
  198309. *rp = *(rp + 4);
  198310. *(rp + 4) = save;
  198311. save = *(rp + 1);
  198312. *(rp + 1) = *(rp + 5);
  198313. *(rp + 5) = save;
  198314. }
  198315. }
  198316. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198317. {
  198318. png_bytep rp;
  198319. png_uint_32 i;
  198320. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198321. {
  198322. png_byte save = *rp;
  198323. *rp = *(rp + 4);
  198324. *(rp + 4) = save;
  198325. save = *(rp + 1);
  198326. *(rp + 1) = *(rp + 5);
  198327. *(rp + 5) = save;
  198328. }
  198329. }
  198330. }
  198331. }
  198332. }
  198333. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198334. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198335. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198336. defined(PNG_LEGACY_SUPPORTED)
  198337. void PNGAPI
  198338. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198339. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198340. {
  198341. png_debug(1, "in png_set_user_transform_info\n");
  198342. if(png_ptr == NULL) return;
  198343. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198344. png_ptr->user_transform_ptr = user_transform_ptr;
  198345. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198346. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198347. #else
  198348. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198349. png_warning(png_ptr,
  198350. "This version of libpng does not support user transform info");
  198351. #endif
  198352. }
  198353. #endif
  198354. /* This function returns a pointer to the user_transform_ptr associated with
  198355. * the user transform functions. The application should free any memory
  198356. * associated with this pointer before png_write_destroy and png_read_destroy
  198357. * are called.
  198358. */
  198359. png_voidp PNGAPI
  198360. png_get_user_transform_ptr(png_structp png_ptr)
  198361. {
  198362. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198363. if (png_ptr == NULL) return (NULL);
  198364. return ((png_voidp)png_ptr->user_transform_ptr);
  198365. #else
  198366. return (NULL);
  198367. #endif
  198368. }
  198369. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198370. /*** End of inlined file: pngtrans.c ***/
  198371. /*** Start of inlined file: pngwio.c ***/
  198372. /* pngwio.c - functions for data output
  198373. *
  198374. * Last changed in libpng 1.2.13 November 13, 2006
  198375. * For conditions of distribution and use, see copyright notice in png.h
  198376. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198377. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198378. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198379. *
  198380. * This file provides a location for all output. Users who need
  198381. * special handling are expected to write functions that have the same
  198382. * arguments as these and perform similar functions, but that possibly
  198383. * use different output methods. Note that you shouldn't change these
  198384. * functions, but rather write replacement functions and then change
  198385. * them at run time with png_set_write_fn(...).
  198386. */
  198387. #define PNG_INTERNAL
  198388. #ifdef PNG_WRITE_SUPPORTED
  198389. /* Write the data to whatever output you are using. The default routine
  198390. writes to a file pointer. Note that this routine sometimes gets called
  198391. with very small lengths, so you should implement some kind of simple
  198392. buffering if you are using unbuffered writes. This should never be asked
  198393. to write more than 64K on a 16 bit machine. */
  198394. void /* PRIVATE */
  198395. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198396. {
  198397. if (png_ptr->write_data_fn != NULL )
  198398. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198399. else
  198400. png_error(png_ptr, "Call to NULL write function");
  198401. }
  198402. #if !defined(PNG_NO_STDIO)
  198403. /* This is the function that does the actual writing of data. If you are
  198404. not writing to a standard C stream, you should create a replacement
  198405. write_data function and use it at run time with png_set_write_fn(), rather
  198406. than changing the library. */
  198407. #ifndef USE_FAR_KEYWORD
  198408. void PNGAPI
  198409. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198410. {
  198411. png_uint_32 check;
  198412. if(png_ptr == NULL) return;
  198413. #if defined(_WIN32_WCE)
  198414. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198415. check = 0;
  198416. #else
  198417. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198418. #endif
  198419. if (check != length)
  198420. png_error(png_ptr, "Write Error");
  198421. }
  198422. #else
  198423. /* this is the model-independent version. Since the standard I/O library
  198424. can't handle far buffers in the medium and small models, we have to copy
  198425. the data.
  198426. */
  198427. #define NEAR_BUF_SIZE 1024
  198428. #define MIN(a,b) (a <= b ? a : b)
  198429. void PNGAPI
  198430. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198431. {
  198432. png_uint_32 check;
  198433. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198434. png_FILE_p io_ptr;
  198435. if(png_ptr == NULL) return;
  198436. /* Check if data really is near. If so, use usual code. */
  198437. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198438. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198439. if ((png_bytep)near_data == data)
  198440. {
  198441. #if defined(_WIN32_WCE)
  198442. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198443. check = 0;
  198444. #else
  198445. check = fwrite(near_data, 1, length, io_ptr);
  198446. #endif
  198447. }
  198448. else
  198449. {
  198450. png_byte buf[NEAR_BUF_SIZE];
  198451. png_size_t written, remaining, err;
  198452. check = 0;
  198453. remaining = length;
  198454. do
  198455. {
  198456. written = MIN(NEAR_BUF_SIZE, remaining);
  198457. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198458. #if defined(_WIN32_WCE)
  198459. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198460. err = 0;
  198461. #else
  198462. err = fwrite(buf, 1, written, io_ptr);
  198463. #endif
  198464. if (err != written)
  198465. break;
  198466. else
  198467. check += err;
  198468. data += written;
  198469. remaining -= written;
  198470. }
  198471. while (remaining != 0);
  198472. }
  198473. if (check != length)
  198474. png_error(png_ptr, "Write Error");
  198475. }
  198476. #endif
  198477. #endif
  198478. /* This function is called to output any data pending writing (normally
  198479. to disk). After png_flush is called, there should be no data pending
  198480. writing in any buffers. */
  198481. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198482. void /* PRIVATE */
  198483. png_flush(png_structp png_ptr)
  198484. {
  198485. if (png_ptr->output_flush_fn != NULL)
  198486. (*(png_ptr->output_flush_fn))(png_ptr);
  198487. }
  198488. #if !defined(PNG_NO_STDIO)
  198489. void PNGAPI
  198490. png_default_flush(png_structp png_ptr)
  198491. {
  198492. #if !defined(_WIN32_WCE)
  198493. png_FILE_p io_ptr;
  198494. #endif
  198495. if(png_ptr == NULL) return;
  198496. #if !defined(_WIN32_WCE)
  198497. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198498. if (io_ptr != NULL)
  198499. fflush(io_ptr);
  198500. #endif
  198501. }
  198502. #endif
  198503. #endif
  198504. /* This function allows the application to supply new output functions for
  198505. libpng if standard C streams aren't being used.
  198506. This function takes as its arguments:
  198507. png_ptr - pointer to a png output data structure
  198508. io_ptr - pointer to user supplied structure containing info about
  198509. the output functions. May be NULL.
  198510. write_data_fn - pointer to a new output function that takes as its
  198511. arguments a pointer to a png_struct, a pointer to
  198512. data to be written, and a 32-bit unsigned int that is
  198513. the number of bytes to be written. The new write
  198514. function should call png_error(png_ptr, "Error msg")
  198515. to exit and output any fatal error messages.
  198516. flush_data_fn - pointer to a new flush function that takes as its
  198517. arguments a pointer to a png_struct. After a call to
  198518. the flush function, there should be no data in any buffers
  198519. or pending transmission. If the output method doesn't do
  198520. any buffering of ouput, a function prototype must still be
  198521. supplied although it doesn't have to do anything. If
  198522. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198523. time, output_flush_fn will be ignored, although it must be
  198524. supplied for compatibility. */
  198525. void PNGAPI
  198526. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198527. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198528. {
  198529. if(png_ptr == NULL) return;
  198530. png_ptr->io_ptr = io_ptr;
  198531. #if !defined(PNG_NO_STDIO)
  198532. if (write_data_fn != NULL)
  198533. png_ptr->write_data_fn = write_data_fn;
  198534. else
  198535. png_ptr->write_data_fn = png_default_write_data;
  198536. #else
  198537. png_ptr->write_data_fn = write_data_fn;
  198538. #endif
  198539. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198540. #if !defined(PNG_NO_STDIO)
  198541. if (output_flush_fn != NULL)
  198542. png_ptr->output_flush_fn = output_flush_fn;
  198543. else
  198544. png_ptr->output_flush_fn = png_default_flush;
  198545. #else
  198546. png_ptr->output_flush_fn = output_flush_fn;
  198547. #endif
  198548. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198549. /* It is an error to read while writing a png file */
  198550. if (png_ptr->read_data_fn != NULL)
  198551. {
  198552. png_ptr->read_data_fn = NULL;
  198553. png_warning(png_ptr,
  198554. "Attempted to set both read_data_fn and write_data_fn in");
  198555. png_warning(png_ptr,
  198556. "the same structure. Resetting read_data_fn to NULL.");
  198557. }
  198558. }
  198559. #if defined(USE_FAR_KEYWORD)
  198560. #if defined(_MSC_VER)
  198561. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198562. {
  198563. void *near_ptr;
  198564. void FAR *far_ptr;
  198565. FP_OFF(near_ptr) = FP_OFF(ptr);
  198566. far_ptr = (void FAR *)near_ptr;
  198567. if(check != 0)
  198568. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198569. png_error(png_ptr,"segment lost in conversion");
  198570. return(near_ptr);
  198571. }
  198572. # else
  198573. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198574. {
  198575. void *near_ptr;
  198576. void FAR *far_ptr;
  198577. near_ptr = (void FAR *)ptr;
  198578. far_ptr = (void FAR *)near_ptr;
  198579. if(check != 0)
  198580. if(far_ptr != ptr)
  198581. png_error(png_ptr,"segment lost in conversion");
  198582. return(near_ptr);
  198583. }
  198584. # endif
  198585. # endif
  198586. #endif /* PNG_WRITE_SUPPORTED */
  198587. /*** End of inlined file: pngwio.c ***/
  198588. /*** Start of inlined file: pngwrite.c ***/
  198589. /* pngwrite.c - general routines to write a PNG file
  198590. *
  198591. * Last changed in libpng 1.2.15 January 5, 2007
  198592. * For conditions of distribution and use, see copyright notice in png.h
  198593. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198594. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198595. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198596. */
  198597. /* get internal access to png.h */
  198598. #define PNG_INTERNAL
  198599. #ifdef PNG_WRITE_SUPPORTED
  198600. /* Writes all the PNG information. This is the suggested way to use the
  198601. * library. If you have a new chunk to add, make a function to write it,
  198602. * and put it in the correct location here. If you want the chunk written
  198603. * after the image data, put it in png_write_end(). I strongly encourage
  198604. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198605. * the chunk, as that will keep the code from breaking if you want to just
  198606. * write a plain PNG file. If you have long comments, I suggest writing
  198607. * them in png_write_end(), and compressing them.
  198608. */
  198609. void PNGAPI
  198610. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198611. {
  198612. png_debug(1, "in png_write_info_before_PLTE\n");
  198613. if (png_ptr == NULL || info_ptr == NULL)
  198614. return;
  198615. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198616. {
  198617. png_write_sig(png_ptr); /* write PNG signature */
  198618. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198619. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198620. {
  198621. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198622. png_ptr->mng_features_permitted=0;
  198623. }
  198624. #endif
  198625. /* write IHDR information. */
  198626. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198627. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198628. info_ptr->filter_type,
  198629. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198630. info_ptr->interlace_type);
  198631. #else
  198632. 0);
  198633. #endif
  198634. /* the rest of these check to see if the valid field has the appropriate
  198635. flag set, and if it does, writes the chunk. */
  198636. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198637. if (info_ptr->valid & PNG_INFO_gAMA)
  198638. {
  198639. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198640. png_write_gAMA(png_ptr, info_ptr->gamma);
  198641. #else
  198642. #ifdef PNG_FIXED_POINT_SUPPORTED
  198643. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198644. # endif
  198645. #endif
  198646. }
  198647. #endif
  198648. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198649. if (info_ptr->valid & PNG_INFO_sRGB)
  198650. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198651. #endif
  198652. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198653. if (info_ptr->valid & PNG_INFO_iCCP)
  198654. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198655. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198656. #endif
  198657. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198658. if (info_ptr->valid & PNG_INFO_sBIT)
  198659. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198660. #endif
  198661. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198662. if (info_ptr->valid & PNG_INFO_cHRM)
  198663. {
  198664. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198665. png_write_cHRM(png_ptr,
  198666. info_ptr->x_white, info_ptr->y_white,
  198667. info_ptr->x_red, info_ptr->y_red,
  198668. info_ptr->x_green, info_ptr->y_green,
  198669. info_ptr->x_blue, info_ptr->y_blue);
  198670. #else
  198671. # ifdef PNG_FIXED_POINT_SUPPORTED
  198672. png_write_cHRM_fixed(png_ptr,
  198673. info_ptr->int_x_white, info_ptr->int_y_white,
  198674. info_ptr->int_x_red, info_ptr->int_y_red,
  198675. info_ptr->int_x_green, info_ptr->int_y_green,
  198676. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198677. # endif
  198678. #endif
  198679. }
  198680. #endif
  198681. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198682. if (info_ptr->unknown_chunks_num)
  198683. {
  198684. png_unknown_chunk *up;
  198685. png_debug(5, "writing extra chunks\n");
  198686. for (up = info_ptr->unknown_chunks;
  198687. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198688. up++)
  198689. {
  198690. int keep=png_handle_as_unknown(png_ptr, up->name);
  198691. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198692. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198693. !(up->location & PNG_HAVE_IDAT) &&
  198694. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198695. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198696. {
  198697. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198698. }
  198699. }
  198700. }
  198701. #endif
  198702. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198703. }
  198704. }
  198705. void PNGAPI
  198706. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198707. {
  198708. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198709. int i;
  198710. #endif
  198711. png_debug(1, "in png_write_info\n");
  198712. if (png_ptr == NULL || info_ptr == NULL)
  198713. return;
  198714. png_write_info_before_PLTE(png_ptr, info_ptr);
  198715. if (info_ptr->valid & PNG_INFO_PLTE)
  198716. png_write_PLTE(png_ptr, info_ptr->palette,
  198717. (png_uint_32)info_ptr->num_palette);
  198718. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198719. png_error(png_ptr, "Valid palette required for paletted images");
  198720. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198721. if (info_ptr->valid & PNG_INFO_tRNS)
  198722. {
  198723. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198724. /* invert the alpha channel (in tRNS) */
  198725. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198726. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198727. {
  198728. int j;
  198729. for (j=0; j<(int)info_ptr->num_trans; j++)
  198730. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198731. }
  198732. #endif
  198733. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198734. info_ptr->num_trans, info_ptr->color_type);
  198735. }
  198736. #endif
  198737. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198738. if (info_ptr->valid & PNG_INFO_bKGD)
  198739. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198740. #endif
  198741. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198742. if (info_ptr->valid & PNG_INFO_hIST)
  198743. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198744. #endif
  198745. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198746. if (info_ptr->valid & PNG_INFO_oFFs)
  198747. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198748. info_ptr->offset_unit_type);
  198749. #endif
  198750. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198751. if (info_ptr->valid & PNG_INFO_pCAL)
  198752. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198753. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198754. info_ptr->pcal_units, info_ptr->pcal_params);
  198755. #endif
  198756. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198757. if (info_ptr->valid & PNG_INFO_sCAL)
  198758. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198759. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198760. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198761. #else
  198762. #ifdef PNG_FIXED_POINT_SUPPORTED
  198763. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198764. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198765. #else
  198766. png_warning(png_ptr,
  198767. "png_write_sCAL not supported; sCAL chunk not written.");
  198768. #endif
  198769. #endif
  198770. #endif
  198771. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198772. if (info_ptr->valid & PNG_INFO_pHYs)
  198773. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198774. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198775. #endif
  198776. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198777. if (info_ptr->valid & PNG_INFO_tIME)
  198778. {
  198779. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198780. png_ptr->mode |= PNG_WROTE_tIME;
  198781. }
  198782. #endif
  198783. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198784. if (info_ptr->valid & PNG_INFO_sPLT)
  198785. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198786. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198787. #endif
  198788. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198789. /* Check to see if we need to write text chunks */
  198790. for (i = 0; i < info_ptr->num_text; i++)
  198791. {
  198792. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198793. info_ptr->text[i].compression);
  198794. /* an internationalized chunk? */
  198795. if (info_ptr->text[i].compression > 0)
  198796. {
  198797. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198798. /* write international chunk */
  198799. png_write_iTXt(png_ptr,
  198800. info_ptr->text[i].compression,
  198801. info_ptr->text[i].key,
  198802. info_ptr->text[i].lang,
  198803. info_ptr->text[i].lang_key,
  198804. info_ptr->text[i].text);
  198805. #else
  198806. png_warning(png_ptr, "Unable to write international text");
  198807. #endif
  198808. /* Mark this chunk as written */
  198809. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198810. }
  198811. /* If we want a compressed text chunk */
  198812. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198813. {
  198814. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198815. /* write compressed chunk */
  198816. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198817. info_ptr->text[i].text, 0,
  198818. info_ptr->text[i].compression);
  198819. #else
  198820. png_warning(png_ptr, "Unable to write compressed text");
  198821. #endif
  198822. /* Mark this chunk as written */
  198823. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198824. }
  198825. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198826. {
  198827. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198828. /* write uncompressed chunk */
  198829. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198830. info_ptr->text[i].text,
  198831. 0);
  198832. #else
  198833. png_warning(png_ptr, "Unable to write uncompressed text");
  198834. #endif
  198835. /* Mark this chunk as written */
  198836. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198837. }
  198838. }
  198839. #endif
  198840. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198841. if (info_ptr->unknown_chunks_num)
  198842. {
  198843. png_unknown_chunk *up;
  198844. png_debug(5, "writing extra chunks\n");
  198845. for (up = info_ptr->unknown_chunks;
  198846. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198847. up++)
  198848. {
  198849. int keep=png_handle_as_unknown(png_ptr, up->name);
  198850. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198851. up->location && (up->location & PNG_HAVE_PLTE) &&
  198852. !(up->location & PNG_HAVE_IDAT) &&
  198853. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198854. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198855. {
  198856. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198857. }
  198858. }
  198859. }
  198860. #endif
  198861. }
  198862. /* Writes the end of the PNG file. If you don't want to write comments or
  198863. * time information, you can pass NULL for info. If you already wrote these
  198864. * in png_write_info(), do not write them again here. If you have long
  198865. * comments, I suggest writing them here, and compressing them.
  198866. */
  198867. void PNGAPI
  198868. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198869. {
  198870. png_debug(1, "in png_write_end\n");
  198871. if (png_ptr == NULL)
  198872. return;
  198873. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198874. png_error(png_ptr, "No IDATs written into file");
  198875. /* see if user wants us to write information chunks */
  198876. if (info_ptr != NULL)
  198877. {
  198878. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198879. int i; /* local index variable */
  198880. #endif
  198881. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198882. /* check to see if user has supplied a time chunk */
  198883. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198884. !(png_ptr->mode & PNG_WROTE_tIME))
  198885. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198886. #endif
  198887. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198888. /* loop through comment chunks */
  198889. for (i = 0; i < info_ptr->num_text; i++)
  198890. {
  198891. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198892. info_ptr->text[i].compression);
  198893. /* an internationalized chunk? */
  198894. if (info_ptr->text[i].compression > 0)
  198895. {
  198896. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198897. /* write international chunk */
  198898. png_write_iTXt(png_ptr,
  198899. info_ptr->text[i].compression,
  198900. info_ptr->text[i].key,
  198901. info_ptr->text[i].lang,
  198902. info_ptr->text[i].lang_key,
  198903. info_ptr->text[i].text);
  198904. #else
  198905. png_warning(png_ptr, "Unable to write international text");
  198906. #endif
  198907. /* Mark this chunk as written */
  198908. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198909. }
  198910. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198911. {
  198912. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198913. /* write compressed chunk */
  198914. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198915. info_ptr->text[i].text, 0,
  198916. info_ptr->text[i].compression);
  198917. #else
  198918. png_warning(png_ptr, "Unable to write compressed text");
  198919. #endif
  198920. /* Mark this chunk as written */
  198921. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198922. }
  198923. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198924. {
  198925. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198926. /* write uncompressed chunk */
  198927. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198928. info_ptr->text[i].text, 0);
  198929. #else
  198930. png_warning(png_ptr, "Unable to write uncompressed text");
  198931. #endif
  198932. /* Mark this chunk as written */
  198933. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198934. }
  198935. }
  198936. #endif
  198937. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198938. if (info_ptr->unknown_chunks_num)
  198939. {
  198940. png_unknown_chunk *up;
  198941. png_debug(5, "writing extra chunks\n");
  198942. for (up = info_ptr->unknown_chunks;
  198943. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198944. up++)
  198945. {
  198946. int keep=png_handle_as_unknown(png_ptr, up->name);
  198947. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198948. up->location && (up->location & PNG_AFTER_IDAT) &&
  198949. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198950. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198951. {
  198952. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198953. }
  198954. }
  198955. }
  198956. #endif
  198957. }
  198958. png_ptr->mode |= PNG_AFTER_IDAT;
  198959. /* write end of PNG file */
  198960. png_write_IEND(png_ptr);
  198961. }
  198962. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198963. #if !defined(_WIN32_WCE)
  198964. /* "time.h" functions are not supported on WindowsCE */
  198965. void PNGAPI
  198966. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198967. {
  198968. png_debug(1, "in png_convert_from_struct_tm\n");
  198969. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198970. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198971. ptime->day = (png_byte)ttime->tm_mday;
  198972. ptime->hour = (png_byte)ttime->tm_hour;
  198973. ptime->minute = (png_byte)ttime->tm_min;
  198974. ptime->second = (png_byte)ttime->tm_sec;
  198975. }
  198976. void PNGAPI
  198977. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198978. {
  198979. struct tm *tbuf;
  198980. png_debug(1, "in png_convert_from_time_t\n");
  198981. tbuf = gmtime(&ttime);
  198982. png_convert_from_struct_tm(ptime, tbuf);
  198983. }
  198984. #endif
  198985. #endif
  198986. /* Initialize png_ptr structure, and allocate any memory needed */
  198987. png_structp PNGAPI
  198988. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198989. png_error_ptr error_fn, png_error_ptr warn_fn)
  198990. {
  198991. #ifdef PNG_USER_MEM_SUPPORTED
  198992. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198993. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198994. }
  198995. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198996. png_structp PNGAPI
  198997. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198998. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198999. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199000. {
  199001. #endif /* PNG_USER_MEM_SUPPORTED */
  199002. png_structp png_ptr;
  199003. #ifdef PNG_SETJMP_SUPPORTED
  199004. #ifdef USE_FAR_KEYWORD
  199005. jmp_buf jmpbuf;
  199006. #endif
  199007. #endif
  199008. int i;
  199009. png_debug(1, "in png_create_write_struct\n");
  199010. #ifdef PNG_USER_MEM_SUPPORTED
  199011. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199012. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199013. #else
  199014. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199015. #endif /* PNG_USER_MEM_SUPPORTED */
  199016. if (png_ptr == NULL)
  199017. return (NULL);
  199018. /* added at libpng-1.2.6 */
  199019. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199020. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199021. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199022. #endif
  199023. #ifdef PNG_SETJMP_SUPPORTED
  199024. #ifdef USE_FAR_KEYWORD
  199025. if (setjmp(jmpbuf))
  199026. #else
  199027. if (setjmp(png_ptr->jmpbuf))
  199028. #endif
  199029. {
  199030. png_free(png_ptr, png_ptr->zbuf);
  199031. png_ptr->zbuf=NULL;
  199032. png_destroy_struct(png_ptr);
  199033. return (NULL);
  199034. }
  199035. #ifdef USE_FAR_KEYWORD
  199036. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199037. #endif
  199038. #endif
  199039. #ifdef PNG_USER_MEM_SUPPORTED
  199040. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199041. #endif /* PNG_USER_MEM_SUPPORTED */
  199042. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199043. i=0;
  199044. do
  199045. {
  199046. if(user_png_ver[i] != png_libpng_ver[i])
  199047. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199048. } while (png_libpng_ver[i++]);
  199049. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199050. {
  199051. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199052. * we must recompile any applications that use any older library version.
  199053. * For versions after libpng 1.0, we will be compatible, so we need
  199054. * only check the first digit.
  199055. */
  199056. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199057. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199058. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199059. {
  199060. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199061. char msg[80];
  199062. if (user_png_ver)
  199063. {
  199064. png_snprintf(msg, 80,
  199065. "Application was compiled with png.h from libpng-%.20s",
  199066. user_png_ver);
  199067. png_warning(png_ptr, msg);
  199068. }
  199069. png_snprintf(msg, 80,
  199070. "Application is running with png.c from libpng-%.20s",
  199071. png_libpng_ver);
  199072. png_warning(png_ptr, msg);
  199073. #endif
  199074. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199075. png_ptr->flags=0;
  199076. #endif
  199077. png_error(png_ptr,
  199078. "Incompatible libpng version in application and library");
  199079. }
  199080. }
  199081. /* initialize zbuf - compression buffer */
  199082. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199083. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199084. (png_uint_32)png_ptr->zbuf_size);
  199085. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199086. png_flush_ptr_NULL);
  199087. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199088. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199089. 1, png_doublep_NULL, png_doublep_NULL);
  199090. #endif
  199091. #ifdef PNG_SETJMP_SUPPORTED
  199092. /* Applications that neglect to set up their own setjmp() and then encounter
  199093. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199094. abort instead of returning. */
  199095. #ifdef USE_FAR_KEYWORD
  199096. if (setjmp(jmpbuf))
  199097. PNG_ABORT();
  199098. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199099. #else
  199100. if (setjmp(png_ptr->jmpbuf))
  199101. PNG_ABORT();
  199102. #endif
  199103. #endif
  199104. return (png_ptr);
  199105. }
  199106. /* Initialize png_ptr structure, and allocate any memory needed */
  199107. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199108. /* Deprecated. */
  199109. #undef png_write_init
  199110. void PNGAPI
  199111. png_write_init(png_structp png_ptr)
  199112. {
  199113. /* We only come here via pre-1.0.7-compiled applications */
  199114. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199115. }
  199116. void PNGAPI
  199117. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199118. png_size_t png_struct_size, png_size_t png_info_size)
  199119. {
  199120. /* We only come here via pre-1.0.12-compiled applications */
  199121. if(png_ptr == NULL) return;
  199122. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199123. if(png_sizeof(png_struct) > png_struct_size ||
  199124. png_sizeof(png_info) > png_info_size)
  199125. {
  199126. char msg[80];
  199127. png_ptr->warning_fn=NULL;
  199128. if (user_png_ver)
  199129. {
  199130. png_snprintf(msg, 80,
  199131. "Application was compiled with png.h from libpng-%.20s",
  199132. user_png_ver);
  199133. png_warning(png_ptr, msg);
  199134. }
  199135. png_snprintf(msg, 80,
  199136. "Application is running with png.c from libpng-%.20s",
  199137. png_libpng_ver);
  199138. png_warning(png_ptr, msg);
  199139. }
  199140. #endif
  199141. if(png_sizeof(png_struct) > png_struct_size)
  199142. {
  199143. png_ptr->error_fn=NULL;
  199144. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199145. png_ptr->flags=0;
  199146. #endif
  199147. png_error(png_ptr,
  199148. "The png struct allocated by the application for writing is too small.");
  199149. }
  199150. if(png_sizeof(png_info) > png_info_size)
  199151. {
  199152. png_ptr->error_fn=NULL;
  199153. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199154. png_ptr->flags=0;
  199155. #endif
  199156. png_error(png_ptr,
  199157. "The info struct allocated by the application for writing is too small.");
  199158. }
  199159. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199160. }
  199161. #endif /* PNG_1_0_X || PNG_1_2_X */
  199162. void PNGAPI
  199163. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199164. png_size_t png_struct_size)
  199165. {
  199166. png_structp png_ptr=*ptr_ptr;
  199167. #ifdef PNG_SETJMP_SUPPORTED
  199168. jmp_buf tmp_jmp; /* to save current jump buffer */
  199169. #endif
  199170. int i = 0;
  199171. if (png_ptr == NULL)
  199172. return;
  199173. do
  199174. {
  199175. if (user_png_ver[i] != png_libpng_ver[i])
  199176. {
  199177. #ifdef PNG_LEGACY_SUPPORTED
  199178. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199179. #else
  199180. png_ptr->warning_fn=NULL;
  199181. png_warning(png_ptr,
  199182. "Application uses deprecated png_write_init() and should be recompiled.");
  199183. break;
  199184. #endif
  199185. }
  199186. } while (png_libpng_ver[i++]);
  199187. png_debug(1, "in png_write_init_3\n");
  199188. #ifdef PNG_SETJMP_SUPPORTED
  199189. /* save jump buffer and error functions */
  199190. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199191. #endif
  199192. if (png_sizeof(png_struct) > png_struct_size)
  199193. {
  199194. png_destroy_struct(png_ptr);
  199195. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199196. *ptr_ptr = png_ptr;
  199197. }
  199198. /* reset all variables to 0 */
  199199. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199200. /* added at libpng-1.2.6 */
  199201. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199202. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199203. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199204. #endif
  199205. #ifdef PNG_SETJMP_SUPPORTED
  199206. /* restore jump buffer */
  199207. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199208. #endif
  199209. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199210. png_flush_ptr_NULL);
  199211. /* initialize zbuf - compression buffer */
  199212. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199213. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199214. (png_uint_32)png_ptr->zbuf_size);
  199215. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199216. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199217. 1, png_doublep_NULL, png_doublep_NULL);
  199218. #endif
  199219. }
  199220. /* Write a few rows of image data. If the image is interlaced,
  199221. * either you will have to write the 7 sub images, or, if you
  199222. * have called png_set_interlace_handling(), you will have to
  199223. * "write" the image seven times.
  199224. */
  199225. void PNGAPI
  199226. png_write_rows(png_structp png_ptr, png_bytepp row,
  199227. png_uint_32 num_rows)
  199228. {
  199229. png_uint_32 i; /* row counter */
  199230. png_bytepp rp; /* row pointer */
  199231. png_debug(1, "in png_write_rows\n");
  199232. if (png_ptr == NULL)
  199233. return;
  199234. /* loop through the rows */
  199235. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199236. {
  199237. png_write_row(png_ptr, *rp);
  199238. }
  199239. }
  199240. /* Write the image. You only need to call this function once, even
  199241. * if you are writing an interlaced image.
  199242. */
  199243. void PNGAPI
  199244. png_write_image(png_structp png_ptr, png_bytepp image)
  199245. {
  199246. png_uint_32 i; /* row index */
  199247. int pass, num_pass; /* pass variables */
  199248. png_bytepp rp; /* points to current row */
  199249. if (png_ptr == NULL)
  199250. return;
  199251. png_debug(1, "in png_write_image\n");
  199252. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199253. /* intialize interlace handling. If image is not interlaced,
  199254. this will set pass to 1 */
  199255. num_pass = png_set_interlace_handling(png_ptr);
  199256. #else
  199257. num_pass = 1;
  199258. #endif
  199259. /* loop through passes */
  199260. for (pass = 0; pass < num_pass; pass++)
  199261. {
  199262. /* loop through image */
  199263. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199264. {
  199265. png_write_row(png_ptr, *rp);
  199266. }
  199267. }
  199268. }
  199269. /* called by user to write a row of image data */
  199270. void PNGAPI
  199271. png_write_row(png_structp png_ptr, png_bytep row)
  199272. {
  199273. if (png_ptr == NULL)
  199274. return;
  199275. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199276. png_ptr->row_number, png_ptr->pass);
  199277. /* initialize transformations and other stuff if first time */
  199278. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199279. {
  199280. /* make sure we wrote the header info */
  199281. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199282. png_error(png_ptr,
  199283. "png_write_info was never called before png_write_row.");
  199284. /* check for transforms that have been set but were defined out */
  199285. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199286. if (png_ptr->transformations & PNG_INVERT_MONO)
  199287. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199288. #endif
  199289. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199290. if (png_ptr->transformations & PNG_FILLER)
  199291. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199292. #endif
  199293. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199294. if (png_ptr->transformations & PNG_PACKSWAP)
  199295. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199296. #endif
  199297. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199298. if (png_ptr->transformations & PNG_PACK)
  199299. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199300. #endif
  199301. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199302. if (png_ptr->transformations & PNG_SHIFT)
  199303. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199304. #endif
  199305. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199306. if (png_ptr->transformations & PNG_BGR)
  199307. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199308. #endif
  199309. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199310. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199311. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199312. #endif
  199313. png_write_start_row(png_ptr);
  199314. }
  199315. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199316. /* if interlaced and not interested in row, return */
  199317. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199318. {
  199319. switch (png_ptr->pass)
  199320. {
  199321. case 0:
  199322. if (png_ptr->row_number & 0x07)
  199323. {
  199324. png_write_finish_row(png_ptr);
  199325. return;
  199326. }
  199327. break;
  199328. case 1:
  199329. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199330. {
  199331. png_write_finish_row(png_ptr);
  199332. return;
  199333. }
  199334. break;
  199335. case 2:
  199336. if ((png_ptr->row_number & 0x07) != 4)
  199337. {
  199338. png_write_finish_row(png_ptr);
  199339. return;
  199340. }
  199341. break;
  199342. case 3:
  199343. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199344. {
  199345. png_write_finish_row(png_ptr);
  199346. return;
  199347. }
  199348. break;
  199349. case 4:
  199350. if ((png_ptr->row_number & 0x03) != 2)
  199351. {
  199352. png_write_finish_row(png_ptr);
  199353. return;
  199354. }
  199355. break;
  199356. case 5:
  199357. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199358. {
  199359. png_write_finish_row(png_ptr);
  199360. return;
  199361. }
  199362. break;
  199363. case 6:
  199364. if (!(png_ptr->row_number & 0x01))
  199365. {
  199366. png_write_finish_row(png_ptr);
  199367. return;
  199368. }
  199369. break;
  199370. }
  199371. }
  199372. #endif
  199373. /* set up row info for transformations */
  199374. png_ptr->row_info.color_type = png_ptr->color_type;
  199375. png_ptr->row_info.width = png_ptr->usr_width;
  199376. png_ptr->row_info.channels = png_ptr->usr_channels;
  199377. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199378. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199379. png_ptr->row_info.channels);
  199380. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199381. png_ptr->row_info.width);
  199382. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199383. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199384. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199385. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199386. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199387. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199388. /* Copy user's row into buffer, leaving room for filter byte. */
  199389. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199390. png_ptr->row_info.rowbytes);
  199391. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199392. /* handle interlacing */
  199393. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199394. (png_ptr->transformations & PNG_INTERLACE))
  199395. {
  199396. png_do_write_interlace(&(png_ptr->row_info),
  199397. png_ptr->row_buf + 1, png_ptr->pass);
  199398. /* this should always get caught above, but still ... */
  199399. if (!(png_ptr->row_info.width))
  199400. {
  199401. png_write_finish_row(png_ptr);
  199402. return;
  199403. }
  199404. }
  199405. #endif
  199406. /* handle other transformations */
  199407. if (png_ptr->transformations)
  199408. png_do_write_transformations(png_ptr);
  199409. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199410. /* Write filter_method 64 (intrapixel differencing) only if
  199411. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199412. * 2. Libpng did not write a PNG signature (this filter_method is only
  199413. * used in PNG datastreams that are embedded in MNG datastreams) and
  199414. * 3. The application called png_permit_mng_features with a mask that
  199415. * included PNG_FLAG_MNG_FILTER_64 and
  199416. * 4. The filter_method is 64 and
  199417. * 5. The color_type is RGB or RGBA
  199418. */
  199419. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199420. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199421. {
  199422. /* Intrapixel differencing */
  199423. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199424. }
  199425. #endif
  199426. /* Find a filter if necessary, filter the row and write it out. */
  199427. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199428. if (png_ptr->write_row_fn != NULL)
  199429. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199430. }
  199431. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199432. /* Set the automatic flush interval or 0 to turn flushing off */
  199433. void PNGAPI
  199434. png_set_flush(png_structp png_ptr, int nrows)
  199435. {
  199436. png_debug(1, "in png_set_flush\n");
  199437. if (png_ptr == NULL)
  199438. return;
  199439. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199440. }
  199441. /* flush the current output buffers now */
  199442. void PNGAPI
  199443. png_write_flush(png_structp png_ptr)
  199444. {
  199445. int wrote_IDAT;
  199446. png_debug(1, "in png_write_flush\n");
  199447. if (png_ptr == NULL)
  199448. return;
  199449. /* We have already written out all of the data */
  199450. if (png_ptr->row_number >= png_ptr->num_rows)
  199451. return;
  199452. do
  199453. {
  199454. int ret;
  199455. /* compress the data */
  199456. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199457. wrote_IDAT = 0;
  199458. /* check for compression errors */
  199459. if (ret != Z_OK)
  199460. {
  199461. if (png_ptr->zstream.msg != NULL)
  199462. png_error(png_ptr, png_ptr->zstream.msg);
  199463. else
  199464. png_error(png_ptr, "zlib error");
  199465. }
  199466. if (!(png_ptr->zstream.avail_out))
  199467. {
  199468. /* write the IDAT and reset the zlib output buffer */
  199469. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199470. png_ptr->zbuf_size);
  199471. png_ptr->zstream.next_out = png_ptr->zbuf;
  199472. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199473. wrote_IDAT = 1;
  199474. }
  199475. } while(wrote_IDAT == 1);
  199476. /* If there is any data left to be output, write it into a new IDAT */
  199477. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199478. {
  199479. /* write the IDAT and reset the zlib output buffer */
  199480. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199481. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199482. png_ptr->zstream.next_out = png_ptr->zbuf;
  199483. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199484. }
  199485. png_ptr->flush_rows = 0;
  199486. png_flush(png_ptr);
  199487. }
  199488. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199489. /* free all memory used by the write */
  199490. void PNGAPI
  199491. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199492. {
  199493. png_structp png_ptr = NULL;
  199494. png_infop info_ptr = NULL;
  199495. #ifdef PNG_USER_MEM_SUPPORTED
  199496. png_free_ptr free_fn = NULL;
  199497. png_voidp mem_ptr = NULL;
  199498. #endif
  199499. png_debug(1, "in png_destroy_write_struct\n");
  199500. if (png_ptr_ptr != NULL)
  199501. {
  199502. png_ptr = *png_ptr_ptr;
  199503. #ifdef PNG_USER_MEM_SUPPORTED
  199504. free_fn = png_ptr->free_fn;
  199505. mem_ptr = png_ptr->mem_ptr;
  199506. #endif
  199507. }
  199508. if (info_ptr_ptr != NULL)
  199509. info_ptr = *info_ptr_ptr;
  199510. if (info_ptr != NULL)
  199511. {
  199512. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199513. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199514. if (png_ptr->num_chunk_list)
  199515. {
  199516. png_free(png_ptr, png_ptr->chunk_list);
  199517. png_ptr->chunk_list=NULL;
  199518. png_ptr->num_chunk_list=0;
  199519. }
  199520. #endif
  199521. #ifdef PNG_USER_MEM_SUPPORTED
  199522. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199523. (png_voidp)mem_ptr);
  199524. #else
  199525. png_destroy_struct((png_voidp)info_ptr);
  199526. #endif
  199527. *info_ptr_ptr = NULL;
  199528. }
  199529. if (png_ptr != NULL)
  199530. {
  199531. png_write_destroy(png_ptr);
  199532. #ifdef PNG_USER_MEM_SUPPORTED
  199533. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199534. (png_voidp)mem_ptr);
  199535. #else
  199536. png_destroy_struct((png_voidp)png_ptr);
  199537. #endif
  199538. *png_ptr_ptr = NULL;
  199539. }
  199540. }
  199541. /* Free any memory used in png_ptr struct (old method) */
  199542. void /* PRIVATE */
  199543. png_write_destroy(png_structp png_ptr)
  199544. {
  199545. #ifdef PNG_SETJMP_SUPPORTED
  199546. jmp_buf tmp_jmp; /* save jump buffer */
  199547. #endif
  199548. png_error_ptr error_fn;
  199549. png_error_ptr warning_fn;
  199550. png_voidp error_ptr;
  199551. #ifdef PNG_USER_MEM_SUPPORTED
  199552. png_free_ptr free_fn;
  199553. #endif
  199554. png_debug(1, "in png_write_destroy\n");
  199555. /* free any memory zlib uses */
  199556. deflateEnd(&png_ptr->zstream);
  199557. /* free our memory. png_free checks NULL for us. */
  199558. png_free(png_ptr, png_ptr->zbuf);
  199559. png_free(png_ptr, png_ptr->row_buf);
  199560. png_free(png_ptr, png_ptr->prev_row);
  199561. png_free(png_ptr, png_ptr->sub_row);
  199562. png_free(png_ptr, png_ptr->up_row);
  199563. png_free(png_ptr, png_ptr->avg_row);
  199564. png_free(png_ptr, png_ptr->paeth_row);
  199565. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199566. png_free(png_ptr, png_ptr->time_buffer);
  199567. #endif
  199568. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199569. png_free(png_ptr, png_ptr->prev_filters);
  199570. png_free(png_ptr, png_ptr->filter_weights);
  199571. png_free(png_ptr, png_ptr->inv_filter_weights);
  199572. png_free(png_ptr, png_ptr->filter_costs);
  199573. png_free(png_ptr, png_ptr->inv_filter_costs);
  199574. #endif
  199575. #ifdef PNG_SETJMP_SUPPORTED
  199576. /* reset structure */
  199577. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199578. #endif
  199579. error_fn = png_ptr->error_fn;
  199580. warning_fn = png_ptr->warning_fn;
  199581. error_ptr = png_ptr->error_ptr;
  199582. #ifdef PNG_USER_MEM_SUPPORTED
  199583. free_fn = png_ptr->free_fn;
  199584. #endif
  199585. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199586. png_ptr->error_fn = error_fn;
  199587. png_ptr->warning_fn = warning_fn;
  199588. png_ptr->error_ptr = error_ptr;
  199589. #ifdef PNG_USER_MEM_SUPPORTED
  199590. png_ptr->free_fn = free_fn;
  199591. #endif
  199592. #ifdef PNG_SETJMP_SUPPORTED
  199593. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199594. #endif
  199595. }
  199596. /* Allow the application to select one or more row filters to use. */
  199597. void PNGAPI
  199598. png_set_filter(png_structp png_ptr, int method, int filters)
  199599. {
  199600. png_debug(1, "in png_set_filter\n");
  199601. if (png_ptr == NULL)
  199602. return;
  199603. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199604. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199605. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199606. method = PNG_FILTER_TYPE_BASE;
  199607. #endif
  199608. if (method == PNG_FILTER_TYPE_BASE)
  199609. {
  199610. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199611. {
  199612. #ifndef PNG_NO_WRITE_FILTER
  199613. case 5:
  199614. case 6:
  199615. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199616. #endif /* PNG_NO_WRITE_FILTER */
  199617. case PNG_FILTER_VALUE_NONE:
  199618. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199619. #ifndef PNG_NO_WRITE_FILTER
  199620. case PNG_FILTER_VALUE_SUB:
  199621. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199622. case PNG_FILTER_VALUE_UP:
  199623. png_ptr->do_filter=PNG_FILTER_UP; break;
  199624. case PNG_FILTER_VALUE_AVG:
  199625. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199626. case PNG_FILTER_VALUE_PAETH:
  199627. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199628. default: png_ptr->do_filter = (png_byte)filters; break;
  199629. #else
  199630. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199631. #endif /* PNG_NO_WRITE_FILTER */
  199632. }
  199633. /* If we have allocated the row_buf, this means we have already started
  199634. * with the image and we should have allocated all of the filter buffers
  199635. * that have been selected. If prev_row isn't already allocated, then
  199636. * it is too late to start using the filters that need it, since we
  199637. * will be missing the data in the previous row. If an application
  199638. * wants to start and stop using particular filters during compression,
  199639. * it should start out with all of the filters, and then add and
  199640. * remove them after the start of compression.
  199641. */
  199642. if (png_ptr->row_buf != NULL)
  199643. {
  199644. #ifndef PNG_NO_WRITE_FILTER
  199645. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199646. {
  199647. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199648. (png_ptr->rowbytes + 1));
  199649. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199650. }
  199651. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199652. {
  199653. if (png_ptr->prev_row == NULL)
  199654. {
  199655. png_warning(png_ptr, "Can't add Up filter after starting");
  199656. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199657. }
  199658. else
  199659. {
  199660. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199661. (png_ptr->rowbytes + 1));
  199662. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199663. }
  199664. }
  199665. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199666. {
  199667. if (png_ptr->prev_row == NULL)
  199668. {
  199669. png_warning(png_ptr, "Can't add Average filter after starting");
  199670. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199671. }
  199672. else
  199673. {
  199674. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199675. (png_ptr->rowbytes + 1));
  199676. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199677. }
  199678. }
  199679. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199680. png_ptr->paeth_row == NULL)
  199681. {
  199682. if (png_ptr->prev_row == NULL)
  199683. {
  199684. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199685. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199686. }
  199687. else
  199688. {
  199689. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199690. (png_ptr->rowbytes + 1));
  199691. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199692. }
  199693. }
  199694. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199695. #endif /* PNG_NO_WRITE_FILTER */
  199696. png_ptr->do_filter = PNG_FILTER_NONE;
  199697. }
  199698. }
  199699. else
  199700. png_error(png_ptr, "Unknown custom filter method");
  199701. }
  199702. /* This allows us to influence the way in which libpng chooses the "best"
  199703. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199704. * differences metric is relatively fast and effective, there is some
  199705. * question as to whether it can be improved upon by trying to keep the
  199706. * filtered data going to zlib more consistent, hopefully resulting in
  199707. * better compression.
  199708. */
  199709. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199710. void PNGAPI
  199711. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199712. int num_weights, png_doublep filter_weights,
  199713. png_doublep filter_costs)
  199714. {
  199715. int i;
  199716. png_debug(1, "in png_set_filter_heuristics\n");
  199717. if (png_ptr == NULL)
  199718. return;
  199719. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199720. {
  199721. png_warning(png_ptr, "Unknown filter heuristic method");
  199722. return;
  199723. }
  199724. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199725. {
  199726. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199727. }
  199728. if (num_weights < 0 || filter_weights == NULL ||
  199729. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199730. {
  199731. num_weights = 0;
  199732. }
  199733. png_ptr->num_prev_filters = (png_byte)num_weights;
  199734. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199735. if (num_weights > 0)
  199736. {
  199737. if (png_ptr->prev_filters == NULL)
  199738. {
  199739. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199740. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199741. /* To make sure that the weighting starts out fairly */
  199742. for (i = 0; i < num_weights; i++)
  199743. {
  199744. png_ptr->prev_filters[i] = 255;
  199745. }
  199746. }
  199747. if (png_ptr->filter_weights == NULL)
  199748. {
  199749. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199750. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199751. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199752. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199753. for (i = 0; i < num_weights; i++)
  199754. {
  199755. png_ptr->inv_filter_weights[i] =
  199756. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199757. }
  199758. }
  199759. for (i = 0; i < num_weights; i++)
  199760. {
  199761. if (filter_weights[i] < 0.0)
  199762. {
  199763. png_ptr->inv_filter_weights[i] =
  199764. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199765. }
  199766. else
  199767. {
  199768. png_ptr->inv_filter_weights[i] =
  199769. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199770. png_ptr->filter_weights[i] =
  199771. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199772. }
  199773. }
  199774. }
  199775. /* If, in the future, there are other filter methods, this would
  199776. * need to be based on png_ptr->filter.
  199777. */
  199778. if (png_ptr->filter_costs == NULL)
  199779. {
  199780. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199781. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199782. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199783. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199784. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199785. {
  199786. png_ptr->inv_filter_costs[i] =
  199787. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199788. }
  199789. }
  199790. /* Here is where we set the relative costs of the different filters. We
  199791. * should take the desired compression level into account when setting
  199792. * the costs, so that Paeth, for instance, has a high relative cost at low
  199793. * compression levels, while it has a lower relative cost at higher
  199794. * compression settings. The filter types are in order of increasing
  199795. * relative cost, so it would be possible to do this with an algorithm.
  199796. */
  199797. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199798. {
  199799. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199800. {
  199801. png_ptr->inv_filter_costs[i] =
  199802. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199803. }
  199804. else if (filter_costs[i] >= 1.0)
  199805. {
  199806. png_ptr->inv_filter_costs[i] =
  199807. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199808. png_ptr->filter_costs[i] =
  199809. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199810. }
  199811. }
  199812. }
  199813. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199814. void PNGAPI
  199815. png_set_compression_level(png_structp png_ptr, int level)
  199816. {
  199817. png_debug(1, "in png_set_compression_level\n");
  199818. if (png_ptr == NULL)
  199819. return;
  199820. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199821. png_ptr->zlib_level = level;
  199822. }
  199823. void PNGAPI
  199824. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199825. {
  199826. png_debug(1, "in png_set_compression_mem_level\n");
  199827. if (png_ptr == NULL)
  199828. return;
  199829. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199830. png_ptr->zlib_mem_level = mem_level;
  199831. }
  199832. void PNGAPI
  199833. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199834. {
  199835. png_debug(1, "in png_set_compression_strategy\n");
  199836. if (png_ptr == NULL)
  199837. return;
  199838. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199839. png_ptr->zlib_strategy = strategy;
  199840. }
  199841. void PNGAPI
  199842. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199843. {
  199844. if (png_ptr == NULL)
  199845. return;
  199846. if (window_bits > 15)
  199847. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199848. else if (window_bits < 8)
  199849. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199850. #ifndef WBITS_8_OK
  199851. /* avoid libpng bug with 256-byte windows */
  199852. if (window_bits == 8)
  199853. {
  199854. png_warning(png_ptr, "Compression window is being reset to 512");
  199855. window_bits=9;
  199856. }
  199857. #endif
  199858. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199859. png_ptr->zlib_window_bits = window_bits;
  199860. }
  199861. void PNGAPI
  199862. png_set_compression_method(png_structp png_ptr, int method)
  199863. {
  199864. png_debug(1, "in png_set_compression_method\n");
  199865. if (png_ptr == NULL)
  199866. return;
  199867. if (method != 8)
  199868. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199869. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199870. png_ptr->zlib_method = method;
  199871. }
  199872. void PNGAPI
  199873. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199874. {
  199875. if (png_ptr == NULL)
  199876. return;
  199877. png_ptr->write_row_fn = write_row_fn;
  199878. }
  199879. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199880. void PNGAPI
  199881. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199882. write_user_transform_fn)
  199883. {
  199884. png_debug(1, "in png_set_write_user_transform_fn\n");
  199885. if (png_ptr == NULL)
  199886. return;
  199887. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199888. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199889. }
  199890. #endif
  199891. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199892. void PNGAPI
  199893. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199894. int transforms, voidp params)
  199895. {
  199896. if (png_ptr == NULL || info_ptr == NULL)
  199897. return;
  199898. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199899. /* invert the alpha channel from opacity to transparency */
  199900. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199901. png_set_invert_alpha(png_ptr);
  199902. #endif
  199903. /* Write the file header information. */
  199904. png_write_info(png_ptr, info_ptr);
  199905. /* ------ these transformations don't touch the info structure ------- */
  199906. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199907. /* invert monochrome pixels */
  199908. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199909. png_set_invert_mono(png_ptr);
  199910. #endif
  199911. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199912. /* Shift the pixels up to a legal bit depth and fill in
  199913. * as appropriate to correctly scale the image.
  199914. */
  199915. if ((transforms & PNG_TRANSFORM_SHIFT)
  199916. && (info_ptr->valid & PNG_INFO_sBIT))
  199917. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199918. #endif
  199919. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199920. /* pack pixels into bytes */
  199921. if (transforms & PNG_TRANSFORM_PACKING)
  199922. png_set_packing(png_ptr);
  199923. #endif
  199924. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199925. /* swap location of alpha bytes from ARGB to RGBA */
  199926. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199927. png_set_swap_alpha(png_ptr);
  199928. #endif
  199929. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199930. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199931. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199932. */
  199933. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199934. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199935. #endif
  199936. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199937. /* flip BGR pixels to RGB */
  199938. if (transforms & PNG_TRANSFORM_BGR)
  199939. png_set_bgr(png_ptr);
  199940. #endif
  199941. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199942. /* swap bytes of 16-bit files to most significant byte first */
  199943. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199944. png_set_swap(png_ptr);
  199945. #endif
  199946. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199947. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199948. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199949. png_set_packswap(png_ptr);
  199950. #endif
  199951. /* ----------------------- end of transformations ------------------- */
  199952. /* write the bits */
  199953. if (info_ptr->valid & PNG_INFO_IDAT)
  199954. png_write_image(png_ptr, info_ptr->row_pointers);
  199955. /* It is REQUIRED to call this to finish writing the rest of the file */
  199956. png_write_end(png_ptr, info_ptr);
  199957. transforms = transforms; /* quiet compiler warnings */
  199958. params = params;
  199959. }
  199960. #endif
  199961. #endif /* PNG_WRITE_SUPPORTED */
  199962. /*** End of inlined file: pngwrite.c ***/
  199963. /*** Start of inlined file: pngwtran.c ***/
  199964. /* pngwtran.c - transforms the data in a row for PNG writers
  199965. *
  199966. * Last changed in libpng 1.2.9 April 14, 2006
  199967. * For conditions of distribution and use, see copyright notice in png.h
  199968. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199969. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199970. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199971. */
  199972. #define PNG_INTERNAL
  199973. #ifdef PNG_WRITE_SUPPORTED
  199974. /* Transform the data according to the user's wishes. The order of
  199975. * transformations is significant.
  199976. */
  199977. void /* PRIVATE */
  199978. png_do_write_transformations(png_structp png_ptr)
  199979. {
  199980. png_debug(1, "in png_do_write_transformations\n");
  199981. if (png_ptr == NULL)
  199982. return;
  199983. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199984. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199985. if(png_ptr->write_user_transform_fn != NULL)
  199986. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199987. (png_ptr, /* png_ptr */
  199988. &(png_ptr->row_info), /* row_info: */
  199989. /* png_uint_32 width; width of row */
  199990. /* png_uint_32 rowbytes; number of bytes in row */
  199991. /* png_byte color_type; color type of pixels */
  199992. /* png_byte bit_depth; bit depth of samples */
  199993. /* png_byte channels; number of channels (1-4) */
  199994. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199995. png_ptr->row_buf + 1); /* start of pixel data for row */
  199996. #endif
  199997. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199998. if (png_ptr->transformations & PNG_FILLER)
  199999. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200000. png_ptr->flags);
  200001. #endif
  200002. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200003. if (png_ptr->transformations & PNG_PACKSWAP)
  200004. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200005. #endif
  200006. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200007. if (png_ptr->transformations & PNG_PACK)
  200008. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200009. (png_uint_32)png_ptr->bit_depth);
  200010. #endif
  200011. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200012. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200013. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200014. #endif
  200015. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200016. if (png_ptr->transformations & PNG_SHIFT)
  200017. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200018. &(png_ptr->shift));
  200019. #endif
  200020. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200021. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200022. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200023. #endif
  200024. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200025. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200026. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200027. #endif
  200028. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200029. if (png_ptr->transformations & PNG_BGR)
  200030. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200031. #endif
  200032. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200033. if (png_ptr->transformations & PNG_INVERT_MONO)
  200034. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200035. #endif
  200036. }
  200037. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200038. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200039. * row_info bit depth should be 8 (one pixel per byte). The channels
  200040. * should be 1 (this only happens on grayscale and paletted images).
  200041. */
  200042. void /* PRIVATE */
  200043. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200044. {
  200045. png_debug(1, "in png_do_pack\n");
  200046. if (row_info->bit_depth == 8 &&
  200047. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200048. row != NULL && row_info != NULL &&
  200049. #endif
  200050. row_info->channels == 1)
  200051. {
  200052. switch ((int)bit_depth)
  200053. {
  200054. case 1:
  200055. {
  200056. png_bytep sp, dp;
  200057. int mask, v;
  200058. png_uint_32 i;
  200059. png_uint_32 row_width = row_info->width;
  200060. sp = row;
  200061. dp = row;
  200062. mask = 0x80;
  200063. v = 0;
  200064. for (i = 0; i < row_width; i++)
  200065. {
  200066. if (*sp != 0)
  200067. v |= mask;
  200068. sp++;
  200069. if (mask > 1)
  200070. mask >>= 1;
  200071. else
  200072. {
  200073. mask = 0x80;
  200074. *dp = (png_byte)v;
  200075. dp++;
  200076. v = 0;
  200077. }
  200078. }
  200079. if (mask != 0x80)
  200080. *dp = (png_byte)v;
  200081. break;
  200082. }
  200083. case 2:
  200084. {
  200085. png_bytep sp, dp;
  200086. int shift, v;
  200087. png_uint_32 i;
  200088. png_uint_32 row_width = row_info->width;
  200089. sp = row;
  200090. dp = row;
  200091. shift = 6;
  200092. v = 0;
  200093. for (i = 0; i < row_width; i++)
  200094. {
  200095. png_byte value;
  200096. value = (png_byte)(*sp & 0x03);
  200097. v |= (value << shift);
  200098. if (shift == 0)
  200099. {
  200100. shift = 6;
  200101. *dp = (png_byte)v;
  200102. dp++;
  200103. v = 0;
  200104. }
  200105. else
  200106. shift -= 2;
  200107. sp++;
  200108. }
  200109. if (shift != 6)
  200110. *dp = (png_byte)v;
  200111. break;
  200112. }
  200113. case 4:
  200114. {
  200115. png_bytep sp, dp;
  200116. int shift, v;
  200117. png_uint_32 i;
  200118. png_uint_32 row_width = row_info->width;
  200119. sp = row;
  200120. dp = row;
  200121. shift = 4;
  200122. v = 0;
  200123. for (i = 0; i < row_width; i++)
  200124. {
  200125. png_byte value;
  200126. value = (png_byte)(*sp & 0x0f);
  200127. v |= (value << shift);
  200128. if (shift == 0)
  200129. {
  200130. shift = 4;
  200131. *dp = (png_byte)v;
  200132. dp++;
  200133. v = 0;
  200134. }
  200135. else
  200136. shift -= 4;
  200137. sp++;
  200138. }
  200139. if (shift != 4)
  200140. *dp = (png_byte)v;
  200141. break;
  200142. }
  200143. }
  200144. row_info->bit_depth = (png_byte)bit_depth;
  200145. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200146. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200147. row_info->width);
  200148. }
  200149. }
  200150. #endif
  200151. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200152. /* Shift pixel values to take advantage of whole range. Pass the
  200153. * true number of bits in bit_depth. The row should be packed
  200154. * according to row_info->bit_depth. Thus, if you had a row of
  200155. * bit depth 4, but the pixels only had values from 0 to 7, you
  200156. * would pass 3 as bit_depth, and this routine would translate the
  200157. * data to 0 to 15.
  200158. */
  200159. void /* PRIVATE */
  200160. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200161. {
  200162. png_debug(1, "in png_do_shift\n");
  200163. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200164. if (row != NULL && row_info != NULL &&
  200165. #else
  200166. if (
  200167. #endif
  200168. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200169. {
  200170. int shift_start[4], shift_dec[4];
  200171. int channels = 0;
  200172. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200173. {
  200174. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200175. shift_dec[channels] = bit_depth->red;
  200176. channels++;
  200177. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200178. shift_dec[channels] = bit_depth->green;
  200179. channels++;
  200180. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200181. shift_dec[channels] = bit_depth->blue;
  200182. channels++;
  200183. }
  200184. else
  200185. {
  200186. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200187. shift_dec[channels] = bit_depth->gray;
  200188. channels++;
  200189. }
  200190. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200191. {
  200192. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200193. shift_dec[channels] = bit_depth->alpha;
  200194. channels++;
  200195. }
  200196. /* with low row depths, could only be grayscale, so one channel */
  200197. if (row_info->bit_depth < 8)
  200198. {
  200199. png_bytep bp = row;
  200200. png_uint_32 i;
  200201. png_byte mask;
  200202. png_uint_32 row_bytes = row_info->rowbytes;
  200203. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200204. mask = 0x55;
  200205. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200206. mask = 0x11;
  200207. else
  200208. mask = 0xff;
  200209. for (i = 0; i < row_bytes; i++, bp++)
  200210. {
  200211. png_uint_16 v;
  200212. int j;
  200213. v = *bp;
  200214. *bp = 0;
  200215. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200216. {
  200217. if (j > 0)
  200218. *bp |= (png_byte)((v << j) & 0xff);
  200219. else
  200220. *bp |= (png_byte)((v >> (-j)) & mask);
  200221. }
  200222. }
  200223. }
  200224. else if (row_info->bit_depth == 8)
  200225. {
  200226. png_bytep bp = row;
  200227. png_uint_32 i;
  200228. png_uint_32 istop = channels * row_info->width;
  200229. for (i = 0; i < istop; i++, bp++)
  200230. {
  200231. png_uint_16 v;
  200232. int j;
  200233. int c = (int)(i%channels);
  200234. v = *bp;
  200235. *bp = 0;
  200236. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200237. {
  200238. if (j > 0)
  200239. *bp |= (png_byte)((v << j) & 0xff);
  200240. else
  200241. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200242. }
  200243. }
  200244. }
  200245. else
  200246. {
  200247. png_bytep bp;
  200248. png_uint_32 i;
  200249. png_uint_32 istop = channels * row_info->width;
  200250. for (bp = row, i = 0; i < istop; i++)
  200251. {
  200252. int c = (int)(i%channels);
  200253. png_uint_16 value, v;
  200254. int j;
  200255. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200256. value = 0;
  200257. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200258. {
  200259. if (j > 0)
  200260. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200261. else
  200262. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200263. }
  200264. *bp++ = (png_byte)(value >> 8);
  200265. *bp++ = (png_byte)(value & 0xff);
  200266. }
  200267. }
  200268. }
  200269. }
  200270. #endif
  200271. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200272. void /* PRIVATE */
  200273. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200274. {
  200275. png_debug(1, "in png_do_write_swap_alpha\n");
  200276. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200277. if (row != NULL && row_info != NULL)
  200278. #endif
  200279. {
  200280. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200281. {
  200282. /* This converts from ARGB to RGBA */
  200283. if (row_info->bit_depth == 8)
  200284. {
  200285. png_bytep sp, dp;
  200286. png_uint_32 i;
  200287. png_uint_32 row_width = row_info->width;
  200288. for (i = 0, sp = dp = row; i < row_width; i++)
  200289. {
  200290. png_byte save = *(sp++);
  200291. *(dp++) = *(sp++);
  200292. *(dp++) = *(sp++);
  200293. *(dp++) = *(sp++);
  200294. *(dp++) = save;
  200295. }
  200296. }
  200297. /* This converts from AARRGGBB to RRGGBBAA */
  200298. else
  200299. {
  200300. png_bytep sp, dp;
  200301. png_uint_32 i;
  200302. png_uint_32 row_width = row_info->width;
  200303. for (i = 0, sp = dp = row; i < row_width; i++)
  200304. {
  200305. png_byte save[2];
  200306. save[0] = *(sp++);
  200307. save[1] = *(sp++);
  200308. *(dp++) = *(sp++);
  200309. *(dp++) = *(sp++);
  200310. *(dp++) = *(sp++);
  200311. *(dp++) = *(sp++);
  200312. *(dp++) = *(sp++);
  200313. *(dp++) = *(sp++);
  200314. *(dp++) = save[0];
  200315. *(dp++) = save[1];
  200316. }
  200317. }
  200318. }
  200319. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200320. {
  200321. /* This converts from AG to GA */
  200322. if (row_info->bit_depth == 8)
  200323. {
  200324. png_bytep sp, dp;
  200325. png_uint_32 i;
  200326. png_uint_32 row_width = row_info->width;
  200327. for (i = 0, sp = dp = row; i < row_width; i++)
  200328. {
  200329. png_byte save = *(sp++);
  200330. *(dp++) = *(sp++);
  200331. *(dp++) = save;
  200332. }
  200333. }
  200334. /* This converts from AAGG to GGAA */
  200335. else
  200336. {
  200337. png_bytep sp, dp;
  200338. png_uint_32 i;
  200339. png_uint_32 row_width = row_info->width;
  200340. for (i = 0, sp = dp = row; i < row_width; i++)
  200341. {
  200342. png_byte save[2];
  200343. save[0] = *(sp++);
  200344. save[1] = *(sp++);
  200345. *(dp++) = *(sp++);
  200346. *(dp++) = *(sp++);
  200347. *(dp++) = save[0];
  200348. *(dp++) = save[1];
  200349. }
  200350. }
  200351. }
  200352. }
  200353. }
  200354. #endif
  200355. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200356. void /* PRIVATE */
  200357. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200358. {
  200359. png_debug(1, "in png_do_write_invert_alpha\n");
  200360. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200361. if (row != NULL && row_info != NULL)
  200362. #endif
  200363. {
  200364. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200365. {
  200366. /* This inverts the alpha channel in RGBA */
  200367. if (row_info->bit_depth == 8)
  200368. {
  200369. png_bytep sp, dp;
  200370. png_uint_32 i;
  200371. png_uint_32 row_width = row_info->width;
  200372. for (i = 0, sp = dp = row; i < row_width; i++)
  200373. {
  200374. /* does nothing
  200375. *(dp++) = *(sp++);
  200376. *(dp++) = *(sp++);
  200377. *(dp++) = *(sp++);
  200378. */
  200379. sp+=3; dp = sp;
  200380. *(dp++) = (png_byte)(255 - *(sp++));
  200381. }
  200382. }
  200383. /* This inverts the alpha channel in RRGGBBAA */
  200384. else
  200385. {
  200386. png_bytep sp, dp;
  200387. png_uint_32 i;
  200388. png_uint_32 row_width = row_info->width;
  200389. for (i = 0, sp = dp = row; i < row_width; i++)
  200390. {
  200391. /* does nothing
  200392. *(dp++) = *(sp++);
  200393. *(dp++) = *(sp++);
  200394. *(dp++) = *(sp++);
  200395. *(dp++) = *(sp++);
  200396. *(dp++) = *(sp++);
  200397. *(dp++) = *(sp++);
  200398. */
  200399. sp+=6; dp = sp;
  200400. *(dp++) = (png_byte)(255 - *(sp++));
  200401. *(dp++) = (png_byte)(255 - *(sp++));
  200402. }
  200403. }
  200404. }
  200405. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200406. {
  200407. /* This inverts the alpha channel in GA */
  200408. if (row_info->bit_depth == 8)
  200409. {
  200410. png_bytep sp, dp;
  200411. png_uint_32 i;
  200412. png_uint_32 row_width = row_info->width;
  200413. for (i = 0, sp = dp = row; i < row_width; i++)
  200414. {
  200415. *(dp++) = *(sp++);
  200416. *(dp++) = (png_byte)(255 - *(sp++));
  200417. }
  200418. }
  200419. /* This inverts the alpha channel in GGAA */
  200420. else
  200421. {
  200422. png_bytep sp, dp;
  200423. png_uint_32 i;
  200424. png_uint_32 row_width = row_info->width;
  200425. for (i = 0, sp = dp = row; i < row_width; i++)
  200426. {
  200427. /* does nothing
  200428. *(dp++) = *(sp++);
  200429. *(dp++) = *(sp++);
  200430. */
  200431. sp+=2; dp = sp;
  200432. *(dp++) = (png_byte)(255 - *(sp++));
  200433. *(dp++) = (png_byte)(255 - *(sp++));
  200434. }
  200435. }
  200436. }
  200437. }
  200438. }
  200439. #endif
  200440. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200441. /* undoes intrapixel differencing */
  200442. void /* PRIVATE */
  200443. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200444. {
  200445. png_debug(1, "in png_do_write_intrapixel\n");
  200446. if (
  200447. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200448. row != NULL && row_info != NULL &&
  200449. #endif
  200450. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200451. {
  200452. int bytes_per_pixel;
  200453. png_uint_32 row_width = row_info->width;
  200454. if (row_info->bit_depth == 8)
  200455. {
  200456. png_bytep rp;
  200457. png_uint_32 i;
  200458. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200459. bytes_per_pixel = 3;
  200460. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200461. bytes_per_pixel = 4;
  200462. else
  200463. return;
  200464. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200465. {
  200466. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200467. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200468. }
  200469. }
  200470. else if (row_info->bit_depth == 16)
  200471. {
  200472. png_bytep rp;
  200473. png_uint_32 i;
  200474. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200475. bytes_per_pixel = 6;
  200476. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200477. bytes_per_pixel = 8;
  200478. else
  200479. return;
  200480. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200481. {
  200482. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200483. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200484. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200485. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200486. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200487. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200488. *(rp+1) = (png_byte)(red & 0xff);
  200489. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200490. *(rp+5) = (png_byte)(blue & 0xff);
  200491. }
  200492. }
  200493. }
  200494. }
  200495. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200496. #endif /* PNG_WRITE_SUPPORTED */
  200497. /*** End of inlined file: pngwtran.c ***/
  200498. /*** Start of inlined file: pngwutil.c ***/
  200499. /* pngwutil.c - utilities to write a PNG file
  200500. *
  200501. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200502. * For conditions of distribution and use, see copyright notice in png.h
  200503. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200504. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200505. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200506. */
  200507. #define PNG_INTERNAL
  200508. #ifdef PNG_WRITE_SUPPORTED
  200509. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200510. * with unsigned numbers for convenience, although one supported
  200511. * ancillary chunk uses signed (two's complement) numbers.
  200512. */
  200513. void PNGAPI
  200514. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200515. {
  200516. buf[0] = (png_byte)((i >> 24) & 0xff);
  200517. buf[1] = (png_byte)((i >> 16) & 0xff);
  200518. buf[2] = (png_byte)((i >> 8) & 0xff);
  200519. buf[3] = (png_byte)(i & 0xff);
  200520. }
  200521. /* The png_save_int_32 function assumes integers are stored in two's
  200522. * complement format. If this isn't the case, then this routine needs to
  200523. * be modified to write data in two's complement format.
  200524. */
  200525. void PNGAPI
  200526. png_save_int_32(png_bytep buf, png_int_32 i)
  200527. {
  200528. buf[0] = (png_byte)((i >> 24) & 0xff);
  200529. buf[1] = (png_byte)((i >> 16) & 0xff);
  200530. buf[2] = (png_byte)((i >> 8) & 0xff);
  200531. buf[3] = (png_byte)(i & 0xff);
  200532. }
  200533. /* Place a 16-bit number into a buffer in PNG byte order.
  200534. * The parameter is declared unsigned int, not png_uint_16,
  200535. * just to avoid potential problems on pre-ANSI C compilers.
  200536. */
  200537. void PNGAPI
  200538. png_save_uint_16(png_bytep buf, unsigned int i)
  200539. {
  200540. buf[0] = (png_byte)((i >> 8) & 0xff);
  200541. buf[1] = (png_byte)(i & 0xff);
  200542. }
  200543. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200544. * representing the chunk name. The array must be at least 4 bytes in
  200545. * length, and does not need to be null terminated. To be safe, pass the
  200546. * pre-defined chunk names here, and if you need a new one, define it
  200547. * where the others are defined. The length is the length of the data.
  200548. * All the data must be present. If that is not possible, use the
  200549. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200550. * functions instead.
  200551. */
  200552. void PNGAPI
  200553. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200554. png_bytep data, png_size_t length)
  200555. {
  200556. if(png_ptr == NULL) return;
  200557. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200558. png_write_chunk_data(png_ptr, data, length);
  200559. png_write_chunk_end(png_ptr);
  200560. }
  200561. /* Write the start of a PNG chunk. The type is the chunk type.
  200562. * The total_length is the sum of the lengths of all the data you will be
  200563. * passing in png_write_chunk_data().
  200564. */
  200565. void PNGAPI
  200566. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200567. png_uint_32 length)
  200568. {
  200569. png_byte buf[4];
  200570. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200571. if(png_ptr == NULL) return;
  200572. /* write the length */
  200573. png_save_uint_32(buf, length);
  200574. png_write_data(png_ptr, buf, (png_size_t)4);
  200575. /* write the chunk name */
  200576. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200577. /* reset the crc and run it over the chunk name */
  200578. png_reset_crc(png_ptr);
  200579. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200580. }
  200581. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200582. * Note that multiple calls to this function are allowed, and that the
  200583. * sum of the lengths from these calls *must* add up to the total_length
  200584. * given to png_write_chunk_start().
  200585. */
  200586. void PNGAPI
  200587. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200588. {
  200589. /* write the data, and run the CRC over it */
  200590. if(png_ptr == NULL) return;
  200591. if (data != NULL && length > 0)
  200592. {
  200593. png_calculate_crc(png_ptr, data, length);
  200594. png_write_data(png_ptr, data, length);
  200595. }
  200596. }
  200597. /* Finish a chunk started with png_write_chunk_start(). */
  200598. void PNGAPI
  200599. png_write_chunk_end(png_structp png_ptr)
  200600. {
  200601. png_byte buf[4];
  200602. if(png_ptr == NULL) return;
  200603. /* write the crc */
  200604. png_save_uint_32(buf, png_ptr->crc);
  200605. png_write_data(png_ptr, buf, (png_size_t)4);
  200606. }
  200607. /* Simple function to write the signature. If we have already written
  200608. * the magic bytes of the signature, or more likely, the PNG stream is
  200609. * being embedded into another stream and doesn't need its own signature,
  200610. * we should call png_set_sig_bytes() to tell libpng how many of the
  200611. * bytes have already been written.
  200612. */
  200613. void /* PRIVATE */
  200614. png_write_sig(png_structp png_ptr)
  200615. {
  200616. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200617. /* write the rest of the 8 byte signature */
  200618. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200619. (png_size_t)8 - png_ptr->sig_bytes);
  200620. if(png_ptr->sig_bytes < 3)
  200621. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200622. }
  200623. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200624. /*
  200625. * This pair of functions encapsulates the operation of (a) compressing a
  200626. * text string, and (b) issuing it later as a series of chunk data writes.
  200627. * The compression_state structure is shared context for these functions
  200628. * set up by the caller in order to make the whole mess thread-safe.
  200629. */
  200630. typedef struct
  200631. {
  200632. char *input; /* the uncompressed input data */
  200633. int input_len; /* its length */
  200634. int num_output_ptr; /* number of output pointers used */
  200635. int max_output_ptr; /* size of output_ptr */
  200636. png_charpp output_ptr; /* array of pointers to output */
  200637. } compression_state;
  200638. /* compress given text into storage in the png_ptr structure */
  200639. static int /* PRIVATE */
  200640. png_text_compress(png_structp png_ptr,
  200641. png_charp text, png_size_t text_len, int compression,
  200642. compression_state *comp)
  200643. {
  200644. int ret;
  200645. comp->num_output_ptr = 0;
  200646. comp->max_output_ptr = 0;
  200647. comp->output_ptr = NULL;
  200648. comp->input = NULL;
  200649. comp->input_len = 0;
  200650. /* we may just want to pass the text right through */
  200651. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200652. {
  200653. comp->input = text;
  200654. comp->input_len = text_len;
  200655. return((int)text_len);
  200656. }
  200657. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200658. {
  200659. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200660. char msg[50];
  200661. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200662. png_warning(png_ptr, msg);
  200663. #else
  200664. png_warning(png_ptr, "Unknown compression type");
  200665. #endif
  200666. }
  200667. /* We can't write the chunk until we find out how much data we have,
  200668. * which means we need to run the compressor first and save the
  200669. * output. This shouldn't be a problem, as the vast majority of
  200670. * comments should be reasonable, but we will set up an array of
  200671. * malloc'd pointers to be sure.
  200672. *
  200673. * If we knew the application was well behaved, we could simplify this
  200674. * greatly by assuming we can always malloc an output buffer large
  200675. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200676. * and malloc this directly. The only time this would be a bad idea is
  200677. * if we can't malloc more than 64K and we have 64K of random input
  200678. * data, or if the input string is incredibly large (although this
  200679. * wouldn't cause a failure, just a slowdown due to swapping).
  200680. */
  200681. /* set up the compression buffers */
  200682. png_ptr->zstream.avail_in = (uInt)text_len;
  200683. png_ptr->zstream.next_in = (Bytef *)text;
  200684. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200685. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200686. /* this is the same compression loop as in png_write_row() */
  200687. do
  200688. {
  200689. /* compress the data */
  200690. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200691. if (ret != Z_OK)
  200692. {
  200693. /* error */
  200694. if (png_ptr->zstream.msg != NULL)
  200695. png_error(png_ptr, png_ptr->zstream.msg);
  200696. else
  200697. png_error(png_ptr, "zlib error");
  200698. }
  200699. /* check to see if we need more room */
  200700. if (!(png_ptr->zstream.avail_out))
  200701. {
  200702. /* make sure the output array has room */
  200703. if (comp->num_output_ptr >= comp->max_output_ptr)
  200704. {
  200705. int old_max;
  200706. old_max = comp->max_output_ptr;
  200707. comp->max_output_ptr = comp->num_output_ptr + 4;
  200708. if (comp->output_ptr != NULL)
  200709. {
  200710. png_charpp old_ptr;
  200711. old_ptr = comp->output_ptr;
  200712. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200713. (png_uint_32)(comp->max_output_ptr *
  200714. png_sizeof (png_charpp)));
  200715. png_memcpy(comp->output_ptr, old_ptr, old_max
  200716. * png_sizeof (png_charp));
  200717. png_free(png_ptr, old_ptr);
  200718. }
  200719. else
  200720. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200721. (png_uint_32)(comp->max_output_ptr *
  200722. png_sizeof (png_charp)));
  200723. }
  200724. /* save the data */
  200725. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200726. (png_uint_32)png_ptr->zbuf_size);
  200727. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200728. png_ptr->zbuf_size);
  200729. comp->num_output_ptr++;
  200730. /* and reset the buffer */
  200731. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200732. png_ptr->zstream.next_out = png_ptr->zbuf;
  200733. }
  200734. /* continue until we don't have any more to compress */
  200735. } while (png_ptr->zstream.avail_in);
  200736. /* finish the compression */
  200737. do
  200738. {
  200739. /* tell zlib we are finished */
  200740. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200741. if (ret == Z_OK)
  200742. {
  200743. /* check to see if we need more room */
  200744. if (!(png_ptr->zstream.avail_out))
  200745. {
  200746. /* check to make sure our output array has room */
  200747. if (comp->num_output_ptr >= comp->max_output_ptr)
  200748. {
  200749. int old_max;
  200750. old_max = comp->max_output_ptr;
  200751. comp->max_output_ptr = comp->num_output_ptr + 4;
  200752. if (comp->output_ptr != NULL)
  200753. {
  200754. png_charpp old_ptr;
  200755. old_ptr = comp->output_ptr;
  200756. /* This could be optimized to realloc() */
  200757. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200758. (png_uint_32)(comp->max_output_ptr *
  200759. png_sizeof (png_charpp)));
  200760. png_memcpy(comp->output_ptr, old_ptr,
  200761. old_max * png_sizeof (png_charp));
  200762. png_free(png_ptr, old_ptr);
  200763. }
  200764. else
  200765. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200766. (png_uint_32)(comp->max_output_ptr *
  200767. png_sizeof (png_charp)));
  200768. }
  200769. /* save off the data */
  200770. comp->output_ptr[comp->num_output_ptr] =
  200771. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200772. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200773. png_ptr->zbuf_size);
  200774. comp->num_output_ptr++;
  200775. /* and reset the buffer pointers */
  200776. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200777. png_ptr->zstream.next_out = png_ptr->zbuf;
  200778. }
  200779. }
  200780. else if (ret != Z_STREAM_END)
  200781. {
  200782. /* we got an error */
  200783. if (png_ptr->zstream.msg != NULL)
  200784. png_error(png_ptr, png_ptr->zstream.msg);
  200785. else
  200786. png_error(png_ptr, "zlib error");
  200787. }
  200788. } while (ret != Z_STREAM_END);
  200789. /* text length is number of buffers plus last buffer */
  200790. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200791. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200792. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200793. return((int)text_len);
  200794. }
  200795. /* ship the compressed text out via chunk writes */
  200796. static void /* PRIVATE */
  200797. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200798. {
  200799. int i;
  200800. /* handle the no-compression case */
  200801. if (comp->input)
  200802. {
  200803. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200804. (png_size_t)comp->input_len);
  200805. return;
  200806. }
  200807. /* write saved output buffers, if any */
  200808. for (i = 0; i < comp->num_output_ptr; i++)
  200809. {
  200810. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200811. png_ptr->zbuf_size);
  200812. png_free(png_ptr, comp->output_ptr[i]);
  200813. comp->output_ptr[i]=NULL;
  200814. }
  200815. if (comp->max_output_ptr != 0)
  200816. png_free(png_ptr, comp->output_ptr);
  200817. comp->output_ptr=NULL;
  200818. /* write anything left in zbuf */
  200819. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200820. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200821. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200822. /* reset zlib for another zTXt/iTXt or image data */
  200823. deflateReset(&png_ptr->zstream);
  200824. png_ptr->zstream.data_type = Z_BINARY;
  200825. }
  200826. #endif
  200827. /* Write the IHDR chunk, and update the png_struct with the necessary
  200828. * information. Note that the rest of this code depends upon this
  200829. * information being correct.
  200830. */
  200831. void /* PRIVATE */
  200832. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200833. int bit_depth, int color_type, int compression_type, int filter_type,
  200834. int interlace_type)
  200835. {
  200836. #ifdef PNG_USE_LOCAL_ARRAYS
  200837. PNG_IHDR;
  200838. #endif
  200839. png_byte buf[13]; /* buffer to store the IHDR info */
  200840. png_debug(1, "in png_write_IHDR\n");
  200841. /* Check that we have valid input data from the application info */
  200842. switch (color_type)
  200843. {
  200844. case PNG_COLOR_TYPE_GRAY:
  200845. switch (bit_depth)
  200846. {
  200847. case 1:
  200848. case 2:
  200849. case 4:
  200850. case 8:
  200851. case 16: png_ptr->channels = 1; break;
  200852. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200853. }
  200854. break;
  200855. case PNG_COLOR_TYPE_RGB:
  200856. if (bit_depth != 8 && bit_depth != 16)
  200857. png_error(png_ptr, "Invalid bit depth for RGB image");
  200858. png_ptr->channels = 3;
  200859. break;
  200860. case PNG_COLOR_TYPE_PALETTE:
  200861. switch (bit_depth)
  200862. {
  200863. case 1:
  200864. case 2:
  200865. case 4:
  200866. case 8: png_ptr->channels = 1; break;
  200867. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200868. }
  200869. break;
  200870. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200871. if (bit_depth != 8 && bit_depth != 16)
  200872. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200873. png_ptr->channels = 2;
  200874. break;
  200875. case PNG_COLOR_TYPE_RGB_ALPHA:
  200876. if (bit_depth != 8 && bit_depth != 16)
  200877. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200878. png_ptr->channels = 4;
  200879. break;
  200880. default:
  200881. png_error(png_ptr, "Invalid image color type specified");
  200882. }
  200883. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200884. {
  200885. png_warning(png_ptr, "Invalid compression type specified");
  200886. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200887. }
  200888. /* Write filter_method 64 (intrapixel differencing) only if
  200889. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200890. * 2. Libpng did not write a PNG signature (this filter_method is only
  200891. * used in PNG datastreams that are embedded in MNG datastreams) and
  200892. * 3. The application called png_permit_mng_features with a mask that
  200893. * included PNG_FLAG_MNG_FILTER_64 and
  200894. * 4. The filter_method is 64 and
  200895. * 5. The color_type is RGB or RGBA
  200896. */
  200897. if (
  200898. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200899. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200900. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200901. (color_type == PNG_COLOR_TYPE_RGB ||
  200902. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200903. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200904. #endif
  200905. filter_type != PNG_FILTER_TYPE_BASE)
  200906. {
  200907. png_warning(png_ptr, "Invalid filter type specified");
  200908. filter_type = PNG_FILTER_TYPE_BASE;
  200909. }
  200910. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200911. if (interlace_type != PNG_INTERLACE_NONE &&
  200912. interlace_type != PNG_INTERLACE_ADAM7)
  200913. {
  200914. png_warning(png_ptr, "Invalid interlace type specified");
  200915. interlace_type = PNG_INTERLACE_ADAM7;
  200916. }
  200917. #else
  200918. interlace_type=PNG_INTERLACE_NONE;
  200919. #endif
  200920. /* save off the relevent information */
  200921. png_ptr->bit_depth = (png_byte)bit_depth;
  200922. png_ptr->color_type = (png_byte)color_type;
  200923. png_ptr->interlaced = (png_byte)interlace_type;
  200924. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200925. png_ptr->filter_type = (png_byte)filter_type;
  200926. #endif
  200927. png_ptr->compression_type = (png_byte)compression_type;
  200928. png_ptr->width = width;
  200929. png_ptr->height = height;
  200930. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200931. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200932. /* set the usr info, so any transformations can modify it */
  200933. png_ptr->usr_width = png_ptr->width;
  200934. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200935. png_ptr->usr_channels = png_ptr->channels;
  200936. /* pack the header information into the buffer */
  200937. png_save_uint_32(buf, width);
  200938. png_save_uint_32(buf + 4, height);
  200939. buf[8] = (png_byte)bit_depth;
  200940. buf[9] = (png_byte)color_type;
  200941. buf[10] = (png_byte)compression_type;
  200942. buf[11] = (png_byte)filter_type;
  200943. buf[12] = (png_byte)interlace_type;
  200944. /* write the chunk */
  200945. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200946. /* initialize zlib with PNG info */
  200947. png_ptr->zstream.zalloc = png_zalloc;
  200948. png_ptr->zstream.zfree = png_zfree;
  200949. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200950. if (!(png_ptr->do_filter))
  200951. {
  200952. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200953. png_ptr->bit_depth < 8)
  200954. png_ptr->do_filter = PNG_FILTER_NONE;
  200955. else
  200956. png_ptr->do_filter = PNG_ALL_FILTERS;
  200957. }
  200958. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200959. {
  200960. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200961. png_ptr->zlib_strategy = Z_FILTERED;
  200962. else
  200963. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200964. }
  200965. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200966. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200967. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200968. png_ptr->zlib_mem_level = 8;
  200969. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200970. png_ptr->zlib_window_bits = 15;
  200971. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200972. png_ptr->zlib_method = 8;
  200973. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200974. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200975. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200976. png_error(png_ptr, "zlib failed to initialize compressor");
  200977. png_ptr->zstream.next_out = png_ptr->zbuf;
  200978. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200979. /* libpng is not interested in zstream.data_type */
  200980. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200981. png_ptr->zstream.data_type = Z_BINARY;
  200982. png_ptr->mode = PNG_HAVE_IHDR;
  200983. }
  200984. /* write the palette. We are careful not to trust png_color to be in the
  200985. * correct order for PNG, so people can redefine it to any convenient
  200986. * structure.
  200987. */
  200988. void /* PRIVATE */
  200989. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200990. {
  200991. #ifdef PNG_USE_LOCAL_ARRAYS
  200992. PNG_PLTE;
  200993. #endif
  200994. png_uint_32 i;
  200995. png_colorp pal_ptr;
  200996. png_byte buf[3];
  200997. png_debug(1, "in png_write_PLTE\n");
  200998. if ((
  200999. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201000. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201001. #endif
  201002. num_pal == 0) || num_pal > 256)
  201003. {
  201004. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201005. {
  201006. png_error(png_ptr, "Invalid number of colors in palette");
  201007. }
  201008. else
  201009. {
  201010. png_warning(png_ptr, "Invalid number of colors in palette");
  201011. return;
  201012. }
  201013. }
  201014. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201015. {
  201016. png_warning(png_ptr,
  201017. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201018. return;
  201019. }
  201020. png_ptr->num_palette = (png_uint_16)num_pal;
  201021. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201022. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201023. #ifndef PNG_NO_POINTER_INDEXING
  201024. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201025. {
  201026. buf[0] = pal_ptr->red;
  201027. buf[1] = pal_ptr->green;
  201028. buf[2] = pal_ptr->blue;
  201029. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201030. }
  201031. #else
  201032. /* This is a little slower but some buggy compilers need to do this instead */
  201033. pal_ptr=palette;
  201034. for (i = 0; i < num_pal; i++)
  201035. {
  201036. buf[0] = pal_ptr[i].red;
  201037. buf[1] = pal_ptr[i].green;
  201038. buf[2] = pal_ptr[i].blue;
  201039. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201040. }
  201041. #endif
  201042. png_write_chunk_end(png_ptr);
  201043. png_ptr->mode |= PNG_HAVE_PLTE;
  201044. }
  201045. /* write an IDAT chunk */
  201046. void /* PRIVATE */
  201047. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201048. {
  201049. #ifdef PNG_USE_LOCAL_ARRAYS
  201050. PNG_IDAT;
  201051. #endif
  201052. png_debug(1, "in png_write_IDAT\n");
  201053. /* Optimize the CMF field in the zlib stream. */
  201054. /* This hack of the zlib stream is compliant to the stream specification. */
  201055. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201056. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201057. {
  201058. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201059. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201060. {
  201061. /* Avoid memory underflows and multiplication overflows. */
  201062. /* The conditions below are practically always satisfied;
  201063. however, they still must be checked. */
  201064. if (length >= 2 &&
  201065. png_ptr->height < 16384 && png_ptr->width < 16384)
  201066. {
  201067. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201068. ((png_ptr->width *
  201069. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201070. unsigned int z_cinfo = z_cmf >> 4;
  201071. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201072. while (uncompressed_idat_size <= half_z_window_size &&
  201073. half_z_window_size >= 256)
  201074. {
  201075. z_cinfo--;
  201076. half_z_window_size >>= 1;
  201077. }
  201078. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201079. if (data[0] != (png_byte)z_cmf)
  201080. {
  201081. data[0] = (png_byte)z_cmf;
  201082. data[1] &= 0xe0;
  201083. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201084. }
  201085. }
  201086. }
  201087. else
  201088. png_error(png_ptr,
  201089. "Invalid zlib compression method or flags in IDAT");
  201090. }
  201091. png_write_chunk(png_ptr, png_IDAT, data, length);
  201092. png_ptr->mode |= PNG_HAVE_IDAT;
  201093. }
  201094. /* write an IEND chunk */
  201095. void /* PRIVATE */
  201096. png_write_IEND(png_structp png_ptr)
  201097. {
  201098. #ifdef PNG_USE_LOCAL_ARRAYS
  201099. PNG_IEND;
  201100. #endif
  201101. png_debug(1, "in png_write_IEND\n");
  201102. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201103. (png_size_t)0);
  201104. png_ptr->mode |= PNG_HAVE_IEND;
  201105. }
  201106. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201107. /* write a gAMA chunk */
  201108. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201109. void /* PRIVATE */
  201110. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201111. {
  201112. #ifdef PNG_USE_LOCAL_ARRAYS
  201113. PNG_gAMA;
  201114. #endif
  201115. png_uint_32 igamma;
  201116. png_byte buf[4];
  201117. png_debug(1, "in png_write_gAMA\n");
  201118. /* file_gamma is saved in 1/100,000ths */
  201119. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201120. png_save_uint_32(buf, igamma);
  201121. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201122. }
  201123. #endif
  201124. #ifdef PNG_FIXED_POINT_SUPPORTED
  201125. void /* PRIVATE */
  201126. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201127. {
  201128. #ifdef PNG_USE_LOCAL_ARRAYS
  201129. PNG_gAMA;
  201130. #endif
  201131. png_byte buf[4];
  201132. png_debug(1, "in png_write_gAMA\n");
  201133. /* file_gamma is saved in 1/100,000ths */
  201134. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201135. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201136. }
  201137. #endif
  201138. #endif
  201139. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201140. /* write a sRGB chunk */
  201141. void /* PRIVATE */
  201142. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201143. {
  201144. #ifdef PNG_USE_LOCAL_ARRAYS
  201145. PNG_sRGB;
  201146. #endif
  201147. png_byte buf[1];
  201148. png_debug(1, "in png_write_sRGB\n");
  201149. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201150. png_warning(png_ptr,
  201151. "Invalid sRGB rendering intent specified");
  201152. buf[0]=(png_byte)srgb_intent;
  201153. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201154. }
  201155. #endif
  201156. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201157. /* write an iCCP chunk */
  201158. void /* PRIVATE */
  201159. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201160. png_charp profile, int profile_len)
  201161. {
  201162. #ifdef PNG_USE_LOCAL_ARRAYS
  201163. PNG_iCCP;
  201164. #endif
  201165. png_size_t name_len;
  201166. png_charp new_name;
  201167. compression_state comp;
  201168. int embedded_profile_len = 0;
  201169. png_debug(1, "in png_write_iCCP\n");
  201170. comp.num_output_ptr = 0;
  201171. comp.max_output_ptr = 0;
  201172. comp.output_ptr = NULL;
  201173. comp.input = NULL;
  201174. comp.input_len = 0;
  201175. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201176. &new_name)) == 0)
  201177. {
  201178. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201179. return;
  201180. }
  201181. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201182. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201183. if (profile == NULL)
  201184. profile_len = 0;
  201185. if (profile_len > 3)
  201186. embedded_profile_len =
  201187. ((*( (png_bytep)profile ))<<24) |
  201188. ((*( (png_bytep)profile+1))<<16) |
  201189. ((*( (png_bytep)profile+2))<< 8) |
  201190. ((*( (png_bytep)profile+3)) );
  201191. if (profile_len < embedded_profile_len)
  201192. {
  201193. png_warning(png_ptr,
  201194. "Embedded profile length too large in iCCP chunk");
  201195. return;
  201196. }
  201197. if (profile_len > embedded_profile_len)
  201198. {
  201199. png_warning(png_ptr,
  201200. "Truncating profile to actual length in iCCP chunk");
  201201. profile_len = embedded_profile_len;
  201202. }
  201203. if (profile_len)
  201204. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201205. PNG_COMPRESSION_TYPE_BASE, &comp);
  201206. /* make sure we include the NULL after the name and the compression type */
  201207. png_write_chunk_start(png_ptr, png_iCCP,
  201208. (png_uint_32)name_len+profile_len+2);
  201209. new_name[name_len+1]=0x00;
  201210. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201211. if (profile_len)
  201212. png_write_compressed_data_out(png_ptr, &comp);
  201213. png_write_chunk_end(png_ptr);
  201214. png_free(png_ptr, new_name);
  201215. }
  201216. #endif
  201217. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201218. /* write a sPLT chunk */
  201219. void /* PRIVATE */
  201220. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201221. {
  201222. #ifdef PNG_USE_LOCAL_ARRAYS
  201223. PNG_sPLT;
  201224. #endif
  201225. png_size_t name_len;
  201226. png_charp new_name;
  201227. png_byte entrybuf[10];
  201228. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201229. int palette_size = entry_size * spalette->nentries;
  201230. png_sPLT_entryp ep;
  201231. #ifdef PNG_NO_POINTER_INDEXING
  201232. int i;
  201233. #endif
  201234. png_debug(1, "in png_write_sPLT\n");
  201235. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201236. spalette->name, &new_name))==0)
  201237. {
  201238. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201239. return;
  201240. }
  201241. /* make sure we include the NULL after the name */
  201242. png_write_chunk_start(png_ptr, png_sPLT,
  201243. (png_uint_32)(name_len + 2 + palette_size));
  201244. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201245. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201246. /* loop through each palette entry, writing appropriately */
  201247. #ifndef PNG_NO_POINTER_INDEXING
  201248. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201249. {
  201250. if (spalette->depth == 8)
  201251. {
  201252. entrybuf[0] = (png_byte)ep->red;
  201253. entrybuf[1] = (png_byte)ep->green;
  201254. entrybuf[2] = (png_byte)ep->blue;
  201255. entrybuf[3] = (png_byte)ep->alpha;
  201256. png_save_uint_16(entrybuf + 4, ep->frequency);
  201257. }
  201258. else
  201259. {
  201260. png_save_uint_16(entrybuf + 0, ep->red);
  201261. png_save_uint_16(entrybuf + 2, ep->green);
  201262. png_save_uint_16(entrybuf + 4, ep->blue);
  201263. png_save_uint_16(entrybuf + 6, ep->alpha);
  201264. png_save_uint_16(entrybuf + 8, ep->frequency);
  201265. }
  201266. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201267. }
  201268. #else
  201269. ep=spalette->entries;
  201270. for (i=0; i>spalette->nentries; i++)
  201271. {
  201272. if (spalette->depth == 8)
  201273. {
  201274. entrybuf[0] = (png_byte)ep[i].red;
  201275. entrybuf[1] = (png_byte)ep[i].green;
  201276. entrybuf[2] = (png_byte)ep[i].blue;
  201277. entrybuf[3] = (png_byte)ep[i].alpha;
  201278. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201279. }
  201280. else
  201281. {
  201282. png_save_uint_16(entrybuf + 0, ep[i].red);
  201283. png_save_uint_16(entrybuf + 2, ep[i].green);
  201284. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201285. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201286. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201287. }
  201288. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201289. }
  201290. #endif
  201291. png_write_chunk_end(png_ptr);
  201292. png_free(png_ptr, new_name);
  201293. }
  201294. #endif
  201295. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201296. /* write the sBIT chunk */
  201297. void /* PRIVATE */
  201298. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201299. {
  201300. #ifdef PNG_USE_LOCAL_ARRAYS
  201301. PNG_sBIT;
  201302. #endif
  201303. png_byte buf[4];
  201304. png_size_t size;
  201305. png_debug(1, "in png_write_sBIT\n");
  201306. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201307. if (color_type & PNG_COLOR_MASK_COLOR)
  201308. {
  201309. png_byte maxbits;
  201310. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201311. png_ptr->usr_bit_depth);
  201312. if (sbit->red == 0 || sbit->red > maxbits ||
  201313. sbit->green == 0 || sbit->green > maxbits ||
  201314. sbit->blue == 0 || sbit->blue > maxbits)
  201315. {
  201316. png_warning(png_ptr, "Invalid sBIT depth specified");
  201317. return;
  201318. }
  201319. buf[0] = sbit->red;
  201320. buf[1] = sbit->green;
  201321. buf[2] = sbit->blue;
  201322. size = 3;
  201323. }
  201324. else
  201325. {
  201326. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201327. {
  201328. png_warning(png_ptr, "Invalid sBIT depth specified");
  201329. return;
  201330. }
  201331. buf[0] = sbit->gray;
  201332. size = 1;
  201333. }
  201334. if (color_type & PNG_COLOR_MASK_ALPHA)
  201335. {
  201336. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201337. {
  201338. png_warning(png_ptr, "Invalid sBIT depth specified");
  201339. return;
  201340. }
  201341. buf[size++] = sbit->alpha;
  201342. }
  201343. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201344. }
  201345. #endif
  201346. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201347. /* write the cHRM chunk */
  201348. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201349. void /* PRIVATE */
  201350. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201351. double red_x, double red_y, double green_x, double green_y,
  201352. double blue_x, double blue_y)
  201353. {
  201354. #ifdef PNG_USE_LOCAL_ARRAYS
  201355. PNG_cHRM;
  201356. #endif
  201357. png_byte buf[32];
  201358. png_uint_32 itemp;
  201359. png_debug(1, "in png_write_cHRM\n");
  201360. /* each value is saved in 1/100,000ths */
  201361. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201362. white_x + white_y > 1.0)
  201363. {
  201364. png_warning(png_ptr, "Invalid cHRM white point specified");
  201365. #if !defined(PNG_NO_CONSOLE_IO)
  201366. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201367. #endif
  201368. return;
  201369. }
  201370. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201371. png_save_uint_32(buf, itemp);
  201372. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201373. png_save_uint_32(buf + 4, itemp);
  201374. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201375. {
  201376. png_warning(png_ptr, "Invalid cHRM red point specified");
  201377. return;
  201378. }
  201379. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201380. png_save_uint_32(buf + 8, itemp);
  201381. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201382. png_save_uint_32(buf + 12, itemp);
  201383. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201384. {
  201385. png_warning(png_ptr, "Invalid cHRM green point specified");
  201386. return;
  201387. }
  201388. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201389. png_save_uint_32(buf + 16, itemp);
  201390. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201391. png_save_uint_32(buf + 20, itemp);
  201392. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201393. {
  201394. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201395. return;
  201396. }
  201397. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201398. png_save_uint_32(buf + 24, itemp);
  201399. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201400. png_save_uint_32(buf + 28, itemp);
  201401. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201402. }
  201403. #endif
  201404. #ifdef PNG_FIXED_POINT_SUPPORTED
  201405. void /* PRIVATE */
  201406. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201407. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201408. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201409. png_fixed_point blue_y)
  201410. {
  201411. #ifdef PNG_USE_LOCAL_ARRAYS
  201412. PNG_cHRM;
  201413. #endif
  201414. png_byte buf[32];
  201415. png_debug(1, "in png_write_cHRM\n");
  201416. /* each value is saved in 1/100,000ths */
  201417. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201418. {
  201419. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201420. #if !defined(PNG_NO_CONSOLE_IO)
  201421. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201422. #endif
  201423. return;
  201424. }
  201425. png_save_uint_32(buf, (png_uint_32)white_x);
  201426. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201427. if (red_x + red_y > 100000L)
  201428. {
  201429. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201430. return;
  201431. }
  201432. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201433. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201434. if (green_x + green_y > 100000L)
  201435. {
  201436. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201437. return;
  201438. }
  201439. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201440. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201441. if (blue_x + blue_y > 100000L)
  201442. {
  201443. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201444. return;
  201445. }
  201446. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201447. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201448. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201449. }
  201450. #endif
  201451. #endif
  201452. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201453. /* write the tRNS chunk */
  201454. void /* PRIVATE */
  201455. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201456. int num_trans, int color_type)
  201457. {
  201458. #ifdef PNG_USE_LOCAL_ARRAYS
  201459. PNG_tRNS;
  201460. #endif
  201461. png_byte buf[6];
  201462. png_debug(1, "in png_write_tRNS\n");
  201463. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201464. {
  201465. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201466. {
  201467. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201468. return;
  201469. }
  201470. /* write the chunk out as it is */
  201471. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201472. }
  201473. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201474. {
  201475. /* one 16 bit value */
  201476. if(tran->gray >= (1 << png_ptr->bit_depth))
  201477. {
  201478. png_warning(png_ptr,
  201479. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201480. return;
  201481. }
  201482. png_save_uint_16(buf, tran->gray);
  201483. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201484. }
  201485. else if (color_type == PNG_COLOR_TYPE_RGB)
  201486. {
  201487. /* three 16 bit values */
  201488. png_save_uint_16(buf, tran->red);
  201489. png_save_uint_16(buf + 2, tran->green);
  201490. png_save_uint_16(buf + 4, tran->blue);
  201491. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201492. {
  201493. png_warning(png_ptr,
  201494. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201495. return;
  201496. }
  201497. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201498. }
  201499. else
  201500. {
  201501. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201502. }
  201503. }
  201504. #endif
  201505. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201506. /* write the background chunk */
  201507. void /* PRIVATE */
  201508. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201509. {
  201510. #ifdef PNG_USE_LOCAL_ARRAYS
  201511. PNG_bKGD;
  201512. #endif
  201513. png_byte buf[6];
  201514. png_debug(1, "in png_write_bKGD\n");
  201515. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201516. {
  201517. if (
  201518. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201519. (png_ptr->num_palette ||
  201520. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201521. #endif
  201522. back->index > png_ptr->num_palette)
  201523. {
  201524. png_warning(png_ptr, "Invalid background palette index");
  201525. return;
  201526. }
  201527. buf[0] = back->index;
  201528. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201529. }
  201530. else if (color_type & PNG_COLOR_MASK_COLOR)
  201531. {
  201532. png_save_uint_16(buf, back->red);
  201533. png_save_uint_16(buf + 2, back->green);
  201534. png_save_uint_16(buf + 4, back->blue);
  201535. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201536. {
  201537. png_warning(png_ptr,
  201538. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201539. return;
  201540. }
  201541. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201542. }
  201543. else
  201544. {
  201545. if(back->gray >= (1 << png_ptr->bit_depth))
  201546. {
  201547. png_warning(png_ptr,
  201548. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201549. return;
  201550. }
  201551. png_save_uint_16(buf, back->gray);
  201552. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201553. }
  201554. }
  201555. #endif
  201556. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201557. /* write the histogram */
  201558. void /* PRIVATE */
  201559. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201560. {
  201561. #ifdef PNG_USE_LOCAL_ARRAYS
  201562. PNG_hIST;
  201563. #endif
  201564. int i;
  201565. png_byte buf[3];
  201566. png_debug(1, "in png_write_hIST\n");
  201567. if (num_hist > (int)png_ptr->num_palette)
  201568. {
  201569. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201570. png_ptr->num_palette);
  201571. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201572. return;
  201573. }
  201574. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201575. for (i = 0; i < num_hist; i++)
  201576. {
  201577. png_save_uint_16(buf, hist[i]);
  201578. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201579. }
  201580. png_write_chunk_end(png_ptr);
  201581. }
  201582. #endif
  201583. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201584. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201585. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201586. * and if invalid, correct the keyword rather than discarding the entire
  201587. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201588. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201589. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201590. *
  201591. * The new_key is allocated to hold the corrected keyword and must be freed
  201592. * by the calling routine. This avoids problems with trying to write to
  201593. * static keywords without having to have duplicate copies of the strings.
  201594. */
  201595. png_size_t /* PRIVATE */
  201596. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201597. {
  201598. png_size_t key_len;
  201599. png_charp kp, dp;
  201600. int kflag;
  201601. int kwarn=0;
  201602. png_debug(1, "in png_check_keyword\n");
  201603. *new_key = NULL;
  201604. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201605. {
  201606. png_warning(png_ptr, "zero length keyword");
  201607. return ((png_size_t)0);
  201608. }
  201609. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201610. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201611. if (*new_key == NULL)
  201612. {
  201613. png_warning(png_ptr, "Out of memory while procesing keyword");
  201614. return ((png_size_t)0);
  201615. }
  201616. /* Replace non-printing characters with a blank and print a warning */
  201617. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201618. {
  201619. if ((png_byte)*kp < 0x20 ||
  201620. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201621. {
  201622. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201623. char msg[40];
  201624. png_snprintf(msg, 40,
  201625. "invalid keyword character 0x%02X", (png_byte)*kp);
  201626. png_warning(png_ptr, msg);
  201627. #else
  201628. png_warning(png_ptr, "invalid character in keyword");
  201629. #endif
  201630. *dp = ' ';
  201631. }
  201632. else
  201633. {
  201634. *dp = *kp;
  201635. }
  201636. }
  201637. *dp = '\0';
  201638. /* Remove any trailing white space. */
  201639. kp = *new_key + key_len - 1;
  201640. if (*kp == ' ')
  201641. {
  201642. png_warning(png_ptr, "trailing spaces removed from keyword");
  201643. while (*kp == ' ')
  201644. {
  201645. *(kp--) = '\0';
  201646. key_len--;
  201647. }
  201648. }
  201649. /* Remove any leading white space. */
  201650. kp = *new_key;
  201651. if (*kp == ' ')
  201652. {
  201653. png_warning(png_ptr, "leading spaces removed from keyword");
  201654. while (*kp == ' ')
  201655. {
  201656. kp++;
  201657. key_len--;
  201658. }
  201659. }
  201660. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201661. /* Remove multiple internal spaces. */
  201662. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201663. {
  201664. if (*kp == ' ' && kflag == 0)
  201665. {
  201666. *(dp++) = *kp;
  201667. kflag = 1;
  201668. }
  201669. else if (*kp == ' ')
  201670. {
  201671. key_len--;
  201672. kwarn=1;
  201673. }
  201674. else
  201675. {
  201676. *(dp++) = *kp;
  201677. kflag = 0;
  201678. }
  201679. }
  201680. *dp = '\0';
  201681. if(kwarn)
  201682. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201683. if (key_len == 0)
  201684. {
  201685. png_free(png_ptr, *new_key);
  201686. *new_key=NULL;
  201687. png_warning(png_ptr, "Zero length keyword");
  201688. }
  201689. if (key_len > 79)
  201690. {
  201691. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201692. new_key[79] = '\0';
  201693. key_len = 79;
  201694. }
  201695. return (key_len);
  201696. }
  201697. #endif
  201698. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201699. /* write a tEXt chunk */
  201700. void /* PRIVATE */
  201701. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201702. png_size_t text_len)
  201703. {
  201704. #ifdef PNG_USE_LOCAL_ARRAYS
  201705. PNG_tEXt;
  201706. #endif
  201707. png_size_t key_len;
  201708. png_charp new_key;
  201709. png_debug(1, "in png_write_tEXt\n");
  201710. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201711. {
  201712. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201713. return;
  201714. }
  201715. if (text == NULL || *text == '\0')
  201716. text_len = 0;
  201717. else
  201718. text_len = png_strlen(text);
  201719. /* make sure we include the 0 after the key */
  201720. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201721. /*
  201722. * We leave it to the application to meet PNG-1.0 requirements on the
  201723. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201724. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201725. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201726. */
  201727. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201728. if (text_len)
  201729. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201730. png_write_chunk_end(png_ptr);
  201731. png_free(png_ptr, new_key);
  201732. }
  201733. #endif
  201734. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201735. /* write a compressed text chunk */
  201736. void /* PRIVATE */
  201737. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201738. png_size_t text_len, int compression)
  201739. {
  201740. #ifdef PNG_USE_LOCAL_ARRAYS
  201741. PNG_zTXt;
  201742. #endif
  201743. png_size_t key_len;
  201744. char buf[1];
  201745. png_charp new_key;
  201746. compression_state comp;
  201747. png_debug(1, "in png_write_zTXt\n");
  201748. comp.num_output_ptr = 0;
  201749. comp.max_output_ptr = 0;
  201750. comp.output_ptr = NULL;
  201751. comp.input = NULL;
  201752. comp.input_len = 0;
  201753. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201754. {
  201755. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201756. return;
  201757. }
  201758. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201759. {
  201760. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201761. png_free(png_ptr, new_key);
  201762. return;
  201763. }
  201764. text_len = png_strlen(text);
  201765. /* compute the compressed data; do it now for the length */
  201766. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201767. &comp);
  201768. /* write start of chunk */
  201769. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201770. (key_len+text_len+2));
  201771. /* write key */
  201772. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201773. png_free(png_ptr, new_key);
  201774. buf[0] = (png_byte)compression;
  201775. /* write compression */
  201776. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201777. /* write the compressed data */
  201778. png_write_compressed_data_out(png_ptr, &comp);
  201779. /* close the chunk */
  201780. png_write_chunk_end(png_ptr);
  201781. }
  201782. #endif
  201783. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201784. /* write an iTXt chunk */
  201785. void /* PRIVATE */
  201786. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201787. png_charp lang, png_charp lang_key, png_charp text)
  201788. {
  201789. #ifdef PNG_USE_LOCAL_ARRAYS
  201790. PNG_iTXt;
  201791. #endif
  201792. png_size_t lang_len, key_len, lang_key_len, text_len;
  201793. png_charp new_lang, new_key;
  201794. png_byte cbuf[2];
  201795. compression_state comp;
  201796. png_debug(1, "in png_write_iTXt\n");
  201797. comp.num_output_ptr = 0;
  201798. comp.max_output_ptr = 0;
  201799. comp.output_ptr = NULL;
  201800. comp.input = NULL;
  201801. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201802. {
  201803. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201804. return;
  201805. }
  201806. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201807. {
  201808. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201809. new_lang = NULL;
  201810. lang_len = 0;
  201811. }
  201812. if (lang_key == NULL)
  201813. lang_key_len = 0;
  201814. else
  201815. lang_key_len = png_strlen(lang_key);
  201816. if (text == NULL)
  201817. text_len = 0;
  201818. else
  201819. text_len = png_strlen(text);
  201820. /* compute the compressed data; do it now for the length */
  201821. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201822. &comp);
  201823. /* make sure we include the compression flag, the compression byte,
  201824. * and the NULs after the key, lang, and lang_key parts */
  201825. png_write_chunk_start(png_ptr, png_iTXt,
  201826. (png_uint_32)(
  201827. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201828. + key_len
  201829. + lang_len
  201830. + lang_key_len
  201831. + text_len));
  201832. /*
  201833. * We leave it to the application to meet PNG-1.0 requirements on the
  201834. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201835. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201836. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201837. */
  201838. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201839. /* set the compression flag */
  201840. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201841. compression == PNG_TEXT_COMPRESSION_NONE)
  201842. cbuf[0] = 0;
  201843. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201844. cbuf[0] = 1;
  201845. /* set the compression method */
  201846. cbuf[1] = 0;
  201847. png_write_chunk_data(png_ptr, cbuf, 2);
  201848. cbuf[0] = 0;
  201849. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201850. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201851. png_write_compressed_data_out(png_ptr, &comp);
  201852. png_write_chunk_end(png_ptr);
  201853. png_free(png_ptr, new_key);
  201854. if (new_lang)
  201855. png_free(png_ptr, new_lang);
  201856. }
  201857. #endif
  201858. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201859. /* write the oFFs chunk */
  201860. void /* PRIVATE */
  201861. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201862. int unit_type)
  201863. {
  201864. #ifdef PNG_USE_LOCAL_ARRAYS
  201865. PNG_oFFs;
  201866. #endif
  201867. png_byte buf[9];
  201868. png_debug(1, "in png_write_oFFs\n");
  201869. if (unit_type >= PNG_OFFSET_LAST)
  201870. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201871. png_save_int_32(buf, x_offset);
  201872. png_save_int_32(buf + 4, y_offset);
  201873. buf[8] = (png_byte)unit_type;
  201874. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201875. }
  201876. #endif
  201877. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201878. /* write the pCAL chunk (described in the PNG extensions document) */
  201879. void /* PRIVATE */
  201880. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201881. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201882. {
  201883. #ifdef PNG_USE_LOCAL_ARRAYS
  201884. PNG_pCAL;
  201885. #endif
  201886. png_size_t purpose_len, units_len, total_len;
  201887. png_uint_32p params_len;
  201888. png_byte buf[10];
  201889. png_charp new_purpose;
  201890. int i;
  201891. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201892. if (type >= PNG_EQUATION_LAST)
  201893. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201894. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201895. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201896. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201897. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201898. total_len = purpose_len + units_len + 10;
  201899. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201900. *png_sizeof(png_uint_32)));
  201901. /* Find the length of each parameter, making sure we don't count the
  201902. null terminator for the last parameter. */
  201903. for (i = 0; i < nparams; i++)
  201904. {
  201905. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201906. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201907. total_len += (png_size_t)params_len[i];
  201908. }
  201909. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201910. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201911. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201912. png_save_int_32(buf, X0);
  201913. png_save_int_32(buf + 4, X1);
  201914. buf[8] = (png_byte)type;
  201915. buf[9] = (png_byte)nparams;
  201916. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201917. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201918. png_free(png_ptr, new_purpose);
  201919. for (i = 0; i < nparams; i++)
  201920. {
  201921. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201922. (png_size_t)params_len[i]);
  201923. }
  201924. png_free(png_ptr, params_len);
  201925. png_write_chunk_end(png_ptr);
  201926. }
  201927. #endif
  201928. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201929. /* write the sCAL chunk */
  201930. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201931. void /* PRIVATE */
  201932. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201933. {
  201934. #ifdef PNG_USE_LOCAL_ARRAYS
  201935. PNG_sCAL;
  201936. #endif
  201937. char buf[64];
  201938. png_size_t total_len;
  201939. png_debug(1, "in png_write_sCAL\n");
  201940. buf[0] = (char)unit;
  201941. #if defined(_WIN32_WCE)
  201942. /* sprintf() function is not supported on WindowsCE */
  201943. {
  201944. wchar_t wc_buf[32];
  201945. size_t wc_len;
  201946. swprintf(wc_buf, TEXT("%12.12e"), width);
  201947. wc_len = wcslen(wc_buf);
  201948. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201949. total_len = wc_len + 2;
  201950. swprintf(wc_buf, TEXT("%12.12e"), height);
  201951. wc_len = wcslen(wc_buf);
  201952. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201953. NULL, NULL);
  201954. total_len += wc_len;
  201955. }
  201956. #else
  201957. png_snprintf(buf + 1, 63, "%12.12e", width);
  201958. total_len = 1 + png_strlen(buf + 1) + 1;
  201959. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201960. total_len += png_strlen(buf + total_len);
  201961. #endif
  201962. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201963. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201964. }
  201965. #else
  201966. #ifdef PNG_FIXED_POINT_SUPPORTED
  201967. void /* PRIVATE */
  201968. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201969. png_charp height)
  201970. {
  201971. #ifdef PNG_USE_LOCAL_ARRAYS
  201972. PNG_sCAL;
  201973. #endif
  201974. png_byte buf[64];
  201975. png_size_t wlen, hlen, total_len;
  201976. png_debug(1, "in png_write_sCAL_s\n");
  201977. wlen = png_strlen(width);
  201978. hlen = png_strlen(height);
  201979. total_len = wlen + hlen + 2;
  201980. if (total_len > 64)
  201981. {
  201982. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201983. return;
  201984. }
  201985. buf[0] = (png_byte)unit;
  201986. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201987. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201988. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201989. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201990. }
  201991. #endif
  201992. #endif
  201993. #endif
  201994. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201995. /* write the pHYs chunk */
  201996. void /* PRIVATE */
  201997. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201998. png_uint_32 y_pixels_per_unit,
  201999. int unit_type)
  202000. {
  202001. #ifdef PNG_USE_LOCAL_ARRAYS
  202002. PNG_pHYs;
  202003. #endif
  202004. png_byte buf[9];
  202005. png_debug(1, "in png_write_pHYs\n");
  202006. if (unit_type >= PNG_RESOLUTION_LAST)
  202007. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202008. png_save_uint_32(buf, x_pixels_per_unit);
  202009. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202010. buf[8] = (png_byte)unit_type;
  202011. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202012. }
  202013. #endif
  202014. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202015. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202016. * or png_convert_from_time_t(), or fill in the structure yourself.
  202017. */
  202018. void /* PRIVATE */
  202019. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202020. {
  202021. #ifdef PNG_USE_LOCAL_ARRAYS
  202022. PNG_tIME;
  202023. #endif
  202024. png_byte buf[7];
  202025. png_debug(1, "in png_write_tIME\n");
  202026. if (mod_time->month > 12 || mod_time->month < 1 ||
  202027. mod_time->day > 31 || mod_time->day < 1 ||
  202028. mod_time->hour > 23 || mod_time->second > 60)
  202029. {
  202030. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202031. return;
  202032. }
  202033. png_save_uint_16(buf, mod_time->year);
  202034. buf[2] = mod_time->month;
  202035. buf[3] = mod_time->day;
  202036. buf[4] = mod_time->hour;
  202037. buf[5] = mod_time->minute;
  202038. buf[6] = mod_time->second;
  202039. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202040. }
  202041. #endif
  202042. /* initializes the row writing capability of libpng */
  202043. void /* PRIVATE */
  202044. png_write_start_row(png_structp png_ptr)
  202045. {
  202046. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202047. #ifdef PNG_USE_LOCAL_ARRAYS
  202048. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202049. /* start of interlace block */
  202050. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202051. /* offset to next interlace block */
  202052. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202053. /* start of interlace block in the y direction */
  202054. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202055. /* offset to next interlace block in the y direction */
  202056. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202057. #endif
  202058. #endif
  202059. png_size_t buf_size;
  202060. png_debug(1, "in png_write_start_row\n");
  202061. buf_size = (png_size_t)(PNG_ROWBYTES(
  202062. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202063. /* set up row buffer */
  202064. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202065. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202066. #ifndef PNG_NO_WRITE_FILTERING
  202067. /* set up filtering buffer, if using this filter */
  202068. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202069. {
  202070. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202071. (png_ptr->rowbytes + 1));
  202072. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202073. }
  202074. /* We only need to keep the previous row if we are using one of these. */
  202075. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202076. {
  202077. /* set up previous row buffer */
  202078. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202079. png_memset(png_ptr->prev_row, 0, buf_size);
  202080. if (png_ptr->do_filter & PNG_FILTER_UP)
  202081. {
  202082. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202083. (png_ptr->rowbytes + 1));
  202084. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202085. }
  202086. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202087. {
  202088. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202089. (png_ptr->rowbytes + 1));
  202090. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202091. }
  202092. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202093. {
  202094. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202095. (png_ptr->rowbytes + 1));
  202096. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202097. }
  202098. #endif /* PNG_NO_WRITE_FILTERING */
  202099. }
  202100. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202101. /* if interlaced, we need to set up width and height of pass */
  202102. if (png_ptr->interlaced)
  202103. {
  202104. if (!(png_ptr->transformations & PNG_INTERLACE))
  202105. {
  202106. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202107. png_pass_ystart[0]) / png_pass_yinc[0];
  202108. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202109. png_pass_start[0]) / png_pass_inc[0];
  202110. }
  202111. else
  202112. {
  202113. png_ptr->num_rows = png_ptr->height;
  202114. png_ptr->usr_width = png_ptr->width;
  202115. }
  202116. }
  202117. else
  202118. #endif
  202119. {
  202120. png_ptr->num_rows = png_ptr->height;
  202121. png_ptr->usr_width = png_ptr->width;
  202122. }
  202123. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202124. png_ptr->zstream.next_out = png_ptr->zbuf;
  202125. }
  202126. /* Internal use only. Called when finished processing a row of data. */
  202127. void /* PRIVATE */
  202128. png_write_finish_row(png_structp png_ptr)
  202129. {
  202130. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202131. #ifdef PNG_USE_LOCAL_ARRAYS
  202132. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202133. /* start of interlace block */
  202134. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202135. /* offset to next interlace block */
  202136. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202137. /* start of interlace block in the y direction */
  202138. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202139. /* offset to next interlace block in the y direction */
  202140. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202141. #endif
  202142. #endif
  202143. int ret;
  202144. png_debug(1, "in png_write_finish_row\n");
  202145. /* next row */
  202146. png_ptr->row_number++;
  202147. /* see if we are done */
  202148. if (png_ptr->row_number < png_ptr->num_rows)
  202149. return;
  202150. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202151. /* if interlaced, go to next pass */
  202152. if (png_ptr->interlaced)
  202153. {
  202154. png_ptr->row_number = 0;
  202155. if (png_ptr->transformations & PNG_INTERLACE)
  202156. {
  202157. png_ptr->pass++;
  202158. }
  202159. else
  202160. {
  202161. /* loop until we find a non-zero width or height pass */
  202162. do
  202163. {
  202164. png_ptr->pass++;
  202165. if (png_ptr->pass >= 7)
  202166. break;
  202167. png_ptr->usr_width = (png_ptr->width +
  202168. png_pass_inc[png_ptr->pass] - 1 -
  202169. png_pass_start[png_ptr->pass]) /
  202170. png_pass_inc[png_ptr->pass];
  202171. png_ptr->num_rows = (png_ptr->height +
  202172. png_pass_yinc[png_ptr->pass] - 1 -
  202173. png_pass_ystart[png_ptr->pass]) /
  202174. png_pass_yinc[png_ptr->pass];
  202175. if (png_ptr->transformations & PNG_INTERLACE)
  202176. break;
  202177. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202178. }
  202179. /* reset the row above the image for the next pass */
  202180. if (png_ptr->pass < 7)
  202181. {
  202182. if (png_ptr->prev_row != NULL)
  202183. png_memset(png_ptr->prev_row, 0,
  202184. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202185. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202186. return;
  202187. }
  202188. }
  202189. #endif
  202190. /* if we get here, we've just written the last row, so we need
  202191. to flush the compressor */
  202192. do
  202193. {
  202194. /* tell the compressor we are done */
  202195. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202196. /* check for an error */
  202197. if (ret == Z_OK)
  202198. {
  202199. /* check to see if we need more room */
  202200. if (!(png_ptr->zstream.avail_out))
  202201. {
  202202. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202203. png_ptr->zstream.next_out = png_ptr->zbuf;
  202204. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202205. }
  202206. }
  202207. else if (ret != Z_STREAM_END)
  202208. {
  202209. if (png_ptr->zstream.msg != NULL)
  202210. png_error(png_ptr, png_ptr->zstream.msg);
  202211. else
  202212. png_error(png_ptr, "zlib error");
  202213. }
  202214. } while (ret != Z_STREAM_END);
  202215. /* write any extra space */
  202216. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202217. {
  202218. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202219. png_ptr->zstream.avail_out);
  202220. }
  202221. deflateReset(&png_ptr->zstream);
  202222. png_ptr->zstream.data_type = Z_BINARY;
  202223. }
  202224. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202225. /* Pick out the correct pixels for the interlace pass.
  202226. * The basic idea here is to go through the row with a source
  202227. * pointer and a destination pointer (sp and dp), and copy the
  202228. * correct pixels for the pass. As the row gets compacted,
  202229. * sp will always be >= dp, so we should never overwrite anything.
  202230. * See the default: case for the easiest code to understand.
  202231. */
  202232. void /* PRIVATE */
  202233. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202234. {
  202235. #ifdef PNG_USE_LOCAL_ARRAYS
  202236. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202237. /* start of interlace block */
  202238. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202239. /* offset to next interlace block */
  202240. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202241. #endif
  202242. png_debug(1, "in png_do_write_interlace\n");
  202243. /* we don't have to do anything on the last pass (6) */
  202244. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202245. if (row != NULL && row_info != NULL && pass < 6)
  202246. #else
  202247. if (pass < 6)
  202248. #endif
  202249. {
  202250. /* each pixel depth is handled separately */
  202251. switch (row_info->pixel_depth)
  202252. {
  202253. case 1:
  202254. {
  202255. png_bytep sp;
  202256. png_bytep dp;
  202257. int shift;
  202258. int d;
  202259. int value;
  202260. png_uint_32 i;
  202261. png_uint_32 row_width = row_info->width;
  202262. dp = row;
  202263. d = 0;
  202264. shift = 7;
  202265. for (i = png_pass_start[pass]; i < row_width;
  202266. i += png_pass_inc[pass])
  202267. {
  202268. sp = row + (png_size_t)(i >> 3);
  202269. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202270. d |= (value << shift);
  202271. if (shift == 0)
  202272. {
  202273. shift = 7;
  202274. *dp++ = (png_byte)d;
  202275. d = 0;
  202276. }
  202277. else
  202278. shift--;
  202279. }
  202280. if (shift != 7)
  202281. *dp = (png_byte)d;
  202282. break;
  202283. }
  202284. case 2:
  202285. {
  202286. png_bytep sp;
  202287. png_bytep dp;
  202288. int shift;
  202289. int d;
  202290. int value;
  202291. png_uint_32 i;
  202292. png_uint_32 row_width = row_info->width;
  202293. dp = row;
  202294. shift = 6;
  202295. d = 0;
  202296. for (i = png_pass_start[pass]; i < row_width;
  202297. i += png_pass_inc[pass])
  202298. {
  202299. sp = row + (png_size_t)(i >> 2);
  202300. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202301. d |= (value << shift);
  202302. if (shift == 0)
  202303. {
  202304. shift = 6;
  202305. *dp++ = (png_byte)d;
  202306. d = 0;
  202307. }
  202308. else
  202309. shift -= 2;
  202310. }
  202311. if (shift != 6)
  202312. *dp = (png_byte)d;
  202313. break;
  202314. }
  202315. case 4:
  202316. {
  202317. png_bytep sp;
  202318. png_bytep dp;
  202319. int shift;
  202320. int d;
  202321. int value;
  202322. png_uint_32 i;
  202323. png_uint_32 row_width = row_info->width;
  202324. dp = row;
  202325. shift = 4;
  202326. d = 0;
  202327. for (i = png_pass_start[pass]; i < row_width;
  202328. i += png_pass_inc[pass])
  202329. {
  202330. sp = row + (png_size_t)(i >> 1);
  202331. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202332. d |= (value << shift);
  202333. if (shift == 0)
  202334. {
  202335. shift = 4;
  202336. *dp++ = (png_byte)d;
  202337. d = 0;
  202338. }
  202339. else
  202340. shift -= 4;
  202341. }
  202342. if (shift != 4)
  202343. *dp = (png_byte)d;
  202344. break;
  202345. }
  202346. default:
  202347. {
  202348. png_bytep sp;
  202349. png_bytep dp;
  202350. png_uint_32 i;
  202351. png_uint_32 row_width = row_info->width;
  202352. png_size_t pixel_bytes;
  202353. /* start at the beginning */
  202354. dp = row;
  202355. /* find out how many bytes each pixel takes up */
  202356. pixel_bytes = (row_info->pixel_depth >> 3);
  202357. /* loop through the row, only looking at the pixels that
  202358. matter */
  202359. for (i = png_pass_start[pass]; i < row_width;
  202360. i += png_pass_inc[pass])
  202361. {
  202362. /* find out where the original pixel is */
  202363. sp = row + (png_size_t)i * pixel_bytes;
  202364. /* move the pixel */
  202365. if (dp != sp)
  202366. png_memcpy(dp, sp, pixel_bytes);
  202367. /* next pixel */
  202368. dp += pixel_bytes;
  202369. }
  202370. break;
  202371. }
  202372. }
  202373. /* set new row width */
  202374. row_info->width = (row_info->width +
  202375. png_pass_inc[pass] - 1 -
  202376. png_pass_start[pass]) /
  202377. png_pass_inc[pass];
  202378. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202379. row_info->width);
  202380. }
  202381. }
  202382. #endif
  202383. /* This filters the row, chooses which filter to use, if it has not already
  202384. * been specified by the application, and then writes the row out with the
  202385. * chosen filter.
  202386. */
  202387. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202388. #define PNG_HISHIFT 10
  202389. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202390. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202391. void /* PRIVATE */
  202392. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202393. {
  202394. png_bytep best_row;
  202395. #ifndef PNG_NO_WRITE_FILTER
  202396. png_bytep prev_row, row_buf;
  202397. png_uint_32 mins, bpp;
  202398. png_byte filter_to_do = png_ptr->do_filter;
  202399. png_uint_32 row_bytes = row_info->rowbytes;
  202400. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202401. int num_p_filters = (int)png_ptr->num_prev_filters;
  202402. #endif
  202403. png_debug(1, "in png_write_find_filter\n");
  202404. /* find out how many bytes offset each pixel is */
  202405. bpp = (row_info->pixel_depth + 7) >> 3;
  202406. prev_row = png_ptr->prev_row;
  202407. #endif
  202408. best_row = png_ptr->row_buf;
  202409. #ifndef PNG_NO_WRITE_FILTER
  202410. row_buf = best_row;
  202411. mins = PNG_MAXSUM;
  202412. /* The prediction method we use is to find which method provides the
  202413. * smallest value when summing the absolute values of the distances
  202414. * from zero, using anything >= 128 as negative numbers. This is known
  202415. * as the "minimum sum of absolute differences" heuristic. Other
  202416. * heuristics are the "weighted minimum sum of absolute differences"
  202417. * (experimental and can in theory improve compression), and the "zlib
  202418. * predictive" method (not implemented yet), which does test compressions
  202419. * of lines using different filter methods, and then chooses the
  202420. * (series of) filter(s) that give minimum compressed data size (VERY
  202421. * computationally expensive).
  202422. *
  202423. * GRR 980525: consider also
  202424. * (1) minimum sum of absolute differences from running average (i.e.,
  202425. * keep running sum of non-absolute differences & count of bytes)
  202426. * [track dispersion, too? restart average if dispersion too large?]
  202427. * (1b) minimum sum of absolute differences from sliding average, probably
  202428. * with window size <= deflate window (usually 32K)
  202429. * (2) minimum sum of squared differences from zero or running average
  202430. * (i.e., ~ root-mean-square approach)
  202431. */
  202432. /* We don't need to test the 'no filter' case if this is the only filter
  202433. * that has been chosen, as it doesn't actually do anything to the data.
  202434. */
  202435. if ((filter_to_do & PNG_FILTER_NONE) &&
  202436. filter_to_do != PNG_FILTER_NONE)
  202437. {
  202438. png_bytep rp;
  202439. png_uint_32 sum = 0;
  202440. png_uint_32 i;
  202441. int v;
  202442. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202443. {
  202444. v = *rp;
  202445. sum += (v < 128) ? v : 256 - v;
  202446. }
  202447. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202448. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202449. {
  202450. png_uint_32 sumhi, sumlo;
  202451. int j;
  202452. sumlo = sum & PNG_LOMASK;
  202453. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202454. /* Reduce the sum if we match any of the previous rows */
  202455. for (j = 0; j < num_p_filters; j++)
  202456. {
  202457. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202458. {
  202459. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202460. PNG_WEIGHT_SHIFT;
  202461. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202462. PNG_WEIGHT_SHIFT;
  202463. }
  202464. }
  202465. /* Factor in the cost of this filter (this is here for completeness,
  202466. * but it makes no sense to have a "cost" for the NONE filter, as
  202467. * it has the minimum possible computational cost - none).
  202468. */
  202469. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202470. PNG_COST_SHIFT;
  202471. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202472. PNG_COST_SHIFT;
  202473. if (sumhi > PNG_HIMASK)
  202474. sum = PNG_MAXSUM;
  202475. else
  202476. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202477. }
  202478. #endif
  202479. mins = sum;
  202480. }
  202481. /* sub filter */
  202482. if (filter_to_do == PNG_FILTER_SUB)
  202483. /* it's the only filter so no testing is needed */
  202484. {
  202485. png_bytep rp, lp, dp;
  202486. png_uint_32 i;
  202487. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202488. i++, rp++, dp++)
  202489. {
  202490. *dp = *rp;
  202491. }
  202492. for (lp = row_buf + 1; i < row_bytes;
  202493. i++, rp++, lp++, dp++)
  202494. {
  202495. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202496. }
  202497. best_row = png_ptr->sub_row;
  202498. }
  202499. else if (filter_to_do & PNG_FILTER_SUB)
  202500. {
  202501. png_bytep rp, dp, lp;
  202502. png_uint_32 sum = 0, lmins = mins;
  202503. png_uint_32 i;
  202504. int v;
  202505. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202506. /* We temporarily increase the "minimum sum" by the factor we
  202507. * would reduce the sum of this filter, so that we can do the
  202508. * early exit comparison without scaling the sum each time.
  202509. */
  202510. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202511. {
  202512. int j;
  202513. png_uint_32 lmhi, lmlo;
  202514. lmlo = lmins & PNG_LOMASK;
  202515. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202516. for (j = 0; j < num_p_filters; j++)
  202517. {
  202518. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202519. {
  202520. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202521. PNG_WEIGHT_SHIFT;
  202522. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202523. PNG_WEIGHT_SHIFT;
  202524. }
  202525. }
  202526. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202527. PNG_COST_SHIFT;
  202528. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202529. PNG_COST_SHIFT;
  202530. if (lmhi > PNG_HIMASK)
  202531. lmins = PNG_MAXSUM;
  202532. else
  202533. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202534. }
  202535. #endif
  202536. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202537. i++, rp++, dp++)
  202538. {
  202539. v = *dp = *rp;
  202540. sum += (v < 128) ? v : 256 - v;
  202541. }
  202542. for (lp = row_buf + 1; i < row_bytes;
  202543. i++, rp++, lp++, dp++)
  202544. {
  202545. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202546. sum += (v < 128) ? v : 256 - v;
  202547. if (sum > lmins) /* We are already worse, don't continue. */
  202548. break;
  202549. }
  202550. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202551. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202552. {
  202553. int j;
  202554. png_uint_32 sumhi, sumlo;
  202555. sumlo = sum & PNG_LOMASK;
  202556. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202557. for (j = 0; j < num_p_filters; j++)
  202558. {
  202559. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202560. {
  202561. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202562. PNG_WEIGHT_SHIFT;
  202563. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202564. PNG_WEIGHT_SHIFT;
  202565. }
  202566. }
  202567. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202568. PNG_COST_SHIFT;
  202569. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202570. PNG_COST_SHIFT;
  202571. if (sumhi > PNG_HIMASK)
  202572. sum = PNG_MAXSUM;
  202573. else
  202574. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202575. }
  202576. #endif
  202577. if (sum < mins)
  202578. {
  202579. mins = sum;
  202580. best_row = png_ptr->sub_row;
  202581. }
  202582. }
  202583. /* up filter */
  202584. if (filter_to_do == PNG_FILTER_UP)
  202585. {
  202586. png_bytep rp, dp, pp;
  202587. png_uint_32 i;
  202588. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202589. pp = prev_row + 1; i < row_bytes;
  202590. i++, rp++, pp++, dp++)
  202591. {
  202592. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202593. }
  202594. best_row = png_ptr->up_row;
  202595. }
  202596. else if (filter_to_do & PNG_FILTER_UP)
  202597. {
  202598. png_bytep rp, dp, pp;
  202599. png_uint_32 sum = 0, lmins = mins;
  202600. png_uint_32 i;
  202601. int v;
  202602. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202603. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202604. {
  202605. int j;
  202606. png_uint_32 lmhi, lmlo;
  202607. lmlo = lmins & PNG_LOMASK;
  202608. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202609. for (j = 0; j < num_p_filters; j++)
  202610. {
  202611. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202612. {
  202613. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202614. PNG_WEIGHT_SHIFT;
  202615. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202616. PNG_WEIGHT_SHIFT;
  202617. }
  202618. }
  202619. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202620. PNG_COST_SHIFT;
  202621. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202622. PNG_COST_SHIFT;
  202623. if (lmhi > PNG_HIMASK)
  202624. lmins = PNG_MAXSUM;
  202625. else
  202626. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202627. }
  202628. #endif
  202629. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202630. pp = prev_row + 1; i < row_bytes; i++)
  202631. {
  202632. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202633. sum += (v < 128) ? v : 256 - v;
  202634. if (sum > lmins) /* We are already worse, don't continue. */
  202635. break;
  202636. }
  202637. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202638. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202639. {
  202640. int j;
  202641. png_uint_32 sumhi, sumlo;
  202642. sumlo = sum & PNG_LOMASK;
  202643. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202644. for (j = 0; j < num_p_filters; j++)
  202645. {
  202646. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202647. {
  202648. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202649. PNG_WEIGHT_SHIFT;
  202650. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202651. PNG_WEIGHT_SHIFT;
  202652. }
  202653. }
  202654. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202655. PNG_COST_SHIFT;
  202656. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202657. PNG_COST_SHIFT;
  202658. if (sumhi > PNG_HIMASK)
  202659. sum = PNG_MAXSUM;
  202660. else
  202661. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202662. }
  202663. #endif
  202664. if (sum < mins)
  202665. {
  202666. mins = sum;
  202667. best_row = png_ptr->up_row;
  202668. }
  202669. }
  202670. /* avg filter */
  202671. if (filter_to_do == PNG_FILTER_AVG)
  202672. {
  202673. png_bytep rp, dp, pp, lp;
  202674. png_uint_32 i;
  202675. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202676. pp = prev_row + 1; i < bpp; i++)
  202677. {
  202678. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202679. }
  202680. for (lp = row_buf + 1; i < row_bytes; i++)
  202681. {
  202682. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202683. & 0xff);
  202684. }
  202685. best_row = png_ptr->avg_row;
  202686. }
  202687. else if (filter_to_do & PNG_FILTER_AVG)
  202688. {
  202689. png_bytep rp, dp, pp, lp;
  202690. png_uint_32 sum = 0, lmins = mins;
  202691. png_uint_32 i;
  202692. int v;
  202693. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202694. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202695. {
  202696. int j;
  202697. png_uint_32 lmhi, lmlo;
  202698. lmlo = lmins & PNG_LOMASK;
  202699. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202700. for (j = 0; j < num_p_filters; j++)
  202701. {
  202702. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202703. {
  202704. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202705. PNG_WEIGHT_SHIFT;
  202706. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202707. PNG_WEIGHT_SHIFT;
  202708. }
  202709. }
  202710. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202711. PNG_COST_SHIFT;
  202712. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202713. PNG_COST_SHIFT;
  202714. if (lmhi > PNG_HIMASK)
  202715. lmins = PNG_MAXSUM;
  202716. else
  202717. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202718. }
  202719. #endif
  202720. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202721. pp = prev_row + 1; i < bpp; i++)
  202722. {
  202723. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202724. sum += (v < 128) ? v : 256 - v;
  202725. }
  202726. for (lp = row_buf + 1; i < row_bytes; i++)
  202727. {
  202728. v = *dp++ =
  202729. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202730. sum += (v < 128) ? v : 256 - v;
  202731. if (sum > lmins) /* We are already worse, don't continue. */
  202732. break;
  202733. }
  202734. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202735. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202736. {
  202737. int j;
  202738. png_uint_32 sumhi, sumlo;
  202739. sumlo = sum & PNG_LOMASK;
  202740. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202741. for (j = 0; j < num_p_filters; j++)
  202742. {
  202743. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202744. {
  202745. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202746. PNG_WEIGHT_SHIFT;
  202747. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202748. PNG_WEIGHT_SHIFT;
  202749. }
  202750. }
  202751. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202752. PNG_COST_SHIFT;
  202753. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202754. PNG_COST_SHIFT;
  202755. if (sumhi > PNG_HIMASK)
  202756. sum = PNG_MAXSUM;
  202757. else
  202758. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202759. }
  202760. #endif
  202761. if (sum < mins)
  202762. {
  202763. mins = sum;
  202764. best_row = png_ptr->avg_row;
  202765. }
  202766. }
  202767. /* Paeth filter */
  202768. if (filter_to_do == PNG_FILTER_PAETH)
  202769. {
  202770. png_bytep rp, dp, pp, cp, lp;
  202771. png_uint_32 i;
  202772. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202773. pp = prev_row + 1; i < bpp; i++)
  202774. {
  202775. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202776. }
  202777. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202778. {
  202779. int a, b, c, pa, pb, pc, p;
  202780. b = *pp++;
  202781. c = *cp++;
  202782. a = *lp++;
  202783. p = b - c;
  202784. pc = a - c;
  202785. #ifdef PNG_USE_ABS
  202786. pa = abs(p);
  202787. pb = abs(pc);
  202788. pc = abs(p + pc);
  202789. #else
  202790. pa = p < 0 ? -p : p;
  202791. pb = pc < 0 ? -pc : pc;
  202792. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202793. #endif
  202794. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202795. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202796. }
  202797. best_row = png_ptr->paeth_row;
  202798. }
  202799. else if (filter_to_do & PNG_FILTER_PAETH)
  202800. {
  202801. png_bytep rp, dp, pp, cp, lp;
  202802. png_uint_32 sum = 0, lmins = mins;
  202803. png_uint_32 i;
  202804. int v;
  202805. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202806. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202807. {
  202808. int j;
  202809. png_uint_32 lmhi, lmlo;
  202810. lmlo = lmins & PNG_LOMASK;
  202811. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202812. for (j = 0; j < num_p_filters; j++)
  202813. {
  202814. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202815. {
  202816. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202817. PNG_WEIGHT_SHIFT;
  202818. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202819. PNG_WEIGHT_SHIFT;
  202820. }
  202821. }
  202822. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202823. PNG_COST_SHIFT;
  202824. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202825. PNG_COST_SHIFT;
  202826. if (lmhi > PNG_HIMASK)
  202827. lmins = PNG_MAXSUM;
  202828. else
  202829. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202830. }
  202831. #endif
  202832. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202833. pp = prev_row + 1; i < bpp; i++)
  202834. {
  202835. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202836. sum += (v < 128) ? v : 256 - v;
  202837. }
  202838. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202839. {
  202840. int a, b, c, pa, pb, pc, p;
  202841. b = *pp++;
  202842. c = *cp++;
  202843. a = *lp++;
  202844. #ifndef PNG_SLOW_PAETH
  202845. p = b - c;
  202846. pc = a - c;
  202847. #ifdef PNG_USE_ABS
  202848. pa = abs(p);
  202849. pb = abs(pc);
  202850. pc = abs(p + pc);
  202851. #else
  202852. pa = p < 0 ? -p : p;
  202853. pb = pc < 0 ? -pc : pc;
  202854. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202855. #endif
  202856. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202857. #else /* PNG_SLOW_PAETH */
  202858. p = a + b - c;
  202859. pa = abs(p - a);
  202860. pb = abs(p - b);
  202861. pc = abs(p - c);
  202862. if (pa <= pb && pa <= pc)
  202863. p = a;
  202864. else if (pb <= pc)
  202865. p = b;
  202866. else
  202867. p = c;
  202868. #endif /* PNG_SLOW_PAETH */
  202869. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202870. sum += (v < 128) ? v : 256 - v;
  202871. if (sum > lmins) /* We are already worse, don't continue. */
  202872. break;
  202873. }
  202874. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202875. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202876. {
  202877. int j;
  202878. png_uint_32 sumhi, sumlo;
  202879. sumlo = sum & PNG_LOMASK;
  202880. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202881. for (j = 0; j < num_p_filters; j++)
  202882. {
  202883. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202884. {
  202885. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202886. PNG_WEIGHT_SHIFT;
  202887. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202888. PNG_WEIGHT_SHIFT;
  202889. }
  202890. }
  202891. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202892. PNG_COST_SHIFT;
  202893. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202894. PNG_COST_SHIFT;
  202895. if (sumhi > PNG_HIMASK)
  202896. sum = PNG_MAXSUM;
  202897. else
  202898. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202899. }
  202900. #endif
  202901. if (sum < mins)
  202902. {
  202903. best_row = png_ptr->paeth_row;
  202904. }
  202905. }
  202906. #endif /* PNG_NO_WRITE_FILTER */
  202907. /* Do the actual writing of the filtered row data from the chosen filter. */
  202908. png_write_filtered_row(png_ptr, best_row);
  202909. #ifndef PNG_NO_WRITE_FILTER
  202910. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202911. /* Save the type of filter we picked this time for future calculations */
  202912. if (png_ptr->num_prev_filters > 0)
  202913. {
  202914. int j;
  202915. for (j = 1; j < num_p_filters; j++)
  202916. {
  202917. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202918. }
  202919. png_ptr->prev_filters[j] = best_row[0];
  202920. }
  202921. #endif
  202922. #endif /* PNG_NO_WRITE_FILTER */
  202923. }
  202924. /* Do the actual writing of a previously filtered row. */
  202925. void /* PRIVATE */
  202926. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202927. {
  202928. png_debug(1, "in png_write_filtered_row\n");
  202929. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202930. /* set up the zlib input buffer */
  202931. png_ptr->zstream.next_in = filtered_row;
  202932. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202933. /* repeat until we have compressed all the data */
  202934. do
  202935. {
  202936. int ret; /* return of zlib */
  202937. /* compress the data */
  202938. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202939. /* check for compression errors */
  202940. if (ret != Z_OK)
  202941. {
  202942. if (png_ptr->zstream.msg != NULL)
  202943. png_error(png_ptr, png_ptr->zstream.msg);
  202944. else
  202945. png_error(png_ptr, "zlib error");
  202946. }
  202947. /* see if it is time to write another IDAT */
  202948. if (!(png_ptr->zstream.avail_out))
  202949. {
  202950. /* write the IDAT and reset the zlib output buffer */
  202951. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202952. png_ptr->zstream.next_out = png_ptr->zbuf;
  202953. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202954. }
  202955. /* repeat until all data has been compressed */
  202956. } while (png_ptr->zstream.avail_in);
  202957. /* swap the current and previous rows */
  202958. if (png_ptr->prev_row != NULL)
  202959. {
  202960. png_bytep tptr;
  202961. tptr = png_ptr->prev_row;
  202962. png_ptr->prev_row = png_ptr->row_buf;
  202963. png_ptr->row_buf = tptr;
  202964. }
  202965. /* finish row - updates counters and flushes zlib if last row */
  202966. png_write_finish_row(png_ptr);
  202967. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202968. png_ptr->flush_rows++;
  202969. if (png_ptr->flush_dist > 0 &&
  202970. png_ptr->flush_rows >= png_ptr->flush_dist)
  202971. {
  202972. png_write_flush(png_ptr);
  202973. }
  202974. #endif
  202975. }
  202976. #endif /* PNG_WRITE_SUPPORTED */
  202977. /*** End of inlined file: pngwutil.c ***/
  202978. #else
  202979. extern "C"
  202980. {
  202981. #include <png.h>
  202982. #include <pngconf.h>
  202983. }
  202984. #endif
  202985. }
  202986. #undef max
  202987. #undef min
  202988. #if JUCE_MSVC
  202989. #pragma warning (pop)
  202990. #endif
  202991. BEGIN_JUCE_NAMESPACE
  202992. using ::calloc;
  202993. using ::malloc;
  202994. using ::free;
  202995. namespace PNGHelpers
  202996. {
  202997. using namespace pnglibNamespace;
  202998. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  202999. {
  203000. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203001. }
  203002. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203003. {
  203004. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203005. }
  203006. struct PNGErrorStruct {};
  203007. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203008. {
  203009. throw PNGErrorStruct();
  203010. }
  203011. }
  203012. PNGImageFormat::PNGImageFormat() {}
  203013. PNGImageFormat::~PNGImageFormat() {}
  203014. const String PNGImageFormat::getFormatName()
  203015. {
  203016. return "PNG";
  203017. }
  203018. bool PNGImageFormat::canUnderstand (InputStream& in)
  203019. {
  203020. const int bytesNeeded = 4;
  203021. char header [bytesNeeded];
  203022. return in.read (header, bytesNeeded) == bytesNeeded
  203023. && header[1] == 'P'
  203024. && header[2] == 'N'
  203025. && header[3] == 'G';
  203026. }
  203027. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203028. const Image juce_loadWithCoreImage (InputStream& input);
  203029. #endif
  203030. const Image PNGImageFormat::decodeImage (InputStream& in)
  203031. {
  203032. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203033. return juce_loadWithCoreImage (in);
  203034. #else
  203035. using namespace pnglibNamespace;
  203036. Image image;
  203037. png_structp pngReadStruct;
  203038. png_infop pngInfoStruct;
  203039. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203040. if (pngReadStruct != 0)
  203041. {
  203042. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203043. if (pngInfoStruct == 0)
  203044. {
  203045. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203046. return Image::null;
  203047. }
  203048. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203049. // read the header..
  203050. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203051. png_uint_32 width, height;
  203052. int bitDepth, colorType, interlaceType;
  203053. png_read_info (pngReadStruct, pngInfoStruct);
  203054. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203055. &width, &height,
  203056. &bitDepth, &colorType,
  203057. &interlaceType, 0, 0);
  203058. if (bitDepth == 16)
  203059. png_set_strip_16 (pngReadStruct);
  203060. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203061. png_set_expand (pngReadStruct);
  203062. if (bitDepth < 8)
  203063. png_set_expand (pngReadStruct);
  203064. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203065. png_set_expand (pngReadStruct);
  203066. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203067. png_set_gray_to_rgb (pngReadStruct);
  203068. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203069. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203070. || pngInfoStruct->num_trans > 0;
  203071. // Load the image into a temp buffer in the pnglib format..
  203072. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203073. {
  203074. HeapBlock <png_bytep> rows (height);
  203075. for (int y = (int) height; --y >= 0;)
  203076. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203077. png_read_image (pngReadStruct, rows);
  203078. png_read_end (pngReadStruct, pngInfoStruct);
  203079. }
  203080. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203081. // now convert the data to a juce image format..
  203082. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203083. (int) width, (int) height, hasAlphaChan);
  203084. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  203085. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203086. const Image::BitmapData destData (image, true);
  203087. uint8* srcRow = tempBuffer;
  203088. uint8* destRow = destData.data;
  203089. for (int y = 0; y < (int) height; ++y)
  203090. {
  203091. const uint8* src = srcRow;
  203092. srcRow += (width << 2);
  203093. uint8* dest = destRow;
  203094. destRow += destData.lineStride;
  203095. if (hasAlphaChan)
  203096. {
  203097. for (int i = (int) width; --i >= 0;)
  203098. {
  203099. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203100. ((PixelARGB*) dest)->premultiply();
  203101. dest += destData.pixelStride;
  203102. src += 4;
  203103. }
  203104. }
  203105. else
  203106. {
  203107. for (int i = (int) width; --i >= 0;)
  203108. {
  203109. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203110. dest += destData.pixelStride;
  203111. src += 4;
  203112. }
  203113. }
  203114. }
  203115. }
  203116. return image;
  203117. #endif
  203118. }
  203119. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203120. {
  203121. using namespace pnglibNamespace;
  203122. const int width = image.getWidth();
  203123. const int height = image.getHeight();
  203124. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203125. if (pngWriteStruct == 0)
  203126. return false;
  203127. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203128. if (pngInfoStruct == 0)
  203129. {
  203130. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203131. return false;
  203132. }
  203133. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203134. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203135. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203136. : PNG_COLOR_TYPE_RGB,
  203137. PNG_INTERLACE_NONE,
  203138. PNG_COMPRESSION_TYPE_BASE,
  203139. PNG_FILTER_TYPE_BASE);
  203140. HeapBlock <uint8> rowData (width * 4);
  203141. png_color_8 sig_bit;
  203142. sig_bit.red = 8;
  203143. sig_bit.green = 8;
  203144. sig_bit.blue = 8;
  203145. sig_bit.alpha = 8;
  203146. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203147. png_write_info (pngWriteStruct, pngInfoStruct);
  203148. png_set_shift (pngWriteStruct, &sig_bit);
  203149. png_set_packing (pngWriteStruct);
  203150. const Image::BitmapData srcData (image, false);
  203151. for (int y = 0; y < height; ++y)
  203152. {
  203153. uint8* dst = rowData;
  203154. const uint8* src = srcData.getLinePointer (y);
  203155. if (image.hasAlphaChannel())
  203156. {
  203157. for (int i = width; --i >= 0;)
  203158. {
  203159. PixelARGB p (*(const PixelARGB*) src);
  203160. p.unpremultiply();
  203161. *dst++ = p.getRed();
  203162. *dst++ = p.getGreen();
  203163. *dst++ = p.getBlue();
  203164. *dst++ = p.getAlpha();
  203165. src += srcData.pixelStride;
  203166. }
  203167. }
  203168. else
  203169. {
  203170. for (int i = width; --i >= 0;)
  203171. {
  203172. *dst++ = ((const PixelRGB*) src)->getRed();
  203173. *dst++ = ((const PixelRGB*) src)->getGreen();
  203174. *dst++ = ((const PixelRGB*) src)->getBlue();
  203175. src += srcData.pixelStride;
  203176. }
  203177. }
  203178. png_bytep rowPtr = rowData;
  203179. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203180. }
  203181. png_write_end (pngWriteStruct, pngInfoStruct);
  203182. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203183. out.flush();
  203184. return true;
  203185. }
  203186. END_JUCE_NAMESPACE
  203187. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203188. #endif
  203189. //==============================================================================
  203190. #if JUCE_BUILD_NATIVE
  203191. // Non-public headers that are needed by more than one platform must be included
  203192. // before the platform-specific sections..
  203193. BEGIN_JUCE_NAMESPACE
  203194. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203195. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203196. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203197. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203198. /**
  203199. Helper class that takes chunks of incoming midi bytes, packages them into
  203200. messages, and dispatches them to a midi callback.
  203201. */
  203202. class MidiDataConcatenator
  203203. {
  203204. public:
  203205. MidiDataConcatenator (const int initialBufferSize)
  203206. : pendingData (initialBufferSize),
  203207. pendingBytes (0), pendingDataTime (0)
  203208. {
  203209. }
  203210. void reset()
  203211. {
  203212. pendingBytes = 0;
  203213. pendingDataTime = 0;
  203214. }
  203215. void pushMidiData (const void* data, int numBytes, double time,
  203216. MidiInput* input, MidiInputCallback& callback)
  203217. {
  203218. const uint8* d = static_cast <const uint8*> (data);
  203219. while (numBytes > 0)
  203220. {
  203221. if (pendingBytes > 0 || d[0] == 0xf0)
  203222. {
  203223. processSysex (d, numBytes, time, input, callback);
  203224. }
  203225. else
  203226. {
  203227. int used = 0;
  203228. const MidiMessage m (d, numBytes, used, 0, time);
  203229. if (used <= 0)
  203230. break; // malformed message..
  203231. callback.handleIncomingMidiMessage (input, m);
  203232. numBytes -= used;
  203233. d += used;
  203234. }
  203235. }
  203236. }
  203237. private:
  203238. void processSysex (const uint8*& d, int& numBytes, double time,
  203239. MidiInput* input, MidiInputCallback& callback)
  203240. {
  203241. if (*d == 0xf0)
  203242. {
  203243. pendingBytes = 0;
  203244. pendingDataTime = time;
  203245. }
  203246. pendingData.ensureSize (pendingBytes + numBytes, false);
  203247. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203248. uint8* dest = totalMessage + pendingBytes;
  203249. do
  203250. {
  203251. if (pendingBytes > 0 && *d >= 0x80)
  203252. {
  203253. if (*d >= 0xfa || *d == 0xf8)
  203254. {
  203255. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203256. ++d;
  203257. --numBytes;
  203258. }
  203259. else
  203260. {
  203261. if (*d == 0xf7)
  203262. {
  203263. *dest++ = *d++;
  203264. pendingBytes++;
  203265. --numBytes;
  203266. }
  203267. break;
  203268. }
  203269. }
  203270. else
  203271. {
  203272. *dest++ = *d++;
  203273. pendingBytes++;
  203274. --numBytes;
  203275. }
  203276. }
  203277. while (numBytes > 0);
  203278. if (pendingBytes > 0)
  203279. {
  203280. if (totalMessage [pendingBytes - 1] == 0xf7)
  203281. {
  203282. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203283. pendingBytes = 0;
  203284. }
  203285. else
  203286. {
  203287. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203288. }
  203289. }
  203290. }
  203291. MemoryBlock pendingData;
  203292. int pendingBytes;
  203293. double pendingDataTime;
  203294. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203295. };
  203296. #endif
  203297. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203298. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203299. END_JUCE_NAMESPACE
  203300. #if JUCE_WINDOWS
  203301. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203302. /*
  203303. This file wraps together all the win32-specific code, so that
  203304. we can include all the native headers just once, and compile all our
  203305. platform-specific stuff in one big lump, keeping it out of the way of
  203306. the rest of the codebase.
  203307. */
  203308. #if JUCE_WINDOWS
  203309. BEGIN_JUCE_NAMESPACE
  203310. #define JUCE_INCLUDED_FILE 1
  203311. // Now include the actual code files..
  203312. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203313. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203314. // compiled on its own).
  203315. #if JUCE_INCLUDED_FILE
  203316. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203317. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203318. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203319. #ifndef DOXYGEN
  203320. // use with DynamicLibraryLoader to simplify importing functions
  203321. //
  203322. // functionName: function to import
  203323. // localFunctionName: name you want to use to actually call it (must be different)
  203324. // returnType: the return type
  203325. // object: the DynamicLibraryLoader to use
  203326. // params: list of params (bracketed)
  203327. //
  203328. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203329. typedef returnType (WINAPI *type##localFunctionName) params; \
  203330. type##localFunctionName localFunctionName \
  203331. = (type##localFunctionName)object.findProcAddress (#functionName);
  203332. // loads and unloads a DLL automatically
  203333. class JUCE_API DynamicLibraryLoader
  203334. {
  203335. public:
  203336. DynamicLibraryLoader (const String& name);
  203337. ~DynamicLibraryLoader();
  203338. void* findProcAddress (const String& functionName);
  203339. private:
  203340. void* libHandle;
  203341. };
  203342. #endif
  203343. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203344. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203345. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203346. {
  203347. libHandle = LoadLibrary (name);
  203348. }
  203349. DynamicLibraryLoader::~DynamicLibraryLoader()
  203350. {
  203351. FreeLibrary ((HMODULE) libHandle);
  203352. }
  203353. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203354. {
  203355. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203356. }
  203357. #endif
  203358. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203359. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203360. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203361. // compiled on its own).
  203362. #if JUCE_INCLUDED_FILE
  203363. extern void juce_initialiseThreadEvents();
  203364. void Logger::outputDebugString (const String& text)
  203365. {
  203366. OutputDebugString (text + "\n");
  203367. }
  203368. static int64 hiResTicksPerSecond;
  203369. static double hiResTicksScaleFactor;
  203370. #if JUCE_USE_INTRINSICS
  203371. // CPU info functions using intrinsics...
  203372. #pragma intrinsic (__cpuid)
  203373. #pragma intrinsic (__rdtsc)
  203374. const String SystemStats::getCpuVendor()
  203375. {
  203376. int info [4];
  203377. __cpuid (info, 0);
  203378. char v [12];
  203379. memcpy (v, info + 1, 4);
  203380. memcpy (v + 4, info + 3, 4);
  203381. memcpy (v + 8, info + 2, 4);
  203382. return String (v, 12);
  203383. }
  203384. #else
  203385. // CPU info functions using old fashioned inline asm...
  203386. static void juce_getCpuVendor (char* const v)
  203387. {
  203388. int vendor[4];
  203389. zeromem (vendor, 16);
  203390. #ifdef JUCE_64BIT
  203391. #else
  203392. #ifndef __MINGW32__
  203393. __try
  203394. #endif
  203395. {
  203396. #if JUCE_GCC
  203397. unsigned int dummy = 0;
  203398. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203399. #else
  203400. __asm
  203401. {
  203402. mov eax, 0
  203403. cpuid
  203404. mov [vendor], ebx
  203405. mov [vendor + 4], edx
  203406. mov [vendor + 8], ecx
  203407. }
  203408. #endif
  203409. }
  203410. #ifndef __MINGW32__
  203411. __except (EXCEPTION_EXECUTE_HANDLER)
  203412. {
  203413. *v = 0;
  203414. }
  203415. #endif
  203416. #endif
  203417. memcpy (v, vendor, 16);
  203418. }
  203419. const String SystemStats::getCpuVendor()
  203420. {
  203421. char v [16];
  203422. juce_getCpuVendor (v);
  203423. return String (v, 16);
  203424. }
  203425. #endif
  203426. void SystemStats::initialiseStats()
  203427. {
  203428. juce_initialiseThreadEvents();
  203429. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203430. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203431. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203432. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203433. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203434. #else
  203435. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203436. #endif
  203437. {
  203438. SYSTEM_INFO systemInfo;
  203439. GetSystemInfo (&systemInfo);
  203440. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203441. }
  203442. LARGE_INTEGER f;
  203443. QueryPerformanceFrequency (&f);
  203444. hiResTicksPerSecond = f.QuadPart;
  203445. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203446. String s (SystemStats::getJUCEVersion());
  203447. const MMRESULT res = timeBeginPeriod (1);
  203448. (void) res;
  203449. jassert (res == TIMERR_NOERROR);
  203450. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203451. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203452. #endif
  203453. }
  203454. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203455. {
  203456. OSVERSIONINFO info;
  203457. info.dwOSVersionInfoSize = sizeof (info);
  203458. GetVersionEx (&info);
  203459. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203460. {
  203461. switch (info.dwMajorVersion)
  203462. {
  203463. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203464. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203465. default: jassertfalse; break; // !! not a supported OS!
  203466. }
  203467. }
  203468. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203469. {
  203470. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203471. return Win98;
  203472. }
  203473. return UnknownOS;
  203474. }
  203475. const String SystemStats::getOperatingSystemName()
  203476. {
  203477. const char* name = "Unknown OS";
  203478. switch (getOperatingSystemType())
  203479. {
  203480. case Windows7: name = "Windows 7"; break;
  203481. case WinVista: name = "Windows Vista"; break;
  203482. case WinXP: name = "Windows XP"; break;
  203483. case Win2000: name = "Windows 2000"; break;
  203484. case Win98: name = "Windows 98"; break;
  203485. default: jassertfalse; break; // !! new type of OS?
  203486. }
  203487. return name;
  203488. }
  203489. bool SystemStats::isOperatingSystem64Bit()
  203490. {
  203491. #ifdef _WIN64
  203492. return true;
  203493. #else
  203494. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203495. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203496. BOOL isWow64 = FALSE;
  203497. return (fnIsWow64Process != 0)
  203498. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203499. && (isWow64 != FALSE);
  203500. #endif
  203501. }
  203502. int SystemStats::getMemorySizeInMegabytes()
  203503. {
  203504. MEMORYSTATUSEX mem;
  203505. mem.dwLength = sizeof (mem);
  203506. GlobalMemoryStatusEx (&mem);
  203507. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203508. }
  203509. uint32 juce_millisecondsSinceStartup() throw()
  203510. {
  203511. return (uint32) timeGetTime();
  203512. }
  203513. int64 Time::getHighResolutionTicks() throw()
  203514. {
  203515. LARGE_INTEGER ticks;
  203516. QueryPerformanceCounter (&ticks);
  203517. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203518. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203519. // fix for a very obscure PCI hardware bug that can make the counter
  203520. // sometimes jump forwards by a few seconds..
  203521. static int64 hiResTicksOffset = 0;
  203522. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203523. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203524. hiResTicksOffset = newOffset;
  203525. return ticks.QuadPart + hiResTicksOffset;
  203526. }
  203527. double Time::getMillisecondCounterHiRes() throw()
  203528. {
  203529. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203530. }
  203531. int64 Time::getHighResolutionTicksPerSecond() throw()
  203532. {
  203533. return hiResTicksPerSecond;
  203534. }
  203535. static int64 juce_getClockCycleCounter() throw()
  203536. {
  203537. #if JUCE_USE_INTRINSICS
  203538. // MS intrinsics version...
  203539. return __rdtsc();
  203540. #elif JUCE_GCC
  203541. // GNU inline asm version...
  203542. unsigned int hi = 0, lo = 0;
  203543. __asm__ __volatile__ (
  203544. "xor %%eax, %%eax \n\
  203545. xor %%edx, %%edx \n\
  203546. rdtsc \n\
  203547. movl %%eax, %[lo] \n\
  203548. movl %%edx, %[hi]"
  203549. :
  203550. : [hi] "m" (hi),
  203551. [lo] "m" (lo)
  203552. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203553. return (int64) ((((uint64) hi) << 32) | lo);
  203554. #else
  203555. // MSVC inline asm version...
  203556. unsigned int hi = 0, lo = 0;
  203557. __asm
  203558. {
  203559. xor eax, eax
  203560. xor edx, edx
  203561. rdtsc
  203562. mov lo, eax
  203563. mov hi, edx
  203564. }
  203565. return (int64) ((((uint64) hi) << 32) | lo);
  203566. #endif
  203567. }
  203568. int SystemStats::getCpuSpeedInMegaherz()
  203569. {
  203570. const int64 cycles = juce_getClockCycleCounter();
  203571. const uint32 millis = Time::getMillisecondCounter();
  203572. int lastResult = 0;
  203573. for (;;)
  203574. {
  203575. int n = 1000000;
  203576. while (--n > 0) {}
  203577. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203578. const int64 cyclesNow = juce_getClockCycleCounter();
  203579. if (millisElapsed > 80)
  203580. {
  203581. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203582. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203583. return newResult;
  203584. lastResult = newResult;
  203585. }
  203586. }
  203587. }
  203588. bool Time::setSystemTimeToThisTime() const
  203589. {
  203590. SYSTEMTIME st;
  203591. st.wDayOfWeek = 0;
  203592. st.wYear = (WORD) getYear();
  203593. st.wMonth = (WORD) (getMonth() + 1);
  203594. st.wDay = (WORD) getDayOfMonth();
  203595. st.wHour = (WORD) getHours();
  203596. st.wMinute = (WORD) getMinutes();
  203597. st.wSecond = (WORD) getSeconds();
  203598. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203599. // do this twice because of daylight saving conversion problems - the
  203600. // first one sets it up, the second one kicks it in.
  203601. return SetLocalTime (&st) != 0
  203602. && SetLocalTime (&st) != 0;
  203603. }
  203604. int SystemStats::getPageSize()
  203605. {
  203606. SYSTEM_INFO systemInfo;
  203607. GetSystemInfo (&systemInfo);
  203608. return systemInfo.dwPageSize;
  203609. }
  203610. const String SystemStats::getLogonName()
  203611. {
  203612. TCHAR text [256];
  203613. DWORD len = numElementsInArray (text) - 2;
  203614. zerostruct (text);
  203615. GetUserName (text, &len);
  203616. return String (text, len);
  203617. }
  203618. const String SystemStats::getFullUserName()
  203619. {
  203620. return getLogonName();
  203621. }
  203622. #endif
  203623. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203624. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203625. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203626. // compiled on its own).
  203627. #if JUCE_INCLUDED_FILE
  203628. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203629. extern HWND juce_messageWindowHandle;
  203630. #endif
  203631. #if ! JUCE_USE_INTRINSICS
  203632. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203633. // older ones we have to actually call the ops as win32 functions..
  203634. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203635. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203636. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203637. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203638. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203639. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203640. {
  203641. jassertfalse; // This operation isn't available in old MS compiler versions!
  203642. __int64 oldValue = *value;
  203643. if (oldValue == valueToCompare)
  203644. *value = newValue;
  203645. return oldValue;
  203646. }
  203647. #endif
  203648. CriticalSection::CriticalSection() throw()
  203649. {
  203650. // (just to check the MS haven't changed this structure and broken things...)
  203651. #if JUCE_VC7_OR_EARLIER
  203652. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203653. #else
  203654. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203655. #endif
  203656. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203657. }
  203658. CriticalSection::~CriticalSection() throw()
  203659. {
  203660. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203661. }
  203662. void CriticalSection::enter() const throw()
  203663. {
  203664. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203665. }
  203666. bool CriticalSection::tryEnter() const throw()
  203667. {
  203668. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203669. }
  203670. void CriticalSection::exit() const throw()
  203671. {
  203672. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203673. }
  203674. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203675. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203676. {
  203677. }
  203678. WaitableEvent::~WaitableEvent() throw()
  203679. {
  203680. CloseHandle (internal);
  203681. }
  203682. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203683. {
  203684. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203685. }
  203686. void WaitableEvent::signal() const throw()
  203687. {
  203688. SetEvent (internal);
  203689. }
  203690. void WaitableEvent::reset() const throw()
  203691. {
  203692. ResetEvent (internal);
  203693. }
  203694. void JUCE_API juce_threadEntryPoint (void*);
  203695. static unsigned int __stdcall threadEntryProc (void* userData)
  203696. {
  203697. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203698. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203699. GetCurrentThreadId(), TRUE);
  203700. #endif
  203701. juce_threadEntryPoint (userData);
  203702. _endthreadex (0);
  203703. return 0;
  203704. }
  203705. void juce_CloseThreadHandle (void* handle)
  203706. {
  203707. CloseHandle ((HANDLE) handle);
  203708. }
  203709. void* juce_createThread (void* userData)
  203710. {
  203711. unsigned int threadId;
  203712. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203713. }
  203714. void juce_killThread (void* handle)
  203715. {
  203716. if (handle != 0)
  203717. {
  203718. #if JUCE_DEBUG
  203719. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203720. #endif
  203721. TerminateThread (handle, 0);
  203722. }
  203723. }
  203724. void juce_setCurrentThreadName (const String& name)
  203725. {
  203726. #if JUCE_DEBUG && JUCE_MSVC
  203727. struct
  203728. {
  203729. DWORD dwType;
  203730. LPCSTR szName;
  203731. DWORD dwThreadID;
  203732. DWORD dwFlags;
  203733. } info;
  203734. info.dwType = 0x1000;
  203735. info.szName = name.toCString();
  203736. info.dwThreadID = GetCurrentThreadId();
  203737. info.dwFlags = 0;
  203738. __try
  203739. {
  203740. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203741. }
  203742. __except (EXCEPTION_CONTINUE_EXECUTION)
  203743. {}
  203744. #else
  203745. (void) name;
  203746. #endif
  203747. }
  203748. Thread::ThreadID Thread::getCurrentThreadId()
  203749. {
  203750. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203751. }
  203752. // priority 1 to 10 where 5=normal, 1=low
  203753. bool juce_setThreadPriority (void* threadHandle, int priority)
  203754. {
  203755. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203756. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203757. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203758. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203759. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203760. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203761. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203762. if (threadHandle == 0)
  203763. threadHandle = GetCurrentThread();
  203764. return SetThreadPriority (threadHandle, pri) != FALSE;
  203765. }
  203766. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203767. {
  203768. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203769. }
  203770. static HANDLE sleepEvent = 0;
  203771. void juce_initialiseThreadEvents()
  203772. {
  203773. if (sleepEvent == 0)
  203774. #if JUCE_DEBUG
  203775. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203776. #else
  203777. sleepEvent = CreateEvent (0, 0, 0, 0);
  203778. #endif
  203779. }
  203780. void Thread::yield()
  203781. {
  203782. Sleep (0);
  203783. }
  203784. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203785. {
  203786. if (millisecs >= 10)
  203787. {
  203788. Sleep (millisecs);
  203789. }
  203790. else
  203791. {
  203792. jassert (sleepEvent != 0);
  203793. // unlike Sleep() this is guaranteed to return to the current thread after
  203794. // the time expires, so we'll use this for short waits, which are more likely
  203795. // to need to be accurate
  203796. WaitForSingleObject (sleepEvent, millisecs);
  203797. }
  203798. }
  203799. static int lastProcessPriority = -1;
  203800. // called by WindowDriver because Windows does wierd things to process priority
  203801. // when you swap apps, and this forces an update when the app is brought to the front.
  203802. void juce_repeatLastProcessPriority()
  203803. {
  203804. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203805. {
  203806. DWORD p;
  203807. switch (lastProcessPriority)
  203808. {
  203809. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203810. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203811. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203812. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203813. default: jassertfalse; return; // bad priority value
  203814. }
  203815. SetPriorityClass (GetCurrentProcess(), p);
  203816. }
  203817. }
  203818. void Process::setPriority (ProcessPriority prior)
  203819. {
  203820. if (lastProcessPriority != (int) prior)
  203821. {
  203822. lastProcessPriority = (int) prior;
  203823. juce_repeatLastProcessPriority();
  203824. }
  203825. }
  203826. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  203827. {
  203828. return IsDebuggerPresent() != FALSE;
  203829. }
  203830. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203831. {
  203832. return juce_isRunningUnderDebugger();
  203833. }
  203834. void Process::raisePrivilege()
  203835. {
  203836. jassertfalse; // xxx not implemented
  203837. }
  203838. void Process::lowerPrivilege()
  203839. {
  203840. jassertfalse; // xxx not implemented
  203841. }
  203842. void Process::terminate()
  203843. {
  203844. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203845. _CrtDumpMemoryLeaks();
  203846. #endif
  203847. // bullet in the head in case there's a problem shutting down..
  203848. ExitProcess (0);
  203849. }
  203850. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203851. {
  203852. void* result = 0;
  203853. JUCE_TRY
  203854. {
  203855. result = LoadLibrary (name);
  203856. }
  203857. JUCE_CATCH_ALL
  203858. return result;
  203859. }
  203860. void PlatformUtilities::freeDynamicLibrary (void* h)
  203861. {
  203862. JUCE_TRY
  203863. {
  203864. if (h != 0)
  203865. FreeLibrary ((HMODULE) h);
  203866. }
  203867. JUCE_CATCH_ALL
  203868. }
  203869. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203870. {
  203871. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  203872. }
  203873. class InterProcessLock::Pimpl
  203874. {
  203875. public:
  203876. Pimpl (const String& name, const int timeOutMillisecs)
  203877. : handle (0), refCount (1)
  203878. {
  203879. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203880. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203881. {
  203882. if (timeOutMillisecs == 0)
  203883. {
  203884. close();
  203885. return;
  203886. }
  203887. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203888. {
  203889. case WAIT_OBJECT_0:
  203890. case WAIT_ABANDONED:
  203891. break;
  203892. case WAIT_TIMEOUT:
  203893. default:
  203894. close();
  203895. break;
  203896. }
  203897. }
  203898. }
  203899. ~Pimpl()
  203900. {
  203901. close();
  203902. }
  203903. void close()
  203904. {
  203905. if (handle != 0)
  203906. {
  203907. ReleaseMutex (handle);
  203908. CloseHandle (handle);
  203909. handle = 0;
  203910. }
  203911. }
  203912. HANDLE handle;
  203913. int refCount;
  203914. };
  203915. InterProcessLock::InterProcessLock (const String& name_)
  203916. : name (name_)
  203917. {
  203918. }
  203919. InterProcessLock::~InterProcessLock()
  203920. {
  203921. }
  203922. bool InterProcessLock::enter (const int timeOutMillisecs)
  203923. {
  203924. const ScopedLock sl (lock);
  203925. if (pimpl == 0)
  203926. {
  203927. pimpl = new Pimpl (name, timeOutMillisecs);
  203928. if (pimpl->handle == 0)
  203929. pimpl = 0;
  203930. }
  203931. else
  203932. {
  203933. pimpl->refCount++;
  203934. }
  203935. return pimpl != 0;
  203936. }
  203937. void InterProcessLock::exit()
  203938. {
  203939. const ScopedLock sl (lock);
  203940. // Trying to release the lock too many times!
  203941. jassert (pimpl != 0);
  203942. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203943. pimpl = 0;
  203944. }
  203945. #endif
  203946. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203947. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203948. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203949. // compiled on its own).
  203950. #if JUCE_INCLUDED_FILE
  203951. #ifndef CSIDL_MYMUSIC
  203952. #define CSIDL_MYMUSIC 0x000d
  203953. #endif
  203954. #ifndef CSIDL_MYVIDEO
  203955. #define CSIDL_MYVIDEO 0x000e
  203956. #endif
  203957. #ifndef INVALID_FILE_ATTRIBUTES
  203958. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203959. #endif
  203960. namespace WindowsFileHelpers
  203961. {
  203962. int64 fileTimeToTime (const FILETIME* const ft)
  203963. {
  203964. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203965. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203966. }
  203967. void timeToFileTime (const int64 time, FILETIME* const ft)
  203968. {
  203969. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203970. }
  203971. const String getDriveFromPath (const String& path)
  203972. {
  203973. if (path.isNotEmpty() && path[1] == ':')
  203974. return path.substring (0, 2) + '\\';
  203975. return path;
  203976. }
  203977. int64 getDiskSpaceInfo (const String& path, const bool total)
  203978. {
  203979. ULARGE_INTEGER spc, tot, totFree;
  203980. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  203981. return total ? (int64) tot.QuadPart
  203982. : (int64) spc.QuadPart;
  203983. return 0;
  203984. }
  203985. unsigned int getWindowsDriveType (const String& path)
  203986. {
  203987. return GetDriveType (getDriveFromPath (path));
  203988. }
  203989. const File getSpecialFolderPath (int type)
  203990. {
  203991. WCHAR path [MAX_PATH + 256];
  203992. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203993. return File (String (path));
  203994. return File::nonexistent;
  203995. }
  203996. }
  203997. const juce_wchar File::separator = '\\';
  203998. const String File::separatorString ("\\");
  203999. bool File::exists() const
  204000. {
  204001. return fullPath.isNotEmpty()
  204002. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204003. }
  204004. bool File::existsAsFile() const
  204005. {
  204006. return fullPath.isNotEmpty()
  204007. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204008. }
  204009. bool File::isDirectory() const
  204010. {
  204011. const DWORD attr = GetFileAttributes (fullPath);
  204012. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204013. }
  204014. bool File::hasWriteAccess() const
  204015. {
  204016. if (exists())
  204017. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204018. // on windows, it seems that even read-only directories can still be written into,
  204019. // so checking the parent directory's permissions would return the wrong result..
  204020. return true;
  204021. }
  204022. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204023. {
  204024. DWORD attr = GetFileAttributes (fullPath);
  204025. if (attr == INVALID_FILE_ATTRIBUTES)
  204026. return false;
  204027. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204028. return true;
  204029. if (shouldBeReadOnly)
  204030. attr |= FILE_ATTRIBUTE_READONLY;
  204031. else
  204032. attr &= ~FILE_ATTRIBUTE_READONLY;
  204033. return SetFileAttributes (fullPath, attr) != FALSE;
  204034. }
  204035. bool File::isHidden() const
  204036. {
  204037. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204038. }
  204039. bool File::deleteFile() const
  204040. {
  204041. if (! exists())
  204042. return true;
  204043. else if (isDirectory())
  204044. return RemoveDirectory (fullPath) != 0;
  204045. else
  204046. return DeleteFile (fullPath) != 0;
  204047. }
  204048. bool File::moveToTrash() const
  204049. {
  204050. if (! exists())
  204051. return true;
  204052. SHFILEOPSTRUCT fos;
  204053. zerostruct (fos);
  204054. // The string we pass in must be double null terminated..
  204055. String doubleNullTermPath (getFullPathName() + " ");
  204056. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204057. p [getFullPathName().length()] = 0;
  204058. fos.wFunc = FO_DELETE;
  204059. fos.pFrom = p;
  204060. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204061. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204062. return SHFileOperation (&fos) == 0;
  204063. }
  204064. bool File::copyInternal (const File& dest) const
  204065. {
  204066. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204067. }
  204068. bool File::moveInternal (const File& dest) const
  204069. {
  204070. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204071. }
  204072. void File::createDirectoryInternal (const String& fileName) const
  204073. {
  204074. CreateDirectory (fileName, 0);
  204075. }
  204076. int64 juce_fileSetPosition (void* handle, int64 pos)
  204077. {
  204078. LARGE_INTEGER li;
  204079. li.QuadPart = pos;
  204080. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204081. return li.QuadPart;
  204082. }
  204083. void FileInputStream::openHandle()
  204084. {
  204085. totalSize = file.getSize();
  204086. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204087. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204088. if (h != INVALID_HANDLE_VALUE)
  204089. fileHandle = (void*) h;
  204090. }
  204091. void FileInputStream::closeHandle()
  204092. {
  204093. CloseHandle ((HANDLE) fileHandle);
  204094. }
  204095. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204096. {
  204097. if (fileHandle != 0)
  204098. {
  204099. DWORD actualNum = 0;
  204100. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204101. return (size_t) actualNum;
  204102. }
  204103. return 0;
  204104. }
  204105. void FileOutputStream::openHandle()
  204106. {
  204107. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204108. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204109. if (h != INVALID_HANDLE_VALUE)
  204110. {
  204111. LARGE_INTEGER li;
  204112. li.QuadPart = 0;
  204113. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204114. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204115. {
  204116. fileHandle = (void*) h;
  204117. currentPosition = li.QuadPart;
  204118. }
  204119. }
  204120. }
  204121. void FileOutputStream::closeHandle()
  204122. {
  204123. CloseHandle ((HANDLE) fileHandle);
  204124. }
  204125. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204126. {
  204127. if (fileHandle != 0)
  204128. {
  204129. DWORD actualNum = 0;
  204130. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204131. return (int) actualNum;
  204132. }
  204133. return 0;
  204134. }
  204135. void FileOutputStream::flushInternal()
  204136. {
  204137. if (fileHandle != 0)
  204138. FlushFileBuffers ((HANDLE) fileHandle);
  204139. }
  204140. int64 File::getSize() const
  204141. {
  204142. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204143. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204144. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204145. return 0;
  204146. }
  204147. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204148. {
  204149. using namespace WindowsFileHelpers;
  204150. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204151. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204152. {
  204153. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204154. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204155. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204156. }
  204157. else
  204158. {
  204159. creationTime = accessTime = modificationTime = 0;
  204160. }
  204161. }
  204162. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204163. {
  204164. using namespace WindowsFileHelpers;
  204165. bool ok = false;
  204166. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204167. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204168. if (h != INVALID_HANDLE_VALUE)
  204169. {
  204170. FILETIME m, a, c;
  204171. timeToFileTime (modificationTime, &m);
  204172. timeToFileTime (accessTime, &a);
  204173. timeToFileTime (creationTime, &c);
  204174. ok = SetFileTime (h,
  204175. creationTime > 0 ? &c : 0,
  204176. accessTime > 0 ? &a : 0,
  204177. modificationTime > 0 ? &m : 0) != 0;
  204178. CloseHandle (h);
  204179. }
  204180. return ok;
  204181. }
  204182. void File::findFileSystemRoots (Array<File>& destArray)
  204183. {
  204184. TCHAR buffer [2048];
  204185. buffer[0] = 0;
  204186. buffer[1] = 0;
  204187. GetLogicalDriveStrings (2048, buffer);
  204188. const TCHAR* n = buffer;
  204189. StringArray roots;
  204190. while (*n != 0)
  204191. {
  204192. roots.add (String (n));
  204193. while (*n++ != 0)
  204194. {}
  204195. }
  204196. roots.sort (true);
  204197. for (int i = 0; i < roots.size(); ++i)
  204198. destArray.add (roots [i]);
  204199. }
  204200. const String File::getVolumeLabel() const
  204201. {
  204202. TCHAR dest[64];
  204203. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204204. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204205. dest[0] = 0;
  204206. return dest;
  204207. }
  204208. int File::getVolumeSerialNumber() const
  204209. {
  204210. TCHAR dest[64];
  204211. DWORD serialNum;
  204212. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204213. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204214. return 0;
  204215. return (int) serialNum;
  204216. }
  204217. int64 File::getBytesFreeOnVolume() const
  204218. {
  204219. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204220. }
  204221. int64 File::getVolumeTotalSize() const
  204222. {
  204223. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204224. }
  204225. bool File::isOnCDRomDrive() const
  204226. {
  204227. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204228. }
  204229. bool File::isOnHardDisk() const
  204230. {
  204231. if (fullPath.isEmpty())
  204232. return false;
  204233. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204234. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204235. return n != DRIVE_REMOVABLE;
  204236. else
  204237. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204238. }
  204239. bool File::isOnRemovableDrive() const
  204240. {
  204241. if (fullPath.isEmpty())
  204242. return false;
  204243. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204244. return n == DRIVE_CDROM
  204245. || n == DRIVE_REMOTE
  204246. || n == DRIVE_REMOVABLE
  204247. || n == DRIVE_RAMDISK;
  204248. }
  204249. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204250. {
  204251. int csidlType = 0;
  204252. switch (type)
  204253. {
  204254. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204255. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204256. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204257. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204258. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204259. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204260. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204261. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204262. case tempDirectory:
  204263. {
  204264. WCHAR dest [2048];
  204265. dest[0] = 0;
  204266. GetTempPath (numElementsInArray (dest), dest);
  204267. return File (String (dest));
  204268. }
  204269. case invokedExecutableFile:
  204270. case currentExecutableFile:
  204271. case currentApplicationFile:
  204272. {
  204273. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204274. WCHAR dest [MAX_PATH + 256];
  204275. dest[0] = 0;
  204276. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204277. return File (String (dest));
  204278. }
  204279. case hostApplicationPath:
  204280. {
  204281. WCHAR dest [MAX_PATH + 256];
  204282. dest[0] = 0;
  204283. GetModuleFileName (0, dest, numElementsInArray (dest));
  204284. return File (String (dest));
  204285. }
  204286. default:
  204287. jassertfalse; // unknown type?
  204288. return File::nonexistent;
  204289. }
  204290. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204291. }
  204292. const File File::getCurrentWorkingDirectory()
  204293. {
  204294. WCHAR dest [MAX_PATH + 256];
  204295. dest[0] = 0;
  204296. GetCurrentDirectory (numElementsInArray (dest), dest);
  204297. return File (String (dest));
  204298. }
  204299. bool File::setAsCurrentWorkingDirectory() const
  204300. {
  204301. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204302. }
  204303. const String File::getVersion() const
  204304. {
  204305. String result;
  204306. DWORD handle = 0;
  204307. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204308. HeapBlock<char> buffer;
  204309. buffer.calloc (bufferSize);
  204310. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204311. {
  204312. VS_FIXEDFILEINFO* vffi;
  204313. UINT len = 0;
  204314. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204315. {
  204316. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204317. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204318. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204319. << (int) LOWORD (vffi->dwFileVersionLS);
  204320. }
  204321. }
  204322. return result;
  204323. }
  204324. const File File::getLinkedTarget() const
  204325. {
  204326. File result (*this);
  204327. String p (getFullPathName());
  204328. if (! exists())
  204329. p += ".lnk";
  204330. else if (getFileExtension() != ".lnk")
  204331. return result;
  204332. ComSmartPtr <IShellLink> shellLink;
  204333. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204334. {
  204335. ComSmartPtr <IPersistFile> persistFile;
  204336. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204337. {
  204338. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204339. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204340. {
  204341. WIN32_FIND_DATA winFindData;
  204342. WCHAR resolvedPath [MAX_PATH];
  204343. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204344. result = File (resolvedPath);
  204345. }
  204346. }
  204347. }
  204348. return result;
  204349. }
  204350. class DirectoryIterator::NativeIterator::Pimpl
  204351. {
  204352. public:
  204353. Pimpl (const File& directory, const String& wildCard)
  204354. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204355. handle (INVALID_HANDLE_VALUE)
  204356. {
  204357. }
  204358. ~Pimpl()
  204359. {
  204360. if (handle != INVALID_HANDLE_VALUE)
  204361. FindClose (handle);
  204362. }
  204363. bool next (String& filenameFound,
  204364. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204365. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204366. {
  204367. using namespace WindowsFileHelpers;
  204368. WIN32_FIND_DATA findData;
  204369. if (handle == INVALID_HANDLE_VALUE)
  204370. {
  204371. handle = FindFirstFile (directoryWithWildCard, &findData);
  204372. if (handle == INVALID_HANDLE_VALUE)
  204373. return false;
  204374. }
  204375. else
  204376. {
  204377. if (FindNextFile (handle, &findData) == 0)
  204378. return false;
  204379. }
  204380. filenameFound = findData.cFileName;
  204381. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204382. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204383. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204384. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204385. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204386. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204387. return true;
  204388. }
  204389. private:
  204390. const String directoryWithWildCard;
  204391. HANDLE handle;
  204392. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204393. };
  204394. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204395. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204396. {
  204397. }
  204398. DirectoryIterator::NativeIterator::~NativeIterator()
  204399. {
  204400. }
  204401. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204402. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204403. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204404. {
  204405. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204406. }
  204407. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204408. {
  204409. HINSTANCE hInstance = 0;
  204410. JUCE_TRY
  204411. {
  204412. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204413. }
  204414. JUCE_CATCH_ALL
  204415. return hInstance > (HINSTANCE) 32;
  204416. }
  204417. void File::revealToUser() const
  204418. {
  204419. if (isDirectory())
  204420. startAsProcess();
  204421. else if (getParentDirectory().exists())
  204422. getParentDirectory().startAsProcess();
  204423. }
  204424. class NamedPipeInternal
  204425. {
  204426. public:
  204427. NamedPipeInternal (const String& file, const bool isPipe_)
  204428. : pipeH (0),
  204429. cancelEvent (0),
  204430. connected (false),
  204431. isPipe (isPipe_)
  204432. {
  204433. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204434. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204435. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204436. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204437. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204438. }
  204439. ~NamedPipeInternal()
  204440. {
  204441. disconnectPipe();
  204442. if (pipeH != 0)
  204443. CloseHandle (pipeH);
  204444. CloseHandle (cancelEvent);
  204445. }
  204446. bool connect (const int timeOutMs)
  204447. {
  204448. if (! isPipe)
  204449. return true;
  204450. if (! connected)
  204451. {
  204452. OVERLAPPED over;
  204453. zerostruct (over);
  204454. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204455. if (ConnectNamedPipe (pipeH, &over))
  204456. {
  204457. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204458. }
  204459. else
  204460. {
  204461. const int err = GetLastError();
  204462. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204463. {
  204464. HANDLE handles[] = { over.hEvent, cancelEvent };
  204465. if (WaitForMultipleObjects (2, handles, FALSE,
  204466. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204467. connected = true;
  204468. }
  204469. else if (err == ERROR_PIPE_CONNECTED)
  204470. {
  204471. connected = true;
  204472. }
  204473. }
  204474. CloseHandle (over.hEvent);
  204475. }
  204476. return connected;
  204477. }
  204478. void disconnectPipe()
  204479. {
  204480. if (connected)
  204481. {
  204482. DisconnectNamedPipe (pipeH);
  204483. connected = false;
  204484. }
  204485. }
  204486. HANDLE pipeH;
  204487. HANDLE cancelEvent;
  204488. bool connected, isPipe;
  204489. };
  204490. void NamedPipe::close()
  204491. {
  204492. cancelPendingReads();
  204493. const ScopedLock sl (lock);
  204494. delete static_cast<NamedPipeInternal*> (internal);
  204495. internal = 0;
  204496. }
  204497. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204498. {
  204499. close();
  204500. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204501. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204502. {
  204503. internal = intern.release();
  204504. return true;
  204505. }
  204506. return false;
  204507. }
  204508. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204509. {
  204510. const ScopedLock sl (lock);
  204511. int bytesRead = -1;
  204512. bool waitAgain = true;
  204513. while (waitAgain && internal != 0)
  204514. {
  204515. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204516. waitAgain = false;
  204517. if (! intern->connect (timeOutMilliseconds))
  204518. break;
  204519. if (maxBytesToRead <= 0)
  204520. return 0;
  204521. OVERLAPPED over;
  204522. zerostruct (over);
  204523. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204524. unsigned long numRead;
  204525. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204526. {
  204527. bytesRead = (int) numRead;
  204528. }
  204529. else if (GetLastError() == ERROR_IO_PENDING)
  204530. {
  204531. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204532. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204533. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204534. : INFINITE);
  204535. if (waitResult != WAIT_OBJECT_0)
  204536. {
  204537. // if the operation timed out, let's cancel it...
  204538. CancelIo (intern->pipeH);
  204539. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204540. }
  204541. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204542. {
  204543. bytesRead = (int) numRead;
  204544. }
  204545. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204546. {
  204547. intern->disconnectPipe();
  204548. waitAgain = true;
  204549. }
  204550. }
  204551. else
  204552. {
  204553. waitAgain = internal != 0;
  204554. Sleep (5);
  204555. }
  204556. CloseHandle (over.hEvent);
  204557. }
  204558. return bytesRead;
  204559. }
  204560. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204561. {
  204562. int bytesWritten = -1;
  204563. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204564. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204565. {
  204566. if (numBytesToWrite <= 0)
  204567. return 0;
  204568. OVERLAPPED over;
  204569. zerostruct (over);
  204570. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204571. unsigned long numWritten;
  204572. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204573. {
  204574. bytesWritten = (int) numWritten;
  204575. }
  204576. else if (GetLastError() == ERROR_IO_PENDING)
  204577. {
  204578. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204579. DWORD waitResult;
  204580. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204581. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204582. : INFINITE);
  204583. if (waitResult != WAIT_OBJECT_0)
  204584. {
  204585. CancelIo (intern->pipeH);
  204586. WaitForSingleObject (over.hEvent, INFINITE);
  204587. }
  204588. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204589. {
  204590. bytesWritten = (int) numWritten;
  204591. }
  204592. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204593. {
  204594. intern->disconnectPipe();
  204595. }
  204596. }
  204597. CloseHandle (over.hEvent);
  204598. }
  204599. return bytesWritten;
  204600. }
  204601. void NamedPipe::cancelPendingReads()
  204602. {
  204603. if (internal != 0)
  204604. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204605. }
  204606. #endif
  204607. /*** End of inlined file: juce_win32_Files.cpp ***/
  204608. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204609. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204610. // compiled on its own).
  204611. #if JUCE_INCLUDED_FILE
  204612. #ifndef INTERNET_FLAG_NEED_FILE
  204613. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204614. #endif
  204615. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204616. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204617. #endif
  204618. struct ConnectionAndRequestStruct
  204619. {
  204620. HINTERNET connection, request;
  204621. };
  204622. static HINTERNET sessionHandle = 0;
  204623. #ifndef WORKAROUND_TIMEOUT_BUG
  204624. //#define WORKAROUND_TIMEOUT_BUG 1
  204625. #endif
  204626. #if WORKAROUND_TIMEOUT_BUG
  204627. // Required because of a Microsoft bug in setting a timeout
  204628. class InternetConnectThread : public Thread
  204629. {
  204630. public:
  204631. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204632. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204633. {
  204634. startThread();
  204635. }
  204636. ~InternetConnectThread()
  204637. {
  204638. stopThread (60000);
  204639. }
  204640. void run()
  204641. {
  204642. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204643. uc.nPort, _T(""), _T(""),
  204644. isFtp ? INTERNET_SERVICE_FTP
  204645. : INTERNET_SERVICE_HTTP,
  204646. 0, 0);
  204647. notify();
  204648. }
  204649. private:
  204650. URL_COMPONENTS& uc;
  204651. HINTERNET& connection;
  204652. const bool isFtp;
  204653. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  204654. };
  204655. #endif
  204656. void* juce_openInternetFile (const String& url,
  204657. const String& headers,
  204658. const MemoryBlock& postData,
  204659. const bool isPost,
  204660. URL::OpenStreamProgressCallback* callback,
  204661. void* callbackContext,
  204662. int timeOutMs)
  204663. {
  204664. if (sessionHandle == 0)
  204665. sessionHandle = InternetOpen (_T("juce"),
  204666. INTERNET_OPEN_TYPE_PRECONFIG,
  204667. 0, 0, 0);
  204668. if (sessionHandle != 0)
  204669. {
  204670. // break up the url..
  204671. TCHAR file[1024], server[1024];
  204672. URL_COMPONENTS uc;
  204673. zerostruct (uc);
  204674. uc.dwStructSize = sizeof (uc);
  204675. uc.dwUrlPathLength = sizeof (file);
  204676. uc.dwHostNameLength = sizeof (server);
  204677. uc.lpszUrlPath = file;
  204678. uc.lpszHostName = server;
  204679. if (InternetCrackUrl (url, 0, 0, &uc))
  204680. {
  204681. int disable = 1;
  204682. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204683. if (timeOutMs == 0)
  204684. timeOutMs = 30000;
  204685. else if (timeOutMs < 0)
  204686. timeOutMs = -1;
  204687. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204688. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204689. #if WORKAROUND_TIMEOUT_BUG
  204690. HINTERNET connection = 0;
  204691. {
  204692. InternetConnectThread connectThread (uc, connection, isFtp);
  204693. connectThread.wait (timeOutMs);
  204694. if (connection == 0)
  204695. {
  204696. InternetCloseHandle (sessionHandle);
  204697. sessionHandle = 0;
  204698. }
  204699. }
  204700. #else
  204701. HINTERNET connection = InternetConnect (sessionHandle,
  204702. uc.lpszHostName,
  204703. uc.nPort,
  204704. _T(""), _T(""),
  204705. isFtp ? INTERNET_SERVICE_FTP
  204706. : INTERNET_SERVICE_HTTP,
  204707. 0, 0);
  204708. #endif
  204709. if (connection != 0)
  204710. {
  204711. if (isFtp)
  204712. {
  204713. HINTERNET request = FtpOpenFile (connection,
  204714. uc.lpszUrlPath,
  204715. GENERIC_READ,
  204716. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204717. 0);
  204718. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204719. result->connection = connection;
  204720. result->request = request;
  204721. return result;
  204722. }
  204723. else
  204724. {
  204725. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204726. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204727. if (url.startsWithIgnoreCase ("https:"))
  204728. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204729. // IE7 seems to automatically work out when it's https)
  204730. HINTERNET request = HttpOpenRequest (connection,
  204731. isPost ? _T("POST")
  204732. : _T("GET"),
  204733. uc.lpszUrlPath,
  204734. 0, 0, mimeTypes, flags, 0);
  204735. if (request != 0)
  204736. {
  204737. INTERNET_BUFFERS buffers;
  204738. zerostruct (buffers);
  204739. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204740. buffers.lpcszHeader = (LPCTSTR) headers;
  204741. buffers.dwHeadersLength = headers.length();
  204742. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204743. ConnectionAndRequestStruct* result = 0;
  204744. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204745. {
  204746. int bytesSent = 0;
  204747. for (;;)
  204748. {
  204749. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204750. DWORD bytesDone = 0;
  204751. if (bytesToDo > 0
  204752. && ! InternetWriteFile (request,
  204753. static_cast <const char*> (postData.getData()) + bytesSent,
  204754. bytesToDo, &bytesDone))
  204755. {
  204756. break;
  204757. }
  204758. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204759. {
  204760. result = new ConnectionAndRequestStruct();
  204761. result->connection = connection;
  204762. result->request = request;
  204763. if (! HttpEndRequest (request, 0, 0, 0))
  204764. break;
  204765. return result;
  204766. }
  204767. bytesSent += bytesDone;
  204768. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204769. break;
  204770. }
  204771. }
  204772. InternetCloseHandle (request);
  204773. }
  204774. InternetCloseHandle (connection);
  204775. }
  204776. }
  204777. }
  204778. }
  204779. return 0;
  204780. }
  204781. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204782. {
  204783. DWORD bytesRead = 0;
  204784. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204785. if (crs != 0)
  204786. InternetReadFile (crs->request,
  204787. buffer, bytesToRead,
  204788. &bytesRead);
  204789. return bytesRead;
  204790. }
  204791. int juce_seekInInternetFile (void* handle, int newPosition)
  204792. {
  204793. if (handle != 0)
  204794. {
  204795. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204796. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204797. }
  204798. return -1;
  204799. }
  204800. int64 juce_getInternetFileContentLength (void* handle)
  204801. {
  204802. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204803. if (crs != 0)
  204804. {
  204805. DWORD index = 0, result = 0, size = sizeof (result);
  204806. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204807. return (int64) result;
  204808. }
  204809. return -1;
  204810. }
  204811. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204812. {
  204813. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204814. if (crs != 0)
  204815. {
  204816. DWORD bufferSizeBytes = 4096;
  204817. for (;;)
  204818. {
  204819. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204820. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204821. {
  204822. StringArray headersArray;
  204823. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204824. for (int i = 0; i < headersArray.size(); ++i)
  204825. {
  204826. const String& header = headersArray[i];
  204827. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204828. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204829. const String previousValue (headers [key]);
  204830. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204831. }
  204832. break;
  204833. }
  204834. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204835. break;
  204836. }
  204837. }
  204838. }
  204839. void juce_closeInternetFile (void* handle)
  204840. {
  204841. if (handle != 0)
  204842. {
  204843. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  204844. InternetCloseHandle (crs->request);
  204845. InternetCloseHandle (crs->connection);
  204846. }
  204847. }
  204848. namespace MACAddressHelpers
  204849. {
  204850. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  204851. {
  204852. DynamicLibraryLoader dll ("iphlpapi.dll");
  204853. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204854. if (getAdaptersInfo != 0)
  204855. {
  204856. ULONG len = sizeof (IP_ADAPTER_INFO);
  204857. MemoryBlock mb;
  204858. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204859. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204860. {
  204861. mb.setSize (len);
  204862. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204863. }
  204864. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204865. {
  204866. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  204867. {
  204868. if (adapter->AddressLength >= 6)
  204869. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  204870. }
  204871. }
  204872. }
  204873. }
  204874. void getViaNetBios (Array<MACAddress>& result)
  204875. {
  204876. DynamicLibraryLoader dll ("netapi32.dll");
  204877. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204878. if (NetbiosCall != 0)
  204879. {
  204880. NCB ncb;
  204881. zerostruct (ncb);
  204882. struct ASTAT
  204883. {
  204884. ADAPTER_STATUS adapt;
  204885. NAME_BUFFER NameBuff [30];
  204886. };
  204887. ASTAT astat;
  204888. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204889. LANA_ENUM enums;
  204890. zerostruct (enums);
  204891. ncb.ncb_command = NCBENUM;
  204892. ncb.ncb_buffer = (unsigned char*) &enums;
  204893. ncb.ncb_length = sizeof (LANA_ENUM);
  204894. NetbiosCall (&ncb);
  204895. for (int i = 0; i < enums.length; ++i)
  204896. {
  204897. zerostruct (ncb);
  204898. ncb.ncb_command = NCBRESET;
  204899. ncb.ncb_lana_num = enums.lana[i];
  204900. if (NetbiosCall (&ncb) == 0)
  204901. {
  204902. zerostruct (ncb);
  204903. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204904. ncb.ncb_command = NCBASTAT;
  204905. ncb.ncb_lana_num = enums.lana[i];
  204906. ncb.ncb_buffer = (unsigned char*) &astat;
  204907. ncb.ncb_length = sizeof (ASTAT);
  204908. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  204909. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  204910. }
  204911. }
  204912. }
  204913. }
  204914. }
  204915. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  204916. {
  204917. MACAddressHelpers::getViaGetAdaptersInfo (result);
  204918. MACAddressHelpers::getViaNetBios (result);
  204919. }
  204920. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204921. const String& emailSubject,
  204922. const String& bodyText,
  204923. const StringArray& filesToAttach)
  204924. {
  204925. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204926. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204927. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204928. bool ok = false;
  204929. if (mapiSendMail != 0)
  204930. {
  204931. MapiMessage message;
  204932. zerostruct (message);
  204933. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204934. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204935. MapiRecipDesc recip;
  204936. zerostruct (recip);
  204937. recip.ulRecipClass = MAPI_TO;
  204938. String targetEmailAddress_ (targetEmailAddress);
  204939. if (targetEmailAddress_.isEmpty())
  204940. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204941. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204942. message.nRecipCount = 1;
  204943. message.lpRecips = &recip;
  204944. HeapBlock <MapiFileDesc> files;
  204945. files.calloc (filesToAttach.size());
  204946. message.nFileCount = filesToAttach.size();
  204947. message.lpFiles = files;
  204948. for (int i = 0; i < filesToAttach.size(); ++i)
  204949. {
  204950. files[i].nPosition = (ULONG) -1;
  204951. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204952. }
  204953. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204954. }
  204955. FreeLibrary (h);
  204956. return ok;
  204957. }
  204958. #endif
  204959. /*** End of inlined file: juce_win32_Network.cpp ***/
  204960. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204961. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204962. // compiled on its own).
  204963. #if JUCE_INCLUDED_FILE
  204964. namespace
  204965. {
  204966. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  204967. {
  204968. HKEY rootKey = 0;
  204969. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204970. rootKey = HKEY_CURRENT_USER;
  204971. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204972. rootKey = HKEY_LOCAL_MACHINE;
  204973. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204974. rootKey = HKEY_CLASSES_ROOT;
  204975. if (rootKey != 0)
  204976. {
  204977. name = name.substring (name.indexOfChar ('\\') + 1);
  204978. const int lastSlash = name.lastIndexOfChar ('\\');
  204979. valueName = name.substring (lastSlash + 1);
  204980. name = name.substring (0, lastSlash);
  204981. HKEY key;
  204982. DWORD result;
  204983. if (createForWriting)
  204984. {
  204985. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  204986. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204987. return key;
  204988. }
  204989. else
  204990. {
  204991. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  204992. return key;
  204993. }
  204994. }
  204995. return 0;
  204996. }
  204997. }
  204998. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204999. const String& defaultValue)
  205000. {
  205001. String valueName, result (defaultValue);
  205002. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205003. if (k != 0)
  205004. {
  205005. WCHAR buffer [2048];
  205006. unsigned long bufferSize = sizeof (buffer);
  205007. DWORD type = REG_SZ;
  205008. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205009. {
  205010. if (type == REG_SZ)
  205011. result = buffer;
  205012. else if (type == REG_DWORD)
  205013. result = String ((int) *(DWORD*) buffer);
  205014. }
  205015. RegCloseKey (k);
  205016. }
  205017. return result;
  205018. }
  205019. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205020. const String& value)
  205021. {
  205022. String valueName;
  205023. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205024. if (k != 0)
  205025. {
  205026. RegSetValueEx (k, valueName, 0, REG_SZ,
  205027. (const BYTE*) (const WCHAR*) value,
  205028. sizeof (WCHAR) * (value.length() + 1));
  205029. RegCloseKey (k);
  205030. }
  205031. }
  205032. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205033. {
  205034. bool exists = false;
  205035. String valueName;
  205036. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205037. if (k != 0)
  205038. {
  205039. unsigned char buffer [2048];
  205040. unsigned long bufferSize = sizeof (buffer);
  205041. DWORD type = 0;
  205042. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205043. exists = true;
  205044. RegCloseKey (k);
  205045. }
  205046. return exists;
  205047. }
  205048. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205049. {
  205050. String valueName;
  205051. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205052. if (k != 0)
  205053. {
  205054. RegDeleteValue (k, valueName);
  205055. RegCloseKey (k);
  205056. }
  205057. }
  205058. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205059. {
  205060. String valueName;
  205061. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205062. if (k != 0)
  205063. {
  205064. RegDeleteKey (k, valueName);
  205065. RegCloseKey (k);
  205066. }
  205067. }
  205068. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205069. const String& symbolicDescription,
  205070. const String& fullDescription,
  205071. const File& targetExecutable,
  205072. int iconResourceNumber)
  205073. {
  205074. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205075. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205076. if (iconResourceNumber != 0)
  205077. setRegistryValue (key + "\\DefaultIcon\\",
  205078. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205079. setRegistryValue (key + "\\", fullDescription);
  205080. setRegistryValue (key + "\\shell\\open\\command\\",
  205081. targetExecutable.getFullPathName() + " %1");
  205082. }
  205083. bool juce_IsRunningInWine()
  205084. {
  205085. HKEY key;
  205086. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205087. {
  205088. RegCloseKey (key);
  205089. return true;
  205090. }
  205091. return false;
  205092. }
  205093. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205094. {
  205095. String s (::GetCommandLineW());
  205096. StringArray tokens;
  205097. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205098. return tokens.joinIntoString (" ", 1);
  205099. }
  205100. static void* currentModuleHandle = 0;
  205101. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205102. {
  205103. if (currentModuleHandle == 0)
  205104. currentModuleHandle = GetModuleHandle (0);
  205105. return currentModuleHandle;
  205106. }
  205107. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205108. {
  205109. currentModuleHandle = newHandle;
  205110. }
  205111. void PlatformUtilities::fpuReset()
  205112. {
  205113. #if JUCE_MSVC
  205114. _clearfp();
  205115. #endif
  205116. }
  205117. void PlatformUtilities::beep()
  205118. {
  205119. MessageBeep (MB_OK);
  205120. }
  205121. #endif
  205122. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205123. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205124. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205125. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205126. // compiled on its own).
  205127. #if JUCE_INCLUDED_FILE
  205128. static const unsigned int specialId = WM_APP + 0x4400;
  205129. static const unsigned int broadcastId = WM_APP + 0x4403;
  205130. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205131. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205132. HWND juce_messageWindowHandle = 0;
  205133. extern long improbableWindowNumber; // defined in windowing.cpp
  205134. #ifndef WM_APPCOMMAND
  205135. #define WM_APPCOMMAND 0x0319
  205136. #endif
  205137. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205138. const UINT message,
  205139. const WPARAM wParam,
  205140. const LPARAM lParam) throw()
  205141. {
  205142. JUCE_TRY
  205143. {
  205144. if (h == juce_messageWindowHandle)
  205145. {
  205146. if (message == specialCallbackId)
  205147. {
  205148. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205149. return (LRESULT) (*func) ((void*) lParam);
  205150. }
  205151. else if (message == specialId)
  205152. {
  205153. // these are trapped early in the dispatch call, but must also be checked
  205154. // here in case there are windows modal dialog boxes doing their own
  205155. // dispatch loop and not calling our version
  205156. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205157. return 0;
  205158. }
  205159. else if (message == broadcastId)
  205160. {
  205161. const ScopedPointer <String> messageString ((String*) lParam);
  205162. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205163. return 0;
  205164. }
  205165. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205166. {
  205167. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205168. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205169. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205170. return 0;
  205171. }
  205172. }
  205173. }
  205174. JUCE_CATCH_EXCEPTION
  205175. return DefWindowProc (h, message, wParam, lParam);
  205176. }
  205177. static bool isEventBlockedByModalComps (MSG& m)
  205178. {
  205179. if (Component::getNumCurrentlyModalComponents() == 0
  205180. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205181. return false;
  205182. switch (m.message)
  205183. {
  205184. case WM_MOUSEMOVE:
  205185. case WM_NCMOUSEMOVE:
  205186. case 0x020A: /* WM_MOUSEWHEEL */
  205187. case 0x020E: /* WM_MOUSEHWHEEL */
  205188. case WM_KEYUP:
  205189. case WM_SYSKEYUP:
  205190. case WM_CHAR:
  205191. case WM_APPCOMMAND:
  205192. case WM_LBUTTONUP:
  205193. case WM_MBUTTONUP:
  205194. case WM_RBUTTONUP:
  205195. case WM_MOUSEACTIVATE:
  205196. case WM_NCMOUSEHOVER:
  205197. case WM_MOUSEHOVER:
  205198. return true;
  205199. case WM_NCLBUTTONDOWN:
  205200. case WM_NCLBUTTONDBLCLK:
  205201. case WM_NCRBUTTONDOWN:
  205202. case WM_NCRBUTTONDBLCLK:
  205203. case WM_NCMBUTTONDOWN:
  205204. case WM_NCMBUTTONDBLCLK:
  205205. case WM_LBUTTONDOWN:
  205206. case WM_LBUTTONDBLCLK:
  205207. case WM_MBUTTONDOWN:
  205208. case WM_MBUTTONDBLCLK:
  205209. case WM_RBUTTONDOWN:
  205210. case WM_RBUTTONDBLCLK:
  205211. case WM_KEYDOWN:
  205212. case WM_SYSKEYDOWN:
  205213. {
  205214. Component* const modal = Component::getCurrentlyModalComponent (0);
  205215. if (modal != 0)
  205216. modal->inputAttemptWhenModal();
  205217. return true;
  205218. }
  205219. default:
  205220. break;
  205221. }
  205222. return false;
  205223. }
  205224. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205225. {
  205226. MSG m;
  205227. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205228. return false;
  205229. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205230. {
  205231. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205232. {
  205233. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205234. }
  205235. else if (m.message == WM_QUIT)
  205236. {
  205237. if (JUCEApplication::getInstance() != 0)
  205238. JUCEApplication::getInstance()->systemRequestedQuit();
  205239. }
  205240. else if (! isEventBlockedByModalComps (m))
  205241. {
  205242. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205243. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205244. {
  205245. // if it's someone else's window being clicked on, and the focus is
  205246. // currently on a juce window, pass the kb focus over..
  205247. HWND currentFocus = GetFocus();
  205248. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205249. SetFocus (m.hwnd);
  205250. }
  205251. TranslateMessage (&m);
  205252. DispatchMessage (&m);
  205253. }
  205254. }
  205255. return true;
  205256. }
  205257. bool juce_postMessageToSystemQueue (Message* message)
  205258. {
  205259. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205260. }
  205261. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205262. void* userData)
  205263. {
  205264. if (MessageManager::getInstance()->isThisTheMessageThread())
  205265. {
  205266. return (*callback) (userData);
  205267. }
  205268. else
  205269. {
  205270. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205271. // deadlock because the message manager is blocked from running, and can't
  205272. // call your function..
  205273. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205274. return (void*) SendMessage (juce_messageWindowHandle,
  205275. specialCallbackId,
  205276. (WPARAM) callback,
  205277. (LPARAM) userData);
  205278. }
  205279. }
  205280. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205281. {
  205282. if (hwnd != juce_messageWindowHandle)
  205283. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205284. return TRUE;
  205285. }
  205286. void MessageManager::broadcastMessage (const String& value)
  205287. {
  205288. Array<void*> windows;
  205289. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205290. const String localCopy (value);
  205291. COPYDATASTRUCT data;
  205292. data.dwData = broadcastId;
  205293. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205294. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205295. for (int i = windows.size(); --i >= 0;)
  205296. {
  205297. HWND hwnd = (HWND) windows.getUnchecked(i);
  205298. TCHAR windowName [64]; // no need to read longer strings than this
  205299. GetWindowText (hwnd, windowName, 64);
  205300. windowName [63] = 0;
  205301. if (String (windowName) == messageWindowName)
  205302. {
  205303. DWORD_PTR result;
  205304. SendMessageTimeout (hwnd, WM_COPYDATA,
  205305. (WPARAM) juce_messageWindowHandle,
  205306. (LPARAM) &data,
  205307. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205308. 8000,
  205309. &result);
  205310. }
  205311. }
  205312. }
  205313. static const String getMessageWindowClassName()
  205314. {
  205315. // this name has to be different for each app/dll instance because otherwise
  205316. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205317. // window class).
  205318. static int number = 0;
  205319. if (number == 0)
  205320. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205321. return "JUCEcs_" + String (number);
  205322. }
  205323. void MessageManager::doPlatformSpecificInitialisation()
  205324. {
  205325. OleInitialize (0);
  205326. const String className (getMessageWindowClassName());
  205327. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205328. WNDCLASSEX wc;
  205329. zerostruct (wc);
  205330. wc.cbSize = sizeof (wc);
  205331. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205332. wc.cbWndExtra = 4;
  205333. wc.hInstance = hmod;
  205334. wc.lpszClassName = className;
  205335. RegisterClassEx (&wc);
  205336. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205337. messageWindowName,
  205338. 0, 0, 0, 0, 0, 0, 0,
  205339. hmod, 0);
  205340. }
  205341. void MessageManager::doPlatformSpecificShutdown()
  205342. {
  205343. DestroyWindow (juce_messageWindowHandle);
  205344. UnregisterClass (getMessageWindowClassName(), 0);
  205345. OleUninitialize();
  205346. }
  205347. #endif
  205348. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205349. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205350. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205351. // compiled on its own).
  205352. #if JUCE_INCLUDED_FILE
  205353. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205354. NEWTEXTMETRICEXW*,
  205355. int type,
  205356. LPARAM lParam)
  205357. {
  205358. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205359. {
  205360. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205361. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205362. }
  205363. return 1;
  205364. }
  205365. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205366. NEWTEXTMETRICEXW*,
  205367. int type,
  205368. LPARAM lParam)
  205369. {
  205370. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205371. {
  205372. LOGFONTW lf;
  205373. zerostruct (lf);
  205374. lf.lfWeight = FW_DONTCARE;
  205375. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205376. lf.lfQuality = DEFAULT_QUALITY;
  205377. lf.lfCharSet = DEFAULT_CHARSET;
  205378. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205379. lf.lfPitchAndFamily = FF_DONTCARE;
  205380. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205381. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205382. HDC dc = CreateCompatibleDC (0);
  205383. EnumFontFamiliesEx (dc, &lf,
  205384. (FONTENUMPROCW) &wfontEnum2,
  205385. lParam, 0);
  205386. DeleteDC (dc);
  205387. }
  205388. return 1;
  205389. }
  205390. const StringArray Font::findAllTypefaceNames()
  205391. {
  205392. StringArray results;
  205393. HDC dc = CreateCompatibleDC (0);
  205394. {
  205395. LOGFONTW lf;
  205396. zerostruct (lf);
  205397. lf.lfWeight = FW_DONTCARE;
  205398. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205399. lf.lfQuality = DEFAULT_QUALITY;
  205400. lf.lfCharSet = DEFAULT_CHARSET;
  205401. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205402. lf.lfPitchAndFamily = FF_DONTCARE;
  205403. lf.lfFaceName[0] = 0;
  205404. EnumFontFamiliesEx (dc, &lf,
  205405. (FONTENUMPROCW) &wfontEnum1,
  205406. (LPARAM) &results, 0);
  205407. }
  205408. DeleteDC (dc);
  205409. results.sort (true);
  205410. return results;
  205411. }
  205412. extern bool juce_IsRunningInWine();
  205413. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205414. {
  205415. if (juce_IsRunningInWine())
  205416. {
  205417. // If we're running in Wine, then use fonts that might be available on Linux..
  205418. defaultSans = "Bitstream Vera Sans";
  205419. defaultSerif = "Bitstream Vera Serif";
  205420. defaultFixed = "Bitstream Vera Sans Mono";
  205421. }
  205422. else
  205423. {
  205424. defaultSans = "Verdana";
  205425. defaultSerif = "Times";
  205426. defaultFixed = "Lucida Console";
  205427. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205428. }
  205429. }
  205430. class FontDCHolder : private DeletedAtShutdown
  205431. {
  205432. public:
  205433. FontDCHolder()
  205434. : dc (0), numKPs (0), size (0),
  205435. bold (false), italic (false)
  205436. {
  205437. }
  205438. ~FontDCHolder()
  205439. {
  205440. if (dc != 0)
  205441. {
  205442. DeleteDC (dc);
  205443. DeleteObject (fontH);
  205444. }
  205445. clearSingletonInstance();
  205446. }
  205447. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205448. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205449. {
  205450. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205451. {
  205452. fontName = fontName_;
  205453. bold = bold_;
  205454. italic = italic_;
  205455. size = size_;
  205456. if (dc != 0)
  205457. {
  205458. DeleteDC (dc);
  205459. DeleteObject (fontH);
  205460. kps.free();
  205461. }
  205462. fontH = 0;
  205463. dc = CreateCompatibleDC (0);
  205464. SetMapperFlags (dc, 0);
  205465. SetMapMode (dc, MM_TEXT);
  205466. LOGFONTW lfw;
  205467. zerostruct (lfw);
  205468. lfw.lfCharSet = DEFAULT_CHARSET;
  205469. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205470. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205471. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205472. lfw.lfQuality = PROOF_QUALITY;
  205473. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205474. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205475. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205476. lfw.lfHeight = size > 0 ? size : -256;
  205477. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205478. if (standardSizedFont != 0)
  205479. {
  205480. if (SelectObject (dc, standardSizedFont) != 0)
  205481. {
  205482. fontH = standardSizedFont;
  205483. if (size == 0)
  205484. {
  205485. OUTLINETEXTMETRIC otm;
  205486. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205487. {
  205488. lfw.lfHeight = -(int) otm.otmEMSquare;
  205489. fontH = CreateFontIndirect (&lfw);
  205490. SelectObject (dc, fontH);
  205491. DeleteObject (standardSizedFont);
  205492. }
  205493. }
  205494. }
  205495. else
  205496. {
  205497. jassertfalse;
  205498. }
  205499. }
  205500. else
  205501. {
  205502. jassertfalse;
  205503. }
  205504. }
  205505. return dc;
  205506. }
  205507. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205508. {
  205509. if (kps == 0)
  205510. {
  205511. numKPs = GetKerningPairs (dc, 0, 0);
  205512. kps.calloc (numKPs);
  205513. GetKerningPairs (dc, numKPs, kps);
  205514. }
  205515. numKPs_ = numKPs;
  205516. return kps;
  205517. }
  205518. private:
  205519. HFONT fontH;
  205520. HDC dc;
  205521. String fontName;
  205522. HeapBlock <KERNINGPAIR> kps;
  205523. int numKPs, size;
  205524. bool bold, italic;
  205525. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205526. };
  205527. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205528. class WindowsTypeface : public CustomTypeface
  205529. {
  205530. public:
  205531. WindowsTypeface (const Font& font)
  205532. {
  205533. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205534. font.isBold(), font.isItalic(), 0);
  205535. TEXTMETRIC tm;
  205536. tm.tmAscent = tm.tmHeight = 1;
  205537. tm.tmDefaultChar = 0;
  205538. GetTextMetrics (dc, &tm);
  205539. setCharacteristics (font.getTypefaceName(),
  205540. tm.tmAscent / (float) tm.tmHeight,
  205541. font.isBold(), font.isItalic(),
  205542. tm.tmDefaultChar);
  205543. }
  205544. bool loadGlyphIfPossible (juce_wchar character)
  205545. {
  205546. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205547. GLYPHMETRICS gm;
  205548. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205549. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205550. // gets correctly created later on.
  205551. if (! isFallbackFont)
  205552. {
  205553. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205554. WORD index = 0;
  205555. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205556. && index == 0xffff)
  205557. {
  205558. return false;
  205559. }
  205560. }
  205561. Path glyphPath;
  205562. TEXTMETRIC tm;
  205563. if (! GetTextMetrics (dc, &tm))
  205564. {
  205565. addGlyph (character, glyphPath, 0);
  205566. return true;
  205567. }
  205568. const float height = (float) tm.tmHeight;
  205569. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205570. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205571. &gm, 0, 0, &identityMatrix);
  205572. if (bufSize > 0)
  205573. {
  205574. HeapBlock<char> data (bufSize);
  205575. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205576. bufSize, data, &identityMatrix);
  205577. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205578. const float scaleX = 1.0f / height;
  205579. const float scaleY = -1.0f / height;
  205580. while ((char*) pheader < data + bufSize)
  205581. {
  205582. float x = scaleX * pheader->pfxStart.x.value;
  205583. float y = scaleY * pheader->pfxStart.y.value;
  205584. glyphPath.startNewSubPath (x, y);
  205585. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205586. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205587. while ((const char*) curve < curveEnd)
  205588. {
  205589. if (curve->wType == TT_PRIM_LINE)
  205590. {
  205591. for (int i = 0; i < curve->cpfx; ++i)
  205592. {
  205593. x = scaleX * curve->apfx[i].x.value;
  205594. y = scaleY * curve->apfx[i].y.value;
  205595. glyphPath.lineTo (x, y);
  205596. }
  205597. }
  205598. else if (curve->wType == TT_PRIM_QSPLINE)
  205599. {
  205600. for (int i = 0; i < curve->cpfx - 1; ++i)
  205601. {
  205602. const float x2 = scaleX * curve->apfx[i].x.value;
  205603. const float y2 = scaleY * curve->apfx[i].y.value;
  205604. float x3, y3;
  205605. if (i < curve->cpfx - 2)
  205606. {
  205607. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205608. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205609. }
  205610. else
  205611. {
  205612. x3 = scaleX * curve->apfx[i + 1].x.value;
  205613. y3 = scaleY * curve->apfx[i + 1].y.value;
  205614. }
  205615. glyphPath.quadraticTo (x2, y2, x3, y3);
  205616. x = x3;
  205617. y = y3;
  205618. }
  205619. }
  205620. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205621. }
  205622. pheader = (const TTPOLYGONHEADER*) curve;
  205623. glyphPath.closeSubPath();
  205624. }
  205625. }
  205626. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205627. int numKPs;
  205628. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205629. for (int i = 0; i < numKPs; ++i)
  205630. {
  205631. if (kps[i].wFirst == character)
  205632. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205633. kps[i].iKernAmount / height);
  205634. }
  205635. return true;
  205636. }
  205637. private:
  205638. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  205639. };
  205640. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205641. {
  205642. return new WindowsTypeface (font);
  205643. }
  205644. #endif
  205645. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205646. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205647. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205648. // compiled on its own).
  205649. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205650. class SharedD2DFactory : public DeletedAtShutdown
  205651. {
  205652. public:
  205653. SharedD2DFactory()
  205654. {
  205655. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205656. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205657. if (directWriteFactory != 0)
  205658. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205659. }
  205660. ~SharedD2DFactory()
  205661. {
  205662. clearSingletonInstance();
  205663. }
  205664. juce_DeclareSingleton (SharedD2DFactory, false);
  205665. ComSmartPtr <ID2D1Factory> d2dFactory;
  205666. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205667. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205668. };
  205669. juce_ImplementSingleton (SharedD2DFactory)
  205670. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205671. {
  205672. public:
  205673. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205674. : hwnd (hwnd_),
  205675. currentState (0)
  205676. {
  205677. RECT windowRect;
  205678. GetClientRect (hwnd, &windowRect);
  205679. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205680. bounds.setSize (size.width, size.height);
  205681. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205682. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205683. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205684. // xxx check for error
  205685. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205686. }
  205687. ~Direct2DLowLevelGraphicsContext()
  205688. {
  205689. states.clear();
  205690. }
  205691. void resized()
  205692. {
  205693. RECT windowRect;
  205694. GetClientRect (hwnd, &windowRect);
  205695. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205696. renderingTarget->Resize (size);
  205697. bounds.setSize (size.width, size.height);
  205698. }
  205699. void clear()
  205700. {
  205701. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205702. }
  205703. void start()
  205704. {
  205705. renderingTarget->BeginDraw();
  205706. saveState();
  205707. }
  205708. void end()
  205709. {
  205710. states.clear();
  205711. currentState = 0;
  205712. renderingTarget->EndDraw();
  205713. renderingTarget->CheckWindowState();
  205714. }
  205715. bool isVectorDevice() const { return false; }
  205716. void setOrigin (int x, int y)
  205717. {
  205718. currentState->origin.addXY (x, y);
  205719. }
  205720. void addTransform (const AffineTransform& transform)
  205721. {
  205722. //xxx todo
  205723. jassertfalse;
  205724. }
  205725. bool clipToRectangle (const Rectangle<int>& r)
  205726. {
  205727. currentState->clipToRectangle (r);
  205728. return ! isClipEmpty();
  205729. }
  205730. bool clipToRectangleList (const RectangleList& clipRegion)
  205731. {
  205732. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205733. return ! isClipEmpty();
  205734. }
  205735. void excludeClipRectangle (const Rectangle<int>&)
  205736. {
  205737. //xxx
  205738. }
  205739. void clipToPath (const Path& path, const AffineTransform& transform)
  205740. {
  205741. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205742. }
  205743. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205744. {
  205745. currentState->clipToImage (sourceImage,transform);
  205746. }
  205747. bool clipRegionIntersects (const Rectangle<int>& r)
  205748. {
  205749. const Rectangle<int> r2 (r + currentState->origin);
  205750. return currentState->clipRect.intersects (r2);
  205751. }
  205752. const Rectangle<int> getClipBounds() const
  205753. {
  205754. // xxx could this take into account complex clip regions?
  205755. return currentState->clipRect - currentState->origin;
  205756. }
  205757. bool isClipEmpty() const
  205758. {
  205759. return currentState->clipRect.isEmpty();
  205760. }
  205761. void saveState()
  205762. {
  205763. states.add (new SavedState (*this));
  205764. currentState = states.getLast();
  205765. }
  205766. void restoreState()
  205767. {
  205768. jassert (states.size() > 1) //you should never pop the last state!
  205769. states.removeLast (1);
  205770. currentState = states.getLast();
  205771. }
  205772. void beginTransparencyLayer (float opacity)
  205773. {
  205774. jassertfalse; //xxx todo
  205775. }
  205776. void endTransparencyLayer()
  205777. {
  205778. jassertfalse; //xxx todo
  205779. }
  205780. void setFill (const FillType& fillType)
  205781. {
  205782. currentState->setFill (fillType);
  205783. }
  205784. void setOpacity (float newOpacity)
  205785. {
  205786. currentState->setOpacity (newOpacity);
  205787. }
  205788. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205789. {
  205790. }
  205791. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205792. {
  205793. currentState->createBrush();
  205794. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205795. }
  205796. void fillPath (const Path& p, const AffineTransform& transform)
  205797. {
  205798. currentState->createBrush();
  205799. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205800. if (renderingTarget != 0)
  205801. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205802. }
  205803. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205804. {
  205805. const int x = currentState->origin.getX();
  205806. const int y = currentState->origin.getY();
  205807. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205808. D2D1_SIZE_U size;
  205809. size.width = image.getWidth();
  205810. size.height = image.getHeight();
  205811. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205812. Image img (image.convertedToFormat (Image::ARGB));
  205813. Image::BitmapData bd (img, false);
  205814. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205815. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205816. {
  205817. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205818. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  205819. if (tempBitmap != 0)
  205820. renderingTarget->DrawBitmap (tempBitmap);
  205821. }
  205822. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205823. }
  205824. void drawLine (const Line <float>& line)
  205825. {
  205826. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205827. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205828. line.getEnd() + currentState->origin.toFloat());
  205829. currentState->createBrush();
  205830. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205831. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205832. currentState->currentBrush);
  205833. }
  205834. void drawVerticalLine (int x, float top, float bottom)
  205835. {
  205836. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205837. currentState->createBrush();
  205838. x += currentState->origin.getX();
  205839. const int y = currentState->origin.getY();
  205840. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205841. D2D1::Point2F (x, y + bottom),
  205842. currentState->currentBrush);
  205843. }
  205844. void drawHorizontalLine (int y, float left, float right)
  205845. {
  205846. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205847. currentState->createBrush();
  205848. y += currentState->origin.getY();
  205849. const int x = currentState->origin.getX();
  205850. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205851. D2D1::Point2F (x + right, y),
  205852. currentState->currentBrush);
  205853. }
  205854. void setFont (const Font& newFont)
  205855. {
  205856. currentState->setFont (newFont);
  205857. }
  205858. const Font getFont()
  205859. {
  205860. return currentState->font;
  205861. }
  205862. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205863. {
  205864. const float x = currentState->origin.getX();
  205865. const float y = currentState->origin.getY();
  205866. currentState->createBrush();
  205867. currentState->createFont();
  205868. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  205869. float hScale = currentState->font.getHorizontalScale();
  205870. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205871. float dpiX = 0, dpiY = 0;
  205872. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  205873. UINT32 glyphNum = glyphNumber;
  205874. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  205875. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  205876. DWRITE_GLYPH_OFFSET offset;
  205877. offset.advanceOffset = 0;
  205878. offset.ascenderOffset = 0;
  205879. float glyphAdvances = 0;
  205880. DWRITE_GLYPH_RUN glyph;
  205881. glyph.fontFace = currentState->currentFontFace;
  205882. glyph.glyphCount = 1;
  205883. glyph.glyphIndices = &glyphNum1;
  205884. glyph.isSideways = FALSE;
  205885. glyph.glyphAdvances = &glyphAdvances;
  205886. glyph.glyphOffsets = &offset;
  205887. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  205888. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  205889. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205890. }
  205891. class SavedState
  205892. {
  205893. public:
  205894. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  205895. : owner (owner_), currentBrush (0),
  205896. fontScaling (1.0f), currentFontFace (0),
  205897. clipsRect (false), shouldClipRect (false),
  205898. clipsRectList (false), shouldClipRectList (false),
  205899. clipsComplex (false), shouldClipComplex (false),
  205900. clipsBitmap (false), shouldClipBitmap (false)
  205901. {
  205902. if (owner.currentState != 0)
  205903. {
  205904. // xxx seems like a very slow way to create one of these, and this is a performance
  205905. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  205906. setFill (owner.currentState->fillType);
  205907. currentBrush = owner.currentState->currentBrush;
  205908. origin = owner.currentState->origin;
  205909. clipRect = owner.currentState->clipRect;
  205910. font = owner.currentState->font;
  205911. currentFontFace = owner.currentState->currentFontFace;
  205912. }
  205913. else
  205914. {
  205915. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  205916. clipRect.setSize (size.width, size.height);
  205917. setFill (FillType (Colours::black));
  205918. }
  205919. }
  205920. ~SavedState()
  205921. {
  205922. clearClip();
  205923. clearFont();
  205924. clearFill();
  205925. clearPathClip();
  205926. clearImageClip();
  205927. complexClipLayer = 0;
  205928. bitmapMaskLayer = 0;
  205929. }
  205930. void clearClip()
  205931. {
  205932. popClips();
  205933. shouldClipRect = false;
  205934. }
  205935. void clipToRectangle (const Rectangle<int>& r)
  205936. {
  205937. clearClip();
  205938. clipRect = r + origin;
  205939. shouldClipRect = true;
  205940. pushClips();
  205941. }
  205942. void clearPathClip()
  205943. {
  205944. popClips();
  205945. if (shouldClipComplex)
  205946. {
  205947. complexClipGeometry = 0;
  205948. shouldClipComplex = false;
  205949. }
  205950. }
  205951. void clipToPath (ID2D1Geometry* geometry)
  205952. {
  205953. clearPathClip();
  205954. if (complexClipLayer == 0)
  205955. owner.renderingTarget->CreateLayer (&complexClipLayer);
  205956. complexClipGeometry = geometry;
  205957. shouldClipComplex = true;
  205958. pushClips();
  205959. }
  205960. void clearRectListClip()
  205961. {
  205962. popClips();
  205963. if (shouldClipRectList)
  205964. {
  205965. rectListGeometry = 0;
  205966. shouldClipRectList = false;
  205967. }
  205968. }
  205969. void clipToRectList (ID2D1Geometry* geometry)
  205970. {
  205971. clearRectListClip();
  205972. if (rectListLayer == 0)
  205973. owner.renderingTarget->CreateLayer (&rectListLayer);
  205974. rectListGeometry = geometry;
  205975. shouldClipRectList = true;
  205976. pushClips();
  205977. }
  205978. void clearImageClip()
  205979. {
  205980. popClips();
  205981. if (shouldClipBitmap)
  205982. {
  205983. maskBitmap = 0;
  205984. bitmapMaskBrush = 0;
  205985. shouldClipBitmap = false;
  205986. }
  205987. }
  205988. void clipToImage (const Image& image, const AffineTransform& transform)
  205989. {
  205990. clearImageClip();
  205991. if (bitmapMaskLayer == 0)
  205992. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  205993. D2D1_BRUSH_PROPERTIES brushProps;
  205994. brushProps.opacity = 1;
  205995. brushProps.transform = transfromToMatrix (transform);
  205996. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  205997. D2D1_SIZE_U size;
  205998. size.width = image.getWidth();
  205999. size.height = image.getHeight();
  206000. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206001. maskImage = image.convertedToFormat (Image::ARGB);
  206002. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206003. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206004. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206005. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206006. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206007. imageMaskLayerParams = D2D1::LayerParameters();
  206008. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206009. shouldClipBitmap = true;
  206010. pushClips();
  206011. }
  206012. void popClips()
  206013. {
  206014. if (clipsBitmap)
  206015. {
  206016. owner.renderingTarget->PopLayer();
  206017. clipsBitmap = false;
  206018. }
  206019. if (clipsComplex)
  206020. {
  206021. owner.renderingTarget->PopLayer();
  206022. clipsComplex = false;
  206023. }
  206024. if (clipsRectList)
  206025. {
  206026. owner.renderingTarget->PopLayer();
  206027. clipsRectList = false;
  206028. }
  206029. if (clipsRect)
  206030. {
  206031. owner.renderingTarget->PopAxisAlignedClip();
  206032. clipsRect = false;
  206033. }
  206034. }
  206035. void pushClips()
  206036. {
  206037. if (shouldClipRect && ! clipsRect)
  206038. {
  206039. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206040. clipsRect = true;
  206041. }
  206042. if (shouldClipRectList && ! clipsRectList)
  206043. {
  206044. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206045. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206046. layerParams.geometricMask = rectListGeometry;
  206047. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206048. clipsRectList = true;
  206049. }
  206050. if (shouldClipComplex && ! clipsComplex)
  206051. {
  206052. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206053. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206054. layerParams.geometricMask = complexClipGeometry;
  206055. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206056. clipsComplex = true;
  206057. }
  206058. if (shouldClipBitmap && ! clipsBitmap)
  206059. {
  206060. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206061. clipsBitmap = true;
  206062. }
  206063. }
  206064. void setFill (const FillType& newFillType)
  206065. {
  206066. if (fillType != newFillType)
  206067. {
  206068. fillType = newFillType;
  206069. clearFill();
  206070. }
  206071. }
  206072. void clearFont()
  206073. {
  206074. currentFontFace = localFontFace = 0;
  206075. }
  206076. void setFont (const Font& newFont)
  206077. {
  206078. if (font != newFont)
  206079. {
  206080. font = newFont;
  206081. clearFont();
  206082. }
  206083. }
  206084. void createFont()
  206085. {
  206086. // xxx The font shouldn't be managed by the graphics context.
  206087. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206088. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206089. // WindowsTypeface class.
  206090. if (currentFontFace == 0)
  206091. {
  206092. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206093. fontScaling = systemType->getAscent();
  206094. BOOL fontFound;
  206095. uint32 fontIndex;
  206096. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206097. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206098. if (! fontFound)
  206099. fontIndex = 0;
  206100. ComSmartPtr <IDWriteFontFamily> fontFam;
  206101. fonts->GetFontFamily (fontIndex, &fontFam);
  206102. ComSmartPtr <IDWriteFont> font;
  206103. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206104. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206105. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206106. font->CreateFontFace (&localFontFace);
  206107. currentFontFace = localFontFace;
  206108. }
  206109. }
  206110. void setOpacity (float newOpacity)
  206111. {
  206112. fillType.setOpacity (newOpacity);
  206113. if (currentBrush != 0)
  206114. currentBrush->SetOpacity (newOpacity);
  206115. }
  206116. void clearFill()
  206117. {
  206118. gradientStops = 0;
  206119. linearGradient = 0;
  206120. radialGradient = 0;
  206121. bitmap = 0;
  206122. bitmapBrush = 0;
  206123. currentBrush = 0;
  206124. }
  206125. void createBrush()
  206126. {
  206127. if (currentBrush == 0)
  206128. {
  206129. const int x = origin.getX();
  206130. const int y = origin.getY();
  206131. if (fillType.isColour())
  206132. {
  206133. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206134. owner.colourBrush->SetColor (colour);
  206135. currentBrush = owner.colourBrush;
  206136. }
  206137. else if (fillType.isTiledImage())
  206138. {
  206139. D2D1_BRUSH_PROPERTIES brushProps;
  206140. brushProps.opacity = fillType.getOpacity();
  206141. brushProps.transform = transfromToMatrix (fillType.transform);
  206142. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206143. image = fillType.image;
  206144. D2D1_SIZE_U size;
  206145. size.width = image.getWidth();
  206146. size.height = image.getHeight();
  206147. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206148. this->image = image.convertedToFormat (Image::ARGB);
  206149. Image::BitmapData bd (this->image, false);
  206150. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206151. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206152. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206153. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206154. currentBrush = bitmapBrush;
  206155. }
  206156. else if (fillType.isGradient())
  206157. {
  206158. gradientStops = 0;
  206159. D2D1_BRUSH_PROPERTIES brushProps;
  206160. brushProps.opacity = fillType.getOpacity();
  206161. brushProps.transform = transfromToMatrix (fillType.transform);
  206162. const int numColors = fillType.gradient->getNumColours();
  206163. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206164. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206165. {
  206166. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206167. stops[i].position = fillType.gradient->getColourPosition(i);
  206168. }
  206169. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206170. if (fillType.gradient->isRadial)
  206171. {
  206172. radialGradient = 0;
  206173. const Point<float>& p1 = fillType.gradient->point1;
  206174. const Point<float>& p2 = fillType.gradient->point2;
  206175. float r = p1.getDistanceFrom (p2);
  206176. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206177. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206178. D2D1::Point2F (0, 0),
  206179. r, r);
  206180. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206181. currentBrush = radialGradient;
  206182. }
  206183. else
  206184. {
  206185. linearGradient = 0;
  206186. const Point<float>& p1 = fillType.gradient->point1;
  206187. const Point<float>& p2 = fillType.gradient->point2;
  206188. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206189. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206190. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206191. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206192. currentBrush = linearGradient;
  206193. }
  206194. }
  206195. }
  206196. }
  206197. //xxx most of these members should probably be private...
  206198. Direct2DLowLevelGraphicsContext& owner;
  206199. Point<int> origin;
  206200. Font font;
  206201. float fontScaling;
  206202. IDWriteFontFace* currentFontFace;
  206203. ComSmartPtr <IDWriteFontFace> localFontFace;
  206204. FillType fillType;
  206205. Image image;
  206206. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206207. Rectangle<int> clipRect;
  206208. bool clipsRect, shouldClipRect;
  206209. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206210. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206211. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206212. bool clipsComplex, shouldClipComplex;
  206213. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206214. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206215. ComSmartPtr <ID2D1Layer> rectListLayer;
  206216. bool clipsRectList, shouldClipRectList;
  206217. Image maskImage;
  206218. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206219. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206220. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206221. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206222. bool clipsBitmap, shouldClipBitmap;
  206223. ID2D1Brush* currentBrush;
  206224. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206225. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206226. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206227. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206228. private:
  206229. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206230. };
  206231. private:
  206232. HWND hwnd;
  206233. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206234. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206235. Rectangle<int> bounds;
  206236. SavedState* currentState;
  206237. OwnedArray<SavedState> states;
  206238. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206239. {
  206240. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206241. }
  206242. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206243. {
  206244. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206245. }
  206246. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206247. {
  206248. transform.transformPoint (x, y);
  206249. return D2D1::Point2F (x, y);
  206250. }
  206251. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206252. {
  206253. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206254. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206255. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206256. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206257. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206258. }
  206259. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206260. {
  206261. ID2D1PathGeometry* p = 0;
  206262. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206263. ComSmartPtr <ID2D1GeometrySink> sink;
  206264. HRESULT hr = p->Open (&sink); // xxx handle error
  206265. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206266. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206267. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206268. hr = sink->Close();
  206269. return p;
  206270. }
  206271. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206272. {
  206273. Path::Iterator it (path);
  206274. while (it.next())
  206275. {
  206276. switch (it.elementType)
  206277. {
  206278. case Path::Iterator::cubicTo:
  206279. {
  206280. D2D1_BEZIER_SEGMENT seg;
  206281. transform.transformPoint (it.x1, it.y1);
  206282. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206283. transform.transformPoint (it.x2, it.y2);
  206284. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206285. transform.transformPoint(it.x3, it.y3);
  206286. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206287. sink->AddBezier (seg);
  206288. break;
  206289. }
  206290. case Path::Iterator::lineTo:
  206291. {
  206292. transform.transformPoint (it.x1, it.y1);
  206293. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206294. break;
  206295. }
  206296. case Path::Iterator::quadraticTo:
  206297. {
  206298. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206299. transform.transformPoint (it.x1, it.y1);
  206300. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206301. transform.transformPoint (it.x2, it.y2);
  206302. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206303. sink->AddQuadraticBezier (seg);
  206304. break;
  206305. }
  206306. case Path::Iterator::closePath:
  206307. {
  206308. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206309. break;
  206310. }
  206311. case Path::Iterator::startNewSubPath:
  206312. {
  206313. transform.transformPoint (it.x1, it.y1);
  206314. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206315. break;
  206316. }
  206317. }
  206318. }
  206319. }
  206320. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206321. {
  206322. ID2D1PathGeometry* p = 0;
  206323. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206324. ComSmartPtr <ID2D1GeometrySink> sink;
  206325. HRESULT hr = p->Open (&sink);
  206326. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206327. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206328. hr = sink->Close();
  206329. return p;
  206330. }
  206331. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206332. {
  206333. D2D1::Matrix3x2F matrix;
  206334. matrix._11 = transform.mat00;
  206335. matrix._12 = transform.mat10;
  206336. matrix._21 = transform.mat01;
  206337. matrix._22 = transform.mat11;
  206338. matrix._31 = transform.mat02;
  206339. matrix._32 = transform.mat12;
  206340. return matrix;
  206341. }
  206342. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206343. };
  206344. #endif
  206345. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206346. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206347. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206348. // compiled on its own).
  206349. #if JUCE_INCLUDED_FILE
  206350. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206351. // these are in the windows SDK, but need to be repeated here for GCC..
  206352. #ifndef GET_APPCOMMAND_LPARAM
  206353. #define FAPPCOMMAND_MASK 0xF000
  206354. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206355. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206356. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206357. #define APPCOMMAND_MEDIA_STOP 13
  206358. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206359. #define WM_APPCOMMAND 0x0319
  206360. #endif
  206361. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206362. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206363. extern bool juce_IsRunningInWine();
  206364. #ifndef ULW_ALPHA
  206365. #define ULW_ALPHA 0x00000002
  206366. #endif
  206367. #ifndef AC_SRC_ALPHA
  206368. #define AC_SRC_ALPHA 0x01
  206369. #endif
  206370. static HPALETTE palette = 0;
  206371. static bool createPaletteIfNeeded = true;
  206372. static bool shouldDeactivateTitleBar = true;
  206373. #define WM_TRAYNOTIFY WM_USER + 100
  206374. using ::abs;
  206375. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206376. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206377. bool Desktop::canUseSemiTransparentWindows() throw()
  206378. {
  206379. if (updateLayeredWindow == 0)
  206380. {
  206381. if (! juce_IsRunningInWine())
  206382. {
  206383. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206384. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206385. }
  206386. }
  206387. return updateLayeredWindow != 0;
  206388. }
  206389. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206390. {
  206391. return upright;
  206392. }
  206393. const int extendedKeyModifier = 0x10000;
  206394. const int KeyPress::spaceKey = VK_SPACE;
  206395. const int KeyPress::returnKey = VK_RETURN;
  206396. const int KeyPress::escapeKey = VK_ESCAPE;
  206397. const int KeyPress::backspaceKey = VK_BACK;
  206398. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206399. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206400. const int KeyPress::tabKey = VK_TAB;
  206401. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206402. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206403. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206404. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206405. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206406. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206407. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206408. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206409. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206410. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206411. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206412. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206413. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206414. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206415. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206416. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206417. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206418. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206419. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206420. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206421. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206422. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206423. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206424. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206425. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206426. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206427. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206428. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206429. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206430. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206431. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206432. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206433. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206434. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206435. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206436. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206437. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206438. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206439. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206440. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206441. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206442. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206443. const int KeyPress::playKey = 0x30000;
  206444. const int KeyPress::stopKey = 0x30001;
  206445. const int KeyPress::fastForwardKey = 0x30002;
  206446. const int KeyPress::rewindKey = 0x30003;
  206447. class WindowsBitmapImage : public Image::SharedImage
  206448. {
  206449. public:
  206450. HBITMAP hBitmap;
  206451. BITMAPV4HEADER bitmapInfo;
  206452. HDC hdc;
  206453. unsigned char* bitmapData;
  206454. WindowsBitmapImage (const Image::PixelFormat format_,
  206455. const int w, const int h, const bool clearImage)
  206456. : Image::SharedImage (format_, w, h)
  206457. {
  206458. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206459. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206460. zerostruct (bitmapInfo);
  206461. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206462. bitmapInfo.bV4Width = w;
  206463. bitmapInfo.bV4Height = h;
  206464. bitmapInfo.bV4Planes = 1;
  206465. bitmapInfo.bV4CSType = 1;
  206466. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206467. if (format_ == Image::ARGB)
  206468. {
  206469. bitmapInfo.bV4AlphaMask = 0xff000000;
  206470. bitmapInfo.bV4RedMask = 0xff0000;
  206471. bitmapInfo.bV4GreenMask = 0xff00;
  206472. bitmapInfo.bV4BlueMask = 0xff;
  206473. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206474. }
  206475. else
  206476. {
  206477. bitmapInfo.bV4V4Compression = BI_RGB;
  206478. }
  206479. lineStride = -((w * pixelStride + 3) & ~3);
  206480. HDC dc = GetDC (0);
  206481. hdc = CreateCompatibleDC (dc);
  206482. ReleaseDC (0, dc);
  206483. SetMapMode (hdc, MM_TEXT);
  206484. hBitmap = CreateDIBSection (hdc,
  206485. (BITMAPINFO*) &(bitmapInfo),
  206486. DIB_RGB_COLORS,
  206487. (void**) &bitmapData,
  206488. 0, 0);
  206489. SelectObject (hdc, hBitmap);
  206490. if (format_ == Image::ARGB && clearImage)
  206491. zeromem (bitmapData, abs (h * lineStride));
  206492. imageData = bitmapData - (lineStride * (h - 1));
  206493. }
  206494. ~WindowsBitmapImage()
  206495. {
  206496. DeleteDC (hdc);
  206497. DeleteObject (hBitmap);
  206498. }
  206499. Image::ImageType getType() const { return Image::NativeImage; }
  206500. LowLevelGraphicsContext* createLowLevelContext()
  206501. {
  206502. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206503. }
  206504. Image::SharedImage* clone()
  206505. {
  206506. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206507. for (int i = 0; i < height; ++i)
  206508. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206509. return im;
  206510. }
  206511. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206512. const int x, const int y,
  206513. const RectangleList& maskedRegion,
  206514. const uint8 updateLayeredWindowAlpha) throw()
  206515. {
  206516. static HDRAWDIB hdd = 0;
  206517. static bool needToCreateDrawDib = true;
  206518. if (needToCreateDrawDib)
  206519. {
  206520. needToCreateDrawDib = false;
  206521. HDC dc = GetDC (0);
  206522. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206523. ReleaseDC (0, dc);
  206524. // only open if we're not palettised
  206525. if (n > 8)
  206526. hdd = DrawDibOpen();
  206527. }
  206528. if (createPaletteIfNeeded)
  206529. {
  206530. HDC dc = GetDC (0);
  206531. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206532. ReleaseDC (0, dc);
  206533. if (n <= 8)
  206534. palette = CreateHalftonePalette (dc);
  206535. createPaletteIfNeeded = false;
  206536. }
  206537. if (palette != 0)
  206538. {
  206539. SelectPalette (dc, palette, FALSE);
  206540. RealizePalette (dc);
  206541. SetStretchBltMode (dc, HALFTONE);
  206542. }
  206543. SetMapMode (dc, MM_TEXT);
  206544. if (transparent)
  206545. {
  206546. POINT p, pos;
  206547. SIZE size;
  206548. RECT windowBounds;
  206549. GetWindowRect (hwnd, &windowBounds);
  206550. p.x = -x;
  206551. p.y = -y;
  206552. pos.x = windowBounds.left;
  206553. pos.y = windowBounds.top;
  206554. size.cx = windowBounds.right - windowBounds.left;
  206555. size.cy = windowBounds.bottom - windowBounds.top;
  206556. BLENDFUNCTION bf;
  206557. bf.AlphaFormat = AC_SRC_ALPHA;
  206558. bf.BlendFlags = 0;
  206559. bf.BlendOp = AC_SRC_OVER;
  206560. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206561. if (! maskedRegion.isEmpty())
  206562. {
  206563. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206564. {
  206565. const Rectangle<int>& r = *i.getRectangle();
  206566. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206567. }
  206568. }
  206569. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206570. }
  206571. else
  206572. {
  206573. int savedDC = 0;
  206574. if (! maskedRegion.isEmpty())
  206575. {
  206576. savedDC = SaveDC (dc);
  206577. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206578. {
  206579. const Rectangle<int>& r = *i.getRectangle();
  206580. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206581. }
  206582. }
  206583. if (hdd == 0)
  206584. {
  206585. StretchDIBits (dc,
  206586. x, y, width, height,
  206587. 0, 0, width, height,
  206588. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206589. DIB_RGB_COLORS, SRCCOPY);
  206590. }
  206591. else
  206592. {
  206593. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206594. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206595. 0, 0, width, height, 0);
  206596. }
  206597. if (! maskedRegion.isEmpty())
  206598. RestoreDC (dc, savedDC);
  206599. }
  206600. }
  206601. private:
  206602. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206603. };
  206604. namespace IconConverters
  206605. {
  206606. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206607. {
  206608. Image im;
  206609. if (bitmap != 0)
  206610. {
  206611. BITMAP bm;
  206612. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206613. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206614. {
  206615. HDC tempDC = GetDC (0);
  206616. HDC dc = CreateCompatibleDC (tempDC);
  206617. ReleaseDC (0, tempDC);
  206618. SelectObject (dc, bitmap);
  206619. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206620. Image::BitmapData imageData (im, true);
  206621. for (int y = bm.bmHeight; --y >= 0;)
  206622. {
  206623. for (int x = bm.bmWidth; --x >= 0;)
  206624. {
  206625. COLORREF col = GetPixel (dc, x, y);
  206626. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206627. (uint8) GetGValue (col),
  206628. (uint8) GetBValue (col)));
  206629. }
  206630. }
  206631. DeleteDC (dc);
  206632. }
  206633. }
  206634. return im;
  206635. }
  206636. const Image createImageFromHICON (HICON icon)
  206637. {
  206638. ICONINFO info;
  206639. if (GetIconInfo (icon, &info))
  206640. {
  206641. Image mask (createImageFromHBITMAP (info.hbmMask));
  206642. Image image (createImageFromHBITMAP (info.hbmColor));
  206643. if (mask.isValid() && image.isValid())
  206644. {
  206645. for (int y = image.getHeight(); --y >= 0;)
  206646. {
  206647. for (int x = image.getWidth(); --x >= 0;)
  206648. {
  206649. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206650. if (brightness > 0.0f)
  206651. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206652. }
  206653. }
  206654. return image;
  206655. }
  206656. }
  206657. return Image::null;
  206658. }
  206659. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206660. {
  206661. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206662. Image bitmap (nativeBitmap);
  206663. {
  206664. Graphics g (bitmap);
  206665. g.drawImageAt (image, 0, 0);
  206666. }
  206667. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206668. ICONINFO info;
  206669. info.fIcon = isIcon;
  206670. info.xHotspot = hotspotX;
  206671. info.yHotspot = hotspotY;
  206672. info.hbmMask = mask;
  206673. info.hbmColor = nativeBitmap->hBitmap;
  206674. HICON hi = CreateIconIndirect (&info);
  206675. DeleteObject (mask);
  206676. return hi;
  206677. }
  206678. }
  206679. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206680. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206681. {
  206682. SHORT k = (SHORT) keyCode;
  206683. if ((keyCode & extendedKeyModifier) == 0
  206684. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206685. k += (SHORT) 'A' - (SHORT) 'a';
  206686. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206687. (SHORT) '+', VK_OEM_PLUS,
  206688. (SHORT) '-', VK_OEM_MINUS,
  206689. (SHORT) '.', VK_OEM_PERIOD,
  206690. (SHORT) ';', VK_OEM_1,
  206691. (SHORT) ':', VK_OEM_1,
  206692. (SHORT) '/', VK_OEM_2,
  206693. (SHORT) '?', VK_OEM_2,
  206694. (SHORT) '[', VK_OEM_4,
  206695. (SHORT) ']', VK_OEM_6 };
  206696. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206697. if (k == translatedValues [i])
  206698. k = translatedValues [i + 1];
  206699. return (GetKeyState (k) & 0x8000) != 0;
  206700. }
  206701. class Win32ComponentPeer : public ComponentPeer
  206702. {
  206703. public:
  206704. enum RenderingEngineType
  206705. {
  206706. softwareRenderingEngine = 0,
  206707. direct2DRenderingEngine
  206708. };
  206709. Win32ComponentPeer (Component* const component,
  206710. const int windowStyleFlags,
  206711. HWND parentToAddTo_)
  206712. : ComponentPeer (component, windowStyleFlags),
  206713. dontRepaint (false),
  206714. #if JUCE_DIRECT2D
  206715. currentRenderingEngine (direct2DRenderingEngine),
  206716. #else
  206717. currentRenderingEngine (softwareRenderingEngine),
  206718. #endif
  206719. fullScreen (false),
  206720. isDragging (false),
  206721. isMouseOver (false),
  206722. hasCreatedCaret (false),
  206723. currentWindowIcon (0),
  206724. dropTarget (0),
  206725. updateLayeredWindowAlpha (255),
  206726. parentToAddTo (parentToAddTo_)
  206727. {
  206728. callFunctionIfNotLocked (&createWindowCallback, this);
  206729. setTitle (component->getName());
  206730. if ((windowStyleFlags & windowHasDropShadow) != 0
  206731. && Desktop::canUseSemiTransparentWindows())
  206732. {
  206733. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206734. if (shadower != 0)
  206735. shadower->setOwner (component);
  206736. }
  206737. }
  206738. ~Win32ComponentPeer()
  206739. {
  206740. setTaskBarIcon (Image());
  206741. shadower = 0;
  206742. // do this before the next bit to avoid messages arriving for this window
  206743. // before it's destroyed
  206744. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206745. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206746. if (currentWindowIcon != 0)
  206747. DestroyIcon (currentWindowIcon);
  206748. if (dropTarget != 0)
  206749. {
  206750. dropTarget->Release();
  206751. dropTarget = 0;
  206752. }
  206753. #if JUCE_DIRECT2D
  206754. direct2DContext = 0;
  206755. #endif
  206756. }
  206757. void* getNativeHandle() const
  206758. {
  206759. return hwnd;
  206760. }
  206761. void setVisible (bool shouldBeVisible)
  206762. {
  206763. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206764. if (shouldBeVisible)
  206765. InvalidateRect (hwnd, 0, 0);
  206766. else
  206767. lastPaintTime = 0;
  206768. }
  206769. void setTitle (const String& title)
  206770. {
  206771. SetWindowText (hwnd, title);
  206772. }
  206773. void setPosition (int x, int y)
  206774. {
  206775. offsetWithinParent (x, y);
  206776. SetWindowPos (hwnd, 0,
  206777. x - windowBorder.getLeft(),
  206778. y - windowBorder.getTop(),
  206779. 0, 0,
  206780. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206781. }
  206782. void repaintNowIfTransparent()
  206783. {
  206784. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206785. handlePaintMessage();
  206786. }
  206787. void updateBorderSize()
  206788. {
  206789. WINDOWINFO info;
  206790. info.cbSize = sizeof (info);
  206791. if (GetWindowInfo (hwnd, &info))
  206792. {
  206793. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206794. info.rcClient.left - info.rcWindow.left,
  206795. info.rcWindow.bottom - info.rcClient.bottom,
  206796. info.rcWindow.right - info.rcClient.right);
  206797. }
  206798. #if JUCE_DIRECT2D
  206799. if (direct2DContext != 0)
  206800. direct2DContext->resized();
  206801. #endif
  206802. }
  206803. void setSize (int w, int h)
  206804. {
  206805. SetWindowPos (hwnd, 0, 0, 0,
  206806. w + windowBorder.getLeftAndRight(),
  206807. h + windowBorder.getTopAndBottom(),
  206808. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206809. updateBorderSize();
  206810. repaintNowIfTransparent();
  206811. }
  206812. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206813. {
  206814. fullScreen = isNowFullScreen;
  206815. offsetWithinParent (x, y);
  206816. SetWindowPos (hwnd, 0,
  206817. x - windowBorder.getLeft(),
  206818. y - windowBorder.getTop(),
  206819. w + windowBorder.getLeftAndRight(),
  206820. h + windowBorder.getTopAndBottom(),
  206821. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206822. updateBorderSize();
  206823. repaintNowIfTransparent();
  206824. }
  206825. const Rectangle<int> getBounds() const
  206826. {
  206827. RECT r;
  206828. GetWindowRect (hwnd, &r);
  206829. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206830. HWND parentH = GetParent (hwnd);
  206831. if (parentH != 0)
  206832. {
  206833. GetWindowRect (parentH, &r);
  206834. bounds.translate (-r.left, -r.top);
  206835. }
  206836. return windowBorder.subtractedFrom (bounds);
  206837. }
  206838. const Point<int> getScreenPosition() const
  206839. {
  206840. RECT r;
  206841. GetWindowRect (hwnd, &r);
  206842. return Point<int> (r.left + windowBorder.getLeft(),
  206843. r.top + windowBorder.getTop());
  206844. }
  206845. const Point<int> localToGlobal (const Point<int>& relativePosition)
  206846. {
  206847. return relativePosition + getScreenPosition();
  206848. }
  206849. const Point<int> globalToLocal (const Point<int>& screenPosition)
  206850. {
  206851. return screenPosition - getScreenPosition();
  206852. }
  206853. void setAlpha (float newAlpha)
  206854. {
  206855. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  206856. if (component->isOpaque())
  206857. {
  206858. if (newAlpha < 1.0f)
  206859. {
  206860. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  206861. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  206862. }
  206863. else
  206864. {
  206865. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  206866. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  206867. }
  206868. }
  206869. else
  206870. {
  206871. updateLayeredWindowAlpha = intAlpha;
  206872. component->repaint();
  206873. }
  206874. }
  206875. void setMinimised (bool shouldBeMinimised)
  206876. {
  206877. if (shouldBeMinimised != isMinimised())
  206878. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206879. }
  206880. bool isMinimised() const
  206881. {
  206882. WINDOWPLACEMENT wp;
  206883. wp.length = sizeof (WINDOWPLACEMENT);
  206884. GetWindowPlacement (hwnd, &wp);
  206885. return wp.showCmd == SW_SHOWMINIMIZED;
  206886. }
  206887. void setFullScreen (bool shouldBeFullScreen)
  206888. {
  206889. setMinimised (false);
  206890. if (fullScreen != shouldBeFullScreen)
  206891. {
  206892. fullScreen = shouldBeFullScreen;
  206893. const Component::SafePointer<Component> deletionChecker (component);
  206894. if (! fullScreen)
  206895. {
  206896. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206897. if (hasTitleBar())
  206898. ShowWindow (hwnd, SW_SHOWNORMAL);
  206899. if (! boundsCopy.isEmpty())
  206900. {
  206901. setBounds (boundsCopy.getX(),
  206902. boundsCopy.getY(),
  206903. boundsCopy.getWidth(),
  206904. boundsCopy.getHeight(),
  206905. false);
  206906. }
  206907. }
  206908. else
  206909. {
  206910. if (hasTitleBar())
  206911. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206912. else
  206913. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206914. }
  206915. if (deletionChecker != 0)
  206916. handleMovedOrResized();
  206917. }
  206918. }
  206919. bool isFullScreen() const
  206920. {
  206921. if (! hasTitleBar())
  206922. return fullScreen;
  206923. WINDOWPLACEMENT wp;
  206924. wp.length = sizeof (wp);
  206925. GetWindowPlacement (hwnd, &wp);
  206926. return wp.showCmd == SW_SHOWMAXIMIZED;
  206927. }
  206928. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  206929. {
  206930. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  206931. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  206932. return false;
  206933. RECT r;
  206934. GetWindowRect (hwnd, &r);
  206935. POINT p;
  206936. p.x = position.getX() + r.left + windowBorder.getLeft();
  206937. p.y = position.getY() + r.top + windowBorder.getTop();
  206938. HWND w = WindowFromPoint (p);
  206939. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206940. }
  206941. const BorderSize getFrameSize() const
  206942. {
  206943. return windowBorder;
  206944. }
  206945. bool setAlwaysOnTop (bool alwaysOnTop)
  206946. {
  206947. const bool oldDeactivate = shouldDeactivateTitleBar;
  206948. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206949. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206950. 0, 0, 0, 0,
  206951. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206952. shouldDeactivateTitleBar = oldDeactivate;
  206953. if (shadower != 0)
  206954. shadower->componentBroughtToFront (*component);
  206955. return true;
  206956. }
  206957. void toFront (bool makeActive)
  206958. {
  206959. setMinimised (false);
  206960. const bool oldDeactivate = shouldDeactivateTitleBar;
  206961. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206962. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  206963. shouldDeactivateTitleBar = oldDeactivate;
  206964. if (! makeActive)
  206965. {
  206966. // in this case a broughttofront call won't have occured, so do it now..
  206967. handleBroughtToFront();
  206968. }
  206969. }
  206970. void toBehind (ComponentPeer* other)
  206971. {
  206972. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206973. jassert (otherPeer != 0); // wrong type of window?
  206974. if (otherPeer != 0)
  206975. {
  206976. setMinimised (false);
  206977. // must be careful not to try to put a topmost window behind a normal one, or win32
  206978. // promotes the normal one to be topmost!
  206979. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  206980. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206981. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206982. else if (otherPeer->getComponent()->isAlwaysOnTop())
  206983. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  206984. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206985. }
  206986. }
  206987. bool isFocused() const
  206988. {
  206989. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  206990. }
  206991. void grabFocus()
  206992. {
  206993. const bool oldDeactivate = shouldDeactivateTitleBar;
  206994. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206995. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  206996. shouldDeactivateTitleBar = oldDeactivate;
  206997. }
  206998. void textInputRequired (const Point<int>&)
  206999. {
  207000. if (! hasCreatedCaret)
  207001. {
  207002. hasCreatedCaret = true;
  207003. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207004. }
  207005. ShowCaret (hwnd);
  207006. SetCaretPos (0, 0);
  207007. }
  207008. void repaint (const Rectangle<int>& area)
  207009. {
  207010. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207011. InvalidateRect (hwnd, &r, FALSE);
  207012. }
  207013. void performAnyPendingRepaintsNow()
  207014. {
  207015. MSG m;
  207016. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207017. DispatchMessage (&m);
  207018. }
  207019. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207020. {
  207021. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207022. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207023. return 0;
  207024. }
  207025. void setTaskBarIcon (const Image& image)
  207026. {
  207027. if (image.isValid())
  207028. {
  207029. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  207030. if (taskBarIcon == 0)
  207031. {
  207032. taskBarIcon = new NOTIFYICONDATA();
  207033. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  207034. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207035. taskBarIcon->hWnd = (HWND) hwnd;
  207036. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207037. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207038. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207039. taskBarIcon->hIcon = hicon;
  207040. taskBarIcon->szTip[0] = 0;
  207041. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207042. }
  207043. else
  207044. {
  207045. HICON oldIcon = taskBarIcon->hIcon;
  207046. taskBarIcon->hIcon = hicon;
  207047. taskBarIcon->uFlags = NIF_ICON;
  207048. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207049. DestroyIcon (oldIcon);
  207050. }
  207051. }
  207052. else if (taskBarIcon != 0)
  207053. {
  207054. taskBarIcon->uFlags = 0;
  207055. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207056. DestroyIcon (taskBarIcon->hIcon);
  207057. taskBarIcon = 0;
  207058. }
  207059. }
  207060. void setTaskBarIconToolTip (const String& toolTip) const
  207061. {
  207062. if (taskBarIcon != 0)
  207063. {
  207064. taskBarIcon->uFlags = NIF_TIP;
  207065. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207066. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207067. }
  207068. }
  207069. void handleTaskBarEvent (const LPARAM lParam, const WPARAM wParam)
  207070. {
  207071. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207072. {
  207073. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207074. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207075. {
  207076. Component* const current = Component::getCurrentlyModalComponent();
  207077. if (current != 0)
  207078. current->inputAttemptWhenModal();
  207079. }
  207080. }
  207081. else
  207082. {
  207083. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  207084. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207085. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  207086. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207087. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  207088. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207089. eventMods = eventMods.withoutMouseButtons();
  207090. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  207091. Point<int>(), eventMods, component, component, getMouseEventTime(),
  207092. Point<int>(), getMouseEventTime(), 1, false);
  207093. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207094. {
  207095. SetFocus (hwnd);
  207096. SetForegroundWindow (hwnd);
  207097. component->mouseDown (e);
  207098. }
  207099. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207100. {
  207101. component->mouseUp (e);
  207102. }
  207103. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207104. {
  207105. component->mouseDoubleClick (e);
  207106. }
  207107. else if (lParam == WM_MOUSEMOVE)
  207108. {
  207109. component->mouseMove (e);
  207110. }
  207111. }
  207112. }
  207113. bool isInside (HWND h) const
  207114. {
  207115. return GetAncestor (hwnd, GA_ROOT) == h;
  207116. }
  207117. static void updateKeyModifiers() throw()
  207118. {
  207119. int keyMods = 0;
  207120. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207121. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207122. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207123. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207124. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207125. }
  207126. static void updateModifiersFromWParam (const WPARAM wParam)
  207127. {
  207128. int mouseMods = 0;
  207129. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207130. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207131. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207132. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207133. updateKeyModifiers();
  207134. }
  207135. static int64 getMouseEventTime()
  207136. {
  207137. static int64 eventTimeOffset = 0;
  207138. static DWORD lastMessageTime = 0;
  207139. const DWORD thisMessageTime = GetMessageTime();
  207140. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207141. {
  207142. lastMessageTime = thisMessageTime;
  207143. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207144. }
  207145. return eventTimeOffset + thisMessageTime;
  207146. }
  207147. bool dontRepaint;
  207148. static ModifierKeys currentModifiers;
  207149. static ModifierKeys modifiersAtLastCallback;
  207150. private:
  207151. HWND hwnd, parentToAddTo;
  207152. ScopedPointer<DropShadower> shadower;
  207153. RenderingEngineType currentRenderingEngine;
  207154. #if JUCE_DIRECT2D
  207155. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207156. #endif
  207157. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207158. BorderSize windowBorder;
  207159. HICON currentWindowIcon;
  207160. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207161. IDropTarget* dropTarget;
  207162. uint8 updateLayeredWindowAlpha;
  207163. class TemporaryImage : public Timer
  207164. {
  207165. public:
  207166. TemporaryImage() {}
  207167. ~TemporaryImage() {}
  207168. const Image& getImage (const bool transparent, const int w, const int h)
  207169. {
  207170. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207171. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207172. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207173. startTimer (3000);
  207174. return image;
  207175. }
  207176. void timerCallback()
  207177. {
  207178. stopTimer();
  207179. image = Image::null;
  207180. }
  207181. private:
  207182. Image image;
  207183. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  207184. };
  207185. TemporaryImage offscreenImageGenerator;
  207186. class WindowClassHolder : public DeletedAtShutdown
  207187. {
  207188. public:
  207189. WindowClassHolder()
  207190. : windowClassName ("JUCE_")
  207191. {
  207192. // this name has to be different for each app/dll instance because otherwise
  207193. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207194. // window class).
  207195. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207196. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207197. TCHAR moduleFile [1024];
  207198. moduleFile[0] = 0;
  207199. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207200. WORD iconNum = 0;
  207201. WNDCLASSEX wcex;
  207202. wcex.cbSize = sizeof (wcex);
  207203. wcex.style = CS_OWNDC;
  207204. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207205. wcex.lpszClassName = windowClassName;
  207206. wcex.cbClsExtra = 0;
  207207. wcex.cbWndExtra = 32;
  207208. wcex.hInstance = moduleHandle;
  207209. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207210. iconNum = 1;
  207211. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207212. wcex.hCursor = 0;
  207213. wcex.hbrBackground = 0;
  207214. wcex.lpszMenuName = 0;
  207215. RegisterClassEx (&wcex);
  207216. }
  207217. ~WindowClassHolder()
  207218. {
  207219. if (ComponentPeer::getNumPeers() == 0)
  207220. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207221. clearSingletonInstance();
  207222. }
  207223. String windowClassName;
  207224. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207225. };
  207226. static void* createWindowCallback (void* userData)
  207227. {
  207228. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207229. return 0;
  207230. }
  207231. void createWindow()
  207232. {
  207233. DWORD exstyle = WS_EX_ACCEPTFILES;
  207234. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207235. if (hasTitleBar())
  207236. {
  207237. type |= WS_OVERLAPPED;
  207238. if ((styleFlags & windowHasCloseButton) != 0)
  207239. {
  207240. type |= WS_SYSMENU;
  207241. }
  207242. else
  207243. {
  207244. // annoyingly, windows won't let you have a min/max button without a close button
  207245. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207246. }
  207247. if ((styleFlags & windowIsResizable) != 0)
  207248. type |= WS_THICKFRAME;
  207249. }
  207250. else if (parentToAddTo != 0)
  207251. {
  207252. type |= WS_CHILD;
  207253. }
  207254. else
  207255. {
  207256. type |= WS_POPUP | WS_SYSMENU;
  207257. }
  207258. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207259. exstyle |= WS_EX_TOOLWINDOW;
  207260. else
  207261. exstyle |= WS_EX_APPWINDOW;
  207262. if ((styleFlags & windowHasMinimiseButton) != 0)
  207263. type |= WS_MINIMIZEBOX;
  207264. if ((styleFlags & windowHasMaximiseButton) != 0)
  207265. type |= WS_MAXIMIZEBOX;
  207266. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207267. exstyle |= WS_EX_TRANSPARENT;
  207268. if ((styleFlags & windowIsSemiTransparent) != 0
  207269. && Desktop::canUseSemiTransparentWindows())
  207270. exstyle |= WS_EX_LAYERED;
  207271. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207272. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207273. #if JUCE_DIRECT2D
  207274. updateDirect2DContext();
  207275. #endif
  207276. if (hwnd != 0)
  207277. {
  207278. SetWindowLongPtr (hwnd, 0, 0);
  207279. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207280. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207281. if (dropTarget == 0)
  207282. dropTarget = new JuceDropTarget (this);
  207283. RegisterDragDrop (hwnd, dropTarget);
  207284. updateBorderSize();
  207285. // Calling this function here is (for some reason) necessary to make Windows
  207286. // correctly enable the menu items that we specify in the wm_initmenu message.
  207287. GetSystemMenu (hwnd, false);
  207288. const float alpha = component->getAlpha();
  207289. if (alpha < 1.0f)
  207290. setAlpha (alpha);
  207291. }
  207292. else
  207293. {
  207294. jassertfalse;
  207295. }
  207296. }
  207297. static void* destroyWindowCallback (void* handle)
  207298. {
  207299. RevokeDragDrop ((HWND) handle);
  207300. DestroyWindow ((HWND) handle);
  207301. return 0;
  207302. }
  207303. static void* toFrontCallback1 (void* h)
  207304. {
  207305. SetForegroundWindow ((HWND) h);
  207306. return 0;
  207307. }
  207308. static void* toFrontCallback2 (void* h)
  207309. {
  207310. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207311. return 0;
  207312. }
  207313. static void* setFocusCallback (void* h)
  207314. {
  207315. SetFocus ((HWND) h);
  207316. return 0;
  207317. }
  207318. static void* getFocusCallback (void*)
  207319. {
  207320. return GetFocus();
  207321. }
  207322. void offsetWithinParent (int& x, int& y) const
  207323. {
  207324. if (isUsingUpdateLayeredWindow())
  207325. {
  207326. HWND parentHwnd = GetParent (hwnd);
  207327. if (parentHwnd != 0)
  207328. {
  207329. RECT parentRect;
  207330. GetWindowRect (parentHwnd, &parentRect);
  207331. x += parentRect.left;
  207332. y += parentRect.top;
  207333. }
  207334. }
  207335. }
  207336. bool isUsingUpdateLayeredWindow() const
  207337. {
  207338. return ! component->isOpaque();
  207339. }
  207340. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207341. void setIcon (const Image& newIcon)
  207342. {
  207343. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207344. if (hicon != 0)
  207345. {
  207346. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207347. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207348. if (currentWindowIcon != 0)
  207349. DestroyIcon (currentWindowIcon);
  207350. currentWindowIcon = hicon;
  207351. }
  207352. }
  207353. void handlePaintMessage()
  207354. {
  207355. #if JUCE_DIRECT2D
  207356. if (direct2DContext != 0)
  207357. {
  207358. RECT r;
  207359. if (GetUpdateRect (hwnd, &r, false))
  207360. {
  207361. direct2DContext->start();
  207362. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207363. handlePaint (*direct2DContext);
  207364. direct2DContext->end();
  207365. }
  207366. }
  207367. else
  207368. #endif
  207369. {
  207370. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207371. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207372. PAINTSTRUCT paintStruct;
  207373. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207374. // message and become re-entrant, but that's OK
  207375. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207376. // corrupt the image it's using to paint into, so do a check here.
  207377. static bool reentrant = false;
  207378. if (reentrant)
  207379. {
  207380. DeleteObject (rgn);
  207381. EndPaint (hwnd, &paintStruct);
  207382. return;
  207383. }
  207384. reentrant = true;
  207385. // this is the rectangle to update..
  207386. int x = paintStruct.rcPaint.left;
  207387. int y = paintStruct.rcPaint.top;
  207388. int w = paintStruct.rcPaint.right - x;
  207389. int h = paintStruct.rcPaint.bottom - y;
  207390. const bool transparent = isUsingUpdateLayeredWindow();
  207391. if (transparent)
  207392. {
  207393. // it's not possible to have a transparent window with a title bar at the moment!
  207394. jassert (! hasTitleBar());
  207395. RECT r;
  207396. GetWindowRect (hwnd, &r);
  207397. x = y = 0;
  207398. w = r.right - r.left;
  207399. h = r.bottom - r.top;
  207400. }
  207401. if (w > 0 && h > 0)
  207402. {
  207403. clearMaskedRegion();
  207404. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207405. RectangleList contextClip;
  207406. const Rectangle<int> clipBounds (0, 0, w, h);
  207407. bool needToPaintAll = true;
  207408. if (regionType == COMPLEXREGION && ! transparent)
  207409. {
  207410. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207411. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207412. DeleteObject (clipRgn);
  207413. char rgnData [8192];
  207414. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207415. if (res > 0 && res <= sizeof (rgnData))
  207416. {
  207417. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207418. if (hdr->iType == RDH_RECTANGLES
  207419. && hdr->rcBound.right - hdr->rcBound.left >= w
  207420. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207421. {
  207422. needToPaintAll = false;
  207423. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207424. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207425. while (--num >= 0)
  207426. {
  207427. if (rects->right <= x + w && rects->bottom <= y + h)
  207428. {
  207429. const int cx = jmax (x, (int) rects->left);
  207430. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207431. .getIntersection (clipBounds));
  207432. }
  207433. else
  207434. {
  207435. needToPaintAll = true;
  207436. break;
  207437. }
  207438. ++rects;
  207439. }
  207440. }
  207441. }
  207442. }
  207443. if (needToPaintAll)
  207444. {
  207445. contextClip.clear();
  207446. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207447. }
  207448. if (transparent)
  207449. {
  207450. RectangleList::Iterator i (contextClip);
  207451. while (i.next())
  207452. offscreenImage.clear (*i.getRectangle());
  207453. }
  207454. // if the component's not opaque, this won't draw properly unless the platform can support this
  207455. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207456. updateCurrentModifiers();
  207457. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207458. handlePaint (context);
  207459. if (! dontRepaint)
  207460. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207461. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207462. }
  207463. DeleteObject (rgn);
  207464. EndPaint (hwnd, &paintStruct);
  207465. reentrant = false;
  207466. }
  207467. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207468. _fpreset(); // because some graphics cards can unmask FP exceptions
  207469. #endif
  207470. lastPaintTime = Time::getMillisecondCounter();
  207471. }
  207472. void doMouseEvent (const Point<int>& position)
  207473. {
  207474. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207475. }
  207476. const StringArray getAvailableRenderingEngines()
  207477. {
  207478. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207479. #if JUCE_DIRECT2D
  207480. // xxx is this correct? Seems to enable it on Vista too??
  207481. OSVERSIONINFO info;
  207482. zerostruct (info);
  207483. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207484. GetVersionEx (&info);
  207485. if (info.dwMajorVersion >= 6)
  207486. s.add ("Direct2D");
  207487. #endif
  207488. return s;
  207489. }
  207490. int getCurrentRenderingEngine() throw()
  207491. {
  207492. return currentRenderingEngine;
  207493. }
  207494. #if JUCE_DIRECT2D
  207495. void updateDirect2DContext()
  207496. {
  207497. if (currentRenderingEngine != direct2DRenderingEngine)
  207498. direct2DContext = 0;
  207499. else if (direct2DContext == 0)
  207500. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207501. }
  207502. #endif
  207503. void setCurrentRenderingEngine (int index)
  207504. {
  207505. (void) index;
  207506. #if JUCE_DIRECT2D
  207507. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207508. updateDirect2DContext();
  207509. repaint (component->getLocalBounds());
  207510. #endif
  207511. }
  207512. void doMouseMove (const Point<int>& position)
  207513. {
  207514. if (! isMouseOver)
  207515. {
  207516. isMouseOver = true;
  207517. updateKeyModifiers();
  207518. TRACKMOUSEEVENT tme;
  207519. tme.cbSize = sizeof (tme);
  207520. tme.dwFlags = TME_LEAVE;
  207521. tme.hwndTrack = hwnd;
  207522. tme.dwHoverTime = 0;
  207523. if (! TrackMouseEvent (&tme))
  207524. jassertfalse;
  207525. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207526. }
  207527. else if (! isDragging)
  207528. {
  207529. if (! contains (position, false))
  207530. return;
  207531. }
  207532. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207533. static uint32 lastMouseTime = 0;
  207534. const uint32 now = Time::getMillisecondCounter();
  207535. const int maxMouseMovesPerSecond = 60;
  207536. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207537. {
  207538. lastMouseTime = now;
  207539. doMouseEvent (position);
  207540. }
  207541. }
  207542. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207543. {
  207544. if (GetCapture() != hwnd)
  207545. SetCapture (hwnd);
  207546. doMouseMove (position);
  207547. updateModifiersFromWParam (wParam);
  207548. isDragging = true;
  207549. doMouseEvent (position);
  207550. }
  207551. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207552. {
  207553. updateModifiersFromWParam (wParam);
  207554. isDragging = false;
  207555. // release the mouse capture if the user has released all buttons
  207556. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207557. ReleaseCapture();
  207558. doMouseEvent (position);
  207559. }
  207560. void doCaptureChanged()
  207561. {
  207562. if (isDragging)
  207563. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207564. }
  207565. void doMouseExit()
  207566. {
  207567. isMouseOver = false;
  207568. doMouseEvent (getCurrentMousePos());
  207569. }
  207570. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207571. {
  207572. updateKeyModifiers();
  207573. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207574. handleMouseWheel (0, position, getMouseEventTime(),
  207575. isVertical ? 0.0f : amount,
  207576. isVertical ? amount : 0.0f);
  207577. }
  207578. void sendModifierKeyChangeIfNeeded()
  207579. {
  207580. if (modifiersAtLastCallback != currentModifiers)
  207581. {
  207582. modifiersAtLastCallback = currentModifiers;
  207583. handleModifierKeysChange();
  207584. }
  207585. }
  207586. bool doKeyUp (const WPARAM key)
  207587. {
  207588. updateKeyModifiers();
  207589. switch (key)
  207590. {
  207591. case VK_SHIFT:
  207592. case VK_CONTROL:
  207593. case VK_MENU:
  207594. case VK_CAPITAL:
  207595. case VK_LWIN:
  207596. case VK_RWIN:
  207597. case VK_APPS:
  207598. case VK_NUMLOCK:
  207599. case VK_SCROLL:
  207600. case VK_LSHIFT:
  207601. case VK_RSHIFT:
  207602. case VK_LCONTROL:
  207603. case VK_LMENU:
  207604. case VK_RCONTROL:
  207605. case VK_RMENU:
  207606. sendModifierKeyChangeIfNeeded();
  207607. }
  207608. return handleKeyUpOrDown (false)
  207609. || Component::getCurrentlyModalComponent() != 0;
  207610. }
  207611. bool doKeyDown (const WPARAM key)
  207612. {
  207613. updateKeyModifiers();
  207614. bool used = false;
  207615. switch (key)
  207616. {
  207617. case VK_SHIFT:
  207618. case VK_LSHIFT:
  207619. case VK_RSHIFT:
  207620. case VK_CONTROL:
  207621. case VK_LCONTROL:
  207622. case VK_RCONTROL:
  207623. case VK_MENU:
  207624. case VK_LMENU:
  207625. case VK_RMENU:
  207626. case VK_LWIN:
  207627. case VK_RWIN:
  207628. case VK_CAPITAL:
  207629. case VK_NUMLOCK:
  207630. case VK_SCROLL:
  207631. case VK_APPS:
  207632. sendModifierKeyChangeIfNeeded();
  207633. break;
  207634. case VK_LEFT:
  207635. case VK_RIGHT:
  207636. case VK_UP:
  207637. case VK_DOWN:
  207638. case VK_PRIOR:
  207639. case VK_NEXT:
  207640. case VK_HOME:
  207641. case VK_END:
  207642. case VK_DELETE:
  207643. case VK_INSERT:
  207644. case VK_F1:
  207645. case VK_F2:
  207646. case VK_F3:
  207647. case VK_F4:
  207648. case VK_F5:
  207649. case VK_F6:
  207650. case VK_F7:
  207651. case VK_F8:
  207652. case VK_F9:
  207653. case VK_F10:
  207654. case VK_F11:
  207655. case VK_F12:
  207656. case VK_F13:
  207657. case VK_F14:
  207658. case VK_F15:
  207659. case VK_F16:
  207660. used = handleKeyUpOrDown (true);
  207661. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207662. break;
  207663. case VK_ADD:
  207664. case VK_SUBTRACT:
  207665. case VK_MULTIPLY:
  207666. case VK_DIVIDE:
  207667. case VK_SEPARATOR:
  207668. case VK_DECIMAL:
  207669. used = handleKeyUpOrDown (true);
  207670. break;
  207671. default:
  207672. used = handleKeyUpOrDown (true);
  207673. {
  207674. MSG msg;
  207675. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207676. {
  207677. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207678. // manually generate the key-press event that matches this key-down.
  207679. const UINT keyChar = MapVirtualKey (key, 2);
  207680. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207681. }
  207682. }
  207683. break;
  207684. }
  207685. if (Component::getCurrentlyModalComponent() != 0)
  207686. used = true;
  207687. return used;
  207688. }
  207689. bool doKeyChar (int key, const LPARAM flags)
  207690. {
  207691. updateKeyModifiers();
  207692. juce_wchar textChar = (juce_wchar) key;
  207693. const int virtualScanCode = (flags >> 16) & 0xff;
  207694. if (key >= '0' && key <= '9')
  207695. {
  207696. switch (virtualScanCode) // check for a numeric keypad scan-code
  207697. {
  207698. case 0x52:
  207699. case 0x4f:
  207700. case 0x50:
  207701. case 0x51:
  207702. case 0x4b:
  207703. case 0x4c:
  207704. case 0x4d:
  207705. case 0x47:
  207706. case 0x48:
  207707. case 0x49:
  207708. key = (key - '0') + KeyPress::numberPad0;
  207709. break;
  207710. default:
  207711. break;
  207712. }
  207713. }
  207714. else
  207715. {
  207716. // convert the scan code to an unmodified character code..
  207717. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207718. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207719. keyChar = LOWORD (keyChar);
  207720. if (keyChar != 0)
  207721. key = (int) keyChar;
  207722. // avoid sending junk text characters for some control-key combinations
  207723. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207724. textChar = 0;
  207725. }
  207726. return handleKeyPress (key, textChar);
  207727. }
  207728. bool doAppCommand (const LPARAM lParam)
  207729. {
  207730. int key = 0;
  207731. switch (GET_APPCOMMAND_LPARAM (lParam))
  207732. {
  207733. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  207734. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  207735. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  207736. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  207737. default: break;
  207738. }
  207739. if (key != 0)
  207740. {
  207741. updateKeyModifiers();
  207742. if (hwnd == GetActiveWindow())
  207743. {
  207744. handleKeyPress (key, 0);
  207745. return true;
  207746. }
  207747. }
  207748. return false;
  207749. }
  207750. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  207751. {
  207752. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207753. {
  207754. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  207755. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  207756. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207757. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  207758. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  207759. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  207760. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  207761. r->left = pos.getX();
  207762. r->top = pos.getY();
  207763. r->right = pos.getRight();
  207764. r->bottom = pos.getBottom();
  207765. }
  207766. return TRUE;
  207767. }
  207768. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  207769. {
  207770. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207771. {
  207772. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  207773. && ! Component::isMouseButtonDownAnywhere())
  207774. {
  207775. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207776. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  207777. constrainer->checkBounds (pos, current,
  207778. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207779. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207780. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207781. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207782. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207783. wp->x = pos.getX();
  207784. wp->y = pos.getY();
  207785. wp->cx = pos.getWidth();
  207786. wp->cy = pos.getHeight();
  207787. }
  207788. }
  207789. return 0;
  207790. }
  207791. void handleAppActivation (const WPARAM wParam)
  207792. {
  207793. modifiersAtLastCallback = -1;
  207794. updateKeyModifiers();
  207795. if (isMinimised())
  207796. {
  207797. component->repaint();
  207798. handleMovedOrResized();
  207799. if (! ComponentPeer::isValidPeer (this))
  207800. return;
  207801. }
  207802. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  207803. {
  207804. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  207805. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207806. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207807. }
  207808. else
  207809. {
  207810. handleBroughtToFront();
  207811. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207812. Component::getCurrentlyModalComponent()->toFront (true);
  207813. }
  207814. }
  207815. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207816. {
  207817. public:
  207818. JuceDropTarget (Win32ComponentPeer* const owner_)
  207819. : owner (owner_)
  207820. {
  207821. }
  207822. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207823. {
  207824. updateFileList (pDataObject);
  207825. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207826. *pdwEffect = DROPEFFECT_COPY;
  207827. return S_OK;
  207828. }
  207829. HRESULT __stdcall DragLeave()
  207830. {
  207831. owner->handleFileDragExit (files);
  207832. return S_OK;
  207833. }
  207834. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207835. {
  207836. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207837. *pdwEffect = DROPEFFECT_COPY;
  207838. return S_OK;
  207839. }
  207840. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207841. {
  207842. updateFileList (pDataObject);
  207843. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207844. *pdwEffect = DROPEFFECT_COPY;
  207845. return S_OK;
  207846. }
  207847. private:
  207848. Win32ComponentPeer* const owner;
  207849. StringArray files;
  207850. void updateFileList (IDataObject* const pDataObject)
  207851. {
  207852. files.clear();
  207853. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207854. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207855. if (pDataObject->GetData (&format, &medium) == S_OK)
  207856. {
  207857. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207858. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207859. unsigned int i = 0;
  207860. if (pDropFiles->fWide)
  207861. {
  207862. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207863. for (;;)
  207864. {
  207865. unsigned int len = 0;
  207866. while (i + len < totalLen && fname [i + len] != 0)
  207867. ++len;
  207868. if (len == 0)
  207869. break;
  207870. files.add (String (fname + i, len));
  207871. i += len + 1;
  207872. }
  207873. }
  207874. else
  207875. {
  207876. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207877. for (;;)
  207878. {
  207879. unsigned int len = 0;
  207880. while (i + len < totalLen && fname [i + len] != 0)
  207881. ++len;
  207882. if (len == 0)
  207883. break;
  207884. files.add (String (fname + i, len));
  207885. i += len + 1;
  207886. }
  207887. }
  207888. GlobalUnlock (medium.hGlobal);
  207889. }
  207890. }
  207891. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  207892. };
  207893. void doSettingChange()
  207894. {
  207895. Desktop::getInstance().refreshMonitorSizes();
  207896. if (fullScreen && ! isMinimised())
  207897. {
  207898. const Rectangle<int> r (component->getParentMonitorArea());
  207899. SetWindowPos (hwnd, 0,
  207900. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207901. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207902. }
  207903. }
  207904. public:
  207905. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207906. {
  207907. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207908. if (peer != 0)
  207909. return peer->peerWindowProc (h, message, wParam, lParam);
  207910. return DefWindowProcW (h, message, wParam, lParam);
  207911. }
  207912. private:
  207913. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  207914. {
  207915. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  207916. return callback (userData);
  207917. else
  207918. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  207919. }
  207920. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207921. {
  207922. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207923. }
  207924. const Point<int> getCurrentMousePos() throw()
  207925. {
  207926. RECT wr;
  207927. GetWindowRect (hwnd, &wr);
  207928. const DWORD mp = GetMessagePos();
  207929. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207930. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207931. }
  207932. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207933. {
  207934. if (isValidPeer (this))
  207935. {
  207936. switch (message)
  207937. {
  207938. case WM_NCHITTEST:
  207939. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207940. return HTTRANSPARENT;
  207941. else if (! hasTitleBar())
  207942. return HTCLIENT;
  207943. break;
  207944. case WM_PAINT:
  207945. handlePaintMessage();
  207946. return 0;
  207947. case WM_NCPAINT:
  207948. if (wParam != 1)
  207949. handlePaintMessage();
  207950. if (hasTitleBar())
  207951. break;
  207952. return 0;
  207953. case WM_ERASEBKGND:
  207954. case WM_NCCALCSIZE:
  207955. if (hasTitleBar())
  207956. break;
  207957. return 1;
  207958. case WM_MOUSEMOVE:
  207959. doMouseMove (getPointFromLParam (lParam));
  207960. return 0;
  207961. case WM_MOUSELEAVE:
  207962. doMouseExit();
  207963. return 0;
  207964. case WM_LBUTTONDOWN:
  207965. case WM_MBUTTONDOWN:
  207966. case WM_RBUTTONDOWN:
  207967. doMouseDown (getPointFromLParam (lParam), wParam);
  207968. return 0;
  207969. case WM_LBUTTONUP:
  207970. case WM_MBUTTONUP:
  207971. case WM_RBUTTONUP:
  207972. doMouseUp (getPointFromLParam (lParam), wParam);
  207973. return 0;
  207974. case WM_CAPTURECHANGED:
  207975. doCaptureChanged();
  207976. return 0;
  207977. case WM_NCMOUSEMOVE:
  207978. if (hasTitleBar())
  207979. break;
  207980. return 0;
  207981. case 0x020A: /* WM_MOUSEWHEEL */
  207982. doMouseWheel (getCurrentMousePos(), wParam, true);
  207983. return 0;
  207984. case 0x020E: /* WM_MOUSEHWHEEL */
  207985. doMouseWheel (getCurrentMousePos(), wParam, false);
  207986. return 0;
  207987. case WM_SIZING:
  207988. return handleSizeConstraining ((RECT*) lParam, wParam);
  207989. case WM_WINDOWPOSCHANGING:
  207990. return handlePositionChanging ((WINDOWPOS*) lParam);
  207991. case WM_WINDOWPOSCHANGED:
  207992. {
  207993. const Point<int> pos (getCurrentMousePos());
  207994. if (contains (pos, false))
  207995. doMouseEvent (pos);
  207996. }
  207997. handleMovedOrResized();
  207998. if (dontRepaint)
  207999. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208000. return 0;
  208001. case WM_KEYDOWN:
  208002. case WM_SYSKEYDOWN:
  208003. if (doKeyDown (wParam))
  208004. return 0;
  208005. break;
  208006. case WM_KEYUP:
  208007. case WM_SYSKEYUP:
  208008. if (doKeyUp (wParam))
  208009. return 0;
  208010. break;
  208011. case WM_CHAR:
  208012. if (doKeyChar ((int) wParam, lParam))
  208013. return 0;
  208014. break;
  208015. case WM_APPCOMMAND:
  208016. if (doAppCommand (lParam))
  208017. return TRUE;
  208018. break;
  208019. case WM_SETFOCUS:
  208020. updateKeyModifiers();
  208021. handleFocusGain();
  208022. break;
  208023. case WM_KILLFOCUS:
  208024. if (hasCreatedCaret)
  208025. {
  208026. hasCreatedCaret = false;
  208027. DestroyCaret();
  208028. }
  208029. handleFocusLoss();
  208030. break;
  208031. case WM_ACTIVATEAPP:
  208032. // Windows does weird things to process priority when you swap apps,
  208033. // so this forces an update when the app is brought to the front
  208034. if (wParam != FALSE)
  208035. juce_repeatLastProcessPriority();
  208036. else
  208037. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208038. juce_CheckCurrentlyFocusedTopLevelWindow();
  208039. modifiersAtLastCallback = -1;
  208040. return 0;
  208041. case WM_ACTIVATE:
  208042. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208043. {
  208044. handleAppActivation (wParam);
  208045. return 0;
  208046. }
  208047. break;
  208048. case WM_NCACTIVATE:
  208049. // while a temporary window is being shown, prevent Windows from deactivating the
  208050. // title bars of our main windows.
  208051. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208052. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208053. break;
  208054. case WM_MOUSEACTIVATE:
  208055. if (! component->getMouseClickGrabsKeyboardFocus())
  208056. return MA_NOACTIVATE;
  208057. break;
  208058. case WM_SHOWWINDOW:
  208059. if (wParam != 0)
  208060. handleBroughtToFront();
  208061. break;
  208062. case WM_CLOSE:
  208063. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208064. handleUserClosingWindow();
  208065. return 0;
  208066. case WM_QUERYENDSESSION:
  208067. if (JUCEApplication::getInstance() != 0)
  208068. {
  208069. JUCEApplication::getInstance()->systemRequestedQuit();
  208070. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208071. }
  208072. return TRUE;
  208073. case WM_TRAYNOTIFY:
  208074. handleTaskBarEvent (lParam, wParam);
  208075. break;
  208076. case WM_SYNCPAINT:
  208077. return 0;
  208078. case WM_PALETTECHANGED:
  208079. InvalidateRect (h, 0, 0);
  208080. break;
  208081. case WM_DISPLAYCHANGE:
  208082. InvalidateRect (h, 0, 0);
  208083. createPaletteIfNeeded = true;
  208084. // intentional fall-through...
  208085. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208086. doSettingChange();
  208087. break;
  208088. case WM_INITMENU:
  208089. if (! hasTitleBar())
  208090. {
  208091. if (isFullScreen())
  208092. {
  208093. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208094. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208095. }
  208096. else if (! isMinimised())
  208097. {
  208098. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208099. }
  208100. }
  208101. break;
  208102. case WM_SYSCOMMAND:
  208103. switch (wParam & 0xfff0)
  208104. {
  208105. case SC_CLOSE:
  208106. if (sendInputAttemptWhenModalMessage())
  208107. return 0;
  208108. if (hasTitleBar())
  208109. {
  208110. PostMessage (h, WM_CLOSE, 0, 0);
  208111. return 0;
  208112. }
  208113. break;
  208114. case SC_KEYMENU:
  208115. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  208116. // situations that can arise if a modal loop is started from an alt-key keypress).
  208117. if (hasTitleBar() && h == GetCapture())
  208118. ReleaseCapture();
  208119. break;
  208120. case SC_MAXIMIZE:
  208121. if (sendInputAttemptWhenModalMessage())
  208122. return 0;
  208123. setFullScreen (true);
  208124. return 0;
  208125. case SC_MINIMIZE:
  208126. if (sendInputAttemptWhenModalMessage())
  208127. return 0;
  208128. if (! hasTitleBar())
  208129. {
  208130. setMinimised (true);
  208131. return 0;
  208132. }
  208133. break;
  208134. case SC_RESTORE:
  208135. if (sendInputAttemptWhenModalMessage())
  208136. return 0;
  208137. if (hasTitleBar())
  208138. {
  208139. if (isFullScreen())
  208140. {
  208141. setFullScreen (false);
  208142. return 0;
  208143. }
  208144. }
  208145. else
  208146. {
  208147. if (isMinimised())
  208148. setMinimised (false);
  208149. else if (isFullScreen())
  208150. setFullScreen (false);
  208151. return 0;
  208152. }
  208153. break;
  208154. }
  208155. break;
  208156. case WM_NCLBUTTONDOWN:
  208157. case WM_NCRBUTTONDOWN:
  208158. case WM_NCMBUTTONDOWN:
  208159. sendInputAttemptWhenModalMessage();
  208160. break;
  208161. //case WM_IME_STARTCOMPOSITION;
  208162. // return 0;
  208163. case WM_GETDLGCODE:
  208164. return DLGC_WANTALLKEYS;
  208165. default:
  208166. if (taskBarIcon != 0)
  208167. {
  208168. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208169. if (message == taskbarCreatedMessage)
  208170. {
  208171. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208172. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208173. }
  208174. }
  208175. break;
  208176. }
  208177. }
  208178. return DefWindowProcW (h, message, wParam, lParam);
  208179. }
  208180. bool sendInputAttemptWhenModalMessage()
  208181. {
  208182. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208183. {
  208184. Component* const current = Component::getCurrentlyModalComponent();
  208185. if (current != 0)
  208186. current->inputAttemptWhenModal();
  208187. return true;
  208188. }
  208189. return false;
  208190. }
  208191. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  208192. };
  208193. ModifierKeys Win32ComponentPeer::currentModifiers;
  208194. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208195. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208196. {
  208197. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208198. }
  208199. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208200. void ModifierKeys::updateCurrentModifiers() throw()
  208201. {
  208202. currentModifiers = Win32ComponentPeer::currentModifiers;
  208203. }
  208204. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208205. {
  208206. Win32ComponentPeer::updateKeyModifiers();
  208207. int mouseMods = 0;
  208208. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208209. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208210. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208211. Win32ComponentPeer::currentModifiers
  208212. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208213. return Win32ComponentPeer::currentModifiers;
  208214. }
  208215. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208216. {
  208217. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208218. if (wp != 0)
  208219. wp->setTaskBarIcon (newImage);
  208220. }
  208221. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208222. {
  208223. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208224. if (wp != 0)
  208225. wp->setTaskBarIconToolTip (tooltip);
  208226. }
  208227. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208228. {
  208229. DWORD val = GetWindowLong (h, styleType);
  208230. if (bitIsSet)
  208231. val |= feature;
  208232. else
  208233. val &= ~feature;
  208234. SetWindowLongPtr (h, styleType, val);
  208235. SetWindowPos (h, 0, 0, 0, 0, 0,
  208236. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208237. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208238. }
  208239. bool Process::isForegroundProcess()
  208240. {
  208241. HWND fg = GetForegroundWindow();
  208242. if (fg == 0)
  208243. return true;
  208244. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208245. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208246. // have to see if any of our windows are children of the foreground window
  208247. fg = GetAncestor (fg, GA_ROOT);
  208248. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208249. {
  208250. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208251. if (wp != 0 && wp->isInside (fg))
  208252. return true;
  208253. }
  208254. return false;
  208255. }
  208256. bool AlertWindow::showNativeDialogBox (const String& title,
  208257. const String& bodyText,
  208258. bool isOkCancel)
  208259. {
  208260. return MessageBox (0, bodyText, title,
  208261. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208262. : MB_OK)) == IDOK;
  208263. }
  208264. void Desktop::createMouseInputSources()
  208265. {
  208266. mouseSources.add (new MouseInputSource (0, true));
  208267. }
  208268. const Point<int> Desktop::getMousePosition()
  208269. {
  208270. POINT mousePos;
  208271. GetCursorPos (&mousePos);
  208272. return Point<int> (mousePos.x, mousePos.y);
  208273. }
  208274. void Desktop::setMousePosition (const Point<int>& newPosition)
  208275. {
  208276. SetCursorPos (newPosition.getX(), newPosition.getY());
  208277. }
  208278. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208279. {
  208280. return createSoftwareImage (format, width, height, clearImage);
  208281. }
  208282. class ScreenSaverDefeater : public Timer,
  208283. public DeletedAtShutdown
  208284. {
  208285. public:
  208286. ScreenSaverDefeater()
  208287. {
  208288. startTimer (10000);
  208289. timerCallback();
  208290. }
  208291. ~ScreenSaverDefeater() {}
  208292. void timerCallback()
  208293. {
  208294. if (Process::isForegroundProcess())
  208295. {
  208296. // simulate a shift key getting pressed..
  208297. INPUT input[2];
  208298. input[0].type = INPUT_KEYBOARD;
  208299. input[0].ki.wVk = VK_SHIFT;
  208300. input[0].ki.dwFlags = 0;
  208301. input[0].ki.dwExtraInfo = 0;
  208302. input[1].type = INPUT_KEYBOARD;
  208303. input[1].ki.wVk = VK_SHIFT;
  208304. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208305. input[1].ki.dwExtraInfo = 0;
  208306. SendInput (2, input, sizeof (INPUT));
  208307. }
  208308. }
  208309. };
  208310. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208311. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208312. {
  208313. if (isEnabled)
  208314. deleteAndZero (screenSaverDefeater);
  208315. else if (screenSaverDefeater == 0)
  208316. screenSaverDefeater = new ScreenSaverDefeater();
  208317. }
  208318. bool Desktop::isScreenSaverEnabled()
  208319. {
  208320. return screenSaverDefeater == 0;
  208321. }
  208322. /* (The code below is the "correct" way to disable the screen saver, but it
  208323. completely fails on winXP when the saver is password-protected...)
  208324. static bool juce_screenSaverEnabled = true;
  208325. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208326. {
  208327. juce_screenSaverEnabled = isEnabled;
  208328. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208329. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208330. }
  208331. bool Desktop::isScreenSaverEnabled() throw()
  208332. {
  208333. return juce_screenSaverEnabled;
  208334. }
  208335. */
  208336. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208337. {
  208338. if (enableOrDisable)
  208339. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208340. }
  208341. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208342. {
  208343. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208344. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208345. return TRUE;
  208346. }
  208347. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208348. {
  208349. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208350. // make sure the first in the list is the main monitor
  208351. for (int i = 1; i < monitorCoords.size(); ++i)
  208352. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208353. monitorCoords.swap (i, 0);
  208354. if (monitorCoords.size() == 0)
  208355. {
  208356. RECT r;
  208357. GetWindowRect (GetDesktopWindow(), &r);
  208358. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208359. }
  208360. if (clipToWorkArea)
  208361. {
  208362. // clip the main monitor to the active non-taskbar area
  208363. RECT r;
  208364. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208365. Rectangle<int>& screen = monitorCoords.getReference (0);
  208366. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208367. jmax (screen.getY(), (int) r.top));
  208368. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208369. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208370. }
  208371. }
  208372. const Image juce_createIconForFile (const File& file)
  208373. {
  208374. Image image;
  208375. WCHAR filename [1024];
  208376. file.getFullPathName().copyToUnicode (filename, 1023);
  208377. WORD iconNum = 0;
  208378. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208379. filename, &iconNum);
  208380. if (icon != 0)
  208381. {
  208382. image = IconConverters::createImageFromHICON (icon);
  208383. DestroyIcon (icon);
  208384. }
  208385. return image;
  208386. }
  208387. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208388. {
  208389. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208390. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208391. Image im (image);
  208392. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208393. {
  208394. im = im.rescaled (maxW, maxH);
  208395. hotspotX = (hotspotX * maxW) / image.getWidth();
  208396. hotspotY = (hotspotY * maxH) / image.getHeight();
  208397. }
  208398. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208399. }
  208400. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208401. {
  208402. if (cursorHandle != 0 && ! isStandard)
  208403. DestroyCursor ((HCURSOR) cursorHandle);
  208404. }
  208405. enum
  208406. {
  208407. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208408. };
  208409. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208410. {
  208411. LPCTSTR cursorName = IDC_ARROW;
  208412. switch (type)
  208413. {
  208414. case NormalCursor: break;
  208415. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208416. case WaitCursor: cursorName = IDC_WAIT; break;
  208417. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208418. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208419. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208420. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208421. case LeftRightResizeCursor:
  208422. case LeftEdgeResizeCursor:
  208423. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208424. case UpDownResizeCursor:
  208425. case TopEdgeResizeCursor:
  208426. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208427. case TopLeftCornerResizeCursor:
  208428. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208429. case TopRightCornerResizeCursor:
  208430. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208431. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208432. case DraggingHandCursor:
  208433. {
  208434. static void* dragHandCursor = 0;
  208435. if (dragHandCursor == 0)
  208436. {
  208437. static const unsigned char dragHandData[] =
  208438. { 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,
  208439. 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,
  208440. 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 };
  208441. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208442. }
  208443. return dragHandCursor;
  208444. }
  208445. default:
  208446. jassertfalse; break;
  208447. }
  208448. HCURSOR cursorH = LoadCursor (0, cursorName);
  208449. if (cursorH == 0)
  208450. cursorH = LoadCursor (0, IDC_ARROW);
  208451. return cursorH;
  208452. }
  208453. void MouseCursor::showInWindow (ComponentPeer*) const
  208454. {
  208455. HCURSOR c = (HCURSOR) getHandle();
  208456. if (c == 0)
  208457. c = LoadCursor (0, IDC_ARROW);
  208458. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208459. c = 0;
  208460. SetCursor (c);
  208461. }
  208462. void MouseCursor::showInAllWindows() const
  208463. {
  208464. showInWindow (0);
  208465. }
  208466. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208467. {
  208468. public:
  208469. JuceDropSource() {}
  208470. ~JuceDropSource() {}
  208471. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208472. {
  208473. if (escapePressed)
  208474. return DRAGDROP_S_CANCEL;
  208475. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208476. return DRAGDROP_S_DROP;
  208477. return S_OK;
  208478. }
  208479. HRESULT __stdcall GiveFeedback (DWORD)
  208480. {
  208481. return DRAGDROP_S_USEDEFAULTCURSORS;
  208482. }
  208483. };
  208484. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208485. {
  208486. public:
  208487. JuceEnumFormatEtc (const FORMATETC* const format_)
  208488. : format (format_),
  208489. index (0)
  208490. {
  208491. }
  208492. ~JuceEnumFormatEtc() {}
  208493. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208494. {
  208495. if (result == 0)
  208496. return E_POINTER;
  208497. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208498. newOne->index = index;
  208499. *result = newOne;
  208500. return S_OK;
  208501. }
  208502. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208503. {
  208504. if (pceltFetched != 0)
  208505. *pceltFetched = 0;
  208506. else if (celt != 1)
  208507. return S_FALSE;
  208508. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208509. {
  208510. copyFormatEtc (lpFormatEtc [0], *format);
  208511. ++index;
  208512. if (pceltFetched != 0)
  208513. *pceltFetched = 1;
  208514. return S_OK;
  208515. }
  208516. return S_FALSE;
  208517. }
  208518. HRESULT __stdcall Skip (ULONG celt)
  208519. {
  208520. if (index + (int) celt >= 1)
  208521. return S_FALSE;
  208522. index += celt;
  208523. return S_OK;
  208524. }
  208525. HRESULT __stdcall Reset()
  208526. {
  208527. index = 0;
  208528. return S_OK;
  208529. }
  208530. private:
  208531. const FORMATETC* const format;
  208532. int index;
  208533. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208534. {
  208535. dest = source;
  208536. if (source.ptd != 0)
  208537. {
  208538. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208539. *(dest.ptd) = *(source.ptd);
  208540. }
  208541. }
  208542. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208543. };
  208544. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208545. {
  208546. public:
  208547. JuceDataObject (JuceDropSource* const dropSource_,
  208548. const FORMATETC* const format_,
  208549. const STGMEDIUM* const medium_)
  208550. : dropSource (dropSource_),
  208551. format (format_),
  208552. medium (medium_)
  208553. {
  208554. }
  208555. ~JuceDataObject()
  208556. {
  208557. jassert (refCount == 0);
  208558. }
  208559. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208560. {
  208561. if ((pFormatEtc->tymed & format->tymed) != 0
  208562. && pFormatEtc->cfFormat == format->cfFormat
  208563. && pFormatEtc->dwAspect == format->dwAspect)
  208564. {
  208565. pMedium->tymed = format->tymed;
  208566. pMedium->pUnkForRelease = 0;
  208567. if (format->tymed == TYMED_HGLOBAL)
  208568. {
  208569. const SIZE_T len = GlobalSize (medium->hGlobal);
  208570. void* const src = GlobalLock (medium->hGlobal);
  208571. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208572. memcpy (dst, src, len);
  208573. GlobalUnlock (medium->hGlobal);
  208574. pMedium->hGlobal = dst;
  208575. return S_OK;
  208576. }
  208577. }
  208578. return DV_E_FORMATETC;
  208579. }
  208580. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208581. {
  208582. if (f == 0)
  208583. return E_INVALIDARG;
  208584. if (f->tymed == format->tymed
  208585. && f->cfFormat == format->cfFormat
  208586. && f->dwAspect == format->dwAspect)
  208587. return S_OK;
  208588. return DV_E_FORMATETC;
  208589. }
  208590. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208591. {
  208592. pFormatEtcOut->ptd = 0;
  208593. return E_NOTIMPL;
  208594. }
  208595. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208596. {
  208597. if (result == 0)
  208598. return E_POINTER;
  208599. if (direction == DATADIR_GET)
  208600. {
  208601. *result = new JuceEnumFormatEtc (format);
  208602. return S_OK;
  208603. }
  208604. *result = 0;
  208605. return E_NOTIMPL;
  208606. }
  208607. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208608. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208609. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208610. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208611. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208612. private:
  208613. JuceDropSource* const dropSource;
  208614. const FORMATETC* const format;
  208615. const STGMEDIUM* const medium;
  208616. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  208617. };
  208618. static HDROP createHDrop (const StringArray& fileNames)
  208619. {
  208620. int totalChars = 0;
  208621. for (int i = fileNames.size(); --i >= 0;)
  208622. totalChars += fileNames[i].length() + 1;
  208623. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208624. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208625. if (hDrop != 0)
  208626. {
  208627. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208628. pDropFiles->pFiles = sizeof (DROPFILES);
  208629. pDropFiles->fWide = true;
  208630. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208631. for (int i = 0; i < fileNames.size(); ++i)
  208632. {
  208633. fileNames[i].copyToUnicode (fname, 2048);
  208634. fname += fileNames[i].length() + 1;
  208635. }
  208636. *fname = 0;
  208637. GlobalUnlock (hDrop);
  208638. }
  208639. return hDrop;
  208640. }
  208641. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208642. {
  208643. JuceDropSource* const source = new JuceDropSource();
  208644. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208645. DWORD effect;
  208646. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208647. data->Release();
  208648. source->Release();
  208649. return res == DRAGDROP_S_DROP;
  208650. }
  208651. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208652. {
  208653. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208654. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208655. medium.hGlobal = createHDrop (files);
  208656. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208657. : DROPEFFECT_COPY);
  208658. }
  208659. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208660. {
  208661. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208662. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208663. const int numChars = text.length();
  208664. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208665. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208666. text.copyToUnicode (data, numChars + 1);
  208667. format.cfFormat = CF_UNICODETEXT;
  208668. GlobalUnlock (medium.hGlobal);
  208669. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208670. }
  208671. #endif
  208672. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208673. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208674. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208675. // compiled on its own).
  208676. #if JUCE_INCLUDED_FILE
  208677. namespace FileChooserHelpers
  208678. {
  208679. static bool areThereAnyAlwaysOnTopWindows()
  208680. {
  208681. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208682. {
  208683. Component* c = Desktop::getInstance().getComponent (i);
  208684. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208685. return true;
  208686. }
  208687. return false;
  208688. }
  208689. struct FileChooserCallbackInfo
  208690. {
  208691. String initialPath;
  208692. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208693. ScopedPointer<Component> customComponent;
  208694. };
  208695. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208696. {
  208697. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208698. if (msg == BFFM_INITIALIZED)
  208699. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  208700. else if (msg == BFFM_VALIDATEFAILEDW)
  208701. info->returnedString = (LPCWSTR) lParam;
  208702. else if (msg == BFFM_VALIDATEFAILEDA)
  208703. info->returnedString = (const char*) lParam;
  208704. return 0;
  208705. }
  208706. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208707. {
  208708. if (uiMsg == WM_INITDIALOG)
  208709. {
  208710. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208711. HWND dialogH = GetParent (hdlg);
  208712. jassert (dialogH != 0);
  208713. if (dialogH == 0)
  208714. dialogH = hdlg;
  208715. RECT r, cr;
  208716. GetWindowRect (dialogH, &r);
  208717. GetClientRect (dialogH, &cr);
  208718. SetWindowPos (dialogH, 0,
  208719. r.left, r.top,
  208720. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208721. jmax (150, (int) (r.bottom - r.top)),
  208722. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208723. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208724. customComp->addToDesktop (0, dialogH);
  208725. }
  208726. else if (uiMsg == WM_NOTIFY)
  208727. {
  208728. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208729. if (ofn->hdr.code == CDN_SELCHANGE)
  208730. {
  208731. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208732. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208733. if (comp != 0)
  208734. {
  208735. WCHAR path [MAX_PATH * 2];
  208736. zerostruct (path);
  208737. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208738. comp->selectedFileChanged (File (path));
  208739. }
  208740. }
  208741. }
  208742. return 0;
  208743. }
  208744. class CustomComponentHolder : public Component
  208745. {
  208746. public:
  208747. CustomComponentHolder (Component* customComp)
  208748. {
  208749. setVisible (true);
  208750. setOpaque (true);
  208751. addAndMakeVisible (customComp);
  208752. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208753. }
  208754. void paint (Graphics& g)
  208755. {
  208756. g.fillAll (Colours::lightgrey);
  208757. }
  208758. void resized()
  208759. {
  208760. if (getNumChildComponents() > 0)
  208761. getChildComponent(0)->setBounds (getLocalBounds());
  208762. }
  208763. private:
  208764. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  208765. };
  208766. }
  208767. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208768. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208769. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208770. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208771. {
  208772. using namespace FileChooserHelpers;
  208773. HeapBlock<WCHAR> files;
  208774. const int charsAvailableForResult = 32768;
  208775. files.calloc (charsAvailableForResult + 1);
  208776. int filenameOffset = 0;
  208777. FileChooserCallbackInfo info;
  208778. // use a modal window as the parent for this dialog box
  208779. // to block input from other app windows
  208780. Component parentWindow (String::empty);
  208781. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208782. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208783. mainMon.getY() + mainMon.getHeight() / 4,
  208784. 0, 0);
  208785. parentWindow.setOpaque (true);
  208786. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208787. parentWindow.addToDesktop (0);
  208788. if (extraInfoComponent == 0)
  208789. parentWindow.enterModalState();
  208790. if (currentFileOrDirectory.isDirectory())
  208791. {
  208792. info.initialPath = currentFileOrDirectory.getFullPathName();
  208793. }
  208794. else
  208795. {
  208796. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  208797. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208798. }
  208799. if (selectsDirectory)
  208800. {
  208801. BROWSEINFO bi;
  208802. zerostruct (bi);
  208803. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208804. bi.pszDisplayName = files;
  208805. bi.lpszTitle = title;
  208806. bi.lParam = (LPARAM) &info;
  208807. bi.lpfn = browseCallbackProc;
  208808. #ifdef BIF_USENEWUI
  208809. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208810. #else
  208811. bi.ulFlags = 0x50;
  208812. #endif
  208813. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208814. if (! SHGetPathFromIDListW (list, files))
  208815. {
  208816. files[0] = 0;
  208817. info.returnedString = String::empty;
  208818. }
  208819. LPMALLOC al;
  208820. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208821. al->Free (list);
  208822. if (info.returnedString.isNotEmpty())
  208823. {
  208824. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208825. return;
  208826. }
  208827. }
  208828. else
  208829. {
  208830. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208831. if (warnAboutOverwritingExistingFiles)
  208832. flags |= OFN_OVERWRITEPROMPT;
  208833. if (selectMultipleFiles)
  208834. flags |= OFN_ALLOWMULTISELECT;
  208835. if (extraInfoComponent != 0)
  208836. {
  208837. flags |= OFN_ENABLEHOOK;
  208838. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208839. info.customComponent->enterModalState();
  208840. }
  208841. WCHAR filters [1024];
  208842. zerostruct (filters);
  208843. filter.copyToUnicode (filters, 1024);
  208844. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  208845. OPENFILENAMEW of;
  208846. zerostruct (of);
  208847. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208848. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208849. #else
  208850. of.lStructSize = sizeof (of);
  208851. #endif
  208852. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208853. of.lpstrFilter = filters;
  208854. of.nFilterIndex = 1;
  208855. of.lpstrFile = files;
  208856. of.nMaxFile = charsAvailableForResult;
  208857. of.lpstrInitialDir = info.initialPath;
  208858. of.lpstrTitle = title;
  208859. of.Flags = flags;
  208860. of.lCustData = (LPARAM) &info;
  208861. if (extraInfoComponent != 0)
  208862. of.lpfnHook = &openCallback;
  208863. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208864. : GetOpenFileName (&of)))
  208865. return;
  208866. filenameOffset = of.nFileOffset;
  208867. }
  208868. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  208869. {
  208870. const WCHAR* filename = files + filenameOffset;
  208871. while (*filename != 0)
  208872. {
  208873. results.add (File (String (files) + "\\" + String (filename)));
  208874. filename += CharacterFunctions::length (filename) + 1;
  208875. }
  208876. }
  208877. else if (files[0] != 0)
  208878. {
  208879. results.add (File (String (files)));
  208880. }
  208881. }
  208882. #endif
  208883. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208884. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  208885. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208886. // compiled on its own).
  208887. #if JUCE_INCLUDED_FILE
  208888. void SystemClipboard::copyTextToClipboard (const String& text)
  208889. {
  208890. if (OpenClipboard (0) != 0)
  208891. {
  208892. if (EmptyClipboard() != 0)
  208893. {
  208894. const int len = text.length();
  208895. if (len > 0)
  208896. {
  208897. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  208898. (len + 1) * sizeof (wchar_t));
  208899. if (bufH != 0)
  208900. {
  208901. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208902. text.copyToUnicode (data, len);
  208903. GlobalUnlock (bufH);
  208904. SetClipboardData (CF_UNICODETEXT, bufH);
  208905. }
  208906. }
  208907. }
  208908. CloseClipboard();
  208909. }
  208910. }
  208911. const String SystemClipboard::getTextFromClipboard()
  208912. {
  208913. String result;
  208914. if (OpenClipboard (0) != 0)
  208915. {
  208916. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  208917. if (bufH != 0)
  208918. {
  208919. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  208920. if (data != 0)
  208921. {
  208922. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  208923. GlobalUnlock (bufH);
  208924. }
  208925. }
  208926. CloseClipboard();
  208927. }
  208928. return result;
  208929. }
  208930. #endif
  208931. /*** End of inlined file: juce_win32_Misc.cpp ***/
  208932. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  208933. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208934. // compiled on its own).
  208935. #if JUCE_INCLUDED_FILE
  208936. namespace ActiveXHelpers
  208937. {
  208938. class JuceIStorage : public ComBaseClassHelper <IStorage>
  208939. {
  208940. public:
  208941. JuceIStorage() {}
  208942. ~JuceIStorage() {}
  208943. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208944. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208945. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208946. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208947. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  208948. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  208949. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  208950. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  208951. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  208952. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  208953. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  208954. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  208955. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  208956. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  208957. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  208958. };
  208959. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  208960. {
  208961. HWND window;
  208962. public:
  208963. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  208964. ~JuceOleInPlaceFrame() {}
  208965. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208966. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208967. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  208968. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208969. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208970. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  208971. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  208972. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  208973. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  208974. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  208975. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  208976. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  208977. };
  208978. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  208979. {
  208980. HWND window;
  208981. JuceOleInPlaceFrame* frame;
  208982. public:
  208983. JuceIOleInPlaceSite (HWND window_)
  208984. : window (window_),
  208985. frame (new JuceOleInPlaceFrame (window))
  208986. {}
  208987. ~JuceIOleInPlaceSite()
  208988. {
  208989. frame->Release();
  208990. }
  208991. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208992. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208993. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  208994. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  208995. HRESULT __stdcall OnUIActivate() { return S_OK; }
  208996. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  208997. {
  208998. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  208999. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209000. */
  209001. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209002. if (lplpDoc != 0) *lplpDoc = 0;
  209003. lpFrameInfo->fMDIApp = FALSE;
  209004. lpFrameInfo->hwndFrame = window;
  209005. lpFrameInfo->haccel = 0;
  209006. lpFrameInfo->cAccelEntries = 0;
  209007. return S_OK;
  209008. }
  209009. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209010. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209011. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209012. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209013. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209014. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209015. };
  209016. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209017. {
  209018. JuceIOleInPlaceSite* inplaceSite;
  209019. public:
  209020. JuceIOleClientSite (HWND window)
  209021. : inplaceSite (new JuceIOleInPlaceSite (window))
  209022. {}
  209023. ~JuceIOleClientSite()
  209024. {
  209025. inplaceSite->Release();
  209026. }
  209027. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209028. {
  209029. if (type == IID_IOleInPlaceSite)
  209030. {
  209031. inplaceSite->AddRef();
  209032. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209033. return S_OK;
  209034. }
  209035. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209036. }
  209037. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209038. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209039. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209040. HRESULT __stdcall ShowObject() { return S_OK; }
  209041. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209042. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209043. };
  209044. static Array<ActiveXControlComponent*> activeXComps;
  209045. static HWND getHWND (const ActiveXControlComponent* const component)
  209046. {
  209047. HWND hwnd = 0;
  209048. const IID iid = IID_IOleWindow;
  209049. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209050. if (window != 0)
  209051. {
  209052. window->GetWindow (&hwnd);
  209053. window->Release();
  209054. }
  209055. return hwnd;
  209056. }
  209057. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209058. {
  209059. RECT activeXRect, peerRect;
  209060. GetWindowRect (hwnd, &activeXRect);
  209061. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209062. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209063. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209064. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209065. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209066. switch (message)
  209067. {
  209068. case WM_MOUSEMOVE:
  209069. case WM_LBUTTONDOWN:
  209070. case WM_MBUTTONDOWN:
  209071. case WM_RBUTTONDOWN:
  209072. case WM_LBUTTONUP:
  209073. case WM_MBUTTONUP:
  209074. case WM_RBUTTONUP:
  209075. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209076. break;
  209077. default:
  209078. break;
  209079. }
  209080. }
  209081. }
  209082. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209083. {
  209084. ActiveXControlComponent& owner;
  209085. bool wasShowing;
  209086. public:
  209087. HWND controlHWND;
  209088. IStorage* storage;
  209089. IOleClientSite* clientSite;
  209090. IOleObject* control;
  209091. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209092. : ComponentMovementWatcher (&owner_),
  209093. owner (owner_),
  209094. wasShowing (owner_.isShowing()),
  209095. controlHWND (0),
  209096. storage (new ActiveXHelpers::JuceIStorage()),
  209097. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209098. control (0)
  209099. {
  209100. }
  209101. ~Pimpl()
  209102. {
  209103. if (control != 0)
  209104. {
  209105. control->Close (OLECLOSE_NOSAVE);
  209106. control->Release();
  209107. }
  209108. clientSite->Release();
  209109. storage->Release();
  209110. }
  209111. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209112. {
  209113. Component* const topComp = owner.getTopLevelComponent();
  209114. if (topComp->getPeer() != 0)
  209115. {
  209116. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  209117. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209118. }
  209119. }
  209120. void componentPeerChanged()
  209121. {
  209122. const bool isShowingNow = owner.isShowing();
  209123. if (wasShowing != isShowingNow)
  209124. {
  209125. wasShowing = isShowingNow;
  209126. owner.setControlVisible (isShowingNow);
  209127. }
  209128. componentMovedOrResized (true, true);
  209129. }
  209130. void componentVisibilityChanged (Component&)
  209131. {
  209132. componentPeerChanged();
  209133. }
  209134. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209135. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209136. {
  209137. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209138. {
  209139. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209140. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209141. {
  209142. switch (message)
  209143. {
  209144. case WM_MOUSEMOVE:
  209145. case WM_LBUTTONDOWN:
  209146. case WM_MBUTTONDOWN:
  209147. case WM_RBUTTONDOWN:
  209148. case WM_LBUTTONUP:
  209149. case WM_MBUTTONUP:
  209150. case WM_RBUTTONUP:
  209151. case WM_LBUTTONDBLCLK:
  209152. case WM_MBUTTONDBLCLK:
  209153. case WM_RBUTTONDBLCLK:
  209154. if (ax->isShowing())
  209155. {
  209156. ComponentPeer* const peer = ax->getPeer();
  209157. if (peer != 0)
  209158. {
  209159. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209160. if (! ax->areMouseEventsAllowed())
  209161. return 0;
  209162. }
  209163. }
  209164. break;
  209165. default:
  209166. break;
  209167. }
  209168. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209169. }
  209170. }
  209171. return DefWindowProc (hwnd, message, wParam, lParam);
  209172. }
  209173. };
  209174. ActiveXControlComponent::ActiveXControlComponent()
  209175. : originalWndProc (0),
  209176. mouseEventsAllowed (true)
  209177. {
  209178. ActiveXHelpers::activeXComps.add (this);
  209179. }
  209180. ActiveXControlComponent::~ActiveXControlComponent()
  209181. {
  209182. deleteControl();
  209183. ActiveXHelpers::activeXComps.removeValue (this);
  209184. }
  209185. void ActiveXControlComponent::paint (Graphics& g)
  209186. {
  209187. if (control == 0)
  209188. g.fillAll (Colours::lightgrey);
  209189. }
  209190. bool ActiveXControlComponent::createControl (const void* controlIID)
  209191. {
  209192. deleteControl();
  209193. ComponentPeer* const peer = getPeer();
  209194. // the component must have already been added to a real window when you call this!
  209195. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209196. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209197. {
  209198. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209199. HWND hwnd = (HWND) peer->getNativeHandle();
  209200. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209201. HRESULT hr;
  209202. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209203. newControl->clientSite, newControl->storage,
  209204. (void**) &(newControl->control))) == S_OK)
  209205. {
  209206. newControl->control->SetHostNames (L"Juce", 0);
  209207. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209208. {
  209209. RECT rect;
  209210. rect.left = pos.getX();
  209211. rect.top = pos.getY();
  209212. rect.right = pos.getX() + getWidth();
  209213. rect.bottom = pos.getY() + getHeight();
  209214. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209215. {
  209216. control = newControl;
  209217. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209218. control->controlHWND = ActiveXHelpers::getHWND (this);
  209219. if (control->controlHWND != 0)
  209220. {
  209221. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209222. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209223. }
  209224. return true;
  209225. }
  209226. }
  209227. }
  209228. }
  209229. return false;
  209230. }
  209231. void ActiveXControlComponent::deleteControl()
  209232. {
  209233. control = 0;
  209234. originalWndProc = 0;
  209235. }
  209236. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209237. {
  209238. void* result = 0;
  209239. if (control != 0 && control->control != 0
  209240. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209241. return result;
  209242. return 0;
  209243. }
  209244. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209245. {
  209246. if (control->controlHWND != 0)
  209247. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209248. }
  209249. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209250. {
  209251. if (control->controlHWND != 0)
  209252. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209253. }
  209254. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209255. {
  209256. mouseEventsAllowed = eventsCanReachControl;
  209257. }
  209258. #endif
  209259. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209260. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209261. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209262. // compiled on its own).
  209263. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209264. using namespace QTOLibrary;
  209265. using namespace QTOControlLib;
  209266. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209267. static bool isQTAvailable = false;
  209268. class QuickTimeMovieComponent::Pimpl
  209269. {
  209270. public:
  209271. Pimpl() : dataHandle (0)
  209272. {
  209273. }
  209274. ~Pimpl()
  209275. {
  209276. clearHandle();
  209277. }
  209278. void clearHandle()
  209279. {
  209280. if (dataHandle != 0)
  209281. {
  209282. DisposeHandle (dataHandle);
  209283. dataHandle = 0;
  209284. }
  209285. }
  209286. IQTControlPtr qtControl;
  209287. IQTMoviePtr qtMovie;
  209288. Handle dataHandle;
  209289. };
  209290. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209291. : movieLoaded (false),
  209292. controllerVisible (true)
  209293. {
  209294. pimpl = new Pimpl();
  209295. setMouseEventsAllowed (false);
  209296. }
  209297. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209298. {
  209299. closeMovie();
  209300. pimpl->qtControl = 0;
  209301. deleteControl();
  209302. pimpl = 0;
  209303. }
  209304. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209305. {
  209306. if (! isQTAvailable)
  209307. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209308. return isQTAvailable;
  209309. }
  209310. void QuickTimeMovieComponent::createControlIfNeeded()
  209311. {
  209312. if (isShowing() && ! isControlCreated())
  209313. {
  209314. const IID qtIID = __uuidof (QTControl);
  209315. if (createControl (&qtIID))
  209316. {
  209317. const IID qtInterfaceIID = __uuidof (IQTControl);
  209318. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209319. if (pimpl->qtControl != 0)
  209320. {
  209321. pimpl->qtControl->Release(); // it has one ref too many at this point
  209322. pimpl->qtControl->QuickTimeInitialize();
  209323. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209324. if (movieFile != File::nonexistent)
  209325. loadMovie (movieFile, controllerVisible);
  209326. }
  209327. }
  209328. }
  209329. }
  209330. bool QuickTimeMovieComponent::isControlCreated() const
  209331. {
  209332. return isControlOpen();
  209333. }
  209334. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209335. const bool isControllerVisible)
  209336. {
  209337. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209338. movieFile = File::nonexistent;
  209339. movieLoaded = false;
  209340. pimpl->qtMovie = 0;
  209341. controllerVisible = isControllerVisible;
  209342. createControlIfNeeded();
  209343. if (isControlCreated())
  209344. {
  209345. if (pimpl->qtControl != 0)
  209346. {
  209347. pimpl->qtControl->Put_MovieHandle (0);
  209348. pimpl->clearHandle();
  209349. Movie movie;
  209350. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209351. {
  209352. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209353. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209354. if (pimpl->qtMovie != 0)
  209355. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209356. : qtMovieControllerTypeNone);
  209357. }
  209358. if (movie == 0)
  209359. pimpl->clearHandle();
  209360. }
  209361. movieLoaded = (pimpl->qtMovie != 0);
  209362. }
  209363. else
  209364. {
  209365. // You're trying to open a movie when the control hasn't yet been created, probably because
  209366. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209367. jassertfalse;
  209368. }
  209369. return movieLoaded;
  209370. }
  209371. void QuickTimeMovieComponent::closeMovie()
  209372. {
  209373. stop();
  209374. movieFile = File::nonexistent;
  209375. movieLoaded = false;
  209376. pimpl->qtMovie = 0;
  209377. if (pimpl->qtControl != 0)
  209378. pimpl->qtControl->Put_MovieHandle (0);
  209379. pimpl->clearHandle();
  209380. }
  209381. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209382. {
  209383. return movieFile;
  209384. }
  209385. bool QuickTimeMovieComponent::isMovieOpen() const
  209386. {
  209387. return movieLoaded;
  209388. }
  209389. double QuickTimeMovieComponent::getMovieDuration() const
  209390. {
  209391. if (pimpl->qtMovie != 0)
  209392. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209393. return 0.0;
  209394. }
  209395. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209396. {
  209397. if (pimpl->qtMovie != 0)
  209398. {
  209399. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209400. width = r.right - r.left;
  209401. height = r.bottom - r.top;
  209402. }
  209403. else
  209404. {
  209405. width = height = 0;
  209406. }
  209407. }
  209408. void QuickTimeMovieComponent::play()
  209409. {
  209410. if (pimpl->qtMovie != 0)
  209411. pimpl->qtMovie->Play();
  209412. }
  209413. void QuickTimeMovieComponent::stop()
  209414. {
  209415. if (pimpl->qtMovie != 0)
  209416. pimpl->qtMovie->Stop();
  209417. }
  209418. bool QuickTimeMovieComponent::isPlaying() const
  209419. {
  209420. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209421. }
  209422. void QuickTimeMovieComponent::setPosition (const double seconds)
  209423. {
  209424. if (pimpl->qtMovie != 0)
  209425. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209426. }
  209427. double QuickTimeMovieComponent::getPosition() const
  209428. {
  209429. if (pimpl->qtMovie != 0)
  209430. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209431. return 0.0;
  209432. }
  209433. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209434. {
  209435. if (pimpl->qtMovie != 0)
  209436. pimpl->qtMovie->PutRate (newSpeed);
  209437. }
  209438. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209439. {
  209440. if (pimpl->qtMovie != 0)
  209441. {
  209442. pimpl->qtMovie->PutAudioVolume (newVolume);
  209443. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209444. }
  209445. }
  209446. float QuickTimeMovieComponent::getMovieVolume() const
  209447. {
  209448. if (pimpl->qtMovie != 0)
  209449. return pimpl->qtMovie->GetAudioVolume();
  209450. return 0.0f;
  209451. }
  209452. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209453. {
  209454. if (pimpl->qtMovie != 0)
  209455. pimpl->qtMovie->PutLoop (shouldLoop);
  209456. }
  209457. bool QuickTimeMovieComponent::isLooping() const
  209458. {
  209459. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209460. }
  209461. bool QuickTimeMovieComponent::isControllerVisible() const
  209462. {
  209463. return controllerVisible;
  209464. }
  209465. void QuickTimeMovieComponent::parentHierarchyChanged()
  209466. {
  209467. createControlIfNeeded();
  209468. QTCompBaseClass::parentHierarchyChanged();
  209469. }
  209470. void QuickTimeMovieComponent::visibilityChanged()
  209471. {
  209472. createControlIfNeeded();
  209473. QTCompBaseClass::visibilityChanged();
  209474. }
  209475. void QuickTimeMovieComponent::paint (Graphics& g)
  209476. {
  209477. if (! isControlCreated())
  209478. g.fillAll (Colours::black);
  209479. }
  209480. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209481. {
  209482. Handle dataRef = 0;
  209483. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209484. if (err == noErr)
  209485. {
  209486. Str255 suffix;
  209487. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209488. StringPtr name = suffix;
  209489. err = PtrAndHand (name, dataRef, name[0] + 1);
  209490. if (err == noErr)
  209491. {
  209492. long atoms[3];
  209493. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209494. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209495. atoms[2] = EndianU32_NtoB (MovieFileType);
  209496. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209497. if (err == noErr)
  209498. return dataRef;
  209499. }
  209500. DisposeHandle (dataRef);
  209501. }
  209502. return 0;
  209503. }
  209504. static CFStringRef juceStringToCFString (const String& s)
  209505. {
  209506. const int len = s.length();
  209507. const juce_wchar* const t = s;
  209508. HeapBlock <UniChar> temp (len + 2);
  209509. for (int i = 0; i <= len; ++i)
  209510. temp[i] = t[i];
  209511. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209512. }
  209513. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209514. {
  209515. Boolean trueBool = true;
  209516. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209517. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209518. props[prop].propValueSize = sizeof (trueBool);
  209519. props[prop].propValueAddress = &trueBool;
  209520. ++prop;
  209521. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209522. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209523. props[prop].propValueSize = sizeof (trueBool);
  209524. props[prop].propValueAddress = &trueBool;
  209525. ++prop;
  209526. Boolean isActive = true;
  209527. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209528. props[prop].propID = kQTNewMoviePropertyID_Active;
  209529. props[prop].propValueSize = sizeof (isActive);
  209530. props[prop].propValueAddress = &isActive;
  209531. ++prop;
  209532. MacSetPort (0);
  209533. jassert (prop <= 5);
  209534. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209535. return err == noErr;
  209536. }
  209537. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209538. {
  209539. if (input == 0)
  209540. return false;
  209541. dataHandle = 0;
  209542. bool ok = false;
  209543. QTNewMoviePropertyElement props[5];
  209544. zeromem (props, sizeof (props));
  209545. int prop = 0;
  209546. DataReferenceRecord dr;
  209547. props[prop].propClass = kQTPropertyClass_DataLocation;
  209548. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209549. props[prop].propValueSize = sizeof (dr);
  209550. props[prop].propValueAddress = &dr;
  209551. ++prop;
  209552. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209553. if (fin != 0)
  209554. {
  209555. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209556. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209557. &dr.dataRef, &dr.dataRefType);
  209558. ok = openMovie (props, prop, movie);
  209559. DisposeHandle (dr.dataRef);
  209560. CFRelease (filePath);
  209561. }
  209562. else
  209563. {
  209564. // sanity-check because this currently needs to load the whole stream into memory..
  209565. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209566. dataHandle = NewHandle ((Size) input->getTotalLength());
  209567. HLock (dataHandle);
  209568. // read the entire stream into memory - this is a pain, but can't get it to work
  209569. // properly using a custom callback to supply the data.
  209570. input->read (*dataHandle, (int) input->getTotalLength());
  209571. HUnlock (dataHandle);
  209572. // different types to get QT to try. (We should really be a bit smarter here by
  209573. // working out in advance which one the stream contains, rather than just trying
  209574. // each one)
  209575. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209576. "\04.avi", "\04.m4a" };
  209577. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209578. {
  209579. /* // this fails for some bizarre reason - it can be bodged to work with
  209580. // movies, but can't seem to do it for other file types..
  209581. QTNewMovieUserProcRecord procInfo;
  209582. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209583. procInfo.getMovieUserProcRefcon = this;
  209584. procInfo.defaultDataRef.dataRef = dataRef;
  209585. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209586. props[prop].propClass = kQTPropertyClass_DataLocation;
  209587. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209588. props[prop].propValueSize = sizeof (procInfo);
  209589. props[prop].propValueAddress = (void*) &procInfo;
  209590. ++prop; */
  209591. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209592. dr.dataRefType = HandleDataHandlerSubType;
  209593. ok = openMovie (props, prop, movie);
  209594. DisposeHandle (dr.dataRef);
  209595. }
  209596. }
  209597. return ok;
  209598. }
  209599. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209600. const bool isControllerVisible)
  209601. {
  209602. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209603. movieFile = movieFile_;
  209604. return ok;
  209605. }
  209606. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209607. const bool isControllerVisible)
  209608. {
  209609. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209610. }
  209611. void QuickTimeMovieComponent::goToStart()
  209612. {
  209613. setPosition (0.0);
  209614. }
  209615. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209616. const RectanglePlacement& placement)
  209617. {
  209618. int normalWidth, normalHeight;
  209619. getMovieNormalSize (normalWidth, normalHeight);
  209620. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209621. {
  209622. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209623. placement.applyTo (x, y, w, h,
  209624. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209625. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209626. if (w > 0 && h > 0)
  209627. {
  209628. setBounds (roundToInt (x), roundToInt (y),
  209629. roundToInt (w), roundToInt (h));
  209630. }
  209631. }
  209632. else
  209633. {
  209634. setBounds (spaceToFitWithin);
  209635. }
  209636. }
  209637. #endif
  209638. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209639. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209640. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209641. // compiled on its own).
  209642. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209643. class WebBrowserComponentInternal : public ActiveXControlComponent
  209644. {
  209645. public:
  209646. WebBrowserComponentInternal()
  209647. : browser (0),
  209648. connectionPoint (0),
  209649. adviseCookie (0)
  209650. {
  209651. }
  209652. ~WebBrowserComponentInternal()
  209653. {
  209654. if (connectionPoint != 0)
  209655. connectionPoint->Unadvise (adviseCookie);
  209656. if (browser != 0)
  209657. browser->Release();
  209658. }
  209659. void createBrowser()
  209660. {
  209661. createControl (&CLSID_WebBrowser);
  209662. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209663. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209664. if (connectionPointContainer != 0)
  209665. {
  209666. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209667. &connectionPoint);
  209668. if (connectionPoint != 0)
  209669. {
  209670. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209671. jassert (owner != 0);
  209672. EventHandler* handler = new EventHandler (owner);
  209673. connectionPoint->Advise (handler, &adviseCookie);
  209674. handler->Release();
  209675. }
  209676. }
  209677. }
  209678. void goToURL (const String& url,
  209679. const StringArray* headers,
  209680. const MemoryBlock* postData)
  209681. {
  209682. if (browser != 0)
  209683. {
  209684. LPSAFEARRAY sa = 0;
  209685. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209686. VariantInit (&flags);
  209687. VariantInit (&frame);
  209688. VariantInit (&postDataVar);
  209689. VariantInit (&headersVar);
  209690. if (headers != 0)
  209691. {
  209692. V_VT (&headersVar) = VT_BSTR;
  209693. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209694. }
  209695. if (postData != 0 && postData->getSize() > 0)
  209696. {
  209697. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209698. if (sa != 0)
  209699. {
  209700. void* data = 0;
  209701. SafeArrayAccessData (sa, &data);
  209702. jassert (data != 0);
  209703. if (data != 0)
  209704. {
  209705. postData->copyTo (data, 0, postData->getSize());
  209706. SafeArrayUnaccessData (sa);
  209707. VARIANT postDataVar2;
  209708. VariantInit (&postDataVar2);
  209709. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209710. V_ARRAY (&postDataVar2) = sa;
  209711. postDataVar = postDataVar2;
  209712. }
  209713. }
  209714. }
  209715. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209716. &flags, &frame,
  209717. &postDataVar, &headersVar);
  209718. if (sa != 0)
  209719. SafeArrayDestroy (sa);
  209720. VariantClear (&flags);
  209721. VariantClear (&frame);
  209722. VariantClear (&postDataVar);
  209723. VariantClear (&headersVar);
  209724. }
  209725. }
  209726. IWebBrowser2* browser;
  209727. private:
  209728. IConnectionPoint* connectionPoint;
  209729. DWORD adviseCookie;
  209730. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209731. public ComponentMovementWatcher
  209732. {
  209733. public:
  209734. EventHandler (WebBrowserComponent* const owner_)
  209735. : ComponentMovementWatcher (owner_),
  209736. owner (owner_)
  209737. {
  209738. }
  209739. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  209740. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  209741. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  209742. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  209743. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  209744. {
  209745. switch (dispIdMember)
  209746. {
  209747. case DISPID_BEFORENAVIGATE2:
  209748. {
  209749. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209750. String url;
  209751. if ((vurl->vt & VT_BYREF) != 0)
  209752. url = *vurl->pbstrVal;
  209753. else
  209754. url = vurl->bstrVal;
  209755. *pDispParams->rgvarg->pboolVal
  209756. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209757. : VARIANT_TRUE;
  209758. return S_OK;
  209759. }
  209760. default:
  209761. break;
  209762. }
  209763. return E_NOTIMPL;
  209764. }
  209765. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209766. void componentPeerChanged() {}
  209767. void componentVisibilityChanged (Component&)
  209768. {
  209769. owner->visibilityChanged();
  209770. }
  209771. private:
  209772. WebBrowserComponent* const owner;
  209773. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  209774. };
  209775. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  209776. };
  209777. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209778. : browser (0),
  209779. blankPageShown (false),
  209780. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209781. {
  209782. setOpaque (true);
  209783. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209784. }
  209785. WebBrowserComponent::~WebBrowserComponent()
  209786. {
  209787. delete browser;
  209788. }
  209789. void WebBrowserComponent::goToURL (const String& url,
  209790. const StringArray* headers,
  209791. const MemoryBlock* postData)
  209792. {
  209793. lastURL = url;
  209794. lastHeaders.clear();
  209795. if (headers != 0)
  209796. lastHeaders = *headers;
  209797. lastPostData.setSize (0);
  209798. if (postData != 0)
  209799. lastPostData = *postData;
  209800. blankPageShown = false;
  209801. browser->goToURL (url, headers, postData);
  209802. }
  209803. void WebBrowserComponent::stop()
  209804. {
  209805. if (browser->browser != 0)
  209806. browser->browser->Stop();
  209807. }
  209808. void WebBrowserComponent::goBack()
  209809. {
  209810. lastURL = String::empty;
  209811. blankPageShown = false;
  209812. if (browser->browser != 0)
  209813. browser->browser->GoBack();
  209814. }
  209815. void WebBrowserComponent::goForward()
  209816. {
  209817. lastURL = String::empty;
  209818. if (browser->browser != 0)
  209819. browser->browser->GoForward();
  209820. }
  209821. void WebBrowserComponent::refresh()
  209822. {
  209823. if (browser->browser != 0)
  209824. browser->browser->Refresh();
  209825. }
  209826. void WebBrowserComponent::paint (Graphics& g)
  209827. {
  209828. if (browser->browser == 0)
  209829. g.fillAll (Colours::white);
  209830. }
  209831. void WebBrowserComponent::checkWindowAssociation()
  209832. {
  209833. if (isShowing())
  209834. {
  209835. if (browser->browser == 0 && getPeer() != 0)
  209836. {
  209837. browser->createBrowser();
  209838. reloadLastURL();
  209839. }
  209840. else
  209841. {
  209842. if (blankPageShown)
  209843. goBack();
  209844. }
  209845. }
  209846. else
  209847. {
  209848. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209849. {
  209850. // when the component becomes invisible, some stuff like flash
  209851. // carries on playing audio, so we need to force it onto a blank
  209852. // page to avoid this..
  209853. blankPageShown = true;
  209854. browser->goToURL ("about:blank", 0, 0);
  209855. }
  209856. }
  209857. }
  209858. void WebBrowserComponent::reloadLastURL()
  209859. {
  209860. if (lastURL.isNotEmpty())
  209861. {
  209862. goToURL (lastURL, &lastHeaders, &lastPostData);
  209863. lastURL = String::empty;
  209864. }
  209865. }
  209866. void WebBrowserComponent::parentHierarchyChanged()
  209867. {
  209868. checkWindowAssociation();
  209869. }
  209870. void WebBrowserComponent::resized()
  209871. {
  209872. browser->setSize (getWidth(), getHeight());
  209873. }
  209874. void WebBrowserComponent::visibilityChanged()
  209875. {
  209876. checkWindowAssociation();
  209877. }
  209878. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209879. {
  209880. return true;
  209881. }
  209882. #endif
  209883. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209884. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209885. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209886. // compiled on its own).
  209887. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209888. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209889. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209890. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209891. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209892. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209893. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209894. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209895. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209896. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209897. #define WGL_ACCELERATION_ARB 0x2003
  209898. #define WGL_SWAP_METHOD_ARB 0x2007
  209899. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209900. #define WGL_PIXEL_TYPE_ARB 0x2013
  209901. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209902. #define WGL_COLOR_BITS_ARB 0x2014
  209903. #define WGL_RED_BITS_ARB 0x2015
  209904. #define WGL_GREEN_BITS_ARB 0x2017
  209905. #define WGL_BLUE_BITS_ARB 0x2019
  209906. #define WGL_ALPHA_BITS_ARB 0x201B
  209907. #define WGL_DEPTH_BITS_ARB 0x2022
  209908. #define WGL_STENCIL_BITS_ARB 0x2023
  209909. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209910. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209911. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209912. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209913. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209914. #define WGL_STEREO_ARB 0x2012
  209915. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  209916. #define WGL_SAMPLES_ARB 0x2042
  209917. #define WGL_TYPE_RGBA_ARB 0x202B
  209918. static void getWglExtensions (HDC dc, StringArray& result) throw()
  209919. {
  209920. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  209921. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  209922. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  209923. else
  209924. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  209925. }
  209926. class WindowedGLContext : public OpenGLContext
  209927. {
  209928. public:
  209929. WindowedGLContext (Component* const component_,
  209930. HGLRC contextToShareWith,
  209931. const OpenGLPixelFormat& pixelFormat)
  209932. : renderContext (0),
  209933. dc (0),
  209934. component (component_)
  209935. {
  209936. jassert (component != 0);
  209937. createNativeWindow();
  209938. // Use a default pixel format that should be supported everywhere
  209939. PIXELFORMATDESCRIPTOR pfd;
  209940. zerostruct (pfd);
  209941. pfd.nSize = sizeof (pfd);
  209942. pfd.nVersion = 1;
  209943. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  209944. pfd.iPixelType = PFD_TYPE_RGBA;
  209945. pfd.cColorBits = 24;
  209946. pfd.cDepthBits = 16;
  209947. const int format = ChoosePixelFormat (dc, &pfd);
  209948. if (format != 0)
  209949. SetPixelFormat (dc, format, &pfd);
  209950. renderContext = wglCreateContext (dc);
  209951. makeActive();
  209952. setPixelFormat (pixelFormat);
  209953. if (contextToShareWith != 0 && renderContext != 0)
  209954. wglShareLists (contextToShareWith, renderContext);
  209955. }
  209956. ~WindowedGLContext()
  209957. {
  209958. deleteContext();
  209959. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209960. nativeWindow = 0;
  209961. }
  209962. void deleteContext()
  209963. {
  209964. makeInactive();
  209965. if (renderContext != 0)
  209966. {
  209967. wglDeleteContext (renderContext);
  209968. renderContext = 0;
  209969. }
  209970. }
  209971. bool makeActive() const throw()
  209972. {
  209973. jassert (renderContext != 0);
  209974. return wglMakeCurrent (dc, renderContext) != 0;
  209975. }
  209976. bool makeInactive() const throw()
  209977. {
  209978. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  209979. }
  209980. bool isActive() const throw()
  209981. {
  209982. return wglGetCurrentContext() == renderContext;
  209983. }
  209984. const OpenGLPixelFormat getPixelFormat() const
  209985. {
  209986. OpenGLPixelFormat pf;
  209987. makeActive();
  209988. StringArray availableExtensions;
  209989. getWglExtensions (dc, availableExtensions);
  209990. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  209991. return pf;
  209992. }
  209993. void* getRawContext() const throw()
  209994. {
  209995. return renderContext;
  209996. }
  209997. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  209998. {
  209999. makeActive();
  210000. PIXELFORMATDESCRIPTOR pfd;
  210001. zerostruct (pfd);
  210002. pfd.nSize = sizeof (pfd);
  210003. pfd.nVersion = 1;
  210004. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210005. pfd.iPixelType = PFD_TYPE_RGBA;
  210006. pfd.iLayerType = PFD_MAIN_PLANE;
  210007. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210008. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210009. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210010. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210011. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210012. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210013. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210014. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210015. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210016. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210017. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210018. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210019. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210020. int format = 0;
  210021. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210022. StringArray availableExtensions;
  210023. getWglExtensions (dc, availableExtensions);
  210024. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210025. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210026. {
  210027. int attributes[64];
  210028. int n = 0;
  210029. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210030. attributes[n++] = GL_TRUE;
  210031. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210032. attributes[n++] = GL_TRUE;
  210033. attributes[n++] = WGL_ACCELERATION_ARB;
  210034. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210035. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210036. attributes[n++] = GL_TRUE;
  210037. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210038. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210039. attributes[n++] = WGL_COLOR_BITS_ARB;
  210040. attributes[n++] = pfd.cColorBits;
  210041. attributes[n++] = WGL_RED_BITS_ARB;
  210042. attributes[n++] = pixelFormat.redBits;
  210043. attributes[n++] = WGL_GREEN_BITS_ARB;
  210044. attributes[n++] = pixelFormat.greenBits;
  210045. attributes[n++] = WGL_BLUE_BITS_ARB;
  210046. attributes[n++] = pixelFormat.blueBits;
  210047. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210048. attributes[n++] = pixelFormat.alphaBits;
  210049. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210050. attributes[n++] = pixelFormat.depthBufferBits;
  210051. if (pixelFormat.stencilBufferBits > 0)
  210052. {
  210053. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210054. attributes[n++] = pixelFormat.stencilBufferBits;
  210055. }
  210056. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210057. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210058. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210059. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210060. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210061. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210062. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210063. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210064. if (availableExtensions.contains ("WGL_ARB_multisample")
  210065. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210066. {
  210067. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210068. attributes[n++] = 1;
  210069. attributes[n++] = WGL_SAMPLES_ARB;
  210070. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210071. }
  210072. attributes[n++] = 0;
  210073. UINT formatsCount;
  210074. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210075. (void) ok;
  210076. jassert (ok);
  210077. }
  210078. else
  210079. {
  210080. format = ChoosePixelFormat (dc, &pfd);
  210081. }
  210082. if (format != 0)
  210083. {
  210084. makeInactive();
  210085. // win32 can't change the pixel format of a window, so need to delete the
  210086. // old one and create a new one..
  210087. jassert (nativeWindow != 0);
  210088. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210089. nativeWindow = 0;
  210090. createNativeWindow();
  210091. if (SetPixelFormat (dc, format, &pfd))
  210092. {
  210093. wglDeleteContext (renderContext);
  210094. renderContext = wglCreateContext (dc);
  210095. jassert (renderContext != 0);
  210096. return renderContext != 0;
  210097. }
  210098. }
  210099. return false;
  210100. }
  210101. void updateWindowPosition (int x, int y, int w, int h, int)
  210102. {
  210103. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210104. x, y, w, h,
  210105. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210106. }
  210107. void repaint()
  210108. {
  210109. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210110. }
  210111. void swapBuffers()
  210112. {
  210113. SwapBuffers (dc);
  210114. }
  210115. bool setSwapInterval (int numFramesPerSwap)
  210116. {
  210117. makeActive();
  210118. StringArray availableExtensions;
  210119. getWglExtensions (dc, availableExtensions);
  210120. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210121. return availableExtensions.contains ("WGL_EXT_swap_control")
  210122. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210123. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210124. }
  210125. int getSwapInterval() const
  210126. {
  210127. makeActive();
  210128. StringArray availableExtensions;
  210129. getWglExtensions (dc, availableExtensions);
  210130. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210131. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210132. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210133. return wglGetSwapIntervalEXT();
  210134. return 0;
  210135. }
  210136. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210137. {
  210138. jassert (isActive());
  210139. StringArray availableExtensions;
  210140. getWglExtensions (dc, availableExtensions);
  210141. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210142. int numTypes = 0;
  210143. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210144. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210145. {
  210146. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210147. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210148. jassertfalse;
  210149. }
  210150. else
  210151. {
  210152. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210153. }
  210154. OpenGLPixelFormat pf;
  210155. for (int i = 0; i < numTypes; ++i)
  210156. {
  210157. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210158. {
  210159. bool alreadyListed = false;
  210160. for (int j = results.size(); --j >= 0;)
  210161. if (pf == *results.getUnchecked(j))
  210162. alreadyListed = true;
  210163. if (! alreadyListed)
  210164. results.add (new OpenGLPixelFormat (pf));
  210165. }
  210166. }
  210167. }
  210168. void* getNativeWindowHandle() const
  210169. {
  210170. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210171. }
  210172. HGLRC renderContext;
  210173. private:
  210174. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210175. Component* const component;
  210176. HDC dc;
  210177. void createNativeWindow()
  210178. {
  210179. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210180. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210181. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210182. nativeWindow->dontRepaint = true;
  210183. nativeWindow->setVisible (true);
  210184. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210185. }
  210186. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210187. OpenGLPixelFormat& result,
  210188. const StringArray& availableExtensions) const throw()
  210189. {
  210190. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210191. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210192. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210193. {
  210194. int attributes[32];
  210195. int numAttributes = 0;
  210196. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210197. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210198. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210199. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210200. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210201. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210202. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210203. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210204. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210205. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210206. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210207. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210208. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210209. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210210. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210211. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210212. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210213. int values[32];
  210214. zeromem (values, sizeof (values));
  210215. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210216. {
  210217. int n = 0;
  210218. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210219. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210220. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210221. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210222. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210223. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210224. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210225. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210226. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210227. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210228. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210229. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210230. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210231. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210232. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210233. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210234. return isValidFormat;
  210235. }
  210236. else
  210237. {
  210238. jassertfalse;
  210239. }
  210240. }
  210241. else
  210242. {
  210243. PIXELFORMATDESCRIPTOR pfd;
  210244. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210245. {
  210246. result.redBits = pfd.cRedBits;
  210247. result.greenBits = pfd.cGreenBits;
  210248. result.blueBits = pfd.cBlueBits;
  210249. result.alphaBits = pfd.cAlphaBits;
  210250. result.depthBufferBits = pfd.cDepthBits;
  210251. result.stencilBufferBits = pfd.cStencilBits;
  210252. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210253. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210254. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210255. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210256. result.fullSceneAntiAliasingNumSamples = 0;
  210257. return true;
  210258. }
  210259. else
  210260. {
  210261. jassertfalse;
  210262. }
  210263. }
  210264. return false;
  210265. }
  210266. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210267. };
  210268. OpenGLContext* OpenGLComponent::createContext()
  210269. {
  210270. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210271. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210272. preferredPixelFormat));
  210273. return (c->renderContext != 0) ? c.release() : 0;
  210274. }
  210275. void* OpenGLComponent::getNativeWindowHandle() const
  210276. {
  210277. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210278. }
  210279. void juce_glViewport (const int w, const int h)
  210280. {
  210281. glViewport (0, 0, w, h);
  210282. }
  210283. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210284. OwnedArray <OpenGLPixelFormat>& results)
  210285. {
  210286. Component tempComp;
  210287. {
  210288. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210289. wc.makeActive();
  210290. wc.findAlternativeOpenGLPixelFormats (results);
  210291. }
  210292. }
  210293. #endif
  210294. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210295. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210296. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210297. // compiled on its own).
  210298. #if JUCE_INCLUDED_FILE
  210299. #if JUCE_USE_CDREADER
  210300. namespace CDReaderHelpers
  210301. {
  210302. //***************************************************************************
  210303. // %%% TARGET STATUS VALUES %%%
  210304. //***************************************************************************
  210305. #define STATUS_GOOD 0x00 // Status Good
  210306. #define STATUS_CHKCOND 0x02 // Check Condition
  210307. #define STATUS_CONDMET 0x04 // Condition Met
  210308. #define STATUS_BUSY 0x08 // Busy
  210309. #define STATUS_INTERM 0x10 // Intermediate
  210310. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210311. #define STATUS_RESCONF 0x18 // Reservation conflict
  210312. #define STATUS_COMTERM 0x22 // Command Terminated
  210313. #define STATUS_QFULL 0x28 // Queue full
  210314. //***************************************************************************
  210315. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210316. //***************************************************************************
  210317. #define MAXLUN 7 // Maximum Logical Unit Id
  210318. #define MAXTARG 7 // Maximum Target Id
  210319. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210320. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210321. //***************************************************************************
  210322. // %%% Commands for all Device Types %%%
  210323. //***************************************************************************
  210324. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210325. #define SCSI_COMPARE 0x39 // Compare (O)
  210326. #define SCSI_COPY 0x18 // Copy (O)
  210327. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210328. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210329. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210330. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210331. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210332. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210333. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210334. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210335. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210336. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210337. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210338. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210339. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210340. //***************************************************************************
  210341. // %%% Commands Unique to Direct Access Devices %%%
  210342. //***************************************************************************
  210343. #define SCSI_COMPARE 0x39 // Compare (O)
  210344. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210345. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210346. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210347. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210348. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210349. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210350. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210351. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210352. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210353. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210354. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210355. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210356. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210357. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210358. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210359. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210360. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210361. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210362. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210363. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210364. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210365. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210366. #define SCSI_VERIFY 0x2F // Verify (O)
  210367. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210368. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210369. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210370. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210371. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210372. //***************************************************************************
  210373. // %%% Commands Unique to Sequential Access Devices %%%
  210374. //***************************************************************************
  210375. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210376. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210377. #define SCSI_LOCATE 0x2B // Locate (O)
  210378. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210379. #define SCSI_READ_POS 0x34 // Read Position (O)
  210380. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210381. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210382. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210383. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210384. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210385. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210386. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210387. //***************************************************************************
  210388. // %%% Commands Unique to Printer Devices %%%
  210389. //***************************************************************************
  210390. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210391. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210392. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210393. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210394. //***************************************************************************
  210395. // %%% Commands Unique to Processor Devices %%%
  210396. //***************************************************************************
  210397. #define SCSI_RECEIVE 0x08 // Receive (O)
  210398. #define SCSI_SEND 0x0A // Send (O)
  210399. //***************************************************************************
  210400. // %%% Commands Unique to Write-Once Devices %%%
  210401. //***************************************************************************
  210402. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210403. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210404. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210405. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210406. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210407. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210408. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210409. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210410. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210411. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210412. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210413. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210414. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210415. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210416. //***************************************************************************
  210417. // %%% Commands Unique to CD-ROM Devices %%%
  210418. //***************************************************************************
  210419. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210420. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210421. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210422. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210423. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210424. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210425. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210426. #define SCSI_READHEADER 0x44 // Read Header (O)
  210427. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210428. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210429. //***************************************************************************
  210430. // %%% Commands Unique to Scanner Devices %%%
  210431. //***************************************************************************
  210432. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210433. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210434. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210435. #define SCSI_SCAN 0x1B // Scan (O)
  210436. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210437. //***************************************************************************
  210438. // %%% Commands Unique to Optical Memory Devices %%%
  210439. //***************************************************************************
  210440. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210441. //***************************************************************************
  210442. // %%% Commands Unique to Medium Changer Devices %%%
  210443. //***************************************************************************
  210444. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210445. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210446. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210447. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210448. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210449. //***************************************************************************
  210450. // %%% Commands Unique to Communication Devices %%%
  210451. //***************************************************************************
  210452. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210453. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210454. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210455. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210456. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210457. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210458. //***************************************************************************
  210459. // %%% Request Sense Data Format %%%
  210460. //***************************************************************************
  210461. typedef struct {
  210462. BYTE ErrorCode; // Error Code (70H or 71H)
  210463. BYTE SegmentNum; // Number of current segment descriptor
  210464. BYTE SenseKey; // Sense Key(See bit definitions too)
  210465. BYTE InfoByte0; // Information MSB
  210466. BYTE InfoByte1; // Information MID
  210467. BYTE InfoByte2; // Information MID
  210468. BYTE InfoByte3; // Information LSB
  210469. BYTE AddSenLen; // Additional Sense Length
  210470. BYTE ComSpecInf0; // Command Specific Information MSB
  210471. BYTE ComSpecInf1; // Command Specific Information MID
  210472. BYTE ComSpecInf2; // Command Specific Information MID
  210473. BYTE ComSpecInf3; // Command Specific Information LSB
  210474. BYTE AddSenseCode; // Additional Sense Code
  210475. BYTE AddSenQual; // Additional Sense Code Qualifier
  210476. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210477. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210478. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210479. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210480. BYTE AddSenseBytes; // Additional Sense Bytes
  210481. } SENSE_DATA_FMT;
  210482. //***************************************************************************
  210483. // %%% REQUEST SENSE ERROR CODE %%%
  210484. //***************************************************************************
  210485. #define SERROR_CURRENT 0x70 // Current Errors
  210486. #define SERROR_DEFERED 0x71 // Deferred Errors
  210487. //***************************************************************************
  210488. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210489. //***************************************************************************
  210490. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210491. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210492. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210493. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210494. //***************************************************************************
  210495. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210496. //***************************************************************************
  210497. #define KEY_NOSENSE 0x00 // No Sense
  210498. #define KEY_RECERROR 0x01 // Recovered Error
  210499. #define KEY_NOTREADY 0x02 // Not Ready
  210500. #define KEY_MEDIUMERR 0x03 // Medium Error
  210501. #define KEY_HARDERROR 0x04 // Hardware Error
  210502. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210503. #define KEY_UNITATT 0x06 // Unit Attention
  210504. #define KEY_DATAPROT 0x07 // Data Protect
  210505. #define KEY_BLANKCHK 0x08 // Blank Check
  210506. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210507. #define KEY_COPYABORT 0x0A // Copy Abort
  210508. #define KEY_EQUAL 0x0C // Equal (Search)
  210509. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210510. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210511. #define KEY_RESERVED 0x0F // Reserved
  210512. //***************************************************************************
  210513. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210514. //***************************************************************************
  210515. #define DTYPE_DASD 0x00 // Disk Device
  210516. #define DTYPE_SEQD 0x01 // Tape Device
  210517. #define DTYPE_PRNT 0x02 // Printer
  210518. #define DTYPE_PROC 0x03 // Processor
  210519. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210520. #define DTYPE_CROM 0x05 // CD-ROM device
  210521. #define DTYPE_SCAN 0x06 // Scanner device
  210522. #define DTYPE_OPTI 0x07 // Optical memory device
  210523. #define DTYPE_JUKE 0x08 // Medium Changer device
  210524. #define DTYPE_COMM 0x09 // Communications device
  210525. #define DTYPE_RESL 0x0A // Reserved (low)
  210526. #define DTYPE_RESH 0x1E // Reserved (high)
  210527. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210528. //***************************************************************************
  210529. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210530. //***************************************************************************
  210531. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210532. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210533. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210534. #define ANSI_RESLO 0x3 // Reserved (low)
  210535. #define ANSI_RESHI 0x7 // Reserved (high)
  210536. typedef struct
  210537. {
  210538. USHORT Length;
  210539. UCHAR ScsiStatus;
  210540. UCHAR PathId;
  210541. UCHAR TargetId;
  210542. UCHAR Lun;
  210543. UCHAR CdbLength;
  210544. UCHAR SenseInfoLength;
  210545. UCHAR DataIn;
  210546. ULONG DataTransferLength;
  210547. ULONG TimeOutValue;
  210548. ULONG DataBufferOffset;
  210549. ULONG SenseInfoOffset;
  210550. UCHAR Cdb[16];
  210551. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210552. typedef struct
  210553. {
  210554. USHORT Length;
  210555. UCHAR ScsiStatus;
  210556. UCHAR PathId;
  210557. UCHAR TargetId;
  210558. UCHAR Lun;
  210559. UCHAR CdbLength;
  210560. UCHAR SenseInfoLength;
  210561. UCHAR DataIn;
  210562. ULONG DataTransferLength;
  210563. ULONG TimeOutValue;
  210564. PVOID DataBuffer;
  210565. ULONG SenseInfoOffset;
  210566. UCHAR Cdb[16];
  210567. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210568. typedef struct
  210569. {
  210570. SCSI_PASS_THROUGH_DIRECT spt;
  210571. ULONG Filler;
  210572. UCHAR ucSenseBuf[32];
  210573. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210574. typedef struct
  210575. {
  210576. ULONG Length;
  210577. UCHAR PortNumber;
  210578. UCHAR PathId;
  210579. UCHAR TargetId;
  210580. UCHAR Lun;
  210581. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210582. #define METHOD_BUFFERED 0
  210583. #define METHOD_IN_DIRECT 1
  210584. #define METHOD_OUT_DIRECT 2
  210585. #define METHOD_NEITHER 3
  210586. #define FILE_ANY_ACCESS 0
  210587. #ifndef FILE_READ_ACCESS
  210588. #define FILE_READ_ACCESS (0x0001)
  210589. #endif
  210590. #ifndef FILE_WRITE_ACCESS
  210591. #define FILE_WRITE_ACCESS (0x0002)
  210592. #endif
  210593. #define IOCTL_SCSI_BASE 0x00000004
  210594. #define SCSI_IOCTL_DATA_OUT 0
  210595. #define SCSI_IOCTL_DATA_IN 1
  210596. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210597. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210598. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210599. )
  210600. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210601. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210602. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210603. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210604. #define SENSE_LEN 14
  210605. #define SRB_DIR_SCSI 0x00
  210606. #define SRB_POSTING 0x01
  210607. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210608. #define SRB_DIR_IN 0x08
  210609. #define SRB_DIR_OUT 0x10
  210610. #define SRB_EVENT_NOTIFY 0x40
  210611. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210612. #define MAX_SRB_TIMEOUT 1080001u
  210613. #define DEFAULT_SRB_TIMEOUT 1080001u
  210614. #define SC_HA_INQUIRY 0x00
  210615. #define SC_GET_DEV_TYPE 0x01
  210616. #define SC_EXEC_SCSI_CMD 0x02
  210617. #define SC_ABORT_SRB 0x03
  210618. #define SC_RESET_DEV 0x04
  210619. #define SC_SET_HA_PARMS 0x05
  210620. #define SC_GET_DISK_INFO 0x06
  210621. #define SC_RESCAN_SCSI_BUS 0x07
  210622. #define SC_GETSET_TIMEOUTS 0x08
  210623. #define SS_PENDING 0x00
  210624. #define SS_COMP 0x01
  210625. #define SS_ABORTED 0x02
  210626. #define SS_ABORT_FAIL 0x03
  210627. #define SS_ERR 0x04
  210628. #define SS_INVALID_CMD 0x80
  210629. #define SS_INVALID_HA 0x81
  210630. #define SS_NO_DEVICE 0x82
  210631. #define SS_INVALID_SRB 0xE0
  210632. #define SS_OLD_MANAGER 0xE1
  210633. #define SS_BUFFER_ALIGN 0xE1
  210634. #define SS_ILLEGAL_MODE 0xE2
  210635. #define SS_NO_ASPI 0xE3
  210636. #define SS_FAILED_INIT 0xE4
  210637. #define SS_ASPI_IS_BUSY 0xE5
  210638. #define SS_BUFFER_TO_BIG 0xE6
  210639. #define SS_BUFFER_TOO_BIG 0xE6
  210640. #define SS_MISMATCHED_COMPONENTS 0xE7
  210641. #define SS_NO_ADAPTERS 0xE8
  210642. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210643. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210644. #define SS_BAD_INSTALL 0xEB
  210645. #define HASTAT_OK 0x00
  210646. #define HASTAT_SEL_TO 0x11
  210647. #define HASTAT_DO_DU 0x12
  210648. #define HASTAT_BUS_FREE 0x13
  210649. #define HASTAT_PHASE_ERR 0x14
  210650. #define HASTAT_TIMEOUT 0x09
  210651. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210652. #define HASTAT_MESSAGE_REJECT 0x0D
  210653. #define HASTAT_BUS_RESET 0x0E
  210654. #define HASTAT_PARITY_ERROR 0x0F
  210655. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210656. #define PACKED
  210657. #pragma pack(1)
  210658. typedef struct
  210659. {
  210660. BYTE SRB_Cmd;
  210661. BYTE SRB_Status;
  210662. BYTE SRB_HaID;
  210663. BYTE SRB_Flags;
  210664. DWORD SRB_Hdr_Rsvd;
  210665. BYTE HA_Count;
  210666. BYTE HA_SCSI_ID;
  210667. BYTE HA_ManagerId[16];
  210668. BYTE HA_Identifier[16];
  210669. BYTE HA_Unique[16];
  210670. WORD HA_Rsvd1;
  210671. BYTE pad[20];
  210672. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210673. typedef struct
  210674. {
  210675. BYTE SRB_Cmd;
  210676. BYTE SRB_Status;
  210677. BYTE SRB_HaID;
  210678. BYTE SRB_Flags;
  210679. DWORD SRB_Hdr_Rsvd;
  210680. BYTE SRB_Target;
  210681. BYTE SRB_Lun;
  210682. BYTE SRB_DeviceType;
  210683. BYTE SRB_Rsvd1;
  210684. BYTE pad[68];
  210685. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  210686. typedef struct
  210687. {
  210688. BYTE SRB_Cmd;
  210689. BYTE SRB_Status;
  210690. BYTE SRB_HaID;
  210691. BYTE SRB_Flags;
  210692. DWORD SRB_Hdr_Rsvd;
  210693. BYTE SRB_Target;
  210694. BYTE SRB_Lun;
  210695. WORD SRB_Rsvd1;
  210696. DWORD SRB_BufLen;
  210697. BYTE FAR *SRB_BufPointer;
  210698. BYTE SRB_SenseLen;
  210699. BYTE SRB_CDBLen;
  210700. BYTE SRB_HaStat;
  210701. BYTE SRB_TargStat;
  210702. VOID FAR *SRB_PostProc;
  210703. BYTE SRB_Rsvd2[20];
  210704. BYTE CDBByte[16];
  210705. BYTE SenseArea[SENSE_LEN+2];
  210706. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  210707. typedef struct
  210708. {
  210709. BYTE SRB_Cmd;
  210710. BYTE SRB_Status;
  210711. BYTE SRB_HaId;
  210712. BYTE SRB_Flags;
  210713. DWORD SRB_Hdr_Rsvd;
  210714. } PACKED SRB, *PSRB, FAR *LPSRB;
  210715. #pragma pack()
  210716. struct CDDeviceInfo
  210717. {
  210718. char vendor[9];
  210719. char productId[17];
  210720. char rev[5];
  210721. char vendorSpec[21];
  210722. BYTE ha;
  210723. BYTE tgt;
  210724. BYTE lun;
  210725. char scsiDriveLetter; // will be 0 if not using scsi
  210726. };
  210727. class CDReadBuffer
  210728. {
  210729. public:
  210730. int startFrame;
  210731. int numFrames;
  210732. int dataStartOffset;
  210733. int dataLength;
  210734. int bufferSize;
  210735. HeapBlock<BYTE> buffer;
  210736. int index;
  210737. bool wantsIndex;
  210738. CDReadBuffer (const int numberOfFrames)
  210739. : startFrame (0),
  210740. numFrames (0),
  210741. dataStartOffset (0),
  210742. dataLength (0),
  210743. bufferSize (2352 * numberOfFrames),
  210744. buffer (bufferSize),
  210745. index (0),
  210746. wantsIndex (false)
  210747. {
  210748. }
  210749. bool isZero() const throw()
  210750. {
  210751. BYTE* p = buffer + dataStartOffset;
  210752. for (int i = dataLength; --i >= 0;)
  210753. if (*p++ != 0)
  210754. return false;
  210755. return true;
  210756. }
  210757. };
  210758. class CDDeviceHandle;
  210759. class CDController
  210760. {
  210761. public:
  210762. CDController();
  210763. virtual ~CDController();
  210764. virtual bool read (CDReadBuffer* t) = 0;
  210765. virtual void shutDown();
  210766. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  210767. int getLastIndex();
  210768. public:
  210769. bool initialised;
  210770. CDDeviceHandle* deviceInfo;
  210771. int framesToCheck, framesOverlap;
  210772. void prepare (SRB_ExecSCSICmd& s);
  210773. void perform (SRB_ExecSCSICmd& s);
  210774. void setPaused (bool paused);
  210775. };
  210776. #pragma pack(1)
  210777. struct TOCTRACK
  210778. {
  210779. BYTE rsvd;
  210780. BYTE ADR;
  210781. BYTE trackNumber;
  210782. BYTE rsvd2;
  210783. BYTE addr[4];
  210784. };
  210785. struct TOC
  210786. {
  210787. WORD tocLen;
  210788. BYTE firstTrack;
  210789. BYTE lastTrack;
  210790. TOCTRACK tracks[100];
  210791. };
  210792. #pragma pack()
  210793. enum
  210794. {
  210795. READTYPE_ANY = 0,
  210796. READTYPE_ATAPI1 = 1,
  210797. READTYPE_ATAPI2 = 2,
  210798. READTYPE_READ6 = 3,
  210799. READTYPE_READ10 = 4,
  210800. READTYPE_READ_D8 = 5,
  210801. READTYPE_READ_D4 = 6,
  210802. READTYPE_READ_D4_1 = 7,
  210803. READTYPE_READ10_2 = 8
  210804. };
  210805. class CDDeviceHandle
  210806. {
  210807. public:
  210808. CDDeviceHandle (const CDDeviceInfo* const device)
  210809. : scsiHandle (0),
  210810. readType (READTYPE_ANY),
  210811. controller (0)
  210812. {
  210813. memcpy (&info, device, sizeof (info));
  210814. }
  210815. ~CDDeviceHandle()
  210816. {
  210817. if (controller != 0)
  210818. {
  210819. controller->shutDown();
  210820. controller = 0;
  210821. }
  210822. if (scsiHandle != 0)
  210823. CloseHandle (scsiHandle);
  210824. }
  210825. bool readTOC (TOC* lpToc);
  210826. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  210827. void openDrawer (bool shouldBeOpen);
  210828. CDDeviceInfo info;
  210829. HANDLE scsiHandle;
  210830. BYTE readType;
  210831. private:
  210832. ScopedPointer<CDController> controller;
  210833. bool testController (const int readType,
  210834. CDController* const newController,
  210835. CDReadBuffer* const bufferToUse);
  210836. };
  210837. DWORD (*fGetASPI32SupportInfo)(void);
  210838. DWORD (*fSendASPI32Command)(LPSRB);
  210839. static HINSTANCE winAspiLib = 0;
  210840. static bool usingScsi = false;
  210841. static bool initialised = false;
  210842. bool InitialiseCDRipper()
  210843. {
  210844. if (! initialised)
  210845. {
  210846. initialised = true;
  210847. OSVERSIONINFO info;
  210848. info.dwOSVersionInfoSize = sizeof (info);
  210849. GetVersionEx (&info);
  210850. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  210851. if (! usingScsi)
  210852. {
  210853. fGetASPI32SupportInfo = 0;
  210854. fSendASPI32Command = 0;
  210855. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  210856. if (winAspiLib != 0)
  210857. {
  210858. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  210859. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  210860. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  210861. return false;
  210862. }
  210863. else
  210864. {
  210865. usingScsi = true;
  210866. }
  210867. }
  210868. }
  210869. return true;
  210870. }
  210871. void DeinitialiseCDRipper()
  210872. {
  210873. if (winAspiLib != 0)
  210874. {
  210875. fGetASPI32SupportInfo = 0;
  210876. fSendASPI32Command = 0;
  210877. FreeLibrary (winAspiLib);
  210878. winAspiLib = 0;
  210879. }
  210880. initialised = false;
  210881. }
  210882. HANDLE CreateSCSIDeviceHandle (char driveLetter)
  210883. {
  210884. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210885. OSVERSIONINFO info;
  210886. info.dwOSVersionInfoSize = sizeof (info);
  210887. GetVersionEx (&info);
  210888. DWORD flags = GENERIC_READ;
  210889. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  210890. flags = GENERIC_READ | GENERIC_WRITE;
  210891. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210892. if (h == INVALID_HANDLE_VALUE)
  210893. {
  210894. flags ^= GENERIC_WRITE;
  210895. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210896. }
  210897. return h;
  210898. }
  210899. DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb, const char driveLetter,
  210900. HANDLE& deviceHandle, const bool retryOnFailure = true)
  210901. {
  210902. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210903. zerostruct (s);
  210904. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210905. s.spt.CdbLength = srb->SRB_CDBLen;
  210906. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210907. ? SCSI_IOCTL_DATA_IN
  210908. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210909. ? SCSI_IOCTL_DATA_OUT
  210910. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210911. s.spt.DataTransferLength = srb->SRB_BufLen;
  210912. s.spt.TimeOutValue = 5;
  210913. s.spt.DataBuffer = srb->SRB_BufPointer;
  210914. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210915. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210916. srb->SRB_Status = SS_ERR;
  210917. srb->SRB_TargStat = 0x0004;
  210918. DWORD bytesReturned = 0;
  210919. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210920. &s, sizeof (s),
  210921. &s, sizeof (s),
  210922. &bytesReturned, 0) != 0)
  210923. {
  210924. srb->SRB_Status = SS_COMP;
  210925. }
  210926. else if (retryOnFailure)
  210927. {
  210928. const DWORD error = GetLastError();
  210929. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210930. {
  210931. if (error != ERROR_INVALID_HANDLE)
  210932. CloseHandle (deviceHandle);
  210933. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  210934. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210935. }
  210936. }
  210937. return srb->SRB_Status;
  210938. }
  210939. // Controller types..
  210940. class ControllerType1 : public CDController
  210941. {
  210942. public:
  210943. ControllerType1() {}
  210944. ~ControllerType1() {}
  210945. bool read (CDReadBuffer* rb)
  210946. {
  210947. if (rb->numFrames * 2352 > rb->bufferSize)
  210948. return false;
  210949. SRB_ExecSCSICmd s;
  210950. prepare (s);
  210951. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210952. s.SRB_BufLen = rb->bufferSize;
  210953. s.SRB_BufPointer = rb->buffer;
  210954. s.SRB_CDBLen = 12;
  210955. s.CDBByte[0] = 0xBE;
  210956. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  210957. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  210958. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  210959. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  210960. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  210961. perform (s);
  210962. if (s.SRB_Status != SS_COMP)
  210963. return false;
  210964. rb->dataLength = rb->numFrames * 2352;
  210965. rb->dataStartOffset = 0;
  210966. return true;
  210967. }
  210968. };
  210969. class ControllerType2 : public CDController
  210970. {
  210971. public:
  210972. ControllerType2() {}
  210973. ~ControllerType2() {}
  210974. void shutDown()
  210975. {
  210976. if (initialised)
  210977. {
  210978. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  210979. SRB_ExecSCSICmd s;
  210980. prepare (s);
  210981. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  210982. s.SRB_BufLen = 0x0C;
  210983. s.SRB_BufPointer = bufPointer;
  210984. s.SRB_CDBLen = 6;
  210985. s.CDBByte[0] = 0x15;
  210986. s.CDBByte[4] = 0x0C;
  210987. perform (s);
  210988. }
  210989. }
  210990. bool init()
  210991. {
  210992. SRB_ExecSCSICmd s;
  210993. s.SRB_Status = SS_ERR;
  210994. if (deviceInfo->readType == READTYPE_READ10_2)
  210995. {
  210996. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  210997. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  210998. for (int i = 0; i < 2; ++i)
  210999. {
  211000. prepare (s);
  211001. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211002. s.SRB_BufLen = 0x14;
  211003. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211004. s.SRB_CDBLen = 6;
  211005. s.CDBByte[0] = 0x15;
  211006. s.CDBByte[1] = 0x10;
  211007. s.CDBByte[4] = 0x14;
  211008. perform (s);
  211009. if (s.SRB_Status != SS_COMP)
  211010. return false;
  211011. }
  211012. }
  211013. else
  211014. {
  211015. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211016. prepare (s);
  211017. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211018. s.SRB_BufLen = 0x0C;
  211019. s.SRB_BufPointer = bufPointer;
  211020. s.SRB_CDBLen = 6;
  211021. s.CDBByte[0] = 0x15;
  211022. s.CDBByte[4] = 0x0C;
  211023. perform (s);
  211024. }
  211025. return s.SRB_Status == SS_COMP;
  211026. }
  211027. bool read (CDReadBuffer* rb)
  211028. {
  211029. if (rb->numFrames * 2352 > rb->bufferSize)
  211030. return false;
  211031. if (!initialised)
  211032. {
  211033. initialised = init();
  211034. if (!initialised)
  211035. return false;
  211036. }
  211037. SRB_ExecSCSICmd s;
  211038. prepare (s);
  211039. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211040. s.SRB_BufLen = rb->bufferSize;
  211041. s.SRB_BufPointer = rb->buffer;
  211042. s.SRB_CDBLen = 10;
  211043. s.CDBByte[0] = 0x28;
  211044. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211045. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211046. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211047. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211048. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211049. perform (s);
  211050. if (s.SRB_Status != SS_COMP)
  211051. return false;
  211052. rb->dataLength = rb->numFrames * 2352;
  211053. rb->dataStartOffset = 0;
  211054. return true;
  211055. }
  211056. };
  211057. class ControllerType3 : public CDController
  211058. {
  211059. public:
  211060. ControllerType3() {}
  211061. ~ControllerType3() {}
  211062. bool read (CDReadBuffer* rb)
  211063. {
  211064. if (rb->numFrames * 2352 > rb->bufferSize)
  211065. return false;
  211066. if (!initialised)
  211067. {
  211068. setPaused (false);
  211069. initialised = true;
  211070. }
  211071. SRB_ExecSCSICmd s;
  211072. prepare (s);
  211073. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211074. s.SRB_BufLen = rb->numFrames * 2352;
  211075. s.SRB_BufPointer = rb->buffer;
  211076. s.SRB_CDBLen = 12;
  211077. s.CDBByte[0] = 0xD8;
  211078. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211079. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211080. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211081. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211082. perform (s);
  211083. if (s.SRB_Status != SS_COMP)
  211084. return false;
  211085. rb->dataLength = rb->numFrames * 2352;
  211086. rb->dataStartOffset = 0;
  211087. return true;
  211088. }
  211089. };
  211090. class ControllerType4 : public CDController
  211091. {
  211092. public:
  211093. ControllerType4() {}
  211094. ~ControllerType4() {}
  211095. bool selectD4Mode()
  211096. {
  211097. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211098. SRB_ExecSCSICmd s;
  211099. prepare (s);
  211100. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211101. s.SRB_CDBLen = 6;
  211102. s.SRB_BufLen = 12;
  211103. s.SRB_BufPointer = bufPointer;
  211104. s.CDBByte[0] = 0x15;
  211105. s.CDBByte[1] = 0x10;
  211106. s.CDBByte[4] = 0x08;
  211107. perform (s);
  211108. return s.SRB_Status == SS_COMP;
  211109. }
  211110. bool read (CDReadBuffer* rb)
  211111. {
  211112. if (rb->numFrames * 2352 > rb->bufferSize)
  211113. return false;
  211114. if (!initialised)
  211115. {
  211116. setPaused (true);
  211117. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211118. selectD4Mode();
  211119. initialised = true;
  211120. }
  211121. SRB_ExecSCSICmd s;
  211122. prepare (s);
  211123. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211124. s.SRB_BufLen = rb->bufferSize;
  211125. s.SRB_BufPointer = rb->buffer;
  211126. s.SRB_CDBLen = 10;
  211127. s.CDBByte[0] = 0xD4;
  211128. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211129. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211130. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211131. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211132. perform (s);
  211133. if (s.SRB_Status != SS_COMP)
  211134. return false;
  211135. rb->dataLength = rb->numFrames * 2352;
  211136. rb->dataStartOffset = 0;
  211137. return true;
  211138. }
  211139. };
  211140. CDController::CDController() : initialised (false)
  211141. {
  211142. }
  211143. CDController::~CDController()
  211144. {
  211145. }
  211146. void CDController::prepare (SRB_ExecSCSICmd& s)
  211147. {
  211148. zerostruct (s);
  211149. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211150. s.SRB_HaID = deviceInfo->info.ha;
  211151. s.SRB_Target = deviceInfo->info.tgt;
  211152. s.SRB_Lun = deviceInfo->info.lun;
  211153. s.SRB_SenseLen = SENSE_LEN;
  211154. }
  211155. void CDController::perform (SRB_ExecSCSICmd& s)
  211156. {
  211157. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211158. s.SRB_PostProc = event;
  211159. ResetEvent (event);
  211160. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211161. deviceInfo->info.scsiDriveLetter,
  211162. deviceInfo->scsiHandle)
  211163. : fSendASPI32Command ((LPSRB)&s);
  211164. if (status == SS_PENDING)
  211165. WaitForSingleObject (event, 4000);
  211166. CloseHandle (event);
  211167. }
  211168. void CDController::setPaused (bool paused)
  211169. {
  211170. SRB_ExecSCSICmd s;
  211171. prepare (s);
  211172. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211173. s.SRB_CDBLen = 10;
  211174. s.CDBByte[0] = 0x4B;
  211175. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211176. perform (s);
  211177. }
  211178. void CDController::shutDown()
  211179. {
  211180. }
  211181. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211182. {
  211183. if (overlapBuffer != 0)
  211184. {
  211185. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211186. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211187. if (doJitter
  211188. && overlapBuffer->startFrame > 0
  211189. && overlapBuffer->numFrames > 0
  211190. && overlapBuffer->dataLength > 0)
  211191. {
  211192. const int numFrames = rb->numFrames;
  211193. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211194. {
  211195. rb->startFrame -= framesOverlap;
  211196. if (framesToCheck < framesOverlap
  211197. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211198. rb->numFrames += framesOverlap;
  211199. }
  211200. else
  211201. {
  211202. overlapBuffer->dataLength = 0;
  211203. overlapBuffer->startFrame = 0;
  211204. overlapBuffer->numFrames = 0;
  211205. }
  211206. }
  211207. if (! read (rb))
  211208. return false;
  211209. if (doJitter)
  211210. {
  211211. const int checkLen = framesToCheck * 2352;
  211212. const int maxToCheck = rb->dataLength - checkLen;
  211213. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211214. return true;
  211215. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211216. bool found = false;
  211217. for (int i = 0; i < maxToCheck; ++i)
  211218. {
  211219. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211220. {
  211221. i += checkLen;
  211222. rb->dataStartOffset = i;
  211223. rb->dataLength -= i;
  211224. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211225. found = true;
  211226. break;
  211227. }
  211228. }
  211229. rb->numFrames = rb->dataLength / 2352;
  211230. rb->dataLength = 2352 * rb->numFrames;
  211231. if (!found)
  211232. return false;
  211233. }
  211234. if (canDoJitter)
  211235. {
  211236. memcpy (overlapBuffer->buffer,
  211237. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211238. 2352 * framesToCheck);
  211239. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211240. overlapBuffer->numFrames = framesToCheck;
  211241. overlapBuffer->dataLength = 2352 * framesToCheck;
  211242. overlapBuffer->dataStartOffset = 0;
  211243. }
  211244. else
  211245. {
  211246. overlapBuffer->startFrame = 0;
  211247. overlapBuffer->numFrames = 0;
  211248. overlapBuffer->dataLength = 0;
  211249. }
  211250. return true;
  211251. }
  211252. else
  211253. {
  211254. return read (rb);
  211255. }
  211256. }
  211257. int CDController::getLastIndex()
  211258. {
  211259. char qdata[100];
  211260. SRB_ExecSCSICmd s;
  211261. prepare (s);
  211262. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211263. s.SRB_BufLen = sizeof (qdata);
  211264. s.SRB_BufPointer = (BYTE*)qdata;
  211265. s.SRB_CDBLen = 12;
  211266. s.CDBByte[0] = 0x42;
  211267. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211268. s.CDBByte[2] = 64;
  211269. s.CDBByte[3] = 1; // get current position
  211270. s.CDBByte[7] = 0;
  211271. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211272. perform (s);
  211273. if (s.SRB_Status == SS_COMP)
  211274. return qdata[7];
  211275. return 0;
  211276. }
  211277. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211278. {
  211279. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211280. SRB_ExecSCSICmd s;
  211281. zerostruct (s);
  211282. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211283. s.SRB_HaID = info.ha;
  211284. s.SRB_Target = info.tgt;
  211285. s.SRB_Lun = info.lun;
  211286. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211287. s.SRB_BufLen = 0x324;
  211288. s.SRB_BufPointer = (BYTE*)lpToc;
  211289. s.SRB_SenseLen = 0x0E;
  211290. s.SRB_CDBLen = 0x0A;
  211291. s.SRB_PostProc = event;
  211292. s.CDBByte[0] = 0x43;
  211293. s.CDBByte[1] = 0x00;
  211294. s.CDBByte[7] = 0x03;
  211295. s.CDBByte[8] = 0x24;
  211296. ResetEvent (event);
  211297. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211298. : fSendASPI32Command ((LPSRB)&s);
  211299. if (status == SS_PENDING)
  211300. WaitForSingleObject (event, 4000);
  211301. CloseHandle (event);
  211302. return (s.SRB_Status == SS_COMP);
  211303. }
  211304. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211305. CDReadBuffer* const overlapBuffer)
  211306. {
  211307. if (controller == 0)
  211308. {
  211309. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211310. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211311. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211312. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211313. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211314. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211315. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211316. }
  211317. buffer->index = 0;
  211318. if ((controller != 0)
  211319. && controller->readAudio (buffer, overlapBuffer))
  211320. {
  211321. if (buffer->wantsIndex)
  211322. buffer->index = controller->getLastIndex();
  211323. return true;
  211324. }
  211325. return false;
  211326. }
  211327. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211328. {
  211329. if (shouldBeOpen)
  211330. {
  211331. if (controller != 0)
  211332. {
  211333. controller->shutDown();
  211334. controller = 0;
  211335. }
  211336. if (scsiHandle != 0)
  211337. {
  211338. CloseHandle (scsiHandle);
  211339. scsiHandle = 0;
  211340. }
  211341. }
  211342. SRB_ExecSCSICmd s;
  211343. zerostruct (s);
  211344. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211345. s.SRB_HaID = info.ha;
  211346. s.SRB_Target = info.tgt;
  211347. s.SRB_Lun = info.lun;
  211348. s.SRB_SenseLen = SENSE_LEN;
  211349. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211350. s.SRB_BufLen = 0;
  211351. s.SRB_BufPointer = 0;
  211352. s.SRB_CDBLen = 12;
  211353. s.CDBByte[0] = 0x1b;
  211354. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211355. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211356. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211357. s.SRB_PostProc = event;
  211358. ResetEvent (event);
  211359. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211360. : fSendASPI32Command ((LPSRB)&s);
  211361. if (status == SS_PENDING)
  211362. WaitForSingleObject (event, 4000);
  211363. CloseHandle (event);
  211364. }
  211365. bool CDDeviceHandle::testController (const int type,
  211366. CDController* const newController,
  211367. CDReadBuffer* const rb)
  211368. {
  211369. controller = newController;
  211370. readType = (BYTE)type;
  211371. controller->deviceInfo = this;
  211372. controller->framesToCheck = 1;
  211373. controller->framesOverlap = 3;
  211374. bool passed = false;
  211375. memset (rb->buffer, 0xcd, rb->bufferSize);
  211376. if (controller->read (rb))
  211377. {
  211378. passed = true;
  211379. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211380. int wrong = 0;
  211381. for (int i = rb->dataLength / 4; --i >= 0;)
  211382. {
  211383. if (*p++ == (int) 0xcdcdcdcd)
  211384. {
  211385. if (++wrong == 4)
  211386. {
  211387. passed = false;
  211388. break;
  211389. }
  211390. }
  211391. else
  211392. {
  211393. wrong = 0;
  211394. }
  211395. }
  211396. }
  211397. if (! passed)
  211398. {
  211399. controller->shutDown();
  211400. controller = 0;
  211401. }
  211402. return passed;
  211403. }
  211404. void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211405. {
  211406. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211407. const int bufSize = 128;
  211408. BYTE buffer[bufSize];
  211409. zeromem (buffer, bufSize);
  211410. SRB_ExecSCSICmd s;
  211411. zerostruct (s);
  211412. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211413. s.SRB_HaID = ha;
  211414. s.SRB_Target = tgt;
  211415. s.SRB_Lun = lun;
  211416. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211417. s.SRB_BufLen = bufSize;
  211418. s.SRB_BufPointer = buffer;
  211419. s.SRB_SenseLen = SENSE_LEN;
  211420. s.SRB_CDBLen = 6;
  211421. s.SRB_PostProc = event;
  211422. s.CDBByte[0] = SCSI_INQUIRY;
  211423. s.CDBByte[4] = 100;
  211424. ResetEvent (event);
  211425. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211426. WaitForSingleObject (event, 4000);
  211427. CloseHandle (event);
  211428. if (s.SRB_Status == SS_COMP)
  211429. {
  211430. memcpy (dev->vendor, &buffer[8], 8);
  211431. memcpy (dev->productId, &buffer[16], 16);
  211432. memcpy (dev->rev, &buffer[32], 4);
  211433. memcpy (dev->vendorSpec, &buffer[36], 20);
  211434. }
  211435. }
  211436. int FindCDDevices (CDDeviceInfo* const list, int maxItems)
  211437. {
  211438. int count = 0;
  211439. if (usingScsi)
  211440. {
  211441. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211442. {
  211443. TCHAR drivePath[8];
  211444. drivePath[0] = driveLetter;
  211445. drivePath[1] = ':';
  211446. drivePath[2] = '\\';
  211447. drivePath[3] = 0;
  211448. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211449. {
  211450. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211451. if (h != INVALID_HANDLE_VALUE)
  211452. {
  211453. BYTE buffer[100], passThroughStruct[1024];
  211454. zeromem (buffer, sizeof (buffer));
  211455. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211456. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211457. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211458. p->spt.CdbLength = 6;
  211459. p->spt.SenseInfoLength = 24;
  211460. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211461. p->spt.DataTransferLength = 100;
  211462. p->spt.TimeOutValue = 2;
  211463. p->spt.DataBuffer = buffer;
  211464. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211465. p->spt.Cdb[0] = 0x12;
  211466. p->spt.Cdb[4] = 100;
  211467. DWORD bytesReturned = 0;
  211468. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211469. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211470. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211471. &bytesReturned, 0) != 0)
  211472. {
  211473. zeromem (&list[count], sizeof (CDDeviceInfo));
  211474. list[count].scsiDriveLetter = driveLetter;
  211475. memcpy (list[count].vendor, &buffer[8], 8);
  211476. memcpy (list[count].productId, &buffer[16], 16);
  211477. memcpy (list[count].rev, &buffer[32], 4);
  211478. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211479. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211480. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211481. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211482. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211483. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211484. &bytesReturned, 0) != 0)
  211485. {
  211486. list[count].ha = scsiAddr->PortNumber;
  211487. list[count].tgt = scsiAddr->TargetId;
  211488. list[count].lun = scsiAddr->Lun;
  211489. ++count;
  211490. }
  211491. }
  211492. CloseHandle (h);
  211493. }
  211494. }
  211495. }
  211496. }
  211497. else
  211498. {
  211499. const DWORD d = fGetASPI32SupportInfo();
  211500. BYTE status = HIBYTE (LOWORD (d));
  211501. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211502. return 0;
  211503. const int numAdapters = LOBYTE (LOWORD (d));
  211504. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211505. {
  211506. SRB_HAInquiry s;
  211507. zerostruct (s);
  211508. s.SRB_Cmd = SC_HA_INQUIRY;
  211509. s.SRB_HaID = ha;
  211510. fSendASPI32Command ((LPSRB)&s);
  211511. if (s.SRB_Status == SS_COMP)
  211512. {
  211513. maxItems = (int)s.HA_Unique[3];
  211514. if (maxItems == 0)
  211515. maxItems = 8;
  211516. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211517. {
  211518. for (BYTE lun = 0; lun < 8; ++lun)
  211519. {
  211520. SRB_GDEVBlock sb;
  211521. zerostruct (sb);
  211522. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211523. sb.SRB_HaID = ha;
  211524. sb.SRB_Target = tgt;
  211525. sb.SRB_Lun = lun;
  211526. fSendASPI32Command ((LPSRB) &sb);
  211527. if (sb.SRB_Status == SS_COMP
  211528. && sb.SRB_DeviceType == DTYPE_CROM)
  211529. {
  211530. zeromem (&list[count], sizeof (CDDeviceInfo));
  211531. list[count].ha = ha;
  211532. list[count].tgt = tgt;
  211533. list[count].lun = lun;
  211534. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211535. ++count;
  211536. }
  211537. }
  211538. }
  211539. }
  211540. }
  211541. }
  211542. return count;
  211543. }
  211544. static int ripperUsers = 0;
  211545. static bool initialisedOk = false;
  211546. class DeinitialiseTimer : private Timer,
  211547. private DeletedAtShutdown
  211548. {
  211549. public:
  211550. DeinitialiseTimer()
  211551. {
  211552. startTimer (4000);
  211553. }
  211554. ~DeinitialiseTimer()
  211555. {
  211556. if (--ripperUsers == 0)
  211557. DeinitialiseCDRipper();
  211558. }
  211559. void timerCallback()
  211560. {
  211561. delete this;
  211562. }
  211563. private:
  211564. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DeinitialiseTimer);
  211565. };
  211566. static void incUserCount()
  211567. {
  211568. if (ripperUsers++ == 0)
  211569. initialisedOk = InitialiseCDRipper();
  211570. }
  211571. static void decUserCount()
  211572. {
  211573. new DeinitialiseTimer();
  211574. }
  211575. struct CDDeviceWrapper
  211576. {
  211577. ScopedPointer<CDDeviceHandle> cdH;
  211578. ScopedPointer<CDReadBuffer> overlapBuffer;
  211579. bool jitter;
  211580. };
  211581. int getAddressOf (const TOCTRACK* const t)
  211582. {
  211583. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211584. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211585. }
  211586. static const int samplesPerFrame = 44100 / 75;
  211587. static const int bytesPerFrame = samplesPerFrame * 4;
  211588. CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211589. {
  211590. SRB_GDEVBlock s;
  211591. zerostruct (s);
  211592. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211593. s.SRB_HaID = device->ha;
  211594. s.SRB_Target = device->tgt;
  211595. s.SRB_Lun = device->lun;
  211596. if (usingScsi)
  211597. {
  211598. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211599. if (h != INVALID_HANDLE_VALUE)
  211600. {
  211601. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211602. cdh->scsiHandle = h;
  211603. return cdh;
  211604. }
  211605. }
  211606. else
  211607. {
  211608. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211609. && s.SRB_DeviceType == DTYPE_CROM)
  211610. {
  211611. return new CDDeviceHandle (device);
  211612. }
  211613. }
  211614. return 0;
  211615. }
  211616. }
  211617. const StringArray AudioCDReader::getAvailableCDNames()
  211618. {
  211619. using namespace CDReaderHelpers;
  211620. StringArray results;
  211621. incUserCount();
  211622. if (initialisedOk)
  211623. {
  211624. CDDeviceInfo list[8];
  211625. const int num = FindCDDevices (list, 8);
  211626. decUserCount();
  211627. for (int i = 0; i < num; ++i)
  211628. {
  211629. String s;
  211630. if (list[i].scsiDriveLetter > 0)
  211631. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211632. s << String (list[i].vendor).trim()
  211633. << ' ' << String (list[i].productId).trim()
  211634. << ' ' << String (list[i].rev).trim();
  211635. results.add (s);
  211636. }
  211637. }
  211638. return results;
  211639. }
  211640. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211641. {
  211642. using namespace CDReaderHelpers;
  211643. incUserCount();
  211644. if (initialisedOk)
  211645. {
  211646. CDDeviceInfo list[8];
  211647. const int num = FindCDDevices (list, 8);
  211648. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211649. {
  211650. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211651. if (handle != 0)
  211652. {
  211653. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211654. d->cdH = handle;
  211655. d->overlapBuffer = new CDReadBuffer(3);
  211656. return new AudioCDReader (d);
  211657. }
  211658. }
  211659. }
  211660. decUserCount();
  211661. return 0;
  211662. }
  211663. AudioCDReader::AudioCDReader (void* handle_)
  211664. : AudioFormatReader (0, "CD Audio"),
  211665. handle (handle_),
  211666. indexingEnabled (false),
  211667. lastIndex (0),
  211668. firstFrameInBuffer (0),
  211669. samplesInBuffer (0)
  211670. {
  211671. using namespace CDReaderHelpers;
  211672. jassert (handle_ != 0);
  211673. refreshTrackLengths();
  211674. sampleRate = 44100.0;
  211675. bitsPerSample = 16;
  211676. numChannels = 2;
  211677. usesFloatingPointData = false;
  211678. buffer.setSize (4 * bytesPerFrame, true);
  211679. }
  211680. AudioCDReader::~AudioCDReader()
  211681. {
  211682. using namespace CDReaderHelpers;
  211683. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211684. delete device;
  211685. decUserCount();
  211686. }
  211687. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211688. int64 startSampleInFile, int numSamples)
  211689. {
  211690. using namespace CDReaderHelpers;
  211691. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211692. bool ok = true;
  211693. while (numSamples > 0)
  211694. {
  211695. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211696. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211697. if (startSampleInFile >= bufferStartSample
  211698. && startSampleInFile < bufferEndSample)
  211699. {
  211700. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211701. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211702. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211703. const short* src = (const short*) buffer.getData();
  211704. src += 2 * (startSampleInFile - bufferStartSample);
  211705. for (int i = 0; i < toDo; ++i)
  211706. {
  211707. l[i] = src [i << 1] << 16;
  211708. if (r != 0)
  211709. r[i] = src [(i << 1) + 1] << 16;
  211710. }
  211711. startOffsetInDestBuffer += toDo;
  211712. startSampleInFile += toDo;
  211713. numSamples -= toDo;
  211714. }
  211715. else
  211716. {
  211717. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211718. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211719. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211720. {
  211721. device->overlapBuffer->dataLength = 0;
  211722. device->overlapBuffer->startFrame = 0;
  211723. device->overlapBuffer->numFrames = 0;
  211724. device->jitter = false;
  211725. }
  211726. firstFrameInBuffer = frameNeeded;
  211727. lastIndex = 0;
  211728. CDReadBuffer readBuffer (framesInBuffer + 4);
  211729. readBuffer.wantsIndex = indexingEnabled;
  211730. int i;
  211731. for (i = 5; --i >= 0;)
  211732. {
  211733. readBuffer.startFrame = frameNeeded;
  211734. readBuffer.numFrames = framesInBuffer;
  211735. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  211736. break;
  211737. else
  211738. device->overlapBuffer->dataLength = 0;
  211739. }
  211740. if (i >= 0)
  211741. {
  211742. memcpy ((char*) buffer.getData(),
  211743. readBuffer.buffer + readBuffer.dataStartOffset,
  211744. readBuffer.dataLength);
  211745. samplesInBuffer = readBuffer.dataLength >> 2;
  211746. lastIndex = readBuffer.index;
  211747. }
  211748. else
  211749. {
  211750. int* l = destSamples[0] + startOffsetInDestBuffer;
  211751. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211752. while (--numSamples >= 0)
  211753. {
  211754. *l++ = 0;
  211755. if (r != 0)
  211756. *r++ = 0;
  211757. }
  211758. // sometimes the read fails for just the very last couple of blocks, so
  211759. // we'll ignore and errors in the last half-second of the disk..
  211760. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211761. break;
  211762. }
  211763. }
  211764. }
  211765. return ok;
  211766. }
  211767. bool AudioCDReader::isCDStillPresent() const
  211768. {
  211769. using namespace CDReaderHelpers;
  211770. TOC toc;
  211771. zerostruct (toc);
  211772. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  211773. }
  211774. void AudioCDReader::refreshTrackLengths()
  211775. {
  211776. using namespace CDReaderHelpers;
  211777. trackStartSamples.clear();
  211778. zeromem (audioTracks, sizeof (audioTracks));
  211779. TOC toc;
  211780. zerostruct (toc);
  211781. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  211782. {
  211783. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211784. for (int i = 0; i <= numTracks; ++i)
  211785. {
  211786. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  211787. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211788. }
  211789. }
  211790. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211791. }
  211792. bool AudioCDReader::isTrackAudio (int trackNum) const
  211793. {
  211794. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211795. }
  211796. void AudioCDReader::enableIndexScanning (bool b)
  211797. {
  211798. indexingEnabled = b;
  211799. }
  211800. int AudioCDReader::getLastIndex() const
  211801. {
  211802. return lastIndex;
  211803. }
  211804. const int framesPerIndexRead = 4;
  211805. int AudioCDReader::getIndexAt (int samplePos)
  211806. {
  211807. using namespace CDReaderHelpers;
  211808. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211809. const int frameNeeded = samplePos / samplesPerFrame;
  211810. device->overlapBuffer->dataLength = 0;
  211811. device->overlapBuffer->startFrame = 0;
  211812. device->overlapBuffer->numFrames = 0;
  211813. device->jitter = false;
  211814. firstFrameInBuffer = 0;
  211815. lastIndex = 0;
  211816. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211817. readBuffer.wantsIndex = true;
  211818. int i;
  211819. for (i = 5; --i >= 0;)
  211820. {
  211821. readBuffer.startFrame = frameNeeded;
  211822. readBuffer.numFrames = framesPerIndexRead;
  211823. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211824. break;
  211825. }
  211826. if (i >= 0)
  211827. return readBuffer.index;
  211828. return -1;
  211829. }
  211830. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211831. {
  211832. using namespace CDReaderHelpers;
  211833. Array <int> indexes;
  211834. const int trackStart = getPositionOfTrackStart (trackNumber);
  211835. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211836. bool needToScan = true;
  211837. if (trackEnd - trackStart > 20 * 44100)
  211838. {
  211839. // check the end of the track for indexes before scanning the whole thing
  211840. needToScan = false;
  211841. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211842. bool seenAnIndex = false;
  211843. while (pos <= trackEnd - samplesPerFrame)
  211844. {
  211845. const int index = getIndexAt (pos);
  211846. if (index == 0)
  211847. {
  211848. // lead-out, so skip back a bit if we've not found any indexes yet..
  211849. if (seenAnIndex)
  211850. break;
  211851. pos -= 44100 * 5;
  211852. if (pos < trackStart)
  211853. break;
  211854. }
  211855. else
  211856. {
  211857. if (index > 0)
  211858. seenAnIndex = true;
  211859. if (index > 1)
  211860. {
  211861. needToScan = true;
  211862. break;
  211863. }
  211864. pos += samplesPerFrame * framesPerIndexRead;
  211865. }
  211866. }
  211867. }
  211868. if (needToScan)
  211869. {
  211870. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211871. int pos = trackStart;
  211872. int last = -1;
  211873. while (pos < trackEnd - samplesPerFrame * 10)
  211874. {
  211875. const int frameNeeded = pos / samplesPerFrame;
  211876. device->overlapBuffer->dataLength = 0;
  211877. device->overlapBuffer->startFrame = 0;
  211878. device->overlapBuffer->numFrames = 0;
  211879. device->jitter = false;
  211880. firstFrameInBuffer = 0;
  211881. CDReadBuffer readBuffer (4);
  211882. readBuffer.wantsIndex = true;
  211883. int i;
  211884. for (i = 5; --i >= 0;)
  211885. {
  211886. readBuffer.startFrame = frameNeeded;
  211887. readBuffer.numFrames = framesPerIndexRead;
  211888. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211889. break;
  211890. }
  211891. if (i < 0)
  211892. break;
  211893. if (readBuffer.index > last && readBuffer.index > 1)
  211894. {
  211895. last = readBuffer.index;
  211896. indexes.add (pos);
  211897. }
  211898. pos += samplesPerFrame * framesPerIndexRead;
  211899. }
  211900. indexes.removeValue (trackStart);
  211901. }
  211902. return indexes;
  211903. }
  211904. void AudioCDReader::ejectDisk()
  211905. {
  211906. using namespace CDReaderHelpers;
  211907. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  211908. }
  211909. #endif
  211910. #if JUCE_USE_CDBURNER
  211911. namespace CDBurnerHelpers
  211912. {
  211913. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211914. {
  211915. CoInitialize (0);
  211916. IDiscMaster* dm;
  211917. IDiscRecorder* result = 0;
  211918. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211919. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211920. IID_IDiscMaster,
  211921. (void**) &dm)))
  211922. {
  211923. if (SUCCEEDED (dm->Open()))
  211924. {
  211925. IEnumDiscRecorders* drEnum = 0;
  211926. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211927. {
  211928. IDiscRecorder* dr = 0;
  211929. DWORD dummy;
  211930. int index = 0;
  211931. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211932. {
  211933. if (indexToOpen == index)
  211934. {
  211935. result = dr;
  211936. break;
  211937. }
  211938. else if (list != 0)
  211939. {
  211940. BSTR path;
  211941. if (SUCCEEDED (dr->GetPath (&path)))
  211942. list->add ((const WCHAR*) path);
  211943. }
  211944. ++index;
  211945. dr->Release();
  211946. }
  211947. drEnum->Release();
  211948. }
  211949. if (master == 0)
  211950. dm->Close();
  211951. }
  211952. if (master != 0)
  211953. *master = dm;
  211954. else
  211955. dm->Release();
  211956. }
  211957. return result;
  211958. }
  211959. }
  211960. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211961. public Timer
  211962. {
  211963. public:
  211964. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211965. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211966. listener (0), progress (0), shouldCancel (false)
  211967. {
  211968. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211969. jassert (SUCCEEDED (hr));
  211970. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211971. //jassert (SUCCEEDED (hr));
  211972. lastState = getDiskState();
  211973. startTimer (2000);
  211974. }
  211975. ~Pimpl() {}
  211976. void releaseObjects()
  211977. {
  211978. discRecorder->Close();
  211979. if (redbook != 0)
  211980. redbook->Release();
  211981. discRecorder->Release();
  211982. discMaster->Release();
  211983. Release();
  211984. }
  211985. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211986. {
  211987. if (listener != 0 && ! shouldCancel)
  211988. shouldCancel = listener->audioCDBurnProgress (progress);
  211989. *pbCancel = shouldCancel;
  211990. return S_OK;
  211991. }
  211992. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211993. {
  211994. progress = nCompleted / (float) nTotal;
  211995. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211996. return E_NOTIMPL;
  211997. }
  211998. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211999. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212000. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212001. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212002. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212003. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212004. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212005. class ScopedDiscOpener
  212006. {
  212007. public:
  212008. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  212009. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  212010. private:
  212011. Pimpl& pimpl;
  212012. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  212013. };
  212014. DiskState getDiskState()
  212015. {
  212016. const ScopedDiscOpener opener (*this);
  212017. long type, flags;
  212018. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  212019. if (FAILED (hr))
  212020. return unknown;
  212021. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  212022. return writableDiskPresent;
  212023. if (type == 0)
  212024. return noDisc;
  212025. else
  212026. return readOnlyDiskPresent;
  212027. }
  212028. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  212029. {
  212030. ComSmartPtr<IPropertyStorage> prop;
  212031. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212032. return defaultReturn;
  212033. PROPSPEC iPropSpec;
  212034. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212035. iPropSpec.lpwstr = name;
  212036. PROPVARIANT iPropVariant;
  212037. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  212038. ? defaultReturn : (int) iPropVariant.lVal;
  212039. }
  212040. bool setIntProperty (const LPOLESTR name, const int value) const
  212041. {
  212042. ComSmartPtr<IPropertyStorage> prop;
  212043. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212044. return false;
  212045. PROPSPEC iPropSpec;
  212046. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212047. iPropSpec.lpwstr = name;
  212048. PROPVARIANT iPropVariant;
  212049. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  212050. return false;
  212051. iPropVariant.lVal = (long) value;
  212052. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  212053. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  212054. }
  212055. void timerCallback()
  212056. {
  212057. const DiskState state = getDiskState();
  212058. if (state != lastState)
  212059. {
  212060. lastState = state;
  212061. owner.sendChangeMessage();
  212062. }
  212063. }
  212064. AudioCDBurner& owner;
  212065. DiskState lastState;
  212066. IDiscMaster* discMaster;
  212067. IDiscRecorder* discRecorder;
  212068. IRedbookDiscMaster* redbook;
  212069. AudioCDBurner::BurnProgressListener* listener;
  212070. float progress;
  212071. bool shouldCancel;
  212072. };
  212073. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212074. {
  212075. IDiscMaster* discMaster = 0;
  212076. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  212077. if (discRecorder != 0)
  212078. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212079. }
  212080. AudioCDBurner::~AudioCDBurner()
  212081. {
  212082. if (pimpl != 0)
  212083. pimpl.release()->releaseObjects();
  212084. }
  212085. const StringArray AudioCDBurner::findAvailableDevices()
  212086. {
  212087. StringArray devs;
  212088. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  212089. return devs;
  212090. }
  212091. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212092. {
  212093. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212094. if (b->pimpl == 0)
  212095. b = 0;
  212096. return b.release();
  212097. }
  212098. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212099. {
  212100. return pimpl->getDiskState();
  212101. }
  212102. bool AudioCDBurner::isDiskPresent() const
  212103. {
  212104. return getDiskState() == writableDiskPresent;
  212105. }
  212106. bool AudioCDBurner::openTray()
  212107. {
  212108. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212109. return SUCCEEDED (pimpl->discRecorder->Eject());
  212110. }
  212111. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212112. {
  212113. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212114. DiskState oldState = getDiskState();
  212115. DiskState newState = oldState;
  212116. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212117. {
  212118. newState = getDiskState();
  212119. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212120. }
  212121. return newState;
  212122. }
  212123. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212124. {
  212125. Array<int> results;
  212126. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212127. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212128. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212129. if (speeds[i] <= maxSpeed)
  212130. results.add (speeds[i]);
  212131. results.addIfNotAlreadyThere (maxSpeed);
  212132. return results;
  212133. }
  212134. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212135. {
  212136. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212137. return false;
  212138. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212139. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212140. }
  212141. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212142. {
  212143. long blocksFree = 0;
  212144. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212145. return blocksFree;
  212146. }
  212147. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212148. bool performFakeBurnForTesting, int writeSpeed)
  212149. {
  212150. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212151. pimpl->listener = listener;
  212152. pimpl->progress = 0;
  212153. pimpl->shouldCancel = false;
  212154. UINT_PTR cookie;
  212155. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212156. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212157. ejectDiscAfterwards);
  212158. String error;
  212159. if (hr != S_OK)
  212160. {
  212161. const char* e = "Couldn't open or write to the CD device";
  212162. if (hr == IMAPI_E_USERABORT)
  212163. e = "User cancelled the write operation";
  212164. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212165. e = "No Disk present";
  212166. error = e;
  212167. }
  212168. pimpl->discMaster->ProgressUnadvise (cookie);
  212169. pimpl->listener = 0;
  212170. return error;
  212171. }
  212172. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212173. {
  212174. if (audioSource == 0)
  212175. return false;
  212176. ScopedPointer<AudioSource> source (audioSource);
  212177. long bytesPerBlock;
  212178. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212179. const int samplesPerBlock = bytesPerBlock / 4;
  212180. bool ok = true;
  212181. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212182. HeapBlock <byte> buffer (bytesPerBlock);
  212183. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212184. int samplesDone = 0;
  212185. source->prepareToPlay (samplesPerBlock, 44100.0);
  212186. while (ok)
  212187. {
  212188. {
  212189. AudioSourceChannelInfo info;
  212190. info.buffer = &sourceBuffer;
  212191. info.numSamples = samplesPerBlock;
  212192. info.startSample = 0;
  212193. sourceBuffer.clear();
  212194. source->getNextAudioBlock (info);
  212195. }
  212196. zeromem (buffer, bytesPerBlock);
  212197. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212198. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212199. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212200. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212201. CDSampleFormat left (buffer, 2);
  212202. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212203. CDSampleFormat right (buffer + 2, 2);
  212204. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212205. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212206. if (FAILED (hr))
  212207. ok = false;
  212208. samplesDone += samplesPerBlock;
  212209. if (samplesDone >= numSamples)
  212210. break;
  212211. }
  212212. hr = pimpl->redbook->CloseAudioTrack();
  212213. return ok && hr == S_OK;
  212214. }
  212215. #endif
  212216. #endif
  212217. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212218. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212219. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212220. // compiled on its own).
  212221. #if JUCE_INCLUDED_FILE
  212222. class MidiInCollector
  212223. {
  212224. public:
  212225. MidiInCollector (MidiInput* const input_,
  212226. MidiInputCallback& callback_)
  212227. : deviceHandle (0),
  212228. input (input_),
  212229. callback (callback_),
  212230. concatenator (4096),
  212231. isStarted (false),
  212232. startTime (0)
  212233. {
  212234. }
  212235. ~MidiInCollector()
  212236. {
  212237. stop();
  212238. if (deviceHandle != 0)
  212239. {
  212240. int count = 5;
  212241. while (--count >= 0)
  212242. {
  212243. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212244. break;
  212245. Sleep (20);
  212246. }
  212247. }
  212248. }
  212249. void handleMessage (const uint32 message, const uint32 timeStamp)
  212250. {
  212251. if ((message & 0xff) >= 0x80 && isStarted)
  212252. {
  212253. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212254. writeFinishedBlocks();
  212255. }
  212256. }
  212257. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212258. {
  212259. if (isStarted)
  212260. {
  212261. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212262. writeFinishedBlocks();
  212263. }
  212264. }
  212265. void start()
  212266. {
  212267. jassert (deviceHandle != 0);
  212268. if (deviceHandle != 0 && ! isStarted)
  212269. {
  212270. activeMidiCollectors.addIfNotAlreadyThere (this);
  212271. for (int i = 0; i < (int) numHeaders; ++i)
  212272. headers[i].write (deviceHandle);
  212273. startTime = Time::getMillisecondCounter();
  212274. MMRESULT res = midiInStart (deviceHandle);
  212275. if (res == MMSYSERR_NOERROR)
  212276. {
  212277. concatenator.reset();
  212278. isStarted = true;
  212279. }
  212280. else
  212281. {
  212282. unprepareAllHeaders();
  212283. }
  212284. }
  212285. }
  212286. void stop()
  212287. {
  212288. if (isStarted)
  212289. {
  212290. isStarted = false;
  212291. midiInReset (deviceHandle);
  212292. midiInStop (deviceHandle);
  212293. activeMidiCollectors.removeValue (this);
  212294. unprepareAllHeaders();
  212295. concatenator.reset();
  212296. }
  212297. }
  212298. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212299. {
  212300. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212301. if (activeMidiCollectors.contains (collector))
  212302. {
  212303. if (uMsg == MIM_DATA)
  212304. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212305. else if (uMsg == MIM_LONGDATA)
  212306. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212307. }
  212308. }
  212309. HMIDIIN deviceHandle;
  212310. private:
  212311. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212312. MidiInput* input;
  212313. MidiInputCallback& callback;
  212314. MidiDataConcatenator concatenator;
  212315. bool volatile isStarted;
  212316. uint32 startTime;
  212317. class MidiHeader
  212318. {
  212319. public:
  212320. MidiHeader()
  212321. {
  212322. zerostruct (hdr);
  212323. hdr.lpData = data;
  212324. hdr.dwBufferLength = numElementsInArray (data);
  212325. }
  212326. void write (HMIDIIN deviceHandle)
  212327. {
  212328. hdr.dwBytesRecorded = 0;
  212329. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212330. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212331. }
  212332. void writeIfFinished (HMIDIIN deviceHandle)
  212333. {
  212334. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212335. {
  212336. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212337. (void) res;
  212338. write (deviceHandle);
  212339. }
  212340. }
  212341. void unprepare (HMIDIIN deviceHandle)
  212342. {
  212343. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212344. {
  212345. int c = 10;
  212346. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212347. Thread::sleep (20);
  212348. jassert (c >= 0);
  212349. }
  212350. }
  212351. private:
  212352. MIDIHDR hdr;
  212353. char data [256];
  212354. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  212355. };
  212356. enum { numHeaders = 32 };
  212357. MidiHeader headers [numHeaders];
  212358. void writeFinishedBlocks()
  212359. {
  212360. for (int i = 0; i < (int) numHeaders; ++i)
  212361. headers[i].writeIfFinished (deviceHandle);
  212362. }
  212363. void unprepareAllHeaders()
  212364. {
  212365. for (int i = 0; i < (int) numHeaders; ++i)
  212366. headers[i].unprepare (deviceHandle);
  212367. }
  212368. double convertTimeStamp (uint32 timeStamp)
  212369. {
  212370. timeStamp += startTime;
  212371. const uint32 now = Time::getMillisecondCounter();
  212372. if (timeStamp > now)
  212373. {
  212374. if (timeStamp > now + 2)
  212375. --startTime;
  212376. timeStamp = now;
  212377. }
  212378. return timeStamp * 0.001;
  212379. }
  212380. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  212381. };
  212382. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212383. const StringArray MidiInput::getDevices()
  212384. {
  212385. StringArray s;
  212386. const int num = midiInGetNumDevs();
  212387. for (int i = 0; i < num; ++i)
  212388. {
  212389. MIDIINCAPS mc;
  212390. zerostruct (mc);
  212391. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212392. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212393. }
  212394. return s;
  212395. }
  212396. int MidiInput::getDefaultDeviceIndex()
  212397. {
  212398. return 0;
  212399. }
  212400. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212401. {
  212402. if (callback == 0)
  212403. return 0;
  212404. UINT deviceId = MIDI_MAPPER;
  212405. int n = 0;
  212406. String name;
  212407. const int num = midiInGetNumDevs();
  212408. for (int i = 0; i < num; ++i)
  212409. {
  212410. MIDIINCAPS mc;
  212411. zerostruct (mc);
  212412. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212413. {
  212414. if (index == n)
  212415. {
  212416. deviceId = i;
  212417. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212418. break;
  212419. }
  212420. ++n;
  212421. }
  212422. }
  212423. ScopedPointer <MidiInput> in (new MidiInput (name));
  212424. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212425. HMIDIIN h;
  212426. HRESULT err = midiInOpen (&h, deviceId,
  212427. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212428. (DWORD_PTR) (MidiInCollector*) collector,
  212429. CALLBACK_FUNCTION);
  212430. if (err == MMSYSERR_NOERROR)
  212431. {
  212432. collector->deviceHandle = h;
  212433. in->internal = collector.release();
  212434. return in.release();
  212435. }
  212436. return 0;
  212437. }
  212438. MidiInput::MidiInput (const String& name_)
  212439. : name (name_),
  212440. internal (0)
  212441. {
  212442. }
  212443. MidiInput::~MidiInput()
  212444. {
  212445. delete static_cast <MidiInCollector*> (internal);
  212446. }
  212447. void MidiInput::start()
  212448. {
  212449. static_cast <MidiInCollector*> (internal)->start();
  212450. }
  212451. void MidiInput::stop()
  212452. {
  212453. static_cast <MidiInCollector*> (internal)->stop();
  212454. }
  212455. struct MidiOutHandle
  212456. {
  212457. int refCount;
  212458. UINT deviceId;
  212459. HMIDIOUT handle;
  212460. static Array<MidiOutHandle*> activeHandles;
  212461. private:
  212462. JUCE_LEAK_DETECTOR (MidiOutHandle);
  212463. };
  212464. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212465. const StringArray MidiOutput::getDevices()
  212466. {
  212467. StringArray s;
  212468. const int num = midiOutGetNumDevs();
  212469. for (int i = 0; i < num; ++i)
  212470. {
  212471. MIDIOUTCAPS mc;
  212472. zerostruct (mc);
  212473. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212474. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212475. }
  212476. return s;
  212477. }
  212478. int MidiOutput::getDefaultDeviceIndex()
  212479. {
  212480. const int num = midiOutGetNumDevs();
  212481. int n = 0;
  212482. for (int i = 0; i < num; ++i)
  212483. {
  212484. MIDIOUTCAPS mc;
  212485. zerostruct (mc);
  212486. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212487. {
  212488. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212489. return n;
  212490. ++n;
  212491. }
  212492. }
  212493. return 0;
  212494. }
  212495. MidiOutput* MidiOutput::openDevice (int index)
  212496. {
  212497. UINT deviceId = MIDI_MAPPER;
  212498. const int num = midiOutGetNumDevs();
  212499. int i, n = 0;
  212500. for (i = 0; i < num; ++i)
  212501. {
  212502. MIDIOUTCAPS mc;
  212503. zerostruct (mc);
  212504. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212505. {
  212506. // use the microsoft sw synth as a default - best not to allow deviceId
  212507. // to be MIDI_MAPPER, or else device sharing breaks
  212508. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212509. deviceId = i;
  212510. if (index == n)
  212511. {
  212512. deviceId = i;
  212513. break;
  212514. }
  212515. ++n;
  212516. }
  212517. }
  212518. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212519. {
  212520. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212521. if (han != 0 && han->deviceId == deviceId)
  212522. {
  212523. han->refCount++;
  212524. MidiOutput* const out = new MidiOutput();
  212525. out->internal = han;
  212526. return out;
  212527. }
  212528. }
  212529. for (i = 4; --i >= 0;)
  212530. {
  212531. HMIDIOUT h = 0;
  212532. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212533. if (res == MMSYSERR_NOERROR)
  212534. {
  212535. MidiOutHandle* const han = new MidiOutHandle();
  212536. han->deviceId = deviceId;
  212537. han->refCount = 1;
  212538. han->handle = h;
  212539. MidiOutHandle::activeHandles.add (han);
  212540. MidiOutput* const out = new MidiOutput();
  212541. out->internal = han;
  212542. return out;
  212543. }
  212544. else if (res == MMSYSERR_ALLOCATED)
  212545. {
  212546. Sleep (100);
  212547. }
  212548. else
  212549. {
  212550. break;
  212551. }
  212552. }
  212553. return 0;
  212554. }
  212555. MidiOutput::~MidiOutput()
  212556. {
  212557. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212558. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212559. {
  212560. midiOutClose (h->handle);
  212561. MidiOutHandle::activeHandles.removeValue (h);
  212562. delete h;
  212563. }
  212564. }
  212565. void MidiOutput::reset()
  212566. {
  212567. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212568. midiOutReset (h->handle);
  212569. }
  212570. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212571. {
  212572. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212573. DWORD n;
  212574. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212575. {
  212576. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212577. rightVol = nn[0] / (float) 0xffff;
  212578. leftVol = nn[1] / (float) 0xffff;
  212579. return true;
  212580. }
  212581. else
  212582. {
  212583. rightVol = leftVol = 1.0f;
  212584. return false;
  212585. }
  212586. }
  212587. void MidiOutput::setVolume (float leftVol, float rightVol)
  212588. {
  212589. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212590. DWORD n;
  212591. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212592. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212593. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212594. midiOutSetVolume (handle->handle, n);
  212595. }
  212596. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212597. {
  212598. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212599. if (message.getRawDataSize() > 3
  212600. || message.isSysEx())
  212601. {
  212602. MIDIHDR h;
  212603. zerostruct (h);
  212604. h.lpData = (char*) message.getRawData();
  212605. h.dwBufferLength = message.getRawDataSize();
  212606. h.dwBytesRecorded = message.getRawDataSize();
  212607. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212608. {
  212609. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212610. if (res == MMSYSERR_NOERROR)
  212611. {
  212612. while ((h.dwFlags & MHDR_DONE) == 0)
  212613. Sleep (1);
  212614. int count = 500; // 1 sec timeout
  212615. while (--count >= 0)
  212616. {
  212617. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212618. if (res == MIDIERR_STILLPLAYING)
  212619. Sleep (2);
  212620. else
  212621. break;
  212622. }
  212623. }
  212624. }
  212625. }
  212626. else
  212627. {
  212628. midiOutShortMsg (handle->handle,
  212629. *(unsigned int*) message.getRawData());
  212630. }
  212631. }
  212632. #endif
  212633. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212634. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212635. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212636. // compiled on its own).
  212637. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212638. #undef WINDOWS
  212639. // #define ASIO_DEBUGGING 1
  212640. #undef log
  212641. #if ASIO_DEBUGGING
  212642. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212643. #else
  212644. #define log(a) {}
  212645. #endif
  212646. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  212647. to be pretty random about whether or not they do this. If you hit an error using these functions
  212648. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  212649. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  212650. */
  212651. #define JUCE_ASIOCALLBACK __cdecl
  212652. namespace ASIODebugging
  212653. {
  212654. #if ASIO_DEBUGGING
  212655. static void log (const String& context, long error)
  212656. {
  212657. String err ("unknown error");
  212658. if (error == ASE_NotPresent) err = "Not Present";
  212659. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212660. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212661. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212662. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212663. else if (error == ASE_NoClock) err = "No Clock";
  212664. else if (error == ASE_NoMemory) err = "Out of memory";
  212665. log ("!!error: " + context + " - " + err);
  212666. }
  212667. #define logError(a, b) ASIODebugging::log ((a), (b))
  212668. #else
  212669. #define logError(a, b) {}
  212670. #endif
  212671. }
  212672. class ASIOAudioIODevice;
  212673. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212674. static const int maxASIOChannels = 160;
  212675. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212676. private Timer
  212677. {
  212678. public:
  212679. Component ourWindow;
  212680. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212681. const String& optionalDllForDirectLoading_)
  212682. : AudioIODevice (name_, "ASIO"),
  212683. asioObject (0),
  212684. classId (classId_),
  212685. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212686. currentBitDepth (16),
  212687. currentSampleRate (0),
  212688. isOpen_ (false),
  212689. isStarted (false),
  212690. postOutput (true),
  212691. insideControlPanelModalLoop (false),
  212692. shouldUsePreferredSize (false)
  212693. {
  212694. name = name_;
  212695. ourWindow.addToDesktop (0);
  212696. windowHandle = ourWindow.getWindowHandle();
  212697. jassert (currentASIODev [slotNumber] == 0);
  212698. currentASIODev [slotNumber] = this;
  212699. openDevice();
  212700. }
  212701. ~ASIOAudioIODevice()
  212702. {
  212703. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212704. if (currentASIODev[i] == this)
  212705. currentASIODev[i] = 0;
  212706. close();
  212707. log ("ASIO - exiting");
  212708. removeCurrentDriver();
  212709. }
  212710. void updateSampleRates()
  212711. {
  212712. // find a list of sample rates..
  212713. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212714. sampleRates.clear();
  212715. if (asioObject != 0)
  212716. {
  212717. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212718. {
  212719. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212720. if (err == 0)
  212721. {
  212722. sampleRates.add ((int) possibleSampleRates[index]);
  212723. log ("rate: " + String ((int) possibleSampleRates[index]));
  212724. }
  212725. else if (err != ASE_NoClock)
  212726. {
  212727. logError ("CanSampleRate", err);
  212728. }
  212729. }
  212730. if (sampleRates.size() == 0)
  212731. {
  212732. double cr = 0;
  212733. const long err = asioObject->getSampleRate (&cr);
  212734. log ("No sample rates supported - current rate: " + String ((int) cr));
  212735. if (err == 0)
  212736. sampleRates.add ((int) cr);
  212737. }
  212738. }
  212739. }
  212740. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212741. const StringArray getInputChannelNames() { return inputChannelNames; }
  212742. int getNumSampleRates() { return sampleRates.size(); }
  212743. double getSampleRate (int index) { return sampleRates [index]; }
  212744. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212745. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212746. int getDefaultBufferSize() { return preferredSize; }
  212747. const String open (const BigInteger& inputChannels,
  212748. const BigInteger& outputChannels,
  212749. double sr,
  212750. int bufferSizeSamples)
  212751. {
  212752. close();
  212753. currentCallback = 0;
  212754. if (bufferSizeSamples <= 0)
  212755. shouldUsePreferredSize = true;
  212756. if (asioObject == 0 || ! isASIOOpen)
  212757. {
  212758. log ("Warning: device not open");
  212759. const String err (openDevice());
  212760. if (asioObject == 0 || ! isASIOOpen)
  212761. return err;
  212762. }
  212763. isStarted = false;
  212764. bufferIndex = -1;
  212765. long err = 0;
  212766. long newPreferredSize = 0;
  212767. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212768. minSize = 0;
  212769. maxSize = 0;
  212770. newPreferredSize = 0;
  212771. granularity = 0;
  212772. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212773. {
  212774. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212775. shouldUsePreferredSize = true;
  212776. preferredSize = newPreferredSize;
  212777. }
  212778. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212779. // dynamic changes to the buffer size...
  212780. shouldUsePreferredSize = shouldUsePreferredSize
  212781. || getName().containsIgnoreCase ("Digidesign");
  212782. if (shouldUsePreferredSize)
  212783. {
  212784. log ("Using preferred size for buffer..");
  212785. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212786. {
  212787. bufferSizeSamples = preferredSize;
  212788. }
  212789. else
  212790. {
  212791. bufferSizeSamples = 1024;
  212792. logError ("GetBufferSize1", err);
  212793. }
  212794. shouldUsePreferredSize = false;
  212795. }
  212796. int sampleRate = roundDoubleToInt (sr);
  212797. currentSampleRate = sampleRate;
  212798. currentBlockSizeSamples = bufferSizeSamples;
  212799. currentChansOut.clear();
  212800. currentChansIn.clear();
  212801. zeromem (inBuffers, sizeof (inBuffers));
  212802. zeromem (outBuffers, sizeof (outBuffers));
  212803. updateSampleRates();
  212804. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212805. sampleRate = sampleRates[0];
  212806. jassert (sampleRate != 0);
  212807. if (sampleRate == 0)
  212808. sampleRate = 44100;
  212809. long numSources = 32;
  212810. ASIOClockSource clocks[32];
  212811. zeromem (clocks, sizeof (clocks));
  212812. asioObject->getClockSources (clocks, &numSources);
  212813. bool isSourceSet = false;
  212814. // careful not to remove this loop because it does more than just logging!
  212815. int i;
  212816. for (i = 0; i < numSources; ++i)
  212817. {
  212818. String s ("clock: ");
  212819. s += clocks[i].name;
  212820. if (clocks[i].isCurrentSource)
  212821. {
  212822. isSourceSet = true;
  212823. s << " (cur)";
  212824. }
  212825. log (s);
  212826. }
  212827. if (numSources > 1 && ! isSourceSet)
  212828. {
  212829. log ("setting clock source");
  212830. asioObject->setClockSource (clocks[0].index);
  212831. Thread::sleep (20);
  212832. }
  212833. else
  212834. {
  212835. if (numSources == 0)
  212836. {
  212837. log ("ASIO - no clock sources!");
  212838. }
  212839. }
  212840. double cr = 0;
  212841. err = asioObject->getSampleRate (&cr);
  212842. if (err == 0)
  212843. {
  212844. currentSampleRate = cr;
  212845. }
  212846. else
  212847. {
  212848. logError ("GetSampleRate", err);
  212849. currentSampleRate = 0;
  212850. }
  212851. error = String::empty;
  212852. needToReset = false;
  212853. isReSync = false;
  212854. err = 0;
  212855. bool buffersCreated = false;
  212856. if (currentSampleRate != sampleRate)
  212857. {
  212858. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212859. err = asioObject->setSampleRate (sampleRate);
  212860. if (err == ASE_NoClock && numSources > 0)
  212861. {
  212862. log ("trying to set a clock source..");
  212863. Thread::sleep (10);
  212864. err = asioObject->setClockSource (clocks[0].index);
  212865. if (err != 0)
  212866. {
  212867. logError ("SetClock", err);
  212868. }
  212869. Thread::sleep (10);
  212870. err = asioObject->setSampleRate (sampleRate);
  212871. }
  212872. }
  212873. if (err == 0)
  212874. {
  212875. currentSampleRate = sampleRate;
  212876. if (needToReset)
  212877. {
  212878. if (isReSync)
  212879. {
  212880. log ("Resync request");
  212881. }
  212882. log ("! Resetting ASIO after sample rate change");
  212883. removeCurrentDriver();
  212884. loadDriver();
  212885. const String error (initDriver());
  212886. if (error.isNotEmpty())
  212887. {
  212888. log ("ASIOInit: " + error);
  212889. }
  212890. needToReset = false;
  212891. isReSync = false;
  212892. }
  212893. numActiveInputChans = 0;
  212894. numActiveOutputChans = 0;
  212895. ASIOBufferInfo* info = bufferInfos;
  212896. int i;
  212897. for (i = 0; i < totalNumInputChans; ++i)
  212898. {
  212899. if (inputChannels[i])
  212900. {
  212901. currentChansIn.setBit (i);
  212902. info->isInput = 1;
  212903. info->channelNum = i;
  212904. info->buffers[0] = info->buffers[1] = 0;
  212905. ++info;
  212906. ++numActiveInputChans;
  212907. }
  212908. }
  212909. for (i = 0; i < totalNumOutputChans; ++i)
  212910. {
  212911. if (outputChannels[i])
  212912. {
  212913. currentChansOut.setBit (i);
  212914. info->isInput = 0;
  212915. info->channelNum = i;
  212916. info->buffers[0] = info->buffers[1] = 0;
  212917. ++info;
  212918. ++numActiveOutputChans;
  212919. }
  212920. }
  212921. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212922. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212923. if (currentASIODev[0] == this)
  212924. {
  212925. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212926. callbacks.asioMessage = &asioMessagesCallback0;
  212927. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212928. }
  212929. else if (currentASIODev[1] == this)
  212930. {
  212931. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212932. callbacks.asioMessage = &asioMessagesCallback1;
  212933. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212934. }
  212935. else if (currentASIODev[2] == this)
  212936. {
  212937. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212938. callbacks.asioMessage = &asioMessagesCallback2;
  212939. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212940. }
  212941. else
  212942. {
  212943. jassertfalse;
  212944. }
  212945. log ("disposing buffers");
  212946. err = asioObject->disposeBuffers();
  212947. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212948. err = asioObject->createBuffers (bufferInfos,
  212949. totalBuffers,
  212950. currentBlockSizeSamples,
  212951. &callbacks);
  212952. if (err != 0)
  212953. {
  212954. currentBlockSizeSamples = preferredSize;
  212955. logError ("create buffers 2", err);
  212956. asioObject->disposeBuffers();
  212957. err = asioObject->createBuffers (bufferInfos,
  212958. totalBuffers,
  212959. currentBlockSizeSamples,
  212960. &callbacks);
  212961. }
  212962. if (err == 0)
  212963. {
  212964. buffersCreated = true;
  212965. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212966. int n = 0;
  212967. Array <int> types;
  212968. currentBitDepth = 16;
  212969. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212970. {
  212971. if (inputChannels[i])
  212972. {
  212973. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212974. ASIOChannelInfo channelInfo;
  212975. zerostruct (channelInfo);
  212976. channelInfo.channel = i;
  212977. channelInfo.isInput = 1;
  212978. asioObject->getChannelInfo (&channelInfo);
  212979. types.addIfNotAlreadyThere (channelInfo.type);
  212980. typeToFormatParameters (channelInfo.type,
  212981. inputChannelBitDepths[n],
  212982. inputChannelBytesPerSample[n],
  212983. inputChannelIsFloat[n],
  212984. inputChannelLittleEndian[n]);
  212985. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212986. ++n;
  212987. }
  212988. }
  212989. jassert (numActiveInputChans == n);
  212990. n = 0;
  212991. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212992. {
  212993. if (outputChannels[i])
  212994. {
  212995. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212996. ASIOChannelInfo channelInfo;
  212997. zerostruct (channelInfo);
  212998. channelInfo.channel = i;
  212999. channelInfo.isInput = 0;
  213000. asioObject->getChannelInfo (&channelInfo);
  213001. types.addIfNotAlreadyThere (channelInfo.type);
  213002. typeToFormatParameters (channelInfo.type,
  213003. outputChannelBitDepths[n],
  213004. outputChannelBytesPerSample[n],
  213005. outputChannelIsFloat[n],
  213006. outputChannelLittleEndian[n]);
  213007. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213008. ++n;
  213009. }
  213010. }
  213011. jassert (numActiveOutputChans == n);
  213012. for (i = types.size(); --i >= 0;)
  213013. {
  213014. log ("channel format: " + String (types[i]));
  213015. }
  213016. jassert (n <= totalBuffers);
  213017. for (i = 0; i < numActiveOutputChans; ++i)
  213018. {
  213019. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213020. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213021. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213022. {
  213023. log ("!! Null buffers");
  213024. }
  213025. else
  213026. {
  213027. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213028. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213029. }
  213030. }
  213031. inputLatency = outputLatency = 0;
  213032. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213033. {
  213034. log ("ASIO - no latencies");
  213035. }
  213036. else
  213037. {
  213038. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213039. }
  213040. isOpen_ = true;
  213041. log ("starting ASIO");
  213042. calledback = false;
  213043. err = asioObject->start();
  213044. if (err != 0)
  213045. {
  213046. isOpen_ = false;
  213047. log ("ASIO - stop on failure");
  213048. Thread::sleep (10);
  213049. asioObject->stop();
  213050. error = "Can't start device";
  213051. Thread::sleep (10);
  213052. }
  213053. else
  213054. {
  213055. int count = 300;
  213056. while (--count > 0 && ! calledback)
  213057. Thread::sleep (10);
  213058. isStarted = true;
  213059. if (! calledback)
  213060. {
  213061. error = "Device didn't start correctly";
  213062. log ("ASIO didn't callback - stopping..");
  213063. asioObject->stop();
  213064. }
  213065. }
  213066. }
  213067. else
  213068. {
  213069. error = "Can't create i/o buffers";
  213070. }
  213071. }
  213072. else
  213073. {
  213074. error = "Can't set sample rate: ";
  213075. error << sampleRate;
  213076. }
  213077. if (error.isNotEmpty())
  213078. {
  213079. logError (error, err);
  213080. if (asioObject != 0 && buffersCreated)
  213081. asioObject->disposeBuffers();
  213082. Thread::sleep (20);
  213083. isStarted = false;
  213084. isOpen_ = false;
  213085. const String errorCopy (error);
  213086. close(); // (this resets the error string)
  213087. error = errorCopy;
  213088. }
  213089. needToReset = false;
  213090. isReSync = false;
  213091. return error;
  213092. }
  213093. void close()
  213094. {
  213095. error = String::empty;
  213096. stopTimer();
  213097. stop();
  213098. if (isASIOOpen && isOpen_)
  213099. {
  213100. const ScopedLock sl (callbackLock);
  213101. isOpen_ = false;
  213102. isStarted = false;
  213103. needToReset = false;
  213104. isReSync = false;
  213105. log ("ASIO - stopping");
  213106. if (asioObject != 0)
  213107. {
  213108. Thread::sleep (20);
  213109. asioObject->stop();
  213110. Thread::sleep (10);
  213111. asioObject->disposeBuffers();
  213112. }
  213113. Thread::sleep (10);
  213114. }
  213115. }
  213116. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  213117. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  213118. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  213119. double getCurrentSampleRate() { return currentSampleRate; }
  213120. int getCurrentBitDepth() { return currentBitDepth; }
  213121. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  213122. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  213123. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  213124. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  213125. void start (AudioIODeviceCallback* callback)
  213126. {
  213127. if (callback != 0)
  213128. {
  213129. callback->audioDeviceAboutToStart (this);
  213130. const ScopedLock sl (callbackLock);
  213131. currentCallback = callback;
  213132. }
  213133. }
  213134. void stop()
  213135. {
  213136. AudioIODeviceCallback* const lastCallback = currentCallback;
  213137. {
  213138. const ScopedLock sl (callbackLock);
  213139. currentCallback = 0;
  213140. }
  213141. if (lastCallback != 0)
  213142. lastCallback->audioDeviceStopped();
  213143. }
  213144. const String getLastError() { return error; }
  213145. bool hasControlPanel() const { return true; }
  213146. bool showControlPanel()
  213147. {
  213148. log ("ASIO - showing control panel");
  213149. Component modalWindow (String::empty);
  213150. modalWindow.setOpaque (true);
  213151. modalWindow.addToDesktop (0);
  213152. modalWindow.enterModalState();
  213153. bool done = false;
  213154. JUCE_TRY
  213155. {
  213156. // are there are devices that need to be closed before showing their control panel?
  213157. // close();
  213158. insideControlPanelModalLoop = true;
  213159. const uint32 started = Time::getMillisecondCounter();
  213160. if (asioObject != 0)
  213161. {
  213162. asioObject->controlPanel();
  213163. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213164. log ("spent: " + String (spent));
  213165. if (spent > 300)
  213166. {
  213167. shouldUsePreferredSize = true;
  213168. done = true;
  213169. }
  213170. }
  213171. }
  213172. JUCE_CATCH_ALL
  213173. insideControlPanelModalLoop = false;
  213174. return done;
  213175. }
  213176. void resetRequest() throw()
  213177. {
  213178. needToReset = true;
  213179. }
  213180. void resyncRequest() throw()
  213181. {
  213182. needToReset = true;
  213183. isReSync = true;
  213184. }
  213185. void timerCallback()
  213186. {
  213187. if (! insideControlPanelModalLoop)
  213188. {
  213189. stopTimer();
  213190. // used to cause a reset
  213191. log ("! ASIO restart request!");
  213192. if (isOpen_)
  213193. {
  213194. AudioIODeviceCallback* const oldCallback = currentCallback;
  213195. close();
  213196. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213197. currentSampleRate, currentBlockSizeSamples);
  213198. if (oldCallback != 0)
  213199. start (oldCallback);
  213200. }
  213201. }
  213202. else
  213203. {
  213204. startTimer (100);
  213205. }
  213206. }
  213207. private:
  213208. IASIO* volatile asioObject;
  213209. ASIOCallbacks callbacks;
  213210. void* windowHandle;
  213211. CLSID classId;
  213212. const String optionalDllForDirectLoading;
  213213. String error;
  213214. long totalNumInputChans, totalNumOutputChans;
  213215. StringArray inputChannelNames, outputChannelNames;
  213216. Array<int> sampleRates, bufferSizes;
  213217. long inputLatency, outputLatency;
  213218. long minSize, maxSize, preferredSize, granularity;
  213219. int volatile currentBlockSizeSamples;
  213220. int volatile currentBitDepth;
  213221. double volatile currentSampleRate;
  213222. BigInteger currentChansOut, currentChansIn;
  213223. AudioIODeviceCallback* volatile currentCallback;
  213224. CriticalSection callbackLock;
  213225. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213226. float* inBuffers [maxASIOChannels];
  213227. float* outBuffers [maxASIOChannels];
  213228. int inputChannelBitDepths [maxASIOChannels];
  213229. int outputChannelBitDepths [maxASIOChannels];
  213230. int inputChannelBytesPerSample [maxASIOChannels];
  213231. int outputChannelBytesPerSample [maxASIOChannels];
  213232. bool inputChannelIsFloat [maxASIOChannels];
  213233. bool outputChannelIsFloat [maxASIOChannels];
  213234. bool inputChannelLittleEndian [maxASIOChannels];
  213235. bool outputChannelLittleEndian [maxASIOChannels];
  213236. WaitableEvent event1;
  213237. HeapBlock <float> tempBuffer;
  213238. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213239. bool isOpen_, isStarted;
  213240. bool volatile isASIOOpen;
  213241. bool volatile calledback;
  213242. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213243. bool volatile insideControlPanelModalLoop;
  213244. bool volatile shouldUsePreferredSize;
  213245. void removeCurrentDriver()
  213246. {
  213247. if (asioObject != 0)
  213248. {
  213249. asioObject->Release();
  213250. asioObject = 0;
  213251. }
  213252. }
  213253. bool loadDriver()
  213254. {
  213255. removeCurrentDriver();
  213256. JUCE_TRY
  213257. {
  213258. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213259. classId, (void**) &asioObject) == S_OK)
  213260. {
  213261. return true;
  213262. }
  213263. // If a class isn't registered but we have a path for it, we can fallback to
  213264. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213265. if (optionalDllForDirectLoading.isNotEmpty())
  213266. {
  213267. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213268. if (h != 0)
  213269. {
  213270. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213271. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213272. if (dllGetClassObject != 0)
  213273. {
  213274. IClassFactory* classFactory = 0;
  213275. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213276. if (classFactory != 0)
  213277. {
  213278. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213279. classFactory->Release();
  213280. }
  213281. return asioObject != 0;
  213282. }
  213283. }
  213284. }
  213285. }
  213286. JUCE_CATCH_ALL
  213287. asioObject = 0;
  213288. return false;
  213289. }
  213290. const String initDriver()
  213291. {
  213292. if (asioObject != 0)
  213293. {
  213294. char buffer [256];
  213295. zeromem (buffer, sizeof (buffer));
  213296. if (! asioObject->init (windowHandle))
  213297. {
  213298. asioObject->getErrorMessage (buffer);
  213299. return String (buffer, sizeof (buffer) - 1);
  213300. }
  213301. // just in case any daft drivers expect this to be called..
  213302. asioObject->getDriverName (buffer);
  213303. return String::empty;
  213304. }
  213305. return "No Driver";
  213306. }
  213307. const String openDevice()
  213308. {
  213309. // use this in case the driver starts opening dialog boxes..
  213310. Component modalWindow (String::empty);
  213311. modalWindow.setOpaque (true);
  213312. modalWindow.addToDesktop (0);
  213313. modalWindow.enterModalState();
  213314. // open the device and get its info..
  213315. log ("opening ASIO device: " + getName());
  213316. needToReset = false;
  213317. isReSync = false;
  213318. outputChannelNames.clear();
  213319. inputChannelNames.clear();
  213320. bufferSizes.clear();
  213321. sampleRates.clear();
  213322. isASIOOpen = false;
  213323. isOpen_ = false;
  213324. totalNumInputChans = 0;
  213325. totalNumOutputChans = 0;
  213326. numActiveInputChans = 0;
  213327. numActiveOutputChans = 0;
  213328. currentCallback = 0;
  213329. error = String::empty;
  213330. if (getName().isEmpty())
  213331. return error;
  213332. long err = 0;
  213333. if (loadDriver())
  213334. {
  213335. if ((error = initDriver()).isEmpty())
  213336. {
  213337. numActiveInputChans = 0;
  213338. numActiveOutputChans = 0;
  213339. totalNumInputChans = 0;
  213340. totalNumOutputChans = 0;
  213341. if (asioObject != 0
  213342. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213343. {
  213344. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213345. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213346. {
  213347. // find a list of buffer sizes..
  213348. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213349. if (granularity >= 0)
  213350. {
  213351. granularity = jmax (1, (int) granularity);
  213352. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213353. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213354. }
  213355. else if (granularity < 0)
  213356. {
  213357. for (int i = 0; i < 18; ++i)
  213358. {
  213359. const int s = (1 << i);
  213360. if (s >= minSize && s <= maxSize)
  213361. bufferSizes.add (s);
  213362. }
  213363. }
  213364. if (! bufferSizes.contains (preferredSize))
  213365. bufferSizes.insert (0, preferredSize);
  213366. double currentRate = 0;
  213367. asioObject->getSampleRate (&currentRate);
  213368. if (currentRate <= 0.0 || currentRate > 192001.0)
  213369. {
  213370. log ("setting sample rate");
  213371. err = asioObject->setSampleRate (44100.0);
  213372. if (err != 0)
  213373. {
  213374. logError ("setting sample rate", err);
  213375. }
  213376. asioObject->getSampleRate (&currentRate);
  213377. }
  213378. currentSampleRate = currentRate;
  213379. postOutput = (asioObject->outputReady() == 0);
  213380. if (postOutput)
  213381. {
  213382. log ("ASIO outputReady = ok");
  213383. }
  213384. updateSampleRates();
  213385. // ..because cubase does it at this point
  213386. inputLatency = outputLatency = 0;
  213387. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213388. {
  213389. log ("ASIO - no latencies");
  213390. }
  213391. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213392. // create some dummy buffers now.. because cubase does..
  213393. numActiveInputChans = 0;
  213394. numActiveOutputChans = 0;
  213395. ASIOBufferInfo* info = bufferInfos;
  213396. int i, numChans = 0;
  213397. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213398. {
  213399. info->isInput = 1;
  213400. info->channelNum = i;
  213401. info->buffers[0] = info->buffers[1] = 0;
  213402. ++info;
  213403. ++numChans;
  213404. }
  213405. const int outputBufferIndex = numChans;
  213406. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213407. {
  213408. info->isInput = 0;
  213409. info->channelNum = i;
  213410. info->buffers[0] = info->buffers[1] = 0;
  213411. ++info;
  213412. ++numChans;
  213413. }
  213414. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213415. if (currentASIODev[0] == this)
  213416. {
  213417. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213418. callbacks.asioMessage = &asioMessagesCallback0;
  213419. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213420. }
  213421. else if (currentASIODev[1] == this)
  213422. {
  213423. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213424. callbacks.asioMessage = &asioMessagesCallback1;
  213425. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213426. }
  213427. else if (currentASIODev[2] == this)
  213428. {
  213429. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213430. callbacks.asioMessage = &asioMessagesCallback2;
  213431. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213432. }
  213433. else
  213434. {
  213435. jassertfalse;
  213436. }
  213437. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213438. if (preferredSize > 0)
  213439. {
  213440. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213441. if (err != 0)
  213442. {
  213443. logError ("dummy buffers", err);
  213444. }
  213445. }
  213446. long newInps = 0, newOuts = 0;
  213447. asioObject->getChannels (&newInps, &newOuts);
  213448. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213449. {
  213450. totalNumInputChans = newInps;
  213451. totalNumOutputChans = newOuts;
  213452. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213453. }
  213454. updateSampleRates();
  213455. ASIOChannelInfo channelInfo;
  213456. channelInfo.type = 0;
  213457. for (i = 0; i < totalNumInputChans; ++i)
  213458. {
  213459. zerostruct (channelInfo);
  213460. channelInfo.channel = i;
  213461. channelInfo.isInput = 1;
  213462. asioObject->getChannelInfo (&channelInfo);
  213463. inputChannelNames.add (String (channelInfo.name));
  213464. }
  213465. for (i = 0; i < totalNumOutputChans; ++i)
  213466. {
  213467. zerostruct (channelInfo);
  213468. channelInfo.channel = i;
  213469. channelInfo.isInput = 0;
  213470. asioObject->getChannelInfo (&channelInfo);
  213471. outputChannelNames.add (String (channelInfo.name));
  213472. typeToFormatParameters (channelInfo.type,
  213473. outputChannelBitDepths[i],
  213474. outputChannelBytesPerSample[i],
  213475. outputChannelIsFloat[i],
  213476. outputChannelLittleEndian[i]);
  213477. if (i < 2)
  213478. {
  213479. // clear the channels that are used with the dummy stuff
  213480. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213481. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213482. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213483. }
  213484. }
  213485. outputChannelNames.trim();
  213486. inputChannelNames.trim();
  213487. outputChannelNames.appendNumbersToDuplicates (false, true);
  213488. inputChannelNames.appendNumbersToDuplicates (false, true);
  213489. // start and stop because cubase does it..
  213490. asioObject->getLatencies (&inputLatency, &outputLatency);
  213491. if ((err = asioObject->start()) != 0)
  213492. {
  213493. // ignore an error here, as it might start later after setting other stuff up
  213494. logError ("ASIO start", err);
  213495. }
  213496. Thread::sleep (100);
  213497. asioObject->stop();
  213498. }
  213499. else
  213500. {
  213501. error = "Can't detect buffer sizes";
  213502. }
  213503. }
  213504. else
  213505. {
  213506. error = "Can't detect asio channels";
  213507. }
  213508. }
  213509. }
  213510. else
  213511. {
  213512. error = "No such device";
  213513. }
  213514. if (error.isNotEmpty())
  213515. {
  213516. logError (error, err);
  213517. if (asioObject != 0)
  213518. asioObject->disposeBuffers();
  213519. removeCurrentDriver();
  213520. isASIOOpen = false;
  213521. }
  213522. else
  213523. {
  213524. isASIOOpen = true;
  213525. log ("ASIO device open");
  213526. }
  213527. isOpen_ = false;
  213528. needToReset = false;
  213529. isReSync = false;
  213530. return error;
  213531. }
  213532. void JUCE_ASIOCALLBACK callback (const long index)
  213533. {
  213534. if (isStarted)
  213535. {
  213536. bufferIndex = index;
  213537. processBuffer();
  213538. }
  213539. else
  213540. {
  213541. if (postOutput && (asioObject != 0))
  213542. asioObject->outputReady();
  213543. }
  213544. calledback = true;
  213545. }
  213546. void processBuffer()
  213547. {
  213548. const ASIOBufferInfo* const infos = bufferInfos;
  213549. const int bi = bufferIndex;
  213550. const ScopedLock sl (callbackLock);
  213551. if (needToReset)
  213552. {
  213553. needToReset = false;
  213554. if (isReSync)
  213555. {
  213556. log ("! ASIO resync");
  213557. isReSync = false;
  213558. }
  213559. else
  213560. {
  213561. startTimer (20);
  213562. }
  213563. }
  213564. if (bi >= 0)
  213565. {
  213566. const int samps = currentBlockSizeSamples;
  213567. if (currentCallback != 0)
  213568. {
  213569. int i;
  213570. for (i = 0; i < numActiveInputChans; ++i)
  213571. {
  213572. float* const dst = inBuffers[i];
  213573. jassert (dst != 0);
  213574. const char* const src = (const char*) (infos[i].buffers[bi]);
  213575. if (inputChannelIsFloat[i])
  213576. {
  213577. memcpy (dst, src, samps * sizeof (float));
  213578. }
  213579. else
  213580. {
  213581. jassert (dst == tempBuffer + (samps * i));
  213582. switch (inputChannelBitDepths[i])
  213583. {
  213584. case 16:
  213585. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213586. samps, inputChannelLittleEndian[i]);
  213587. break;
  213588. case 24:
  213589. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213590. samps, inputChannelLittleEndian[i]);
  213591. break;
  213592. case 32:
  213593. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213594. samps, inputChannelLittleEndian[i]);
  213595. break;
  213596. case 64:
  213597. jassertfalse;
  213598. break;
  213599. }
  213600. }
  213601. }
  213602. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213603. outBuffers, numActiveOutputChans, samps);
  213604. for (i = 0; i < numActiveOutputChans; ++i)
  213605. {
  213606. float* const src = outBuffers[i];
  213607. jassert (src != 0);
  213608. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213609. if (outputChannelIsFloat[i])
  213610. {
  213611. memcpy (dst, src, samps * sizeof (float));
  213612. }
  213613. else
  213614. {
  213615. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213616. switch (outputChannelBitDepths[i])
  213617. {
  213618. case 16:
  213619. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213620. samps, outputChannelLittleEndian[i]);
  213621. break;
  213622. case 24:
  213623. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213624. samps, outputChannelLittleEndian[i]);
  213625. break;
  213626. case 32:
  213627. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213628. samps, outputChannelLittleEndian[i]);
  213629. break;
  213630. case 64:
  213631. jassertfalse;
  213632. break;
  213633. }
  213634. }
  213635. }
  213636. }
  213637. else
  213638. {
  213639. for (int i = 0; i < numActiveOutputChans; ++i)
  213640. {
  213641. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213642. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213643. }
  213644. }
  213645. }
  213646. if (postOutput)
  213647. asioObject->outputReady();
  213648. }
  213649. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213650. {
  213651. if (currentASIODev[0] != 0)
  213652. currentASIODev[0]->callback (index);
  213653. return 0;
  213654. }
  213655. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213656. {
  213657. if (currentASIODev[1] != 0)
  213658. currentASIODev[1]->callback (index);
  213659. return 0;
  213660. }
  213661. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213662. {
  213663. if (currentASIODev[2] != 0)
  213664. currentASIODev[2]->callback (index);
  213665. return 0;
  213666. }
  213667. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213668. {
  213669. if (currentASIODev[0] != 0)
  213670. currentASIODev[0]->callback (index);
  213671. }
  213672. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213673. {
  213674. if (currentASIODev[1] != 0)
  213675. currentASIODev[1]->callback (index);
  213676. }
  213677. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213678. {
  213679. if (currentASIODev[2] != 0)
  213680. currentASIODev[2]->callback (index);
  213681. }
  213682. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  213683. {
  213684. return asioMessagesCallback (selector, value, 0);
  213685. }
  213686. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  213687. {
  213688. return asioMessagesCallback (selector, value, 1);
  213689. }
  213690. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  213691. {
  213692. return asioMessagesCallback (selector, value, 2);
  213693. }
  213694. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  213695. {
  213696. switch (selector)
  213697. {
  213698. case kAsioSelectorSupported:
  213699. if (value == kAsioResetRequest
  213700. || value == kAsioEngineVersion
  213701. || value == kAsioResyncRequest
  213702. || value == kAsioLatenciesChanged
  213703. || value == kAsioSupportsInputMonitor)
  213704. return 1;
  213705. break;
  213706. case kAsioBufferSizeChange:
  213707. break;
  213708. case kAsioResetRequest:
  213709. if (currentASIODev[deviceIndex] != 0)
  213710. currentASIODev[deviceIndex]->resetRequest();
  213711. return 1;
  213712. case kAsioResyncRequest:
  213713. if (currentASIODev[deviceIndex] != 0)
  213714. currentASIODev[deviceIndex]->resyncRequest();
  213715. return 1;
  213716. case kAsioLatenciesChanged:
  213717. return 1;
  213718. case kAsioEngineVersion:
  213719. return 2;
  213720. case kAsioSupportsTimeInfo:
  213721. case kAsioSupportsTimeCode:
  213722. return 0;
  213723. }
  213724. return 0;
  213725. }
  213726. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213727. {
  213728. }
  213729. static void convertInt16ToFloat (const char* src,
  213730. float* dest,
  213731. const int srcStrideBytes,
  213732. int numSamples,
  213733. const bool littleEndian) throw()
  213734. {
  213735. const double g = 1.0 / 32768.0;
  213736. if (littleEndian)
  213737. {
  213738. while (--numSamples >= 0)
  213739. {
  213740. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213741. src += srcStrideBytes;
  213742. }
  213743. }
  213744. else
  213745. {
  213746. while (--numSamples >= 0)
  213747. {
  213748. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213749. src += srcStrideBytes;
  213750. }
  213751. }
  213752. }
  213753. static void convertFloatToInt16 (const float* src,
  213754. char* dest,
  213755. const int dstStrideBytes,
  213756. int numSamples,
  213757. const bool littleEndian) throw()
  213758. {
  213759. const double maxVal = (double) 0x7fff;
  213760. if (littleEndian)
  213761. {
  213762. while (--numSamples >= 0)
  213763. {
  213764. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213765. dest += dstStrideBytes;
  213766. }
  213767. }
  213768. else
  213769. {
  213770. while (--numSamples >= 0)
  213771. {
  213772. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213773. dest += dstStrideBytes;
  213774. }
  213775. }
  213776. }
  213777. static void convertInt24ToFloat (const char* src,
  213778. float* dest,
  213779. const int srcStrideBytes,
  213780. int numSamples,
  213781. const bool littleEndian) throw()
  213782. {
  213783. const double g = 1.0 / 0x7fffff;
  213784. if (littleEndian)
  213785. {
  213786. while (--numSamples >= 0)
  213787. {
  213788. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213789. src += srcStrideBytes;
  213790. }
  213791. }
  213792. else
  213793. {
  213794. while (--numSamples >= 0)
  213795. {
  213796. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213797. src += srcStrideBytes;
  213798. }
  213799. }
  213800. }
  213801. static void convertFloatToInt24 (const float* src,
  213802. char* dest,
  213803. const int dstStrideBytes,
  213804. int numSamples,
  213805. const bool littleEndian) throw()
  213806. {
  213807. const double maxVal = (double) 0x7fffff;
  213808. if (littleEndian)
  213809. {
  213810. while (--numSamples >= 0)
  213811. {
  213812. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213813. dest += dstStrideBytes;
  213814. }
  213815. }
  213816. else
  213817. {
  213818. while (--numSamples >= 0)
  213819. {
  213820. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213821. dest += dstStrideBytes;
  213822. }
  213823. }
  213824. }
  213825. static void convertInt32ToFloat (const char* src,
  213826. float* dest,
  213827. const int srcStrideBytes,
  213828. int numSamples,
  213829. const bool littleEndian) throw()
  213830. {
  213831. const double g = 1.0 / 0x7fffffff;
  213832. if (littleEndian)
  213833. {
  213834. while (--numSamples >= 0)
  213835. {
  213836. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213837. src += srcStrideBytes;
  213838. }
  213839. }
  213840. else
  213841. {
  213842. while (--numSamples >= 0)
  213843. {
  213844. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213845. src += srcStrideBytes;
  213846. }
  213847. }
  213848. }
  213849. static void convertFloatToInt32 (const float* src,
  213850. char* dest,
  213851. const int dstStrideBytes,
  213852. int numSamples,
  213853. const bool littleEndian) throw()
  213854. {
  213855. const double maxVal = (double) 0x7fffffff;
  213856. if (littleEndian)
  213857. {
  213858. while (--numSamples >= 0)
  213859. {
  213860. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213861. dest += dstStrideBytes;
  213862. }
  213863. }
  213864. else
  213865. {
  213866. while (--numSamples >= 0)
  213867. {
  213868. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213869. dest += dstStrideBytes;
  213870. }
  213871. }
  213872. }
  213873. static void typeToFormatParameters (const long type,
  213874. int& bitDepth,
  213875. int& byteStride,
  213876. bool& formatIsFloat,
  213877. bool& littleEndian) throw()
  213878. {
  213879. bitDepth = 0;
  213880. littleEndian = false;
  213881. formatIsFloat = false;
  213882. switch (type)
  213883. {
  213884. case ASIOSTInt16MSB:
  213885. case ASIOSTInt16LSB:
  213886. case ASIOSTInt32MSB16:
  213887. case ASIOSTInt32LSB16:
  213888. bitDepth = 16; break;
  213889. case ASIOSTFloat32MSB:
  213890. case ASIOSTFloat32LSB:
  213891. formatIsFloat = true;
  213892. bitDepth = 32; break;
  213893. case ASIOSTInt32MSB:
  213894. case ASIOSTInt32LSB:
  213895. bitDepth = 32; break;
  213896. case ASIOSTInt24MSB:
  213897. case ASIOSTInt24LSB:
  213898. case ASIOSTInt32MSB24:
  213899. case ASIOSTInt32LSB24:
  213900. case ASIOSTInt32MSB18:
  213901. case ASIOSTInt32MSB20:
  213902. case ASIOSTInt32LSB18:
  213903. case ASIOSTInt32LSB20:
  213904. bitDepth = 24; break;
  213905. case ASIOSTFloat64MSB:
  213906. case ASIOSTFloat64LSB:
  213907. default:
  213908. bitDepth = 64;
  213909. break;
  213910. }
  213911. switch (type)
  213912. {
  213913. case ASIOSTInt16MSB:
  213914. case ASIOSTInt32MSB16:
  213915. case ASIOSTFloat32MSB:
  213916. case ASIOSTFloat64MSB:
  213917. case ASIOSTInt32MSB:
  213918. case ASIOSTInt32MSB18:
  213919. case ASIOSTInt32MSB20:
  213920. case ASIOSTInt32MSB24:
  213921. case ASIOSTInt24MSB:
  213922. littleEndian = false; break;
  213923. case ASIOSTInt16LSB:
  213924. case ASIOSTInt32LSB16:
  213925. case ASIOSTFloat32LSB:
  213926. case ASIOSTFloat64LSB:
  213927. case ASIOSTInt32LSB:
  213928. case ASIOSTInt32LSB18:
  213929. case ASIOSTInt32LSB20:
  213930. case ASIOSTInt32LSB24:
  213931. case ASIOSTInt24LSB:
  213932. littleEndian = true; break;
  213933. default:
  213934. break;
  213935. }
  213936. switch (type)
  213937. {
  213938. case ASIOSTInt16LSB:
  213939. case ASIOSTInt16MSB:
  213940. byteStride = 2; break;
  213941. case ASIOSTInt24LSB:
  213942. case ASIOSTInt24MSB:
  213943. byteStride = 3; break;
  213944. case ASIOSTInt32MSB16:
  213945. case ASIOSTInt32LSB16:
  213946. case ASIOSTInt32MSB:
  213947. case ASIOSTInt32MSB18:
  213948. case ASIOSTInt32MSB20:
  213949. case ASIOSTInt32MSB24:
  213950. case ASIOSTInt32LSB:
  213951. case ASIOSTInt32LSB18:
  213952. case ASIOSTInt32LSB20:
  213953. case ASIOSTInt32LSB24:
  213954. case ASIOSTFloat32LSB:
  213955. case ASIOSTFloat32MSB:
  213956. byteStride = 4; break;
  213957. case ASIOSTFloat64MSB:
  213958. case ASIOSTFloat64LSB:
  213959. byteStride = 8; break;
  213960. default:
  213961. break;
  213962. }
  213963. }
  213964. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213965. };
  213966. class ASIOAudioIODeviceType : public AudioIODeviceType
  213967. {
  213968. public:
  213969. ASIOAudioIODeviceType()
  213970. : AudioIODeviceType ("ASIO"),
  213971. hasScanned (false)
  213972. {
  213973. CoInitialize (0);
  213974. }
  213975. ~ASIOAudioIODeviceType()
  213976. {
  213977. }
  213978. void scanForDevices()
  213979. {
  213980. hasScanned = true;
  213981. deviceNames.clear();
  213982. classIds.clear();
  213983. HKEY hk = 0;
  213984. int index = 0;
  213985. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213986. {
  213987. for (;;)
  213988. {
  213989. char name [256];
  213990. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213991. {
  213992. addDriverInfo (name, hk);
  213993. }
  213994. else
  213995. {
  213996. break;
  213997. }
  213998. }
  213999. RegCloseKey (hk);
  214000. }
  214001. }
  214002. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214003. {
  214004. jassert (hasScanned); // need to call scanForDevices() before doing this
  214005. return deviceNames;
  214006. }
  214007. int getDefaultDeviceIndex (bool) const
  214008. {
  214009. jassert (hasScanned); // need to call scanForDevices() before doing this
  214010. for (int i = deviceNames.size(); --i >= 0;)
  214011. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214012. return i; // asio4all is a safe choice for a default..
  214013. #if JUCE_DEBUG
  214014. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214015. return 1; // (the digi m-box driver crashes the app when you run
  214016. // it in the debugger, which can be a bit annoying)
  214017. #endif
  214018. return 0;
  214019. }
  214020. static int findFreeSlot()
  214021. {
  214022. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214023. if (currentASIODev[i] == 0)
  214024. return i;
  214025. jassertfalse; // unfortunately you can only have a finite number
  214026. // of ASIO devices open at the same time..
  214027. return -1;
  214028. }
  214029. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214030. {
  214031. jassert (hasScanned); // need to call scanForDevices() before doing this
  214032. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214033. }
  214034. bool hasSeparateInputsAndOutputs() const { return false; }
  214035. AudioIODevice* createDevice (const String& outputDeviceName,
  214036. const String& inputDeviceName)
  214037. {
  214038. // ASIO can't open two different devices for input and output - they must be the same one.
  214039. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214040. jassert (hasScanned); // need to call scanForDevices() before doing this
  214041. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214042. : inputDeviceName);
  214043. if (index >= 0)
  214044. {
  214045. const int freeSlot = findFreeSlot();
  214046. if (freeSlot >= 0)
  214047. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214048. }
  214049. return 0;
  214050. }
  214051. private:
  214052. StringArray deviceNames;
  214053. OwnedArray <CLSID> classIds;
  214054. bool hasScanned;
  214055. static bool checkClassIsOk (const String& classId)
  214056. {
  214057. HKEY hk = 0;
  214058. bool ok = false;
  214059. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214060. {
  214061. int index = 0;
  214062. for (;;)
  214063. {
  214064. WCHAR buf [512];
  214065. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214066. {
  214067. if (classId.equalsIgnoreCase (buf))
  214068. {
  214069. HKEY subKey, pathKey;
  214070. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214071. {
  214072. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214073. {
  214074. WCHAR pathName [1024];
  214075. DWORD dtype = REG_SZ;
  214076. DWORD dsize = sizeof (pathName);
  214077. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214078. ok = File (pathName).exists();
  214079. RegCloseKey (pathKey);
  214080. }
  214081. RegCloseKey (subKey);
  214082. }
  214083. break;
  214084. }
  214085. }
  214086. else
  214087. {
  214088. break;
  214089. }
  214090. }
  214091. RegCloseKey (hk);
  214092. }
  214093. return ok;
  214094. }
  214095. void addDriverInfo (const String& keyName, HKEY hk)
  214096. {
  214097. HKEY subKey;
  214098. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214099. {
  214100. WCHAR buf [256];
  214101. zerostruct (buf);
  214102. DWORD dtype = REG_SZ;
  214103. DWORD dsize = sizeof (buf);
  214104. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214105. {
  214106. if (dsize > 0 && checkClassIsOk (buf))
  214107. {
  214108. CLSID classId;
  214109. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214110. {
  214111. dtype = REG_SZ;
  214112. dsize = sizeof (buf);
  214113. String deviceName;
  214114. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214115. deviceName = buf;
  214116. else
  214117. deviceName = keyName;
  214118. log ("found " + deviceName);
  214119. deviceNames.add (deviceName);
  214120. classIds.add (new CLSID (classId));
  214121. }
  214122. }
  214123. RegCloseKey (subKey);
  214124. }
  214125. }
  214126. }
  214127. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  214128. };
  214129. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214130. {
  214131. return new ASIOAudioIODeviceType();
  214132. }
  214133. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214134. void* guid,
  214135. const String& optionalDllForDirectLoading)
  214136. {
  214137. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214138. if (freeSlot < 0)
  214139. return 0;
  214140. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214141. }
  214142. #undef logError
  214143. #undef log
  214144. #endif
  214145. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214146. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214147. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214148. // compiled on its own).
  214149. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214150. END_JUCE_NAMESPACE
  214151. extern "C"
  214152. {
  214153. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214154. typedef struct typeDSBUFFERDESC
  214155. {
  214156. DWORD dwSize;
  214157. DWORD dwFlags;
  214158. DWORD dwBufferBytes;
  214159. DWORD dwReserved;
  214160. LPWAVEFORMATEX lpwfxFormat;
  214161. GUID guid3DAlgorithm;
  214162. } DSBUFFERDESC;
  214163. struct IDirectSoundBuffer;
  214164. #undef INTERFACE
  214165. #define INTERFACE IDirectSound
  214166. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214167. {
  214168. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214169. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214170. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214171. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214172. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214173. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214174. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214175. STDMETHOD(Compact) (THIS) PURE;
  214176. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214177. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214178. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214179. };
  214180. #undef INTERFACE
  214181. #define INTERFACE IDirectSoundBuffer
  214182. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214183. {
  214184. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214185. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214186. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214187. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214188. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214189. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214190. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214191. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214192. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214193. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214194. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214195. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214196. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214197. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214198. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214199. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214200. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214201. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214202. STDMETHOD(Stop) (THIS) PURE;
  214203. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214204. STDMETHOD(Restore) (THIS) PURE;
  214205. };
  214206. typedef struct typeDSCBUFFERDESC
  214207. {
  214208. DWORD dwSize;
  214209. DWORD dwFlags;
  214210. DWORD dwBufferBytes;
  214211. DWORD dwReserved;
  214212. LPWAVEFORMATEX lpwfxFormat;
  214213. } DSCBUFFERDESC;
  214214. struct IDirectSoundCaptureBuffer;
  214215. #undef INTERFACE
  214216. #define INTERFACE IDirectSoundCapture
  214217. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214218. {
  214219. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214220. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214221. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214222. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214223. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214224. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214225. };
  214226. #undef INTERFACE
  214227. #define INTERFACE IDirectSoundCaptureBuffer
  214228. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214229. {
  214230. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214231. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214232. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214233. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214234. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214235. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214236. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214237. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214238. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214239. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214240. STDMETHOD(Stop) (THIS) PURE;
  214241. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214242. };
  214243. };
  214244. BEGIN_JUCE_NAMESPACE
  214245. namespace
  214246. {
  214247. const String getDSErrorMessage (HRESULT hr)
  214248. {
  214249. const char* result = 0;
  214250. switch (hr)
  214251. {
  214252. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214253. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214254. case E_INVALIDARG: result = "Invalid parameter"; break;
  214255. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214256. case E_FAIL: result = "Generic error"; break;
  214257. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214258. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214259. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214260. case E_NOTIMPL: result = "Unsupported function"; break;
  214261. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214262. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214263. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214264. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214265. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214266. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214267. case E_NOINTERFACE: result = "No interface"; break;
  214268. case S_OK: result = "No error"; break;
  214269. default: return "Unknown error: " + String ((int) hr);
  214270. }
  214271. return result;
  214272. }
  214273. #define DS_DEBUGGING 1
  214274. #ifdef DS_DEBUGGING
  214275. #define CATCH JUCE_CATCH_EXCEPTION
  214276. #undef log
  214277. #define log(a) Logger::writeToLog(a);
  214278. #undef logError
  214279. #define logError(a) logDSError(a, __LINE__);
  214280. static void logDSError (HRESULT hr, int lineNum)
  214281. {
  214282. if (hr != S_OK)
  214283. {
  214284. String error ("DS error at line ");
  214285. error << lineNum << " - " << getDSErrorMessage (hr);
  214286. log (error);
  214287. }
  214288. }
  214289. #else
  214290. #define CATCH JUCE_CATCH_ALL
  214291. #define log(a)
  214292. #define logError(a)
  214293. #endif
  214294. #define DSOUND_FUNCTION(functionName, params) \
  214295. typedef HRESULT (WINAPI *type##functionName) params; \
  214296. static type##functionName ds##functionName = 0;
  214297. #define DSOUND_FUNCTION_LOAD(functionName) \
  214298. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214299. jassert (ds##functionName != 0);
  214300. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214301. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214302. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214303. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214304. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214305. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214306. void initialiseDSoundFunctions()
  214307. {
  214308. if (dsDirectSoundCreate == 0)
  214309. {
  214310. HMODULE h = LoadLibraryA ("dsound.dll");
  214311. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214312. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214313. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214314. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214315. }
  214316. }
  214317. }
  214318. class DSoundInternalOutChannel
  214319. {
  214320. String name;
  214321. LPGUID guid;
  214322. int sampleRate, bufferSizeSamples;
  214323. float* leftBuffer;
  214324. float* rightBuffer;
  214325. IDirectSound* pDirectSound;
  214326. IDirectSoundBuffer* pOutputBuffer;
  214327. DWORD writeOffset;
  214328. int totalBytesPerBuffer;
  214329. int bytesPerBuffer;
  214330. unsigned int lastPlayCursor;
  214331. public:
  214332. int bitDepth;
  214333. bool doneFlag;
  214334. DSoundInternalOutChannel (const String& name_,
  214335. LPGUID guid_,
  214336. int rate,
  214337. int bufferSize,
  214338. float* left,
  214339. float* right)
  214340. : name (name_),
  214341. guid (guid_),
  214342. sampleRate (rate),
  214343. bufferSizeSamples (bufferSize),
  214344. leftBuffer (left),
  214345. rightBuffer (right),
  214346. pDirectSound (0),
  214347. pOutputBuffer (0),
  214348. bitDepth (16)
  214349. {
  214350. }
  214351. ~DSoundInternalOutChannel()
  214352. {
  214353. close();
  214354. }
  214355. void close()
  214356. {
  214357. HRESULT hr;
  214358. if (pOutputBuffer != 0)
  214359. {
  214360. JUCE_TRY
  214361. {
  214362. log ("closing dsound out: " + name);
  214363. hr = pOutputBuffer->Stop();
  214364. logError (hr);
  214365. }
  214366. CATCH
  214367. JUCE_TRY
  214368. {
  214369. hr = pOutputBuffer->Release();
  214370. logError (hr);
  214371. }
  214372. CATCH
  214373. pOutputBuffer = 0;
  214374. }
  214375. if (pDirectSound != 0)
  214376. {
  214377. JUCE_TRY
  214378. {
  214379. hr = pDirectSound->Release();
  214380. logError (hr);
  214381. }
  214382. CATCH
  214383. pDirectSound = 0;
  214384. }
  214385. }
  214386. const String open()
  214387. {
  214388. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214389. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214390. pDirectSound = 0;
  214391. pOutputBuffer = 0;
  214392. writeOffset = 0;
  214393. String error;
  214394. HRESULT hr = E_NOINTERFACE;
  214395. if (dsDirectSoundCreate != 0)
  214396. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214397. if (hr == S_OK)
  214398. {
  214399. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214400. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214401. const int numChannels = 2;
  214402. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214403. logError (hr);
  214404. if (hr == S_OK)
  214405. {
  214406. IDirectSoundBuffer* pPrimaryBuffer;
  214407. DSBUFFERDESC primaryDesc;
  214408. zerostruct (primaryDesc);
  214409. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214410. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214411. primaryDesc.dwBufferBytes = 0;
  214412. primaryDesc.lpwfxFormat = 0;
  214413. log ("opening dsound out step 2");
  214414. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214415. logError (hr);
  214416. if (hr == S_OK)
  214417. {
  214418. WAVEFORMATEX wfFormat;
  214419. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214420. wfFormat.nChannels = (unsigned short) numChannels;
  214421. wfFormat.nSamplesPerSec = sampleRate;
  214422. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214423. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214424. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214425. wfFormat.cbSize = 0;
  214426. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214427. logError (hr);
  214428. if (hr == S_OK)
  214429. {
  214430. DSBUFFERDESC secondaryDesc;
  214431. zerostruct (secondaryDesc);
  214432. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214433. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214434. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214435. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214436. secondaryDesc.lpwfxFormat = &wfFormat;
  214437. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214438. logError (hr);
  214439. if (hr == S_OK)
  214440. {
  214441. log ("opening dsound out step 3");
  214442. DWORD dwDataLen;
  214443. unsigned char* pDSBuffData;
  214444. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214445. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214446. logError (hr);
  214447. if (hr == S_OK)
  214448. {
  214449. zeromem (pDSBuffData, dwDataLen);
  214450. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214451. if (hr == S_OK)
  214452. {
  214453. hr = pOutputBuffer->SetCurrentPosition (0);
  214454. if (hr == S_OK)
  214455. {
  214456. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214457. if (hr == S_OK)
  214458. return String::empty;
  214459. }
  214460. }
  214461. }
  214462. }
  214463. }
  214464. }
  214465. }
  214466. }
  214467. error = getDSErrorMessage (hr);
  214468. close();
  214469. return error;
  214470. }
  214471. void synchronisePosition()
  214472. {
  214473. if (pOutputBuffer != 0)
  214474. {
  214475. DWORD playCursor;
  214476. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214477. }
  214478. }
  214479. bool service()
  214480. {
  214481. if (pOutputBuffer == 0)
  214482. return true;
  214483. DWORD playCursor, writeCursor;
  214484. for (;;)
  214485. {
  214486. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214487. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214488. {
  214489. pOutputBuffer->Restore();
  214490. continue;
  214491. }
  214492. if (hr == S_OK)
  214493. break;
  214494. logError (hr);
  214495. jassertfalse;
  214496. return true;
  214497. }
  214498. int playWriteGap = writeCursor - playCursor;
  214499. if (playWriteGap < 0)
  214500. playWriteGap += totalBytesPerBuffer;
  214501. int bytesEmpty = playCursor - writeOffset;
  214502. if (bytesEmpty < 0)
  214503. bytesEmpty += totalBytesPerBuffer;
  214504. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214505. {
  214506. writeOffset = writeCursor;
  214507. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214508. }
  214509. if (bytesEmpty >= bytesPerBuffer)
  214510. {
  214511. void* lpbuf1 = 0;
  214512. void* lpbuf2 = 0;
  214513. DWORD dwSize1 = 0;
  214514. DWORD dwSize2 = 0;
  214515. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214516. bytesPerBuffer,
  214517. &lpbuf1, &dwSize1,
  214518. &lpbuf2, &dwSize2, 0);
  214519. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214520. {
  214521. pOutputBuffer->Restore();
  214522. hr = pOutputBuffer->Lock (writeOffset,
  214523. bytesPerBuffer,
  214524. &lpbuf1, &dwSize1,
  214525. &lpbuf2, &dwSize2, 0);
  214526. }
  214527. if (hr == S_OK)
  214528. {
  214529. if (bitDepth == 16)
  214530. {
  214531. const float gainL = 32767.0f;
  214532. const float gainR = 32767.0f;
  214533. int* dest = static_cast<int*> (lpbuf1);
  214534. const float* left = leftBuffer;
  214535. const float* right = rightBuffer;
  214536. int samples1 = dwSize1 >> 2;
  214537. int samples2 = dwSize2 >> 2;
  214538. if (left == 0)
  214539. {
  214540. while (--samples1 >= 0)
  214541. {
  214542. int r = roundToInt (gainR * *right++);
  214543. if (r < -32768)
  214544. r = -32768;
  214545. else if (r > 32767)
  214546. r = 32767;
  214547. *dest++ = (r << 16);
  214548. }
  214549. dest = static_cast<int*> (lpbuf2);
  214550. while (--samples2 >= 0)
  214551. {
  214552. int r = roundToInt (gainR * *right++);
  214553. if (r < -32768)
  214554. r = -32768;
  214555. else if (r > 32767)
  214556. r = 32767;
  214557. *dest++ = (r << 16);
  214558. }
  214559. }
  214560. else if (right == 0)
  214561. {
  214562. while (--samples1 >= 0)
  214563. {
  214564. int l = roundToInt (gainL * *left++);
  214565. if (l < -32768)
  214566. l = -32768;
  214567. else if (l > 32767)
  214568. l = 32767;
  214569. l &= 0xffff;
  214570. *dest++ = l;
  214571. }
  214572. dest = static_cast<int*> (lpbuf2);
  214573. while (--samples2 >= 0)
  214574. {
  214575. int l = roundToInt (gainL * *left++);
  214576. if (l < -32768)
  214577. l = -32768;
  214578. else if (l > 32767)
  214579. l = 32767;
  214580. l &= 0xffff;
  214581. *dest++ = l;
  214582. }
  214583. }
  214584. else
  214585. {
  214586. while (--samples1 >= 0)
  214587. {
  214588. int l = roundToInt (gainL * *left++);
  214589. if (l < -32768)
  214590. l = -32768;
  214591. else if (l > 32767)
  214592. l = 32767;
  214593. l &= 0xffff;
  214594. int r = roundToInt (gainR * *right++);
  214595. if (r < -32768)
  214596. r = -32768;
  214597. else if (r > 32767)
  214598. r = 32767;
  214599. *dest++ = (r << 16) | l;
  214600. }
  214601. dest = static_cast<int*> (lpbuf2);
  214602. while (--samples2 >= 0)
  214603. {
  214604. int l = roundToInt (gainL * *left++);
  214605. if (l < -32768)
  214606. l = -32768;
  214607. else if (l > 32767)
  214608. l = 32767;
  214609. l &= 0xffff;
  214610. int r = roundToInt (gainR * *right++);
  214611. if (r < -32768)
  214612. r = -32768;
  214613. else if (r > 32767)
  214614. r = 32767;
  214615. *dest++ = (r << 16) | l;
  214616. }
  214617. }
  214618. }
  214619. else
  214620. {
  214621. jassertfalse;
  214622. }
  214623. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214624. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214625. }
  214626. else
  214627. {
  214628. jassertfalse;
  214629. logError (hr);
  214630. }
  214631. bytesEmpty -= bytesPerBuffer;
  214632. return true;
  214633. }
  214634. else
  214635. {
  214636. return false;
  214637. }
  214638. }
  214639. };
  214640. struct DSoundInternalInChannel
  214641. {
  214642. String name;
  214643. LPGUID guid;
  214644. int sampleRate, bufferSizeSamples;
  214645. float* leftBuffer;
  214646. float* rightBuffer;
  214647. IDirectSound* pDirectSound;
  214648. IDirectSoundCapture* pDirectSoundCapture;
  214649. IDirectSoundCaptureBuffer* pInputBuffer;
  214650. public:
  214651. unsigned int readOffset;
  214652. int bytesPerBuffer, totalBytesPerBuffer;
  214653. int bitDepth;
  214654. bool doneFlag;
  214655. DSoundInternalInChannel (const String& name_,
  214656. LPGUID guid_,
  214657. int rate,
  214658. int bufferSize,
  214659. float* left,
  214660. float* right)
  214661. : name (name_),
  214662. guid (guid_),
  214663. sampleRate (rate),
  214664. bufferSizeSamples (bufferSize),
  214665. leftBuffer (left),
  214666. rightBuffer (right),
  214667. pDirectSound (0),
  214668. pDirectSoundCapture (0),
  214669. pInputBuffer (0),
  214670. bitDepth (16)
  214671. {
  214672. }
  214673. ~DSoundInternalInChannel()
  214674. {
  214675. close();
  214676. }
  214677. void close()
  214678. {
  214679. HRESULT hr;
  214680. if (pInputBuffer != 0)
  214681. {
  214682. JUCE_TRY
  214683. {
  214684. log ("closing dsound in: " + name);
  214685. hr = pInputBuffer->Stop();
  214686. logError (hr);
  214687. }
  214688. CATCH
  214689. JUCE_TRY
  214690. {
  214691. hr = pInputBuffer->Release();
  214692. logError (hr);
  214693. }
  214694. CATCH
  214695. pInputBuffer = 0;
  214696. }
  214697. if (pDirectSoundCapture != 0)
  214698. {
  214699. JUCE_TRY
  214700. {
  214701. hr = pDirectSoundCapture->Release();
  214702. logError (hr);
  214703. }
  214704. CATCH
  214705. pDirectSoundCapture = 0;
  214706. }
  214707. if (pDirectSound != 0)
  214708. {
  214709. JUCE_TRY
  214710. {
  214711. hr = pDirectSound->Release();
  214712. logError (hr);
  214713. }
  214714. CATCH
  214715. pDirectSound = 0;
  214716. }
  214717. }
  214718. const String open()
  214719. {
  214720. log ("opening dsound in device: " + name
  214721. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214722. pDirectSound = 0;
  214723. pDirectSoundCapture = 0;
  214724. pInputBuffer = 0;
  214725. readOffset = 0;
  214726. totalBytesPerBuffer = 0;
  214727. String error;
  214728. HRESULT hr = E_NOINTERFACE;
  214729. if (dsDirectSoundCaptureCreate != 0)
  214730. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214731. logError (hr);
  214732. if (hr == S_OK)
  214733. {
  214734. const int numChannels = 2;
  214735. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214736. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214737. WAVEFORMATEX wfFormat;
  214738. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214739. wfFormat.nChannels = (unsigned short)numChannels;
  214740. wfFormat.nSamplesPerSec = sampleRate;
  214741. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214742. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214743. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214744. wfFormat.cbSize = 0;
  214745. DSCBUFFERDESC captureDesc;
  214746. zerostruct (captureDesc);
  214747. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214748. captureDesc.dwFlags = 0;
  214749. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214750. captureDesc.lpwfxFormat = &wfFormat;
  214751. log ("opening dsound in step 2");
  214752. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214753. logError (hr);
  214754. if (hr == S_OK)
  214755. {
  214756. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214757. logError (hr);
  214758. if (hr == S_OK)
  214759. return String::empty;
  214760. }
  214761. }
  214762. error = getDSErrorMessage (hr);
  214763. close();
  214764. return error;
  214765. }
  214766. void synchronisePosition()
  214767. {
  214768. if (pInputBuffer != 0)
  214769. {
  214770. DWORD capturePos;
  214771. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214772. }
  214773. }
  214774. bool service()
  214775. {
  214776. if (pInputBuffer == 0)
  214777. return true;
  214778. DWORD capturePos, readPos;
  214779. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214780. logError (hr);
  214781. if (hr != S_OK)
  214782. return true;
  214783. int bytesFilled = readPos - readOffset;
  214784. if (bytesFilled < 0)
  214785. bytesFilled += totalBytesPerBuffer;
  214786. if (bytesFilled >= bytesPerBuffer)
  214787. {
  214788. LPBYTE lpbuf1 = 0;
  214789. LPBYTE lpbuf2 = 0;
  214790. DWORD dwsize1 = 0;
  214791. DWORD dwsize2 = 0;
  214792. HRESULT hr = pInputBuffer->Lock (readOffset,
  214793. bytesPerBuffer,
  214794. (void**) &lpbuf1, &dwsize1,
  214795. (void**) &lpbuf2, &dwsize2, 0);
  214796. if (hr == S_OK)
  214797. {
  214798. if (bitDepth == 16)
  214799. {
  214800. const float g = 1.0f / 32768.0f;
  214801. float* destL = leftBuffer;
  214802. float* destR = rightBuffer;
  214803. int samples1 = dwsize1 >> 2;
  214804. int samples2 = dwsize2 >> 2;
  214805. const short* src = (const short*)lpbuf1;
  214806. if (destL == 0)
  214807. {
  214808. while (--samples1 >= 0)
  214809. {
  214810. ++src;
  214811. *destR++ = *src++ * g;
  214812. }
  214813. src = (const short*)lpbuf2;
  214814. while (--samples2 >= 0)
  214815. {
  214816. ++src;
  214817. *destR++ = *src++ * g;
  214818. }
  214819. }
  214820. else if (destR == 0)
  214821. {
  214822. while (--samples1 >= 0)
  214823. {
  214824. *destL++ = *src++ * g;
  214825. ++src;
  214826. }
  214827. src = (const short*)lpbuf2;
  214828. while (--samples2 >= 0)
  214829. {
  214830. *destL++ = *src++ * g;
  214831. ++src;
  214832. }
  214833. }
  214834. else
  214835. {
  214836. while (--samples1 >= 0)
  214837. {
  214838. *destL++ = *src++ * g;
  214839. *destR++ = *src++ * g;
  214840. }
  214841. src = (const short*)lpbuf2;
  214842. while (--samples2 >= 0)
  214843. {
  214844. *destL++ = *src++ * g;
  214845. *destR++ = *src++ * g;
  214846. }
  214847. }
  214848. }
  214849. else
  214850. {
  214851. jassertfalse;
  214852. }
  214853. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214854. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214855. }
  214856. else
  214857. {
  214858. logError (hr);
  214859. jassertfalse;
  214860. }
  214861. bytesFilled -= bytesPerBuffer;
  214862. return true;
  214863. }
  214864. else
  214865. {
  214866. return false;
  214867. }
  214868. }
  214869. };
  214870. class DSoundAudioIODevice : public AudioIODevice,
  214871. public Thread
  214872. {
  214873. public:
  214874. DSoundAudioIODevice (const String& deviceName,
  214875. const int outputDeviceIndex_,
  214876. const int inputDeviceIndex_)
  214877. : AudioIODevice (deviceName, "DirectSound"),
  214878. Thread ("Juce DSound"),
  214879. isOpen_ (false),
  214880. isStarted (false),
  214881. outputDeviceIndex (outputDeviceIndex_),
  214882. inputDeviceIndex (inputDeviceIndex_),
  214883. totalSamplesOut (0),
  214884. sampleRate (0.0),
  214885. inputBuffers (1, 1),
  214886. outputBuffers (1, 1),
  214887. callback (0),
  214888. bufferSizeSamples (0)
  214889. {
  214890. if (outputDeviceIndex_ >= 0)
  214891. {
  214892. outChannels.add (TRANS("Left"));
  214893. outChannels.add (TRANS("Right"));
  214894. }
  214895. if (inputDeviceIndex_ >= 0)
  214896. {
  214897. inChannels.add (TRANS("Left"));
  214898. inChannels.add (TRANS("Right"));
  214899. }
  214900. }
  214901. ~DSoundAudioIODevice()
  214902. {
  214903. close();
  214904. }
  214905. const StringArray getOutputChannelNames()
  214906. {
  214907. return outChannels;
  214908. }
  214909. const StringArray getInputChannelNames()
  214910. {
  214911. return inChannels;
  214912. }
  214913. int getNumSampleRates()
  214914. {
  214915. return 4;
  214916. }
  214917. double getSampleRate (int index)
  214918. {
  214919. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214920. return samps [jlimit (0, 3, index)];
  214921. }
  214922. int getNumBufferSizesAvailable()
  214923. {
  214924. return 50;
  214925. }
  214926. int getBufferSizeSamples (int index)
  214927. {
  214928. int n = 64;
  214929. for (int i = 0; i < index; ++i)
  214930. n += (n < 512) ? 32
  214931. : ((n < 1024) ? 64
  214932. : ((n < 2048) ? 128 : 256));
  214933. return n;
  214934. }
  214935. int getDefaultBufferSize()
  214936. {
  214937. return 2560;
  214938. }
  214939. const String open (const BigInteger& inputChannels,
  214940. const BigInteger& outputChannels,
  214941. double sampleRate,
  214942. int bufferSizeSamples)
  214943. {
  214944. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214945. isOpen_ = lastError.isEmpty();
  214946. return lastError;
  214947. }
  214948. void close()
  214949. {
  214950. stop();
  214951. if (isOpen_)
  214952. {
  214953. closeDevice();
  214954. isOpen_ = false;
  214955. }
  214956. }
  214957. bool isOpen()
  214958. {
  214959. return isOpen_ && isThreadRunning();
  214960. }
  214961. int getCurrentBufferSizeSamples()
  214962. {
  214963. return bufferSizeSamples;
  214964. }
  214965. double getCurrentSampleRate()
  214966. {
  214967. return sampleRate;
  214968. }
  214969. int getCurrentBitDepth()
  214970. {
  214971. int i, bits = 256;
  214972. for (i = inChans.size(); --i >= 0;)
  214973. bits = jmin (bits, inChans[i]->bitDepth);
  214974. for (i = outChans.size(); --i >= 0;)
  214975. bits = jmin (bits, outChans[i]->bitDepth);
  214976. if (bits > 32)
  214977. bits = 16;
  214978. return bits;
  214979. }
  214980. const BigInteger getActiveOutputChannels() const
  214981. {
  214982. return enabledOutputs;
  214983. }
  214984. const BigInteger getActiveInputChannels() const
  214985. {
  214986. return enabledInputs;
  214987. }
  214988. int getOutputLatencyInSamples()
  214989. {
  214990. return (int) (getCurrentBufferSizeSamples() * 1.5);
  214991. }
  214992. int getInputLatencyInSamples()
  214993. {
  214994. return getOutputLatencyInSamples();
  214995. }
  214996. void start (AudioIODeviceCallback* call)
  214997. {
  214998. if (isOpen_ && call != 0 && ! isStarted)
  214999. {
  215000. if (! isThreadRunning())
  215001. {
  215002. // something gone wrong and the thread's stopped..
  215003. isOpen_ = false;
  215004. return;
  215005. }
  215006. call->audioDeviceAboutToStart (this);
  215007. const ScopedLock sl (startStopLock);
  215008. callback = call;
  215009. isStarted = true;
  215010. }
  215011. }
  215012. void stop()
  215013. {
  215014. if (isStarted)
  215015. {
  215016. AudioIODeviceCallback* const callbackLocal = callback;
  215017. {
  215018. const ScopedLock sl (startStopLock);
  215019. isStarted = false;
  215020. }
  215021. if (callbackLocal != 0)
  215022. callbackLocal->audioDeviceStopped();
  215023. }
  215024. }
  215025. bool isPlaying()
  215026. {
  215027. return isStarted && isOpen_ && isThreadRunning();
  215028. }
  215029. const String getLastError()
  215030. {
  215031. return lastError;
  215032. }
  215033. StringArray inChannels, outChannels;
  215034. int outputDeviceIndex, inputDeviceIndex;
  215035. private:
  215036. bool isOpen_;
  215037. bool isStarted;
  215038. String lastError;
  215039. OwnedArray <DSoundInternalInChannel> inChans;
  215040. OwnedArray <DSoundInternalOutChannel> outChans;
  215041. WaitableEvent startEvent;
  215042. int bufferSizeSamples;
  215043. int volatile totalSamplesOut;
  215044. int64 volatile lastBlockTime;
  215045. double sampleRate;
  215046. BigInteger enabledInputs, enabledOutputs;
  215047. AudioSampleBuffer inputBuffers, outputBuffers;
  215048. AudioIODeviceCallback* callback;
  215049. CriticalSection startStopLock;
  215050. const String openDevice (const BigInteger& inputChannels,
  215051. const BigInteger& outputChannels,
  215052. double sampleRate_,
  215053. int bufferSizeSamples_);
  215054. void closeDevice()
  215055. {
  215056. isStarted = false;
  215057. stopThread (5000);
  215058. inChans.clear();
  215059. outChans.clear();
  215060. inputBuffers.setSize (1, 1);
  215061. outputBuffers.setSize (1, 1);
  215062. }
  215063. void resync()
  215064. {
  215065. if (! threadShouldExit())
  215066. {
  215067. sleep (5);
  215068. int i;
  215069. for (i = 0; i < outChans.size(); ++i)
  215070. outChans.getUnchecked(i)->synchronisePosition();
  215071. for (i = 0; i < inChans.size(); ++i)
  215072. inChans.getUnchecked(i)->synchronisePosition();
  215073. }
  215074. }
  215075. public:
  215076. void run()
  215077. {
  215078. while (! threadShouldExit())
  215079. {
  215080. if (wait (100))
  215081. break;
  215082. }
  215083. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215084. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215085. while (! threadShouldExit())
  215086. {
  215087. int numToDo = 0;
  215088. uint32 startTime = Time::getMillisecondCounter();
  215089. int i;
  215090. for (i = inChans.size(); --i >= 0;)
  215091. {
  215092. inChans.getUnchecked(i)->doneFlag = false;
  215093. ++numToDo;
  215094. }
  215095. for (i = outChans.size(); --i >= 0;)
  215096. {
  215097. outChans.getUnchecked(i)->doneFlag = false;
  215098. ++numToDo;
  215099. }
  215100. if (numToDo > 0)
  215101. {
  215102. const int maxCount = 3;
  215103. int count = maxCount;
  215104. for (;;)
  215105. {
  215106. for (i = inChans.size(); --i >= 0;)
  215107. {
  215108. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215109. if ((! in->doneFlag) && in->service())
  215110. {
  215111. in->doneFlag = true;
  215112. --numToDo;
  215113. }
  215114. }
  215115. for (i = outChans.size(); --i >= 0;)
  215116. {
  215117. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215118. if ((! out->doneFlag) && out->service())
  215119. {
  215120. out->doneFlag = true;
  215121. --numToDo;
  215122. }
  215123. }
  215124. if (numToDo <= 0)
  215125. break;
  215126. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215127. {
  215128. resync();
  215129. break;
  215130. }
  215131. if (--count <= 0)
  215132. {
  215133. Sleep (1);
  215134. count = maxCount;
  215135. }
  215136. if (threadShouldExit())
  215137. return;
  215138. }
  215139. }
  215140. else
  215141. {
  215142. sleep (1);
  215143. }
  215144. const ScopedLock sl (startStopLock);
  215145. if (isStarted)
  215146. {
  215147. JUCE_TRY
  215148. {
  215149. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215150. inputBuffers.getNumChannels(),
  215151. outputBuffers.getArrayOfChannels(),
  215152. outputBuffers.getNumChannels(),
  215153. bufferSizeSamples);
  215154. }
  215155. JUCE_CATCH_EXCEPTION
  215156. totalSamplesOut += bufferSizeSamples;
  215157. }
  215158. else
  215159. {
  215160. outputBuffers.clear();
  215161. totalSamplesOut = 0;
  215162. sleep (1);
  215163. }
  215164. }
  215165. }
  215166. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  215167. };
  215168. class DSoundAudioIODeviceType : public AudioIODeviceType
  215169. {
  215170. public:
  215171. DSoundAudioIODeviceType()
  215172. : AudioIODeviceType ("DirectSound"),
  215173. hasScanned (false)
  215174. {
  215175. initialiseDSoundFunctions();
  215176. }
  215177. ~DSoundAudioIODeviceType()
  215178. {
  215179. }
  215180. void scanForDevices()
  215181. {
  215182. hasScanned = true;
  215183. outputDeviceNames.clear();
  215184. outputGuids.clear();
  215185. inputDeviceNames.clear();
  215186. inputGuids.clear();
  215187. if (dsDirectSoundEnumerateW != 0)
  215188. {
  215189. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215190. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215191. }
  215192. }
  215193. const StringArray getDeviceNames (bool wantInputNames) const
  215194. {
  215195. jassert (hasScanned); // need to call scanForDevices() before doing this
  215196. return wantInputNames ? inputDeviceNames
  215197. : outputDeviceNames;
  215198. }
  215199. int getDefaultDeviceIndex (bool /*forInput*/) const
  215200. {
  215201. jassert (hasScanned); // need to call scanForDevices() before doing this
  215202. return 0;
  215203. }
  215204. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215205. {
  215206. jassert (hasScanned); // need to call scanForDevices() before doing this
  215207. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215208. if (d == 0)
  215209. return -1;
  215210. return asInput ? d->inputDeviceIndex
  215211. : d->outputDeviceIndex;
  215212. }
  215213. bool hasSeparateInputsAndOutputs() const { return true; }
  215214. AudioIODevice* createDevice (const String& outputDeviceName,
  215215. const String& inputDeviceName)
  215216. {
  215217. jassert (hasScanned); // need to call scanForDevices() before doing this
  215218. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215219. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215220. if (outputIndex >= 0 || inputIndex >= 0)
  215221. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215222. : inputDeviceName,
  215223. outputIndex, inputIndex);
  215224. return 0;
  215225. }
  215226. StringArray outputDeviceNames;
  215227. OwnedArray <GUID> outputGuids;
  215228. StringArray inputDeviceNames;
  215229. OwnedArray <GUID> inputGuids;
  215230. private:
  215231. bool hasScanned;
  215232. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215233. {
  215234. desc = desc.trim();
  215235. if (desc.isNotEmpty())
  215236. {
  215237. const String origDesc (desc);
  215238. int n = 2;
  215239. while (outputDeviceNames.contains (desc))
  215240. desc = origDesc + " (" + String (n++) + ")";
  215241. outputDeviceNames.add (desc);
  215242. if (lpGUID != 0)
  215243. outputGuids.add (new GUID (*lpGUID));
  215244. else
  215245. outputGuids.add (0);
  215246. }
  215247. return TRUE;
  215248. }
  215249. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215250. {
  215251. return ((DSoundAudioIODeviceType*) object)
  215252. ->outputEnumProc (lpGUID, String (description));
  215253. }
  215254. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215255. {
  215256. return ((DSoundAudioIODeviceType*) object)
  215257. ->outputEnumProc (lpGUID, String (description));
  215258. }
  215259. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215260. {
  215261. desc = desc.trim();
  215262. if (desc.isNotEmpty())
  215263. {
  215264. const String origDesc (desc);
  215265. int n = 2;
  215266. while (inputDeviceNames.contains (desc))
  215267. desc = origDesc + " (" + String (n++) + ")";
  215268. inputDeviceNames.add (desc);
  215269. if (lpGUID != 0)
  215270. inputGuids.add (new GUID (*lpGUID));
  215271. else
  215272. inputGuids.add (0);
  215273. }
  215274. return TRUE;
  215275. }
  215276. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215277. {
  215278. return ((DSoundAudioIODeviceType*) object)
  215279. ->inputEnumProc (lpGUID, String (description));
  215280. }
  215281. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215282. {
  215283. return ((DSoundAudioIODeviceType*) object)
  215284. ->inputEnumProc (lpGUID, String (description));
  215285. }
  215286. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  215287. };
  215288. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215289. const BigInteger& outputChannels,
  215290. double sampleRate_,
  215291. int bufferSizeSamples_)
  215292. {
  215293. closeDevice();
  215294. totalSamplesOut = 0;
  215295. sampleRate = sampleRate_;
  215296. if (bufferSizeSamples_ <= 0)
  215297. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215298. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215299. DSoundAudioIODeviceType dlh;
  215300. dlh.scanForDevices();
  215301. enabledInputs = inputChannels;
  215302. enabledInputs.setRange (inChannels.size(),
  215303. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215304. false);
  215305. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215306. inputBuffers.clear();
  215307. int i, numIns = 0;
  215308. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215309. {
  215310. float* left = 0;
  215311. if (enabledInputs[i])
  215312. left = inputBuffers.getSampleData (numIns++);
  215313. float* right = 0;
  215314. if (enabledInputs[i + 1])
  215315. right = inputBuffers.getSampleData (numIns++);
  215316. if (left != 0 || right != 0)
  215317. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215318. dlh.inputGuids [inputDeviceIndex],
  215319. (int) sampleRate, bufferSizeSamples,
  215320. left, right));
  215321. }
  215322. enabledOutputs = outputChannels;
  215323. enabledOutputs.setRange (outChannels.size(),
  215324. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215325. false);
  215326. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215327. outputBuffers.clear();
  215328. int numOuts = 0;
  215329. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215330. {
  215331. float* left = 0;
  215332. if (enabledOutputs[i])
  215333. left = outputBuffers.getSampleData (numOuts++);
  215334. float* right = 0;
  215335. if (enabledOutputs[i + 1])
  215336. right = outputBuffers.getSampleData (numOuts++);
  215337. if (left != 0 || right != 0)
  215338. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215339. dlh.outputGuids [outputDeviceIndex],
  215340. (int) sampleRate, bufferSizeSamples,
  215341. left, right));
  215342. }
  215343. String error;
  215344. // boost our priority while opening the devices to try to get better sync between them
  215345. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215346. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215347. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215348. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215349. for (i = 0; i < outChans.size(); ++i)
  215350. {
  215351. error = outChans[i]->open();
  215352. if (error.isNotEmpty())
  215353. {
  215354. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215355. break;
  215356. }
  215357. }
  215358. if (error.isEmpty())
  215359. {
  215360. for (i = 0; i < inChans.size(); ++i)
  215361. {
  215362. error = inChans[i]->open();
  215363. if (error.isNotEmpty())
  215364. {
  215365. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215366. break;
  215367. }
  215368. }
  215369. }
  215370. if (error.isEmpty())
  215371. {
  215372. totalSamplesOut = 0;
  215373. for (i = 0; i < outChans.size(); ++i)
  215374. outChans.getUnchecked(i)->synchronisePosition();
  215375. for (i = 0; i < inChans.size(); ++i)
  215376. inChans.getUnchecked(i)->synchronisePosition();
  215377. startThread (9);
  215378. sleep (10);
  215379. notify();
  215380. }
  215381. else
  215382. {
  215383. log (error);
  215384. }
  215385. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215386. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215387. return error;
  215388. }
  215389. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215390. {
  215391. return new DSoundAudioIODeviceType();
  215392. }
  215393. #undef log
  215394. #endif
  215395. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215396. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215397. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215398. // compiled on its own).
  215399. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215400. #ifndef WASAPI_ENABLE_LOGGING
  215401. #define WASAPI_ENABLE_LOGGING 1
  215402. #endif
  215403. namespace WasapiClasses
  215404. {
  215405. void logFailure (HRESULT hr)
  215406. {
  215407. (void) hr;
  215408. #if WASAPI_ENABLE_LOGGING
  215409. if (FAILED (hr))
  215410. {
  215411. String e;
  215412. e << Time::getCurrentTime().toString (true, true, true, true)
  215413. << " -- WASAPI error: ";
  215414. switch (hr)
  215415. {
  215416. case E_POINTER: e << "E_POINTER"; break;
  215417. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215418. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215419. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215420. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215421. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215422. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215423. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215424. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215425. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215426. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215427. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215428. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215429. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215430. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215431. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215432. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215433. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215434. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215435. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215436. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215437. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215438. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215439. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215440. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215441. default: e << String::toHexString ((int) hr); break;
  215442. }
  215443. DBG (e);
  215444. jassertfalse;
  215445. }
  215446. #endif
  215447. }
  215448. #undef check
  215449. bool check (HRESULT hr)
  215450. {
  215451. logFailure (hr);
  215452. return SUCCEEDED (hr);
  215453. }
  215454. const String getDeviceID (IMMDevice* const device)
  215455. {
  215456. String s;
  215457. WCHAR* deviceId = 0;
  215458. if (check (device->GetId (&deviceId)))
  215459. {
  215460. s = String (deviceId);
  215461. CoTaskMemFree (deviceId);
  215462. }
  215463. return s;
  215464. }
  215465. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215466. {
  215467. EDataFlow flow = eRender;
  215468. ComSmartPtr <IMMEndpoint> endPoint;
  215469. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215470. (void) check (endPoint->GetDataFlow (&flow));
  215471. return flow;
  215472. }
  215473. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215474. {
  215475. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215476. }
  215477. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215478. {
  215479. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215480. : sizeof (WAVEFORMATEX));
  215481. }
  215482. class WASAPIDeviceBase
  215483. {
  215484. public:
  215485. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215486. : device (device_),
  215487. sampleRate (0),
  215488. numChannels (0),
  215489. actualNumChannels (0),
  215490. defaultSampleRate (0),
  215491. minBufferSize (0),
  215492. defaultBufferSize (0),
  215493. latencySamples (0),
  215494. useExclusiveMode (useExclusiveMode_)
  215495. {
  215496. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215497. ComSmartPtr <IAudioClient> tempClient (createClient());
  215498. if (tempClient == 0)
  215499. return;
  215500. REFERENCE_TIME defaultPeriod, minPeriod;
  215501. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215502. return;
  215503. WAVEFORMATEX* mixFormat = 0;
  215504. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215505. return;
  215506. WAVEFORMATEXTENSIBLE format;
  215507. copyWavFormat (format, mixFormat);
  215508. CoTaskMemFree (mixFormat);
  215509. actualNumChannels = numChannels = format.Format.nChannels;
  215510. defaultSampleRate = format.Format.nSamplesPerSec;
  215511. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215512. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215513. rates.addUsingDefaultSort (defaultSampleRate);
  215514. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215515. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215516. {
  215517. if (ratesToTest[i] == defaultSampleRate)
  215518. continue;
  215519. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215520. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215521. (WAVEFORMATEX*) &format, 0)))
  215522. if (! rates.contains (ratesToTest[i]))
  215523. rates.addUsingDefaultSort (ratesToTest[i]);
  215524. }
  215525. }
  215526. ~WASAPIDeviceBase()
  215527. {
  215528. device = 0;
  215529. CloseHandle (clientEvent);
  215530. }
  215531. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215532. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215533. {
  215534. sampleRate = newSampleRate;
  215535. channels = newChannels;
  215536. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215537. numChannels = channels.getHighestBit() + 1;
  215538. if (numChannels == 0)
  215539. return true;
  215540. client = createClient();
  215541. if (client != 0
  215542. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215543. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215544. {
  215545. channelMaps.clear();
  215546. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215547. if (channels[i])
  215548. channelMaps.add (i);
  215549. REFERENCE_TIME latency;
  215550. if (check (client->GetStreamLatency (&latency)))
  215551. latencySamples = refTimeToSamples (latency, sampleRate);
  215552. (void) check (client->GetBufferSize (&actualBufferSize));
  215553. return check (client->SetEventHandle (clientEvent));
  215554. }
  215555. return false;
  215556. }
  215557. void closeClient()
  215558. {
  215559. if (client != 0)
  215560. client->Stop();
  215561. client = 0;
  215562. ResetEvent (clientEvent);
  215563. }
  215564. ComSmartPtr <IMMDevice> device;
  215565. ComSmartPtr <IAudioClient> client;
  215566. double sampleRate, defaultSampleRate;
  215567. int numChannels, actualNumChannels;
  215568. int minBufferSize, defaultBufferSize, latencySamples;
  215569. const bool useExclusiveMode;
  215570. Array <double> rates;
  215571. HANDLE clientEvent;
  215572. BigInteger channels;
  215573. Array <int> channelMaps;
  215574. UINT32 actualBufferSize;
  215575. int bytesPerSample;
  215576. virtual void updateFormat (bool isFloat) = 0;
  215577. private:
  215578. const ComSmartPtr <IAudioClient> createClient()
  215579. {
  215580. ComSmartPtr <IAudioClient> client;
  215581. if (device != 0)
  215582. {
  215583. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215584. logFailure (hr);
  215585. }
  215586. return client;
  215587. }
  215588. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215589. {
  215590. WAVEFORMATEXTENSIBLE format;
  215591. zerostruct (format);
  215592. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215593. {
  215594. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215595. }
  215596. else
  215597. {
  215598. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215599. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215600. }
  215601. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215602. format.Format.nChannels = (WORD) numChannels;
  215603. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215604. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215605. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215606. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215607. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215608. switch (numChannels)
  215609. {
  215610. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215611. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215612. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215613. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215614. 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;
  215615. default: break;
  215616. }
  215617. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215618. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215619. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215620. logFailure (hr);
  215621. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215622. {
  215623. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215624. hr = S_OK;
  215625. }
  215626. CoTaskMemFree (nearestFormat);
  215627. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215628. if (useExclusiveMode)
  215629. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215630. GUID session;
  215631. if (hr == S_OK
  215632. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215633. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215634. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215635. {
  215636. actualNumChannels = format.Format.nChannels;
  215637. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215638. bytesPerSample = format.Format.wBitsPerSample / 8;
  215639. updateFormat (isFloat);
  215640. return true;
  215641. }
  215642. return false;
  215643. }
  215644. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  215645. };
  215646. class WASAPIInputDevice : public WASAPIDeviceBase
  215647. {
  215648. public:
  215649. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215650. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215651. reservoir (1, 1)
  215652. {
  215653. }
  215654. ~WASAPIInputDevice()
  215655. {
  215656. close();
  215657. }
  215658. bool open (const double newSampleRate, const BigInteger& newChannels)
  215659. {
  215660. reservoirSize = 0;
  215661. reservoirCapacity = 16384;
  215662. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215663. return openClient (newSampleRate, newChannels)
  215664. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient), (void**) captureClient.resetAndGetPointerAddress())));
  215665. }
  215666. void close()
  215667. {
  215668. closeClient();
  215669. captureClient = 0;
  215670. reservoir.setSize (0);
  215671. }
  215672. void updateFormat (bool isFloat)
  215673. {
  215674. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215675. if (isFloat)
  215676. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215677. else if (bytesPerSample == 4)
  215678. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215679. else if (bytesPerSample == 3)
  215680. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215681. else
  215682. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215683. }
  215684. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215685. {
  215686. if (numChannels <= 0)
  215687. return;
  215688. int offset = 0;
  215689. while (bufferSize > 0)
  215690. {
  215691. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215692. {
  215693. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215694. for (int i = 0; i < numDestBuffers; ++i)
  215695. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215696. bufferSize -= samplesToDo;
  215697. offset += samplesToDo;
  215698. reservoirSize -= samplesToDo;
  215699. }
  215700. else
  215701. {
  215702. UINT32 packetLength = 0;
  215703. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215704. break;
  215705. if (packetLength == 0)
  215706. {
  215707. if (thread.threadShouldExit())
  215708. break;
  215709. Thread::sleep (1);
  215710. continue;
  215711. }
  215712. uint8* inputData = 0;
  215713. UINT32 numSamplesAvailable;
  215714. DWORD flags;
  215715. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215716. {
  215717. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215718. for (int i = 0; i < numDestBuffers; ++i)
  215719. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215720. bufferSize -= samplesToDo;
  215721. offset += samplesToDo;
  215722. if (samplesToDo < (int) numSamplesAvailable)
  215723. {
  215724. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215725. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215726. bytesPerSample * actualNumChannels * reservoirSize);
  215727. }
  215728. captureClient->ReleaseBuffer (numSamplesAvailable);
  215729. }
  215730. }
  215731. }
  215732. }
  215733. ComSmartPtr <IAudioCaptureClient> captureClient;
  215734. MemoryBlock reservoir;
  215735. int reservoirSize, reservoirCapacity;
  215736. ScopedPointer <AudioData::Converter> converter;
  215737. private:
  215738. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  215739. };
  215740. class WASAPIOutputDevice : public WASAPIDeviceBase
  215741. {
  215742. public:
  215743. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215744. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215745. {
  215746. }
  215747. ~WASAPIOutputDevice()
  215748. {
  215749. close();
  215750. }
  215751. bool open (const double newSampleRate, const BigInteger& newChannels)
  215752. {
  215753. return openClient (newSampleRate, newChannels)
  215754. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215755. }
  215756. void close()
  215757. {
  215758. closeClient();
  215759. renderClient = 0;
  215760. }
  215761. void updateFormat (bool isFloat)
  215762. {
  215763. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215764. if (isFloat)
  215765. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215766. else if (bytesPerSample == 4)
  215767. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215768. else if (bytesPerSample == 3)
  215769. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215770. else
  215771. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215772. }
  215773. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215774. {
  215775. if (numChannels <= 0)
  215776. return;
  215777. int offset = 0;
  215778. while (bufferSize > 0)
  215779. {
  215780. UINT32 padding = 0;
  215781. if (! check (client->GetCurrentPadding (&padding)))
  215782. return;
  215783. int samplesToDo = useExclusiveMode ? bufferSize
  215784. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215785. if (samplesToDo <= 0)
  215786. {
  215787. if (thread.threadShouldExit())
  215788. break;
  215789. Thread::sleep (0);
  215790. continue;
  215791. }
  215792. uint8* outputData = 0;
  215793. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215794. {
  215795. for (int i = 0; i < numSrcBuffers; ++i)
  215796. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  215797. renderClient->ReleaseBuffer (samplesToDo, 0);
  215798. offset += samplesToDo;
  215799. bufferSize -= samplesToDo;
  215800. }
  215801. }
  215802. }
  215803. ComSmartPtr <IAudioRenderClient> renderClient;
  215804. ScopedPointer <AudioData::Converter> converter;
  215805. private:
  215806. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  215807. };
  215808. class WASAPIAudioIODevice : public AudioIODevice,
  215809. public Thread
  215810. {
  215811. public:
  215812. WASAPIAudioIODevice (const String& deviceName,
  215813. const String& outputDeviceId_,
  215814. const String& inputDeviceId_,
  215815. const bool useExclusiveMode_)
  215816. : AudioIODevice (deviceName, "Windows Audio"),
  215817. Thread ("Juce WASAPI"),
  215818. isOpen_ (false),
  215819. isStarted (false),
  215820. outputDeviceId (outputDeviceId_),
  215821. inputDeviceId (inputDeviceId_),
  215822. useExclusiveMode (useExclusiveMode_),
  215823. currentBufferSizeSamples (0),
  215824. currentSampleRate (0),
  215825. callback (0)
  215826. {
  215827. }
  215828. ~WASAPIAudioIODevice()
  215829. {
  215830. close();
  215831. }
  215832. bool initialise()
  215833. {
  215834. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215835. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215836. latencyIn = latencyOut = 0;
  215837. Array <double> ratesIn, ratesOut;
  215838. if (createDevices())
  215839. {
  215840. jassert (inputDevice != 0 || outputDevice != 0);
  215841. if (inputDevice != 0 && outputDevice != 0)
  215842. {
  215843. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215844. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215845. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215846. sampleRates = inputDevice->rates;
  215847. sampleRates.removeValuesNotIn (outputDevice->rates);
  215848. }
  215849. else
  215850. {
  215851. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215852. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215853. defaultSampleRate = d->defaultSampleRate;
  215854. minBufferSize = d->minBufferSize;
  215855. defaultBufferSize = d->defaultBufferSize;
  215856. sampleRates = d->rates;
  215857. }
  215858. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215859. if (minBufferSize != defaultBufferSize)
  215860. bufferSizes.addUsingDefaultSort (minBufferSize);
  215861. int n = 64;
  215862. for (int i = 0; i < 40; ++i)
  215863. {
  215864. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215865. bufferSizes.addUsingDefaultSort (n);
  215866. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215867. }
  215868. return true;
  215869. }
  215870. return false;
  215871. }
  215872. const StringArray getOutputChannelNames()
  215873. {
  215874. StringArray outChannels;
  215875. if (outputDevice != 0)
  215876. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215877. outChannels.add ("Output channel " + String (i));
  215878. return outChannels;
  215879. }
  215880. const StringArray getInputChannelNames()
  215881. {
  215882. StringArray inChannels;
  215883. if (inputDevice != 0)
  215884. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215885. inChannels.add ("Input channel " + String (i));
  215886. return inChannels;
  215887. }
  215888. int getNumSampleRates() { return sampleRates.size(); }
  215889. double getSampleRate (int index) { return sampleRates [index]; }
  215890. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215891. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215892. int getDefaultBufferSize() { return defaultBufferSize; }
  215893. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215894. double getCurrentSampleRate() { return currentSampleRate; }
  215895. int getCurrentBitDepth() { return 32; }
  215896. int getOutputLatencyInSamples() { return latencyOut; }
  215897. int getInputLatencyInSamples() { return latencyIn; }
  215898. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215899. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215900. const String getLastError() { return lastError; }
  215901. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215902. double sampleRate, int bufferSizeSamples)
  215903. {
  215904. close();
  215905. lastError = String::empty;
  215906. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215907. {
  215908. lastError = "The input and output devices don't share a common sample rate!";
  215909. return lastError;
  215910. }
  215911. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215912. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215913. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215914. {
  215915. lastError = "Couldn't open the input device!";
  215916. return lastError;
  215917. }
  215918. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215919. {
  215920. close();
  215921. lastError = "Couldn't open the output device!";
  215922. return lastError;
  215923. }
  215924. if (inputDevice != 0)
  215925. ResetEvent (inputDevice->clientEvent);
  215926. if (outputDevice != 0)
  215927. ResetEvent (outputDevice->clientEvent);
  215928. startThread (8);
  215929. Thread::sleep (5);
  215930. if (inputDevice != 0 && inputDevice->client != 0)
  215931. {
  215932. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215933. HRESULT hr = inputDevice->client->Start();
  215934. logFailure (hr); //xxx handle this
  215935. }
  215936. if (outputDevice != 0 && outputDevice->client != 0)
  215937. {
  215938. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215939. HRESULT hr = outputDevice->client->Start();
  215940. logFailure (hr); //xxx handle this
  215941. }
  215942. isOpen_ = true;
  215943. return lastError;
  215944. }
  215945. void close()
  215946. {
  215947. stop();
  215948. if (inputDevice != 0)
  215949. SetEvent (inputDevice->clientEvent);
  215950. if (outputDevice != 0)
  215951. SetEvent (outputDevice->clientEvent);
  215952. stopThread (5000);
  215953. if (inputDevice != 0)
  215954. inputDevice->close();
  215955. if (outputDevice != 0)
  215956. outputDevice->close();
  215957. isOpen_ = false;
  215958. }
  215959. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215960. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215961. void start (AudioIODeviceCallback* call)
  215962. {
  215963. if (isOpen_ && call != 0 && ! isStarted)
  215964. {
  215965. if (! isThreadRunning())
  215966. {
  215967. // something's gone wrong and the thread's stopped..
  215968. isOpen_ = false;
  215969. return;
  215970. }
  215971. call->audioDeviceAboutToStart (this);
  215972. const ScopedLock sl (startStopLock);
  215973. callback = call;
  215974. isStarted = true;
  215975. }
  215976. }
  215977. void stop()
  215978. {
  215979. if (isStarted)
  215980. {
  215981. AudioIODeviceCallback* const callbackLocal = callback;
  215982. {
  215983. const ScopedLock sl (startStopLock);
  215984. isStarted = false;
  215985. }
  215986. if (callbackLocal != 0)
  215987. callbackLocal->audioDeviceStopped();
  215988. }
  215989. }
  215990. void setMMThreadPriority()
  215991. {
  215992. DynamicLibraryLoader dll ("avrt.dll");
  215993. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  215994. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215995. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215996. {
  215997. DWORD dummy = 0;
  215998. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  215999. if (h != 0)
  216000. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216001. }
  216002. }
  216003. void run()
  216004. {
  216005. setMMThreadPriority();
  216006. const int bufferSize = currentBufferSizeSamples;
  216007. HANDLE events[2];
  216008. int numEvents = 0;
  216009. if (inputDevice != 0)
  216010. events [numEvents++] = inputDevice->clientEvent;
  216011. if (outputDevice != 0)
  216012. events [numEvents++] = outputDevice->clientEvent;
  216013. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216014. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216015. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216016. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216017. float** const inputBuffers = ins.getArrayOfChannels();
  216018. float** const outputBuffers = outs.getArrayOfChannels();
  216019. ins.clear();
  216020. while (! threadShouldExit())
  216021. {
  216022. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216023. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216024. if (result == WAIT_TIMEOUT)
  216025. continue;
  216026. if (threadShouldExit())
  216027. break;
  216028. if (inputDevice != 0)
  216029. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216030. // Make the callback..
  216031. {
  216032. const ScopedLock sl (startStopLock);
  216033. if (isStarted)
  216034. {
  216035. JUCE_TRY
  216036. {
  216037. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216038. numInputBuffers,
  216039. outputBuffers,
  216040. numOutputBuffers,
  216041. bufferSize);
  216042. }
  216043. JUCE_CATCH_EXCEPTION
  216044. }
  216045. else
  216046. {
  216047. outs.clear();
  216048. }
  216049. }
  216050. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216051. continue;
  216052. if (outputDevice != 0)
  216053. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216054. }
  216055. }
  216056. String outputDeviceId, inputDeviceId;
  216057. String lastError;
  216058. private:
  216059. // Device stats...
  216060. ScopedPointer<WASAPIInputDevice> inputDevice;
  216061. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216062. const bool useExclusiveMode;
  216063. double defaultSampleRate;
  216064. int minBufferSize, defaultBufferSize;
  216065. int latencyIn, latencyOut;
  216066. Array <double> sampleRates;
  216067. Array <int> bufferSizes;
  216068. // Active state...
  216069. bool isOpen_, isStarted;
  216070. int currentBufferSizeSamples;
  216071. double currentSampleRate;
  216072. AudioIODeviceCallback* callback;
  216073. CriticalSection startStopLock;
  216074. bool createDevices()
  216075. {
  216076. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216077. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216078. return false;
  216079. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216080. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  216081. return false;
  216082. UINT32 numDevices = 0;
  216083. if (! check (deviceCollection->GetCount (&numDevices)))
  216084. return false;
  216085. for (UINT32 i = 0; i < numDevices; ++i)
  216086. {
  216087. ComSmartPtr <IMMDevice> device;
  216088. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216089. continue;
  216090. const String deviceId (getDeviceID (device));
  216091. if (deviceId.isEmpty())
  216092. continue;
  216093. const EDataFlow flow = getDataFlow (device);
  216094. if (deviceId == inputDeviceId && flow == eCapture)
  216095. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216096. else if (deviceId == outputDeviceId && flow == eRender)
  216097. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216098. }
  216099. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216100. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216101. }
  216102. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  216103. };
  216104. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216105. {
  216106. public:
  216107. WASAPIAudioIODeviceType()
  216108. : AudioIODeviceType ("Windows Audio"),
  216109. hasScanned (false)
  216110. {
  216111. }
  216112. ~WASAPIAudioIODeviceType()
  216113. {
  216114. }
  216115. void scanForDevices()
  216116. {
  216117. hasScanned = true;
  216118. outputDeviceNames.clear();
  216119. inputDeviceNames.clear();
  216120. outputDeviceIds.clear();
  216121. inputDeviceIds.clear();
  216122. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216123. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216124. return;
  216125. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216126. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216127. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216128. UINT32 numDevices = 0;
  216129. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  216130. && check (deviceCollection->GetCount (&numDevices))))
  216131. return;
  216132. for (UINT32 i = 0; i < numDevices; ++i)
  216133. {
  216134. ComSmartPtr <IMMDevice> device;
  216135. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216136. continue;
  216137. const String deviceId (getDeviceID (device));
  216138. DWORD state = 0;
  216139. if (! check (device->GetState (&state)))
  216140. continue;
  216141. if (state != DEVICE_STATE_ACTIVE)
  216142. continue;
  216143. String name;
  216144. {
  216145. ComSmartPtr <IPropertyStore> properties;
  216146. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  216147. continue;
  216148. PROPVARIANT value;
  216149. PropVariantInit (&value);
  216150. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216151. name = value.pwszVal;
  216152. PropVariantClear (&value);
  216153. }
  216154. const EDataFlow flow = getDataFlow (device);
  216155. if (flow == eRender)
  216156. {
  216157. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216158. outputDeviceIds.insert (index, deviceId);
  216159. outputDeviceNames.insert (index, name);
  216160. }
  216161. else if (flow == eCapture)
  216162. {
  216163. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216164. inputDeviceIds.insert (index, deviceId);
  216165. inputDeviceNames.insert (index, name);
  216166. }
  216167. }
  216168. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216169. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216170. }
  216171. const StringArray getDeviceNames (bool wantInputNames) const
  216172. {
  216173. jassert (hasScanned); // need to call scanForDevices() before doing this
  216174. return wantInputNames ? inputDeviceNames
  216175. : outputDeviceNames;
  216176. }
  216177. int getDefaultDeviceIndex (bool /*forInput*/) const
  216178. {
  216179. jassert (hasScanned); // need to call scanForDevices() before doing this
  216180. return 0;
  216181. }
  216182. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216183. {
  216184. jassert (hasScanned); // need to call scanForDevices() before doing this
  216185. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216186. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216187. : outputDeviceIds.indexOf (d->outputDeviceId));
  216188. }
  216189. bool hasSeparateInputsAndOutputs() const { return true; }
  216190. AudioIODevice* createDevice (const String& outputDeviceName,
  216191. const String& inputDeviceName)
  216192. {
  216193. jassert (hasScanned); // need to call scanForDevices() before doing this
  216194. const bool useExclusiveMode = false;
  216195. ScopedPointer<WASAPIAudioIODevice> device;
  216196. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216197. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216198. if (outputIndex >= 0 || inputIndex >= 0)
  216199. {
  216200. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216201. : inputDeviceName,
  216202. outputDeviceIds [outputIndex],
  216203. inputDeviceIds [inputIndex],
  216204. useExclusiveMode);
  216205. if (! device->initialise())
  216206. device = 0;
  216207. }
  216208. return device.release();
  216209. }
  216210. StringArray outputDeviceNames, outputDeviceIds;
  216211. StringArray inputDeviceNames, inputDeviceIds;
  216212. private:
  216213. bool hasScanned;
  216214. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216215. {
  216216. String s;
  216217. IMMDevice* dev = 0;
  216218. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216219. eMultimedia, &dev)))
  216220. {
  216221. WCHAR* deviceId = 0;
  216222. if (check (dev->GetId (&deviceId)))
  216223. {
  216224. s = String (deviceId);
  216225. CoTaskMemFree (deviceId);
  216226. }
  216227. dev->Release();
  216228. }
  216229. return s;
  216230. }
  216231. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  216232. };
  216233. }
  216234. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216235. {
  216236. return new WasapiClasses::WASAPIAudioIODeviceType();
  216237. }
  216238. #endif
  216239. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216240. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216241. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216242. // compiled on its own).
  216243. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216244. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216245. {
  216246. public:
  216247. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216248. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216249. const ComSmartPtr <IBaseFilter>& filter_,
  216250. int minWidth, int minHeight,
  216251. int maxWidth, int maxHeight)
  216252. : owner (owner_),
  216253. captureGraphBuilder (captureGraphBuilder_),
  216254. filter (filter_),
  216255. ok (false),
  216256. imageNeedsFlipping (false),
  216257. width (0),
  216258. height (0),
  216259. activeUsers (0),
  216260. recordNextFrameTime (false),
  216261. previewMaxFPS (60)
  216262. {
  216263. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216264. if (FAILED (hr))
  216265. return;
  216266. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216267. if (FAILED (hr))
  216268. return;
  216269. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  216270. if (FAILED (hr))
  216271. return;
  216272. {
  216273. ComSmartPtr <IAMStreamConfig> streamConfig;
  216274. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216275. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  216276. if (streamConfig != 0)
  216277. {
  216278. getVideoSizes (streamConfig);
  216279. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216280. return;
  216281. }
  216282. }
  216283. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216284. if (FAILED (hr))
  216285. return;
  216286. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216287. if (FAILED (hr))
  216288. return;
  216289. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216290. if (FAILED (hr))
  216291. return;
  216292. if (! connectFilters (filter, smartTee))
  216293. return;
  216294. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216295. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216296. if (FAILED (hr))
  216297. return;
  216298. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  216299. if (FAILED (hr))
  216300. return;
  216301. AM_MEDIA_TYPE mt;
  216302. zerostruct (mt);
  216303. mt.majortype = MEDIATYPE_Video;
  216304. mt.subtype = MEDIASUBTYPE_RGB24;
  216305. mt.formattype = FORMAT_VideoInfo;
  216306. sampleGrabber->SetMediaType (&mt);
  216307. callback = new GrabberCallback (*this);
  216308. hr = sampleGrabber->SetCallback (callback, 1);
  216309. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216310. if (FAILED (hr))
  216311. return;
  216312. ComSmartPtr <IPin> grabberInputPin;
  216313. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  216314. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  216315. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  216316. return;
  216317. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216318. if (FAILED (hr))
  216319. return;
  216320. zerostruct (mt);
  216321. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216322. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216323. width = pVih->bmiHeader.biWidth;
  216324. height = pVih->bmiHeader.biHeight;
  216325. ComSmartPtr <IBaseFilter> nullFilter;
  216326. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216327. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216328. if (connectFilters (sampleGrabberBase, nullFilter)
  216329. && addGraphToRot())
  216330. {
  216331. activeImage = Image (Image::RGB, width, height, true);
  216332. loadingImage = Image (Image::RGB, width, height, true);
  216333. ok = true;
  216334. }
  216335. }
  216336. ~DShowCameraDeviceInteral()
  216337. {
  216338. if (mediaControl != 0)
  216339. mediaControl->Stop();
  216340. removeGraphFromRot();
  216341. for (int i = viewerComps.size(); --i >= 0;)
  216342. viewerComps.getUnchecked(i)->ownerDeleted();
  216343. callback = 0;
  216344. graphBuilder = 0;
  216345. sampleGrabber = 0;
  216346. mediaControl = 0;
  216347. filter = 0;
  216348. captureGraphBuilder = 0;
  216349. smartTee = 0;
  216350. smartTeePreviewOutputPin = 0;
  216351. smartTeeCaptureOutputPin = 0;
  216352. asfWriter = 0;
  216353. }
  216354. void addUser()
  216355. {
  216356. if (ok && activeUsers++ == 0)
  216357. mediaControl->Run();
  216358. }
  216359. void removeUser()
  216360. {
  216361. if (ok && --activeUsers == 0)
  216362. mediaControl->Stop();
  216363. }
  216364. int getPreviewMaxFPS() const
  216365. {
  216366. return previewMaxFPS;
  216367. }
  216368. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216369. {
  216370. if (recordNextFrameTime)
  216371. {
  216372. const double defaultCameraLatency = 0.1;
  216373. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216374. recordNextFrameTime = false;
  216375. ComSmartPtr <IPin> pin;
  216376. if (getPin (filter, PINDIR_OUTPUT, pin))
  216377. {
  216378. ComSmartPtr <IAMPushSource> pushSource;
  216379. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  216380. if (pushSource != 0)
  216381. {
  216382. REFERENCE_TIME latency = 0;
  216383. hr = pushSource->GetLatency (&latency);
  216384. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216385. }
  216386. }
  216387. }
  216388. {
  216389. const int lineStride = width * 3;
  216390. const ScopedLock sl (imageSwapLock);
  216391. {
  216392. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216393. for (int i = 0; i < height; ++i)
  216394. memcpy (destData.getLinePointer ((height - 1) - i),
  216395. buffer + lineStride * i,
  216396. lineStride);
  216397. }
  216398. imageNeedsFlipping = true;
  216399. }
  216400. if (listeners.size() > 0)
  216401. callListeners (loadingImage);
  216402. sendChangeMessage();
  216403. }
  216404. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216405. {
  216406. if (imageNeedsFlipping)
  216407. {
  216408. const ScopedLock sl (imageSwapLock);
  216409. swapVariables (loadingImage, activeImage);
  216410. imageNeedsFlipping = false;
  216411. }
  216412. RectanglePlacement rp (RectanglePlacement::centred);
  216413. double dx = 0, dy = 0, dw = width, dh = height;
  216414. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216415. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216416. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216417. g.saveState();
  216418. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216419. g.fillAll (Colours::black);
  216420. g.restoreState();
  216421. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216422. }
  216423. bool createFileCaptureFilter (const File& file, int quality)
  216424. {
  216425. removeFileCaptureFilter();
  216426. file.deleteFile();
  216427. mediaControl->Stop();
  216428. firstRecordedTime = Time();
  216429. recordNextFrameTime = true;
  216430. previewMaxFPS = 60;
  216431. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216432. if (SUCCEEDED (hr))
  216433. {
  216434. ComSmartPtr <IFileSinkFilter> fileSink;
  216435. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216436. if (SUCCEEDED (hr))
  216437. {
  216438. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216439. if (SUCCEEDED (hr))
  216440. {
  216441. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216442. if (SUCCEEDED (hr))
  216443. {
  216444. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216445. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216446. asfConfig->SetIndexMode (true);
  216447. ComSmartPtr <IWMProfileManager> profileManager;
  216448. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216449. // This gibberish is the DirectShow profile for a video-only wmv file.
  216450. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  216451. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  216452. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216453. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  216454. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216455. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  216456. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  216457. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  216458. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216459. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216460. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216461. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  216462. "biclrused=\"0\" biclrimportant=\"0\"/>"
  216463. "</videoinfoheader>"
  216464. "</wmmediatype>"
  216465. "</streamconfig>"
  216466. "</profile>");
  216467. const int fps[] = { 10, 15, 30 };
  216468. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  216469. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216470. maxFramesPerSecond = (quality >> 24) & 0xff;
  216471. prof = prof.replace ("$WIDTH", String (width))
  216472. .replace ("$HEIGHT", String (height))
  216473. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  216474. ComSmartPtr <IWMProfile> currentProfile;
  216475. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  216476. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216477. if (SUCCEEDED (hr))
  216478. {
  216479. ComSmartPtr <IPin> asfWriterInputPin;
  216480. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216481. {
  216482. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216483. if (SUCCEEDED (hr) && ok && activeUsers > 0
  216484. && SUCCEEDED (mediaControl->Run()))
  216485. {
  216486. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  216487. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216488. previewMaxFPS = (quality >> 16) & 0xff;
  216489. return true;
  216490. }
  216491. }
  216492. }
  216493. }
  216494. }
  216495. }
  216496. }
  216497. removeFileCaptureFilter();
  216498. if (ok && activeUsers > 0)
  216499. mediaControl->Run();
  216500. return false;
  216501. }
  216502. void removeFileCaptureFilter()
  216503. {
  216504. mediaControl->Stop();
  216505. if (asfWriter != 0)
  216506. {
  216507. graphBuilder->RemoveFilter (asfWriter);
  216508. asfWriter = 0;
  216509. }
  216510. if (ok && activeUsers > 0)
  216511. mediaControl->Run();
  216512. previewMaxFPS = 60;
  216513. }
  216514. void addListener (CameraDevice::Listener* listenerToAdd)
  216515. {
  216516. const ScopedLock sl (listenerLock);
  216517. if (listeners.size() == 0)
  216518. addUser();
  216519. listeners.addIfNotAlreadyThere (listenerToAdd);
  216520. }
  216521. void removeListener (CameraDevice::Listener* listenerToRemove)
  216522. {
  216523. const ScopedLock sl (listenerLock);
  216524. listeners.removeValue (listenerToRemove);
  216525. if (listeners.size() == 0)
  216526. removeUser();
  216527. }
  216528. void callListeners (const Image& image)
  216529. {
  216530. const ScopedLock sl (listenerLock);
  216531. for (int i = listeners.size(); --i >= 0;)
  216532. {
  216533. CameraDevice::Listener* const l = listeners[i];
  216534. if (l != 0)
  216535. l->imageReceived (image);
  216536. }
  216537. }
  216538. class DShowCaptureViewerComp : public Component,
  216539. public ChangeListener
  216540. {
  216541. public:
  216542. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216543. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  216544. {
  216545. setOpaque (true);
  216546. owner->addChangeListener (this);
  216547. owner->addUser();
  216548. owner->viewerComps.add (this);
  216549. setSize (owner->width, owner->height);
  216550. }
  216551. ~DShowCaptureViewerComp()
  216552. {
  216553. if (owner != 0)
  216554. {
  216555. owner->viewerComps.removeValue (this);
  216556. owner->removeUser();
  216557. owner->removeChangeListener (this);
  216558. }
  216559. }
  216560. void ownerDeleted()
  216561. {
  216562. owner = 0;
  216563. }
  216564. void paint (Graphics& g)
  216565. {
  216566. g.setColour (Colours::black);
  216567. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216568. if (owner != 0)
  216569. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216570. else
  216571. g.fillAll (Colours::black);
  216572. }
  216573. void changeListenerCallback (ChangeBroadcaster*)
  216574. {
  216575. const int64 now = Time::currentTimeMillis();
  216576. if (now >= lastRepaintTime + (1000 / maxFPS))
  216577. {
  216578. lastRepaintTime = now;
  216579. repaint();
  216580. if (owner != 0)
  216581. maxFPS = owner->getPreviewMaxFPS();
  216582. }
  216583. }
  216584. private:
  216585. DShowCameraDeviceInteral* owner;
  216586. int maxFPS;
  216587. int64 lastRepaintTime;
  216588. };
  216589. bool ok;
  216590. int width, height;
  216591. Time firstRecordedTime;
  216592. Array <DShowCaptureViewerComp*> viewerComps;
  216593. private:
  216594. CameraDevice* const owner;
  216595. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216596. ComSmartPtr <IBaseFilter> filter;
  216597. ComSmartPtr <IBaseFilter> smartTee;
  216598. ComSmartPtr <IGraphBuilder> graphBuilder;
  216599. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216600. ComSmartPtr <IMediaControl> mediaControl;
  216601. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216602. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216603. ComSmartPtr <IBaseFilter> asfWriter;
  216604. int activeUsers;
  216605. Array <int> widths, heights;
  216606. DWORD graphRegistrationID;
  216607. CriticalSection imageSwapLock;
  216608. bool imageNeedsFlipping;
  216609. Image loadingImage;
  216610. Image activeImage;
  216611. bool recordNextFrameTime;
  216612. int previewMaxFPS;
  216613. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216614. {
  216615. widths.clear();
  216616. heights.clear();
  216617. int count = 0, size = 0;
  216618. streamConfig->GetNumberOfCapabilities (&count, &size);
  216619. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216620. {
  216621. for (int i = 0; i < count; ++i)
  216622. {
  216623. VIDEO_STREAM_CONFIG_CAPS scc;
  216624. AM_MEDIA_TYPE* config;
  216625. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216626. if (SUCCEEDED (hr))
  216627. {
  216628. const int w = scc.InputSize.cx;
  216629. const int h = scc.InputSize.cy;
  216630. bool duplicate = false;
  216631. for (int j = widths.size(); --j >= 0;)
  216632. {
  216633. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216634. {
  216635. duplicate = true;
  216636. break;
  216637. }
  216638. }
  216639. if (! duplicate)
  216640. {
  216641. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216642. widths.add (w);
  216643. heights.add (h);
  216644. }
  216645. deleteMediaType (config);
  216646. }
  216647. }
  216648. }
  216649. }
  216650. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216651. const int minWidth, const int minHeight,
  216652. const int maxWidth, const int maxHeight)
  216653. {
  216654. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216655. streamConfig->GetNumberOfCapabilities (&count, &size);
  216656. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216657. {
  216658. AM_MEDIA_TYPE* config;
  216659. VIDEO_STREAM_CONFIG_CAPS scc;
  216660. for (int i = 0; i < count; ++i)
  216661. {
  216662. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216663. if (SUCCEEDED (hr))
  216664. {
  216665. if (scc.InputSize.cx >= minWidth
  216666. && scc.InputSize.cy >= minHeight
  216667. && scc.InputSize.cx <= maxWidth
  216668. && scc.InputSize.cy <= maxHeight)
  216669. {
  216670. int area = scc.InputSize.cx * scc.InputSize.cy;
  216671. if (area > bestArea)
  216672. {
  216673. bestIndex = i;
  216674. bestArea = area;
  216675. }
  216676. }
  216677. deleteMediaType (config);
  216678. }
  216679. }
  216680. if (bestIndex >= 0)
  216681. {
  216682. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216683. hr = streamConfig->SetFormat (config);
  216684. deleteMediaType (config);
  216685. return SUCCEEDED (hr);
  216686. }
  216687. }
  216688. return false;
  216689. }
  216690. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216691. {
  216692. ComSmartPtr <IEnumPins> enumerator;
  216693. ComSmartPtr <IPin> pin;
  216694. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216695. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216696. {
  216697. PIN_DIRECTION dir;
  216698. pin->QueryDirection (&dir);
  216699. if (wantedDirection == dir)
  216700. {
  216701. PIN_INFO info;
  216702. zerostruct (info);
  216703. pin->QueryPinInfo (&info);
  216704. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216705. {
  216706. result = pin;
  216707. return true;
  216708. }
  216709. }
  216710. }
  216711. return false;
  216712. }
  216713. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216714. {
  216715. ComSmartPtr <IPin> in, out;
  216716. return getPin (first, PINDIR_OUTPUT, out)
  216717. && getPin (second, PINDIR_INPUT, in)
  216718. && SUCCEEDED (graphBuilder->Connect (out, in));
  216719. }
  216720. bool addGraphToRot()
  216721. {
  216722. ComSmartPtr <IRunningObjectTable> rot;
  216723. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216724. return false;
  216725. ComSmartPtr <IMoniker> moniker;
  216726. WCHAR buffer[128];
  216727. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216728. if (FAILED (hr))
  216729. return false;
  216730. graphRegistrationID = 0;
  216731. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216732. }
  216733. void removeGraphFromRot()
  216734. {
  216735. ComSmartPtr <IRunningObjectTable> rot;
  216736. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216737. rot->Revoke (graphRegistrationID);
  216738. }
  216739. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216740. {
  216741. if (pmt->cbFormat != 0)
  216742. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216743. if (pmt->pUnk != 0)
  216744. pmt->pUnk->Release();
  216745. CoTaskMemFree (pmt);
  216746. }
  216747. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216748. {
  216749. public:
  216750. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216751. : owner (owner_)
  216752. {
  216753. }
  216754. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216755. {
  216756. return E_FAIL;
  216757. }
  216758. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216759. {
  216760. owner.handleFrame (time, buffer, bufferSize);
  216761. return S_OK;
  216762. }
  216763. private:
  216764. DShowCameraDeviceInteral& owner;
  216765. GrabberCallback (const GrabberCallback&);
  216766. GrabberCallback& operator= (const GrabberCallback&);
  216767. };
  216768. ComSmartPtr <GrabberCallback> callback;
  216769. Array <CameraDevice::Listener*> listeners;
  216770. CriticalSection listenerLock;
  216771. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  216772. };
  216773. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216774. : name (name_)
  216775. {
  216776. isRecording = false;
  216777. }
  216778. CameraDevice::~CameraDevice()
  216779. {
  216780. stopRecording();
  216781. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216782. internal = 0;
  216783. }
  216784. Component* CameraDevice::createViewerComponent()
  216785. {
  216786. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216787. }
  216788. const String CameraDevice::getFileExtension()
  216789. {
  216790. return ".wmv";
  216791. }
  216792. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216793. {
  216794. stopRecording();
  216795. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216796. d->addUser();
  216797. isRecording = d->createFileCaptureFilter (file, quality);
  216798. }
  216799. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216800. {
  216801. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216802. return d->firstRecordedTime;
  216803. }
  216804. void CameraDevice::stopRecording()
  216805. {
  216806. if (isRecording)
  216807. {
  216808. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216809. d->removeFileCaptureFilter();
  216810. d->removeUser();
  216811. isRecording = false;
  216812. }
  216813. }
  216814. void CameraDevice::addListener (Listener* listenerToAdd)
  216815. {
  216816. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216817. if (listenerToAdd != 0)
  216818. d->addListener (listenerToAdd);
  216819. }
  216820. void CameraDevice::removeListener (Listener* listenerToRemove)
  216821. {
  216822. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216823. if (listenerToRemove != 0)
  216824. d->removeListener (listenerToRemove);
  216825. }
  216826. namespace
  216827. {
  216828. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216829. const int deviceIndexToOpen,
  216830. String& name)
  216831. {
  216832. int index = 0;
  216833. ComSmartPtr <IBaseFilter> result;
  216834. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216835. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216836. if (SUCCEEDED (hr))
  216837. {
  216838. ComSmartPtr <IEnumMoniker> enumerator;
  216839. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  216840. if (SUCCEEDED (hr) && enumerator != 0)
  216841. {
  216842. ComSmartPtr <IMoniker> moniker;
  216843. ULONG fetched;
  216844. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  216845. {
  216846. ComSmartPtr <IBaseFilter> captureFilter;
  216847. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  216848. if (SUCCEEDED (hr))
  216849. {
  216850. ComSmartPtr <IPropertyBag> propertyBag;
  216851. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  216852. if (SUCCEEDED (hr))
  216853. {
  216854. VARIANT var;
  216855. var.vt = VT_BSTR;
  216856. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216857. propertyBag = 0;
  216858. if (SUCCEEDED (hr))
  216859. {
  216860. if (names != 0)
  216861. names->add (var.bstrVal);
  216862. if (index == deviceIndexToOpen)
  216863. {
  216864. name = var.bstrVal;
  216865. result = captureFilter;
  216866. break;
  216867. }
  216868. ++index;
  216869. }
  216870. }
  216871. }
  216872. }
  216873. }
  216874. }
  216875. return result;
  216876. }
  216877. }
  216878. const StringArray CameraDevice::getAvailableDevices()
  216879. {
  216880. StringArray devs;
  216881. String dummy;
  216882. enumerateCameras (&devs, -1, dummy);
  216883. return devs;
  216884. }
  216885. CameraDevice* CameraDevice::openDevice (int index,
  216886. int minWidth, int minHeight,
  216887. int maxWidth, int maxHeight)
  216888. {
  216889. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216890. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216891. if (SUCCEEDED (hr))
  216892. {
  216893. String name;
  216894. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216895. if (filter != 0)
  216896. {
  216897. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216898. DShowCameraDeviceInteral* const intern
  216899. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216900. minWidth, minHeight, maxWidth, maxHeight);
  216901. cam->internal = intern;
  216902. if (intern->ok)
  216903. return cam.release();
  216904. }
  216905. }
  216906. return 0;
  216907. }
  216908. #endif
  216909. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216910. #endif
  216911. // Auto-link the other win32 libs that are needed by library calls..
  216912. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216913. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216914. // Auto-links to various win32 libs that are needed by library calls..
  216915. #pragma comment(lib, "kernel32.lib")
  216916. #pragma comment(lib, "user32.lib")
  216917. #pragma comment(lib, "shell32.lib")
  216918. #pragma comment(lib, "gdi32.lib")
  216919. #pragma comment(lib, "vfw32.lib")
  216920. #pragma comment(lib, "comdlg32.lib")
  216921. #pragma comment(lib, "winmm.lib")
  216922. #pragma comment(lib, "wininet.lib")
  216923. #pragma comment(lib, "ole32.lib")
  216924. #pragma comment(lib, "oleaut32.lib")
  216925. #pragma comment(lib, "advapi32.lib")
  216926. #pragma comment(lib, "ws2_32.lib")
  216927. #pragma comment(lib, "version.lib")
  216928. #ifdef _NATIVE_WCHAR_T_DEFINED
  216929. #ifdef _DEBUG
  216930. #pragma comment(lib, "comsuppwd.lib")
  216931. #else
  216932. #pragma comment(lib, "comsuppw.lib")
  216933. #endif
  216934. #else
  216935. #ifdef _DEBUG
  216936. #pragma comment(lib, "comsuppd.lib")
  216937. #else
  216938. #pragma comment(lib, "comsupp.lib")
  216939. #endif
  216940. #endif
  216941. #if JUCE_OPENGL
  216942. #pragma comment(lib, "OpenGL32.Lib")
  216943. #pragma comment(lib, "GlU32.Lib")
  216944. #endif
  216945. #if JUCE_QUICKTIME
  216946. #pragma comment (lib, "QTMLClient.lib")
  216947. #endif
  216948. #if JUCE_USE_CAMERA
  216949. #pragma comment (lib, "Strmiids.lib")
  216950. #pragma comment (lib, "wmvcore.lib")
  216951. #endif
  216952. #if JUCE_DIRECT2D
  216953. #pragma comment (lib, "Dwrite.lib")
  216954. #pragma comment (lib, "D2d1.lib")
  216955. #endif
  216956. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216957. #endif
  216958. END_JUCE_NAMESPACE
  216959. #endif
  216960. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216961. #endif
  216962. #if JUCE_LINUX
  216963. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216964. /*
  216965. This file wraps together all the mac-specific code, so that
  216966. we can include all the native headers just once, and compile all our
  216967. platform-specific stuff in one big lump, keeping it out of the way of
  216968. the rest of the codebase.
  216969. */
  216970. #if JUCE_LINUX
  216971. BEGIN_JUCE_NAMESPACE
  216972. #define JUCE_INCLUDED_FILE 1
  216973. // Now include the actual code files..
  216974. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216975. /*
  216976. This file contains posix routines that are common to both the Linux and Mac builds.
  216977. It gets included directly in the cpp files for these platforms.
  216978. */
  216979. CriticalSection::CriticalSection() throw()
  216980. {
  216981. pthread_mutexattr_t atts;
  216982. pthread_mutexattr_init (&atts);
  216983. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216984. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216985. pthread_mutex_init (&internal, &atts);
  216986. }
  216987. CriticalSection::~CriticalSection() throw()
  216988. {
  216989. pthread_mutex_destroy (&internal);
  216990. }
  216991. void CriticalSection::enter() const throw()
  216992. {
  216993. pthread_mutex_lock (&internal);
  216994. }
  216995. bool CriticalSection::tryEnter() const throw()
  216996. {
  216997. return pthread_mutex_trylock (&internal) == 0;
  216998. }
  216999. void CriticalSection::exit() const throw()
  217000. {
  217001. pthread_mutex_unlock (&internal);
  217002. }
  217003. class WaitableEventImpl
  217004. {
  217005. public:
  217006. WaitableEventImpl (const bool manualReset_)
  217007. : triggered (false),
  217008. manualReset (manualReset_)
  217009. {
  217010. pthread_cond_init (&condition, 0);
  217011. pthread_mutexattr_t atts;
  217012. pthread_mutexattr_init (&atts);
  217013. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217014. pthread_mutex_init (&mutex, &atts);
  217015. }
  217016. ~WaitableEventImpl()
  217017. {
  217018. pthread_cond_destroy (&condition);
  217019. pthread_mutex_destroy (&mutex);
  217020. }
  217021. bool wait (const int timeOutMillisecs) throw()
  217022. {
  217023. pthread_mutex_lock (&mutex);
  217024. if (! triggered)
  217025. {
  217026. if (timeOutMillisecs < 0)
  217027. {
  217028. do
  217029. {
  217030. pthread_cond_wait (&condition, &mutex);
  217031. }
  217032. while (! triggered);
  217033. }
  217034. else
  217035. {
  217036. struct timeval now;
  217037. gettimeofday (&now, 0);
  217038. struct timespec time;
  217039. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217040. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217041. if (time.tv_nsec >= 1000000000)
  217042. {
  217043. time.tv_nsec -= 1000000000;
  217044. time.tv_sec++;
  217045. }
  217046. do
  217047. {
  217048. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217049. {
  217050. pthread_mutex_unlock (&mutex);
  217051. return false;
  217052. }
  217053. }
  217054. while (! triggered);
  217055. }
  217056. }
  217057. if (! manualReset)
  217058. triggered = false;
  217059. pthread_mutex_unlock (&mutex);
  217060. return true;
  217061. }
  217062. void signal() throw()
  217063. {
  217064. pthread_mutex_lock (&mutex);
  217065. triggered = true;
  217066. pthread_cond_broadcast (&condition);
  217067. pthread_mutex_unlock (&mutex);
  217068. }
  217069. void reset() throw()
  217070. {
  217071. pthread_mutex_lock (&mutex);
  217072. triggered = false;
  217073. pthread_mutex_unlock (&mutex);
  217074. }
  217075. private:
  217076. pthread_cond_t condition;
  217077. pthread_mutex_t mutex;
  217078. bool triggered;
  217079. const bool manualReset;
  217080. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  217081. };
  217082. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217083. : internal (new WaitableEventImpl (manualReset))
  217084. {
  217085. }
  217086. WaitableEvent::~WaitableEvent() throw()
  217087. {
  217088. delete static_cast <WaitableEventImpl*> (internal);
  217089. }
  217090. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217091. {
  217092. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217093. }
  217094. void WaitableEvent::signal() const throw()
  217095. {
  217096. static_cast <WaitableEventImpl*> (internal)->signal();
  217097. }
  217098. void WaitableEvent::reset() const throw()
  217099. {
  217100. static_cast <WaitableEventImpl*> (internal)->reset();
  217101. }
  217102. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217103. {
  217104. struct timespec time;
  217105. time.tv_sec = millisecs / 1000;
  217106. time.tv_nsec = (millisecs % 1000) * 1000000;
  217107. nanosleep (&time, 0);
  217108. }
  217109. const juce_wchar File::separator = '/';
  217110. const String File::separatorString ("/");
  217111. const File File::getCurrentWorkingDirectory()
  217112. {
  217113. HeapBlock<char> heapBuffer;
  217114. char localBuffer [1024];
  217115. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217116. int bufferSize = 4096;
  217117. while (cwd == 0 && errno == ERANGE)
  217118. {
  217119. heapBuffer.malloc (bufferSize);
  217120. cwd = getcwd (heapBuffer, bufferSize - 1);
  217121. bufferSize += 1024;
  217122. }
  217123. return File (String::fromUTF8 (cwd));
  217124. }
  217125. bool File::setAsCurrentWorkingDirectory() const
  217126. {
  217127. return chdir (getFullPathName().toUTF8()) == 0;
  217128. }
  217129. namespace
  217130. {
  217131. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217132. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  217133. #else
  217134. typedef struct stat juce_statStruct;
  217135. #endif
  217136. bool juce_stat (const String& fileName, juce_statStruct& info)
  217137. {
  217138. return fileName.isNotEmpty()
  217139. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217140. && (stat64 (fileName.toUTF8(), &info) == 0);
  217141. #else
  217142. && (stat (fileName.toUTF8(), &info) == 0);
  217143. #endif
  217144. }
  217145. // if this file doesn't exist, find a parent of it that does..
  217146. bool juce_doStatFS (File f, struct statfs& result)
  217147. {
  217148. for (int i = 5; --i >= 0;)
  217149. {
  217150. if (f.exists())
  217151. break;
  217152. f = f.getParentDirectory();
  217153. }
  217154. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217155. }
  217156. }
  217157. bool File::isDirectory() const
  217158. {
  217159. juce_statStruct info;
  217160. return fullPath.isEmpty()
  217161. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217162. }
  217163. bool File::exists() const
  217164. {
  217165. juce_statStruct info;
  217166. return fullPath.isNotEmpty()
  217167. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217168. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  217169. #else
  217170. && (lstat (fullPath.toUTF8(), &info) == 0);
  217171. #endif
  217172. }
  217173. bool File::existsAsFile() const
  217174. {
  217175. return exists() && ! isDirectory();
  217176. }
  217177. int64 File::getSize() const
  217178. {
  217179. juce_statStruct info;
  217180. return juce_stat (fullPath, info) ? info.st_size : 0;
  217181. }
  217182. bool File::hasWriteAccess() const
  217183. {
  217184. if (exists())
  217185. return access (fullPath.toUTF8(), W_OK) == 0;
  217186. if ((! isDirectory()) && fullPath.containsChar (separator))
  217187. return getParentDirectory().hasWriteAccess();
  217188. return false;
  217189. }
  217190. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217191. {
  217192. juce_statStruct info;
  217193. if (! juce_stat (fullPath, info))
  217194. return false;
  217195. info.st_mode &= 0777; // Just permissions
  217196. if (shouldBeReadOnly)
  217197. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217198. else
  217199. // Give everybody write permission?
  217200. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217201. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217202. }
  217203. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217204. {
  217205. modificationTime = 0;
  217206. accessTime = 0;
  217207. creationTime = 0;
  217208. juce_statStruct info;
  217209. if (juce_stat (fullPath, info))
  217210. {
  217211. modificationTime = (int64) info.st_mtime * 1000;
  217212. accessTime = (int64) info.st_atime * 1000;
  217213. creationTime = (int64) info.st_ctime * 1000;
  217214. }
  217215. }
  217216. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217217. {
  217218. struct utimbuf times;
  217219. times.actime = (time_t) (accessTime / 1000);
  217220. times.modtime = (time_t) (modificationTime / 1000);
  217221. return utime (fullPath.toUTF8(), &times) == 0;
  217222. }
  217223. bool File::deleteFile() const
  217224. {
  217225. if (! exists())
  217226. return true;
  217227. else if (isDirectory())
  217228. return rmdir (fullPath.toUTF8()) == 0;
  217229. else
  217230. return remove (fullPath.toUTF8()) == 0;
  217231. }
  217232. bool File::moveInternal (const File& dest) const
  217233. {
  217234. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217235. return true;
  217236. if (hasWriteAccess() && copyInternal (dest))
  217237. {
  217238. if (deleteFile())
  217239. return true;
  217240. dest.deleteFile();
  217241. }
  217242. return false;
  217243. }
  217244. void File::createDirectoryInternal (const String& fileName) const
  217245. {
  217246. mkdir (fileName.toUTF8(), 0777);
  217247. }
  217248. int64 juce_fileSetPosition (void* handle, int64 pos)
  217249. {
  217250. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217251. return pos;
  217252. return -1;
  217253. }
  217254. void FileInputStream::openHandle()
  217255. {
  217256. totalSize = file.getSize();
  217257. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217258. if (f != -1)
  217259. fileHandle = (void*) f;
  217260. }
  217261. void FileInputStream::closeHandle()
  217262. {
  217263. if (fileHandle != 0)
  217264. {
  217265. close ((int) (pointer_sized_int) fileHandle);
  217266. fileHandle = 0;
  217267. }
  217268. }
  217269. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217270. {
  217271. if (fileHandle != 0)
  217272. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217273. return 0;
  217274. }
  217275. void FileOutputStream::openHandle()
  217276. {
  217277. if (file.exists())
  217278. {
  217279. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217280. if (f != -1)
  217281. {
  217282. currentPosition = lseek (f, 0, SEEK_END);
  217283. if (currentPosition >= 0)
  217284. fileHandle = (void*) f;
  217285. else
  217286. close (f);
  217287. }
  217288. }
  217289. else
  217290. {
  217291. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217292. if (f != -1)
  217293. fileHandle = (void*) f;
  217294. }
  217295. }
  217296. void FileOutputStream::closeHandle()
  217297. {
  217298. if (fileHandle != 0)
  217299. {
  217300. close ((int) (pointer_sized_int) fileHandle);
  217301. fileHandle = 0;
  217302. }
  217303. }
  217304. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217305. {
  217306. if (fileHandle != 0)
  217307. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217308. return 0;
  217309. }
  217310. void FileOutputStream::flushInternal()
  217311. {
  217312. if (fileHandle != 0)
  217313. fsync ((int) (pointer_sized_int) fileHandle);
  217314. }
  217315. const File juce_getExecutableFile()
  217316. {
  217317. Dl_info exeInfo;
  217318. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217319. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217320. }
  217321. int64 File::getBytesFreeOnVolume() const
  217322. {
  217323. struct statfs buf;
  217324. if (juce_doStatFS (*this, buf))
  217325. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217326. return 0;
  217327. }
  217328. int64 File::getVolumeTotalSize() const
  217329. {
  217330. struct statfs buf;
  217331. if (juce_doStatFS (*this, buf))
  217332. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217333. return 0;
  217334. }
  217335. const String File::getVolumeLabel() const
  217336. {
  217337. #if JUCE_MAC
  217338. struct VolAttrBuf
  217339. {
  217340. u_int32_t length;
  217341. attrreference_t mountPointRef;
  217342. char mountPointSpace [MAXPATHLEN];
  217343. } attrBuf;
  217344. struct attrlist attrList;
  217345. zerostruct (attrList);
  217346. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217347. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217348. File f (*this);
  217349. for (;;)
  217350. {
  217351. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217352. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217353. (int) attrBuf.mountPointRef.attr_length);
  217354. const File parent (f.getParentDirectory());
  217355. if (f == parent)
  217356. break;
  217357. f = parent;
  217358. }
  217359. #endif
  217360. return String::empty;
  217361. }
  217362. int File::getVolumeSerialNumber() const
  217363. {
  217364. return 0; // xxx
  217365. }
  217366. void juce_runSystemCommand (const String& command)
  217367. {
  217368. int result = system (command.toUTF8());
  217369. (void) result;
  217370. }
  217371. const String juce_getOutputFromCommand (const String& command)
  217372. {
  217373. // slight bodge here, as we just pipe the output into a temp file and read it...
  217374. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217375. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217376. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217377. String result (tempFile.loadFileAsString());
  217378. tempFile.deleteFile();
  217379. return result;
  217380. }
  217381. class InterProcessLock::Pimpl
  217382. {
  217383. public:
  217384. Pimpl (const String& name, const int timeOutMillisecs)
  217385. : handle (0), refCount (1)
  217386. {
  217387. #if JUCE_MAC
  217388. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217389. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217390. #else
  217391. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217392. #endif
  217393. temp.create();
  217394. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217395. if (handle != 0)
  217396. {
  217397. struct flock fl;
  217398. zerostruct (fl);
  217399. fl.l_whence = SEEK_SET;
  217400. fl.l_type = F_WRLCK;
  217401. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217402. for (;;)
  217403. {
  217404. const int result = fcntl (handle, F_SETLK, &fl);
  217405. if (result >= 0)
  217406. return;
  217407. if (errno != EINTR)
  217408. {
  217409. if (timeOutMillisecs == 0
  217410. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217411. break;
  217412. Thread::sleep (10);
  217413. }
  217414. }
  217415. }
  217416. closeFile();
  217417. }
  217418. ~Pimpl()
  217419. {
  217420. closeFile();
  217421. }
  217422. void closeFile()
  217423. {
  217424. if (handle != 0)
  217425. {
  217426. struct flock fl;
  217427. zerostruct (fl);
  217428. fl.l_whence = SEEK_SET;
  217429. fl.l_type = F_UNLCK;
  217430. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217431. {}
  217432. close (handle);
  217433. handle = 0;
  217434. }
  217435. }
  217436. int handle, refCount;
  217437. };
  217438. InterProcessLock::InterProcessLock (const String& name_)
  217439. : name (name_)
  217440. {
  217441. }
  217442. InterProcessLock::~InterProcessLock()
  217443. {
  217444. }
  217445. bool InterProcessLock::enter (const int timeOutMillisecs)
  217446. {
  217447. const ScopedLock sl (lock);
  217448. if (pimpl == 0)
  217449. {
  217450. pimpl = new Pimpl (name, timeOutMillisecs);
  217451. if (pimpl->handle == 0)
  217452. pimpl = 0;
  217453. }
  217454. else
  217455. {
  217456. pimpl->refCount++;
  217457. }
  217458. return pimpl != 0;
  217459. }
  217460. void InterProcessLock::exit()
  217461. {
  217462. const ScopedLock sl (lock);
  217463. // Trying to release the lock too many times!
  217464. jassert (pimpl != 0);
  217465. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217466. pimpl = 0;
  217467. }
  217468. void JUCE_API juce_threadEntryPoint (void*);
  217469. void* threadEntryProc (void* userData)
  217470. {
  217471. JUCE_AUTORELEASEPOOL
  217472. juce_threadEntryPoint (userData);
  217473. return 0;
  217474. }
  217475. void* juce_createThread (void* userData)
  217476. {
  217477. pthread_t handle = 0;
  217478. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217479. {
  217480. pthread_detach (handle);
  217481. return (void*) handle;
  217482. }
  217483. return 0;
  217484. }
  217485. void juce_killThread (void* handle)
  217486. {
  217487. if (handle != 0)
  217488. pthread_cancel ((pthread_t) handle);
  217489. }
  217490. void juce_setCurrentThreadName (const String& /*name*/)
  217491. {
  217492. }
  217493. bool juce_setThreadPriority (void* handle, int priority)
  217494. {
  217495. struct sched_param param;
  217496. int policy;
  217497. priority = jlimit (0, 10, priority);
  217498. if (handle == 0)
  217499. handle = (void*) pthread_self();
  217500. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217501. return false;
  217502. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217503. const int minPriority = sched_get_priority_min (policy);
  217504. const int maxPriority = sched_get_priority_max (policy);
  217505. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217506. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217507. }
  217508. Thread::ThreadID Thread::getCurrentThreadId()
  217509. {
  217510. return (ThreadID) pthread_self();
  217511. }
  217512. void Thread::yield()
  217513. {
  217514. sched_yield();
  217515. }
  217516. /* Remove this macro if you're having problems compiling the cpu affinity
  217517. calls (the API for these has changed about quite a bit in various Linux
  217518. versions, and a lot of distros seem to ship with obsolete versions)
  217519. */
  217520. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217521. #define SUPPORT_AFFINITIES 1
  217522. #endif
  217523. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217524. {
  217525. #if SUPPORT_AFFINITIES
  217526. cpu_set_t affinity;
  217527. CPU_ZERO (&affinity);
  217528. for (int i = 0; i < 32; ++i)
  217529. if ((affinityMask & (1 << i)) != 0)
  217530. CPU_SET (i, &affinity);
  217531. /*
  217532. N.B. If this line causes a compile error, then you've probably not got the latest
  217533. version of glibc installed.
  217534. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217535. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217536. */
  217537. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217538. sched_yield();
  217539. #else
  217540. /* affinities aren't supported because either the appropriate header files weren't found,
  217541. or the SUPPORT_AFFINITIES macro was turned off
  217542. */
  217543. jassertfalse;
  217544. #endif
  217545. }
  217546. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217547. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217548. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217549. // compiled on its own).
  217550. #if JUCE_INCLUDED_FILE
  217551. enum
  217552. {
  217553. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  217554. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  217555. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  217556. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  217557. };
  217558. bool File::copyInternal (const File& dest) const
  217559. {
  217560. FileInputStream in (*this);
  217561. if (dest.deleteFile())
  217562. {
  217563. {
  217564. FileOutputStream out (dest);
  217565. if (out.failedToOpen())
  217566. return false;
  217567. if (out.writeFromInputStream (in, -1) == getSize())
  217568. return true;
  217569. }
  217570. dest.deleteFile();
  217571. }
  217572. return false;
  217573. }
  217574. void File::findFileSystemRoots (Array<File>& destArray)
  217575. {
  217576. destArray.add (File ("/"));
  217577. }
  217578. bool File::isOnCDRomDrive() const
  217579. {
  217580. struct statfs buf;
  217581. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217582. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  217583. }
  217584. bool File::isOnHardDisk() const
  217585. {
  217586. struct statfs buf;
  217587. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217588. {
  217589. switch (buf.f_type)
  217590. {
  217591. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217592. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217593. case U_NFS_SUPER_MAGIC: // Network NFS
  217594. case U_SMB_SUPER_MAGIC: // Network Samba
  217595. return false;
  217596. default:
  217597. // Assume anything else is a hard-disk (but note it could
  217598. // be a RAM disk. There isn't a good way of determining
  217599. // this for sure)
  217600. return true;
  217601. }
  217602. }
  217603. // Assume so if this fails for some reason
  217604. return true;
  217605. }
  217606. bool File::isOnRemovableDrive() const
  217607. {
  217608. jassertfalse; // xxx not implemented for linux!
  217609. return false;
  217610. }
  217611. bool File::isHidden() const
  217612. {
  217613. return getFileName().startsWithChar ('.');
  217614. }
  217615. namespace
  217616. {
  217617. const File juce_readlink (const String& file, const File& defaultFile)
  217618. {
  217619. const int size = 8192;
  217620. HeapBlock<char> buffer;
  217621. buffer.malloc (size + 4);
  217622. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217623. if (numBytes > 0 && numBytes <= size)
  217624. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217625. return defaultFile;
  217626. }
  217627. }
  217628. const File File::getLinkedTarget() const
  217629. {
  217630. return juce_readlink (getFullPathName().toUTF8(), *this);
  217631. }
  217632. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217633. const File File::getSpecialLocation (const SpecialLocationType type)
  217634. {
  217635. switch (type)
  217636. {
  217637. case userHomeDirectory:
  217638. {
  217639. const char* homeDir = getenv ("HOME");
  217640. if (homeDir == 0)
  217641. {
  217642. struct passwd* const pw = getpwuid (getuid());
  217643. if (pw != 0)
  217644. homeDir = pw->pw_dir;
  217645. }
  217646. return File (String::fromUTF8 (homeDir));
  217647. }
  217648. case userDocumentsDirectory:
  217649. case userMusicDirectory:
  217650. case userMoviesDirectory:
  217651. case userApplicationDataDirectory:
  217652. return File ("~");
  217653. case userDesktopDirectory:
  217654. return File ("~/Desktop");
  217655. case commonApplicationDataDirectory:
  217656. return File ("/var");
  217657. case globalApplicationsDirectory:
  217658. return File ("/usr");
  217659. case tempDirectory:
  217660. {
  217661. File tmp ("/var/tmp");
  217662. if (! tmp.isDirectory())
  217663. {
  217664. tmp = "/tmp";
  217665. if (! tmp.isDirectory())
  217666. tmp = File::getCurrentWorkingDirectory();
  217667. }
  217668. return tmp;
  217669. }
  217670. case invokedExecutableFile:
  217671. if (juce_Argv0 != 0)
  217672. return File (String::fromUTF8 (juce_Argv0));
  217673. // deliberate fall-through...
  217674. case currentExecutableFile:
  217675. case currentApplicationFile:
  217676. return juce_getExecutableFile();
  217677. case hostApplicationPath:
  217678. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217679. default:
  217680. jassertfalse; // unknown type?
  217681. break;
  217682. }
  217683. return File::nonexistent;
  217684. }
  217685. const String File::getVersion() const
  217686. {
  217687. return String::empty; // xxx not yet implemented
  217688. }
  217689. bool File::moveToTrash() const
  217690. {
  217691. if (! exists())
  217692. return true;
  217693. File trashCan ("~/.Trash");
  217694. if (! trashCan.isDirectory())
  217695. trashCan = "~/.local/share/Trash/files";
  217696. if (! trashCan.isDirectory())
  217697. return false;
  217698. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217699. getFileExtension()));
  217700. }
  217701. class DirectoryIterator::NativeIterator::Pimpl
  217702. {
  217703. public:
  217704. Pimpl (const File& directory, const String& wildCard_)
  217705. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217706. wildCard (wildCard_),
  217707. dir (opendir (directory.getFullPathName().toUTF8()))
  217708. {
  217709. if (wildCard == "*.*")
  217710. wildCard = "*";
  217711. wildcardUTF8 = wildCard.toUTF8();
  217712. }
  217713. ~Pimpl()
  217714. {
  217715. if (dir != 0)
  217716. closedir (dir);
  217717. }
  217718. bool next (String& filenameFound,
  217719. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217720. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217721. {
  217722. if (dir == 0)
  217723. return false;
  217724. for (;;)
  217725. {
  217726. struct dirent* const de = readdir (dir);
  217727. if (de == 0)
  217728. return false;
  217729. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217730. {
  217731. filenameFound = String::fromUTF8 (de->d_name);
  217732. const String path (parentDir + filenameFound);
  217733. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  217734. {
  217735. struct stat info;
  217736. const bool statOk = juce_stat (path, info);
  217737. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  217738. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  217739. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  217740. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  217741. }
  217742. if (isHidden != 0)
  217743. *isHidden = filenameFound.startsWithChar ('.');
  217744. if (isReadOnly != 0)
  217745. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  217746. return true;
  217747. }
  217748. }
  217749. }
  217750. private:
  217751. String parentDir, wildCard;
  217752. const char* wildcardUTF8;
  217753. DIR* dir;
  217754. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  217755. };
  217756. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217757. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217758. {
  217759. }
  217760. DirectoryIterator::NativeIterator::~NativeIterator()
  217761. {
  217762. }
  217763. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217764. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217765. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217766. {
  217767. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217768. }
  217769. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217770. {
  217771. String cmdString (fileName.replace (" ", "\\ ",false));
  217772. cmdString << " " << parameters;
  217773. if (URL::isProbablyAWebsiteURL (fileName)
  217774. || cmdString.startsWithIgnoreCase ("file:")
  217775. || URL::isProbablyAnEmailAddress (fileName))
  217776. {
  217777. // create a command that tries to launch a bunch of likely browsers
  217778. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217779. StringArray cmdLines;
  217780. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217781. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217782. cmdString = cmdLines.joinIntoString (" || ");
  217783. }
  217784. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217785. const int cpid = fork();
  217786. if (cpid == 0)
  217787. {
  217788. setsid();
  217789. // Child process
  217790. execve (argv[0], (char**) argv, environ);
  217791. exit (0);
  217792. }
  217793. return cpid >= 0;
  217794. }
  217795. void File::revealToUser() const
  217796. {
  217797. if (isDirectory())
  217798. startAsProcess();
  217799. else if (getParentDirectory().exists())
  217800. getParentDirectory().startAsProcess();
  217801. }
  217802. #endif
  217803. /*** End of inlined file: juce_linux_Files.cpp ***/
  217804. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217805. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217806. // compiled on its own).
  217807. #if JUCE_INCLUDED_FILE
  217808. struct NamedPipeInternal
  217809. {
  217810. String pipeInName, pipeOutName;
  217811. int pipeIn, pipeOut;
  217812. bool volatile createdPipe, blocked, stopReadOperation;
  217813. static void signalHandler (int) {}
  217814. };
  217815. void NamedPipe::cancelPendingReads()
  217816. {
  217817. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217818. {
  217819. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217820. intern->stopReadOperation = true;
  217821. char buffer [1] = { 0 };
  217822. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217823. (void) bytesWritten;
  217824. int timeout = 2000;
  217825. while (intern->blocked && --timeout >= 0)
  217826. Thread::sleep (2);
  217827. intern->stopReadOperation = false;
  217828. }
  217829. }
  217830. void NamedPipe::close()
  217831. {
  217832. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217833. if (intern != 0)
  217834. {
  217835. internal = 0;
  217836. if (intern->pipeIn != -1)
  217837. ::close (intern->pipeIn);
  217838. if (intern->pipeOut != -1)
  217839. ::close (intern->pipeOut);
  217840. if (intern->createdPipe)
  217841. {
  217842. unlink (intern->pipeInName.toUTF8());
  217843. unlink (intern->pipeOutName.toUTF8());
  217844. }
  217845. delete intern;
  217846. }
  217847. }
  217848. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217849. {
  217850. close();
  217851. NamedPipeInternal* const intern = new NamedPipeInternal();
  217852. internal = intern;
  217853. intern->createdPipe = createPipe;
  217854. intern->blocked = false;
  217855. intern->stopReadOperation = false;
  217856. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217857. siginterrupt (SIGPIPE, 1);
  217858. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217859. intern->pipeInName = pipePath + "_in";
  217860. intern->pipeOutName = pipePath + "_out";
  217861. intern->pipeIn = -1;
  217862. intern->pipeOut = -1;
  217863. if (createPipe)
  217864. {
  217865. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217866. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217867. {
  217868. delete intern;
  217869. internal = 0;
  217870. return false;
  217871. }
  217872. }
  217873. return true;
  217874. }
  217875. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217876. {
  217877. int bytesRead = -1;
  217878. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217879. if (intern != 0)
  217880. {
  217881. intern->blocked = true;
  217882. if (intern->pipeIn == -1)
  217883. {
  217884. if (intern->createdPipe)
  217885. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217886. else
  217887. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217888. if (intern->pipeIn == -1)
  217889. {
  217890. intern->blocked = false;
  217891. return -1;
  217892. }
  217893. }
  217894. bytesRead = 0;
  217895. char* p = static_cast<char*> (destBuffer);
  217896. while (bytesRead < maxBytesToRead)
  217897. {
  217898. const int bytesThisTime = maxBytesToRead - bytesRead;
  217899. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217900. if (numRead <= 0 || intern->stopReadOperation)
  217901. {
  217902. bytesRead = -1;
  217903. break;
  217904. }
  217905. bytesRead += numRead;
  217906. p += bytesRead;
  217907. }
  217908. intern->blocked = false;
  217909. }
  217910. return bytesRead;
  217911. }
  217912. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217913. {
  217914. int bytesWritten = -1;
  217915. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217916. if (intern != 0)
  217917. {
  217918. if (intern->pipeOut == -1)
  217919. {
  217920. if (intern->createdPipe)
  217921. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217922. else
  217923. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217924. if (intern->pipeOut == -1)
  217925. {
  217926. return -1;
  217927. }
  217928. }
  217929. const char* p = static_cast<const char*> (sourceBuffer);
  217930. bytesWritten = 0;
  217931. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217932. while (bytesWritten < numBytesToWrite
  217933. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217934. {
  217935. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217936. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217937. if (numWritten <= 0)
  217938. {
  217939. bytesWritten = -1;
  217940. break;
  217941. }
  217942. bytesWritten += numWritten;
  217943. p += bytesWritten;
  217944. }
  217945. }
  217946. return bytesWritten;
  217947. }
  217948. #endif
  217949. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217950. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217951. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217952. // compiled on its own).
  217953. #if JUCE_INCLUDED_FILE
  217954. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217955. {
  217956. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217957. if (s != -1)
  217958. {
  217959. char buf [1024];
  217960. struct ifconf ifc;
  217961. ifc.ifc_len = sizeof (buf);
  217962. ifc.ifc_buf = buf;
  217963. ioctl (s, SIOCGIFCONF, &ifc);
  217964. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217965. {
  217966. struct ifreq ifr;
  217967. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217968. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217969. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217970. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217971. {
  217972. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217973. }
  217974. }
  217975. close (s);
  217976. }
  217977. }
  217978. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217979. const String& emailSubject,
  217980. const String& bodyText,
  217981. const StringArray& filesToAttach)
  217982. {
  217983. jassertfalse; // xxx todo
  217984. return false;
  217985. }
  217986. /** A HTTP input stream that uses sockets.
  217987. */
  217988. class JUCE_HTTPSocketStream
  217989. {
  217990. public:
  217991. JUCE_HTTPSocketStream()
  217992. : readPosition (0),
  217993. socketHandle (-1),
  217994. levelsOfRedirection (0),
  217995. timeoutSeconds (15)
  217996. {
  217997. }
  217998. ~JUCE_HTTPSocketStream()
  217999. {
  218000. closeSocket();
  218001. }
  218002. bool open (const String& url,
  218003. const String& headers,
  218004. const MemoryBlock& postData,
  218005. const bool isPost,
  218006. URL::OpenStreamProgressCallback* callback,
  218007. void* callbackContext,
  218008. int timeOutMs)
  218009. {
  218010. closeSocket();
  218011. uint32 timeOutTime = Time::getMillisecondCounter();
  218012. if (timeOutMs == 0)
  218013. timeOutTime += 60000;
  218014. else if (timeOutMs < 0)
  218015. timeOutTime = 0xffffffff;
  218016. else
  218017. timeOutTime += timeOutMs;
  218018. String hostName, hostPath;
  218019. int hostPort;
  218020. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218021. return false;
  218022. const struct hostent* host = 0;
  218023. int port = 0;
  218024. String proxyName, proxyPath;
  218025. int proxyPort = 0;
  218026. String proxyURL (getenv ("http_proxy"));
  218027. if (proxyURL.startsWithIgnoreCase ("http://"))
  218028. {
  218029. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218030. return false;
  218031. host = gethostbyname (proxyName.toUTF8());
  218032. port = proxyPort;
  218033. }
  218034. else
  218035. {
  218036. host = gethostbyname (hostName.toUTF8());
  218037. port = hostPort;
  218038. }
  218039. if (host == 0)
  218040. return false;
  218041. struct sockaddr_in address;
  218042. zerostruct (address);
  218043. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218044. address.sin_family = host->h_addrtype;
  218045. address.sin_port = htons (port);
  218046. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218047. if (socketHandle == -1)
  218048. return false;
  218049. int receiveBufferSize = 16384;
  218050. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218051. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218052. #if JUCE_MAC
  218053. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218054. #endif
  218055. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218056. {
  218057. closeSocket();
  218058. return false;
  218059. }
  218060. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  218061. hostPath, url, headers, postData, isPost));
  218062. size_t totalHeaderSent = 0;
  218063. while (totalHeaderSent < requestHeader.getSize())
  218064. {
  218065. if (Time::getMillisecondCounter() > timeOutTime)
  218066. {
  218067. closeSocket();
  218068. return false;
  218069. }
  218070. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218071. if (send (socketHandle, ((const char*) requestHeader.getData()) + totalHeaderSent, numToSend, 0)
  218072. != numToSend)
  218073. {
  218074. closeSocket();
  218075. return false;
  218076. }
  218077. totalHeaderSent += numToSend;
  218078. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218079. {
  218080. closeSocket();
  218081. return false;
  218082. }
  218083. }
  218084. const String responseHeader (readResponse (timeOutTime));
  218085. if (responseHeader.isNotEmpty())
  218086. {
  218087. headerLines.clear();
  218088. headerLines.addLines (responseHeader);
  218089. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218090. .substring (0, 3).getIntValue();
  218091. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218092. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218093. String location (findHeaderItem (headerLines, "Location:"));
  218094. if (statusCode >= 300 && statusCode < 400
  218095. && location.isNotEmpty())
  218096. {
  218097. if (! location.startsWithIgnoreCase ("http://"))
  218098. location = "http://" + location;
  218099. if (levelsOfRedirection++ < 3)
  218100. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218101. }
  218102. else
  218103. {
  218104. levelsOfRedirection = 0;
  218105. return true;
  218106. }
  218107. }
  218108. closeSocket();
  218109. return false;
  218110. }
  218111. int read (void* buffer, int bytesToRead)
  218112. {
  218113. fd_set readbits;
  218114. FD_ZERO (&readbits);
  218115. FD_SET (socketHandle, &readbits);
  218116. struct timeval tv;
  218117. tv.tv_sec = timeoutSeconds;
  218118. tv.tv_usec = 0;
  218119. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218120. return 0; // (timeout)
  218121. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218122. readPosition += bytesRead;
  218123. return bytesRead;
  218124. }
  218125. int readPosition;
  218126. StringArray headerLines;
  218127. private:
  218128. int socketHandle, levelsOfRedirection;
  218129. const int timeoutSeconds;
  218130. void closeSocket()
  218131. {
  218132. if (socketHandle >= 0)
  218133. close (socketHandle);
  218134. socketHandle = -1;
  218135. }
  218136. const MemoryBlock createRequestHeader (const String& hostName,
  218137. const int hostPort,
  218138. const String& proxyName,
  218139. const int proxyPort,
  218140. const String& hostPath,
  218141. const String& originalURL,
  218142. const String& headers,
  218143. const MemoryBlock& postData,
  218144. const bool isPost)
  218145. {
  218146. String header (isPost ? "POST " : "GET ");
  218147. if (proxyName.isEmpty())
  218148. {
  218149. header << hostPath << " HTTP/1.0\r\nHost: "
  218150. << hostName << ':' << hostPort;
  218151. }
  218152. else
  218153. {
  218154. header << originalURL << " HTTP/1.0\r\nHost: "
  218155. << proxyName << ':' << proxyPort;
  218156. }
  218157. header << "\r\nUser-Agent: JUCE/"
  218158. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218159. << "\r\nConnection: Close\r\nContent-Length: "
  218160. << postData.getSize() << "\r\n"
  218161. << headers << "\r\n";
  218162. MemoryBlock mb;
  218163. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218164. mb.append (postData.getData(), postData.getSize());
  218165. return mb;
  218166. }
  218167. const String readResponse (const uint32 timeOutTime)
  218168. {
  218169. int bytesRead = 0, numConsecutiveLFs = 0;
  218170. MemoryBlock buffer (1024, true);
  218171. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218172. && Time::getMillisecondCounter() <= timeOutTime)
  218173. {
  218174. fd_set readbits;
  218175. FD_ZERO (&readbits);
  218176. FD_SET (socketHandle, &readbits);
  218177. struct timeval tv;
  218178. tv.tv_sec = timeoutSeconds;
  218179. tv.tv_usec = 0;
  218180. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218181. return String::empty; // (timeout)
  218182. buffer.ensureSize (bytesRead + 8, true);
  218183. char* const dest = (char*) buffer.getData() + bytesRead;
  218184. if (recv (socketHandle, dest, 1, 0) == -1)
  218185. return String::empty;
  218186. const char lastByte = *dest;
  218187. ++bytesRead;
  218188. if (lastByte == '\n')
  218189. ++numConsecutiveLFs;
  218190. else if (lastByte != '\r')
  218191. numConsecutiveLFs = 0;
  218192. }
  218193. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218194. if (header.startsWithIgnoreCase ("HTTP/"))
  218195. return header.trimEnd();
  218196. return String::empty;
  218197. }
  218198. static bool decomposeURL (const String& url,
  218199. String& host, String& path, int& port)
  218200. {
  218201. if (! url.startsWithIgnoreCase ("http://"))
  218202. return false;
  218203. const int nextSlash = url.indexOfChar (7, '/');
  218204. int nextColon = url.indexOfChar (7, ':');
  218205. if (nextColon > nextSlash && nextSlash > 0)
  218206. nextColon = -1;
  218207. if (nextColon >= 0)
  218208. {
  218209. host = url.substring (7, nextColon);
  218210. if (nextSlash >= 0)
  218211. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218212. else
  218213. port = url.substring (nextColon + 1).getIntValue();
  218214. }
  218215. else
  218216. {
  218217. port = 80;
  218218. if (nextSlash >= 0)
  218219. host = url.substring (7, nextSlash);
  218220. else
  218221. host = url.substring (7);
  218222. }
  218223. if (nextSlash >= 0)
  218224. path = url.substring (nextSlash);
  218225. else
  218226. path = "/";
  218227. return true;
  218228. }
  218229. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218230. {
  218231. for (int i = 0; i < lines.size(); ++i)
  218232. if (lines[i].startsWithIgnoreCase (itemName))
  218233. return lines[i].substring (itemName.length()).trim();
  218234. return String::empty;
  218235. }
  218236. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JUCE_HTTPSocketStream);
  218237. };
  218238. void* juce_openInternetFile (const String& url,
  218239. const String& headers,
  218240. const MemoryBlock& postData,
  218241. const bool isPost,
  218242. URL::OpenStreamProgressCallback* callback,
  218243. void* callbackContext,
  218244. int timeOutMs)
  218245. {
  218246. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218247. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218248. return s.release();
  218249. return 0;
  218250. }
  218251. void juce_closeInternetFile (void* handle)
  218252. {
  218253. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218254. }
  218255. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218256. {
  218257. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218258. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218259. }
  218260. int64 juce_getInternetFileContentLength (void* handle)
  218261. {
  218262. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218263. if (s != 0)
  218264. {
  218265. //xxx todo
  218266. jassertfalse
  218267. }
  218268. return -1;
  218269. }
  218270. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218271. {
  218272. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218273. if (s != 0)
  218274. {
  218275. for (int i = 0; i < s->headerLines.size(); ++i)
  218276. {
  218277. const String& headersEntry = s->headerLines[i];
  218278. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218279. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218280. const String previousValue (headers [key]);
  218281. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218282. }
  218283. }
  218284. }
  218285. int juce_seekInInternetFile (void* handle, int newPosition)
  218286. {
  218287. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218288. return s != 0 ? s->readPosition : 0;
  218289. }
  218290. #endif
  218291. /*** End of inlined file: juce_linux_Network.cpp ***/
  218292. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218293. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218294. // compiled on its own).
  218295. #if JUCE_INCLUDED_FILE
  218296. void Logger::outputDebugString (const String& text)
  218297. {
  218298. std::cerr << text << std::endl;
  218299. }
  218300. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218301. {
  218302. return Linux;
  218303. }
  218304. const String SystemStats::getOperatingSystemName()
  218305. {
  218306. return "Linux";
  218307. }
  218308. bool SystemStats::isOperatingSystem64Bit()
  218309. {
  218310. #if JUCE_64BIT
  218311. return true;
  218312. #else
  218313. //xxx not sure how to find this out?..
  218314. return false;
  218315. #endif
  218316. }
  218317. namespace LinuxStatsHelpers
  218318. {
  218319. const String getCpuInfo (const char* const key)
  218320. {
  218321. StringArray lines;
  218322. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218323. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218324. if (lines[i].startsWithIgnoreCase (key))
  218325. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218326. return String::empty;
  218327. }
  218328. bool getTimeSinceStartup (timeval* const t) throw()
  218329. {
  218330. if (gettimeofday (t, 0) != 0)
  218331. return false;
  218332. static unsigned int calibrate = 0;
  218333. static bool calibrated = false;
  218334. if (! calibrated)
  218335. {
  218336. calibrated = true;
  218337. struct sysinfo sysi;
  218338. if (sysinfo (&sysi) == 0)
  218339. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218340. }
  218341. t->tv_sec -= calibrate;
  218342. return true;
  218343. }
  218344. }
  218345. const String SystemStats::getCpuVendor()
  218346. {
  218347. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  218348. }
  218349. int SystemStats::getCpuSpeedInMegaherz()
  218350. {
  218351. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  218352. }
  218353. int SystemStats::getMemorySizeInMegabytes()
  218354. {
  218355. struct sysinfo sysi;
  218356. if (sysinfo (&sysi) == 0)
  218357. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218358. return 0;
  218359. }
  218360. int SystemStats::getPageSize()
  218361. {
  218362. return sysconf (_SC_PAGESIZE);
  218363. }
  218364. const String SystemStats::getLogonName()
  218365. {
  218366. const char* user = getenv ("USER");
  218367. if (user == 0)
  218368. {
  218369. struct passwd* const pw = getpwuid (getuid());
  218370. if (pw != 0)
  218371. user = pw->pw_name;
  218372. }
  218373. return String::fromUTF8 (user);
  218374. }
  218375. const String SystemStats::getFullUserName()
  218376. {
  218377. return getLogonName();
  218378. }
  218379. void SystemStats::initialiseStats()
  218380. {
  218381. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  218382. cpuFlags.hasMMX = flags.contains ("mmx");
  218383. cpuFlags.hasSSE = flags.contains ("sse");
  218384. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218385. cpuFlags.has3DNow = flags.contains ("3dnow");
  218386. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  218387. }
  218388. void PlatformUtilities::fpuReset()
  218389. {
  218390. }
  218391. uint32 juce_millisecondsSinceStartup() throw()
  218392. {
  218393. timeval t;
  218394. if (LinuxStatsHelpers::getTimeSinceStartup (&t))
  218395. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218396. return 0;
  218397. }
  218398. int64 Time::getHighResolutionTicks() throw()
  218399. {
  218400. timeval t;
  218401. if (LinuxStatsHelpers::getTimeSinceStartup (&t))
  218402. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218403. return 0;
  218404. }
  218405. int64 Time::getHighResolutionTicksPerSecond() throw()
  218406. {
  218407. return 1000000; // (microseconds)
  218408. }
  218409. double Time::getMillisecondCounterHiRes() throw()
  218410. {
  218411. return getHighResolutionTicks() * 0.001;
  218412. }
  218413. bool Time::setSystemTimeToThisTime() const
  218414. {
  218415. timeval t;
  218416. t.tv_sec = millisSinceEpoch / 1000;
  218417. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  218418. return settimeofday (&t, 0) == 0;
  218419. }
  218420. #endif
  218421. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218422. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218423. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218424. // compiled on its own).
  218425. #if JUCE_INCLUDED_FILE
  218426. /*
  218427. Note that a lot of methods that you'd expect to find in this file actually
  218428. live in juce_posix_SharedCode.h!
  218429. */
  218430. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218431. void Process::setPriority (ProcessPriority prior)
  218432. {
  218433. struct sched_param param;
  218434. int policy, maxp, minp;
  218435. const int p = (int) prior;
  218436. if (p <= 1)
  218437. policy = SCHED_OTHER;
  218438. else
  218439. policy = SCHED_RR;
  218440. minp = sched_get_priority_min (policy);
  218441. maxp = sched_get_priority_max (policy);
  218442. if (p < 2)
  218443. param.sched_priority = 0;
  218444. else if (p == 2 )
  218445. // Set to middle of lower realtime priority range
  218446. param.sched_priority = minp + (maxp - minp) / 4;
  218447. else
  218448. // Set to middle of higher realtime priority range
  218449. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218450. pthread_setschedparam (pthread_self(), policy, &param);
  218451. }
  218452. void Process::terminate()
  218453. {
  218454. exit (0);
  218455. }
  218456. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  218457. {
  218458. static char testResult = 0;
  218459. if (testResult == 0)
  218460. {
  218461. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218462. if (testResult >= 0)
  218463. {
  218464. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218465. testResult = 1;
  218466. }
  218467. }
  218468. return testResult < 0;
  218469. }
  218470. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218471. {
  218472. return juce_isRunningUnderDebugger();
  218473. }
  218474. void Process::raisePrivilege()
  218475. {
  218476. // If running suid root, change effective user
  218477. // to root
  218478. if (geteuid() != 0 && getuid() == 0)
  218479. {
  218480. setreuid (geteuid(), getuid());
  218481. setregid (getegid(), getgid());
  218482. }
  218483. }
  218484. void Process::lowerPrivilege()
  218485. {
  218486. // If runing suid root, change effective user
  218487. // back to real user
  218488. if (geteuid() == 0 && getuid() != 0)
  218489. {
  218490. setreuid (geteuid(), getuid());
  218491. setregid (getegid(), getgid());
  218492. }
  218493. }
  218494. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218495. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218496. {
  218497. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218498. }
  218499. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218500. {
  218501. dlclose(handle);
  218502. }
  218503. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218504. {
  218505. return dlsym (libraryHandle, procedureName.toCString());
  218506. }
  218507. #endif
  218508. #endif
  218509. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218510. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218511. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218512. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218513. // compiled on its own).
  218514. #if JUCE_INCLUDED_FILE
  218515. extern Display* display;
  218516. extern Window juce_messageWindowHandle;
  218517. namespace ClipboardHelpers
  218518. {
  218519. static String localClipboardContent;
  218520. static Atom atom_UTF8_STRING;
  218521. static Atom atom_CLIPBOARD;
  218522. static Atom atom_TARGETS;
  218523. static void initSelectionAtoms()
  218524. {
  218525. static bool isInitialised = false;
  218526. if (! isInitialised)
  218527. {
  218528. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218529. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218530. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218531. }
  218532. }
  218533. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218534. // works only for strings shorter than 1000000 bytes
  218535. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218536. {
  218537. String returnData;
  218538. char* clipData;
  218539. Atom actualType;
  218540. int actualFormat;
  218541. unsigned long numItems, bytesLeft;
  218542. if (XGetWindowProperty (display, window, prop,
  218543. 0L /* offset */, 1000000 /* length (max) */, False,
  218544. AnyPropertyType /* format */,
  218545. &actualType, &actualFormat, &numItems, &bytesLeft,
  218546. (unsigned char**) &clipData) == Success)
  218547. {
  218548. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218549. returnData = String::fromUTF8 (clipData, numItems);
  218550. else if (actualType == XA_STRING && actualFormat == 8)
  218551. returnData = String (clipData, numItems);
  218552. if (clipData != 0)
  218553. XFree (clipData);
  218554. jassert (bytesLeft == 0 || numItems == 1000000);
  218555. }
  218556. XDeleteProperty (display, window, prop);
  218557. return returnData;
  218558. }
  218559. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218560. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218561. {
  218562. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218563. // The selection owner will be asked to set the JUCE_SEL property on the
  218564. // juce_messageWindowHandle with the selection content
  218565. XConvertSelection (display, selection, requestedFormat, property_name,
  218566. juce_messageWindowHandle, CurrentTime);
  218567. int count = 50; // will wait at most for 200 ms
  218568. while (--count >= 0)
  218569. {
  218570. XEvent event;
  218571. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218572. {
  218573. if (event.xselection.property == property_name)
  218574. {
  218575. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218576. selectionContent = readWindowProperty (event.xselection.requestor,
  218577. event.xselection.property,
  218578. requestedFormat);
  218579. return true;
  218580. }
  218581. else
  218582. {
  218583. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218584. }
  218585. }
  218586. // not very elegant.. we could do a select() or something like that...
  218587. // however clipboard content requesting is inherently slow on x11, it
  218588. // often takes 50ms or more so...
  218589. Thread::sleep (4);
  218590. }
  218591. return false;
  218592. }
  218593. }
  218594. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218595. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218596. {
  218597. ClipboardHelpers::initSelectionAtoms();
  218598. // the selection content is sent to the target window as a window property
  218599. XSelectionEvent reply;
  218600. reply.type = SelectionNotify;
  218601. reply.display = evt.display;
  218602. reply.requestor = evt.requestor;
  218603. reply.selection = evt.selection;
  218604. reply.target = evt.target;
  218605. reply.property = None; // == "fail"
  218606. reply.time = evt.time;
  218607. HeapBlock <char> data;
  218608. int propertyFormat = 0, numDataItems = 0;
  218609. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218610. {
  218611. if (evt.target == XA_STRING)
  218612. {
  218613. // format data according to system locale
  218614. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218615. data.calloc (numDataItems + 1);
  218616. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218617. propertyFormat = 8; // bits/item
  218618. }
  218619. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218620. {
  218621. // translate to utf8
  218622. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218623. data.calloc (numDataItems + 1);
  218624. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218625. propertyFormat = 8; // bits/item
  218626. }
  218627. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218628. {
  218629. // another application wants to know what we are able to send
  218630. numDataItems = 2;
  218631. propertyFormat = 32; // atoms are 32-bit
  218632. data.calloc (numDataItems * 4);
  218633. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218634. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218635. atoms[1] = XA_STRING;
  218636. }
  218637. }
  218638. else
  218639. {
  218640. DBG ("requested unsupported clipboard");
  218641. }
  218642. if (data != 0)
  218643. {
  218644. const int maxReasonableSelectionSize = 1000000;
  218645. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218646. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218647. {
  218648. XChangeProperty (evt.display, evt.requestor,
  218649. evt.property, evt.target,
  218650. propertyFormat /* 8 or 32 */, PropModeReplace,
  218651. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218652. reply.property = evt.property; // " == success"
  218653. }
  218654. }
  218655. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218656. }
  218657. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218658. {
  218659. ClipboardHelpers::initSelectionAtoms();
  218660. ClipboardHelpers::localClipboardContent = clipText;
  218661. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218662. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218663. }
  218664. const String SystemClipboard::getTextFromClipboard()
  218665. {
  218666. ClipboardHelpers::initSelectionAtoms();
  218667. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218668. level" clipboard that is supposed to be filled by ctrl-C
  218669. etc). When a clipboard manager is running, the content of this
  218670. selection is preserved even when the original selection owner
  218671. exits.
  218672. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218673. filled by good old x11 apps such as xterm)
  218674. */
  218675. String content;
  218676. Atom selection = XA_PRIMARY;
  218677. Window selectionOwner = None;
  218678. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218679. {
  218680. selection = ClipboardHelpers::atom_CLIPBOARD;
  218681. selectionOwner = XGetSelectionOwner (display, selection);
  218682. }
  218683. if (selectionOwner != None)
  218684. {
  218685. if (selectionOwner == juce_messageWindowHandle)
  218686. {
  218687. content = ClipboardHelpers::localClipboardContent;
  218688. }
  218689. else
  218690. {
  218691. // first try: we want an utf8 string
  218692. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218693. if (! ok)
  218694. {
  218695. // second chance, ask for a good old locale-dependent string ..
  218696. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218697. }
  218698. }
  218699. }
  218700. return content;
  218701. }
  218702. #endif
  218703. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218704. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218705. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218706. // compiled on its own).
  218707. #if JUCE_INCLUDED_FILE
  218708. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218709. #define JUCE_DEBUG_XERRORS 1
  218710. #endif
  218711. Display* display = 0;
  218712. Window juce_messageWindowHandle = None;
  218713. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218714. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218715. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218716. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218717. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218718. class InternalMessageQueue
  218719. {
  218720. public:
  218721. InternalMessageQueue()
  218722. : bytesInSocket (0),
  218723. totalEventCount (0)
  218724. {
  218725. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218726. (void) ret; jassert (ret == 0);
  218727. //setNonBlocking (fd[0]);
  218728. //setNonBlocking (fd[1]);
  218729. }
  218730. ~InternalMessageQueue()
  218731. {
  218732. close (fd[0]);
  218733. close (fd[1]);
  218734. clearSingletonInstance();
  218735. }
  218736. void postMessage (Message* msg)
  218737. {
  218738. const int maxBytesInSocketQueue = 128;
  218739. ScopedLock sl (lock);
  218740. queue.add (msg);
  218741. if (bytesInSocket < maxBytesInSocketQueue)
  218742. {
  218743. ++bytesInSocket;
  218744. ScopedUnlock ul (lock);
  218745. const unsigned char x = 0xff;
  218746. size_t bytesWritten = write (fd[0], &x, 1);
  218747. (void) bytesWritten;
  218748. }
  218749. }
  218750. bool isEmpty() const
  218751. {
  218752. ScopedLock sl (lock);
  218753. return queue.size() == 0;
  218754. }
  218755. bool dispatchNextEvent()
  218756. {
  218757. // This alternates between giving priority to XEvents or internal messages,
  218758. // to keep everything running smoothly..
  218759. if ((++totalEventCount & 1) != 0)
  218760. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218761. else
  218762. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218763. }
  218764. // Wait for an event (either XEvent, or an internal Message)
  218765. bool sleepUntilEvent (const int timeoutMs)
  218766. {
  218767. if (! isEmpty())
  218768. return true;
  218769. if (display != 0)
  218770. {
  218771. ScopedXLock xlock;
  218772. if (XPending (display))
  218773. return true;
  218774. }
  218775. struct timeval tv;
  218776. tv.tv_sec = 0;
  218777. tv.tv_usec = timeoutMs * 1000;
  218778. int fd0 = getWaitHandle();
  218779. int fdmax = fd0;
  218780. fd_set readset;
  218781. FD_ZERO (&readset);
  218782. FD_SET (fd0, &readset);
  218783. if (display != 0)
  218784. {
  218785. ScopedXLock xlock;
  218786. int fd1 = XConnectionNumber (display);
  218787. FD_SET (fd1, &readset);
  218788. fdmax = jmax (fd0, fd1);
  218789. }
  218790. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218791. return (ret > 0); // ret <= 0 if error or timeout
  218792. }
  218793. struct MessageThreadFuncCall
  218794. {
  218795. enum { uniqueID = 0x73774623 };
  218796. MessageCallbackFunction* func;
  218797. void* parameter;
  218798. void* result;
  218799. CriticalSection lock;
  218800. WaitableEvent event;
  218801. };
  218802. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218803. private:
  218804. CriticalSection lock;
  218805. OwnedArray <Message> queue;
  218806. int fd[2];
  218807. int bytesInSocket;
  218808. int totalEventCount;
  218809. int getWaitHandle() const throw() { return fd[1]; }
  218810. static bool setNonBlocking (int handle)
  218811. {
  218812. int socketFlags = fcntl (handle, F_GETFL, 0);
  218813. if (socketFlags == -1)
  218814. return false;
  218815. socketFlags |= O_NONBLOCK;
  218816. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218817. }
  218818. static bool dispatchNextXEvent()
  218819. {
  218820. if (display == 0)
  218821. return false;
  218822. XEvent evt;
  218823. {
  218824. ScopedXLock xlock;
  218825. if (! XPending (display))
  218826. return false;
  218827. XNextEvent (display, &evt);
  218828. }
  218829. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218830. juce_handleSelectionRequest (evt.xselectionrequest);
  218831. else if (evt.xany.window != juce_messageWindowHandle)
  218832. juce_windowMessageReceive (&evt);
  218833. return true;
  218834. }
  218835. Message* popNextMessage()
  218836. {
  218837. ScopedLock sl (lock);
  218838. if (bytesInSocket > 0)
  218839. {
  218840. --bytesInSocket;
  218841. ScopedUnlock ul (lock);
  218842. unsigned char x;
  218843. size_t numBytes = read (fd[1], &x, 1);
  218844. (void) numBytes;
  218845. }
  218846. return queue.removeAndReturn (0);
  218847. }
  218848. bool dispatchNextInternalMessage()
  218849. {
  218850. ScopedPointer <Message> msg (popNextMessage());
  218851. if (msg == 0)
  218852. return false;
  218853. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218854. {
  218855. // Handle callback message
  218856. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218857. call->result = (*(call->func)) (call->parameter);
  218858. call->event.signal();
  218859. }
  218860. else
  218861. {
  218862. // Handle "normal" messages
  218863. MessageManager::getInstance()->deliverMessage (msg.release());
  218864. }
  218865. return true;
  218866. }
  218867. };
  218868. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218869. namespace LinuxErrorHandling
  218870. {
  218871. static bool errorOccurred = false;
  218872. static bool keyboardBreakOccurred = false;
  218873. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218874. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218875. // Usually happens when client-server connection is broken
  218876. static int ioErrorHandler (Display* display)
  218877. {
  218878. DBG ("ERROR: connection to X server broken.. terminating.");
  218879. if (JUCEApplication::isStandaloneApp())
  218880. MessageManager::getInstance()->stopDispatchLoop();
  218881. errorOccurred = true;
  218882. return 0;
  218883. }
  218884. // A protocol error has occurred
  218885. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218886. {
  218887. #if JUCE_DEBUG_XERRORS
  218888. char errorStr[64] = { 0 };
  218889. char requestStr[64] = { 0 };
  218890. XGetErrorText (display, event->error_code, errorStr, 64);
  218891. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218892. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218893. #endif
  218894. return 0;
  218895. }
  218896. static void installXErrorHandlers()
  218897. {
  218898. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218899. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218900. }
  218901. static void removeXErrorHandlers()
  218902. {
  218903. if (JUCEApplication::isStandaloneApp())
  218904. {
  218905. XSetIOErrorHandler (oldIOErrorHandler);
  218906. oldIOErrorHandler = 0;
  218907. XSetErrorHandler (oldErrorHandler);
  218908. oldErrorHandler = 0;
  218909. }
  218910. }
  218911. static void keyboardBreakSignalHandler (int sig)
  218912. {
  218913. if (sig == SIGINT)
  218914. keyboardBreakOccurred = true;
  218915. }
  218916. static void installKeyboardBreakHandler()
  218917. {
  218918. struct sigaction saction;
  218919. sigset_t maskSet;
  218920. sigemptyset (&maskSet);
  218921. saction.sa_handler = keyboardBreakSignalHandler;
  218922. saction.sa_mask = maskSet;
  218923. saction.sa_flags = 0;
  218924. sigaction (SIGINT, &saction, 0);
  218925. }
  218926. }
  218927. void MessageManager::doPlatformSpecificInitialisation()
  218928. {
  218929. if (JUCEApplication::isStandaloneApp())
  218930. {
  218931. // Initialise xlib for multiple thread support
  218932. static bool initThreadCalled = false;
  218933. if (! initThreadCalled)
  218934. {
  218935. if (! XInitThreads())
  218936. {
  218937. // This is fatal! Print error and closedown
  218938. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218939. Process::terminate();
  218940. return;
  218941. }
  218942. initThreadCalled = true;
  218943. }
  218944. LinuxErrorHandling::installXErrorHandlers();
  218945. LinuxErrorHandling::installKeyboardBreakHandler();
  218946. }
  218947. // Create the internal message queue
  218948. InternalMessageQueue::getInstance();
  218949. // Try to connect to a display
  218950. String displayName (getenv ("DISPLAY"));
  218951. if (displayName.isEmpty())
  218952. displayName = ":0.0";
  218953. display = XOpenDisplay (displayName.toCString());
  218954. if (display != 0) // This is not fatal! we can run headless.
  218955. {
  218956. // Create a context to store user data associated with Windows we create in WindowDriver
  218957. windowHandleXContext = XUniqueContext();
  218958. // We're only interested in client messages for this window, which are always sent
  218959. XSetWindowAttributes swa;
  218960. swa.event_mask = NoEventMask;
  218961. // Create our message window (this will never be mapped)
  218962. const int screen = DefaultScreen (display);
  218963. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218964. 0, 0, 1, 1, 0, 0, InputOnly,
  218965. DefaultVisual (display, screen),
  218966. CWEventMask, &swa);
  218967. }
  218968. }
  218969. void MessageManager::doPlatformSpecificShutdown()
  218970. {
  218971. InternalMessageQueue::deleteInstance();
  218972. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218973. {
  218974. XDestroyWindow (display, juce_messageWindowHandle);
  218975. XCloseDisplay (display);
  218976. juce_messageWindowHandle = 0;
  218977. display = 0;
  218978. LinuxErrorHandling::removeXErrorHandlers();
  218979. }
  218980. }
  218981. bool juce_postMessageToSystemQueue (Message* message)
  218982. {
  218983. if (LinuxErrorHandling::errorOccurred)
  218984. return false;
  218985. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218986. return true;
  218987. }
  218988. void MessageManager::broadcastMessage (const String& value)
  218989. {
  218990. /* TODO */
  218991. }
  218992. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218993. {
  218994. if (LinuxErrorHandling::errorOccurred)
  218995. return 0;
  218996. if (isThisTheMessageThread())
  218997. return func (parameter);
  218998. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  218999. messageCallContext.func = func;
  219000. messageCallContext.parameter = parameter;
  219001. InternalMessageQueue::getInstanceWithoutCreating()
  219002. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219003. 0, 0, &messageCallContext));
  219004. // Wait for it to complete before continuing
  219005. messageCallContext.event.wait();
  219006. return messageCallContext.result;
  219007. }
  219008. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219009. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219010. {
  219011. while (! LinuxErrorHandling::errorOccurred)
  219012. {
  219013. if (LinuxErrorHandling::keyboardBreakOccurred)
  219014. {
  219015. LinuxErrorHandling::errorOccurred = true;
  219016. if (JUCEApplication::isStandaloneApp())
  219017. Process::terminate();
  219018. break;
  219019. }
  219020. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219021. return true;
  219022. if (returnIfNoPendingMessages)
  219023. break;
  219024. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219025. }
  219026. return false;
  219027. }
  219028. #endif
  219029. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219030. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219031. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219032. // compiled on its own).
  219033. #if JUCE_INCLUDED_FILE
  219034. class FreeTypeFontFace
  219035. {
  219036. public:
  219037. enum FontStyle
  219038. {
  219039. Plain = 0,
  219040. Bold = 1,
  219041. Italic = 2
  219042. };
  219043. FreeTypeFontFace (const String& familyName)
  219044. : hasSerif (false),
  219045. monospaced (false)
  219046. {
  219047. family = familyName;
  219048. }
  219049. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219050. {
  219051. if (names [(int) style].fileName.isEmpty())
  219052. {
  219053. names [(int) style].fileName = name;
  219054. names [(int) style].faceIndex = faceIndex;
  219055. }
  219056. }
  219057. const String& getFamilyName() const throw() { return family; }
  219058. const String& getFileName (const int style, int& faceIndex) const throw()
  219059. {
  219060. faceIndex = names[style].faceIndex;
  219061. return names[style].fileName;
  219062. }
  219063. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219064. bool getMonospaced() const throw() { return monospaced; }
  219065. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219066. bool getSerif() const throw() { return hasSerif; }
  219067. private:
  219068. String family;
  219069. struct FontNameIndex
  219070. {
  219071. String fileName;
  219072. int faceIndex;
  219073. };
  219074. FontNameIndex names[4];
  219075. bool hasSerif, monospaced;
  219076. };
  219077. class FreeTypeInterface : public DeletedAtShutdown
  219078. {
  219079. public:
  219080. FreeTypeInterface()
  219081. : ftLib (0),
  219082. lastFace (0),
  219083. lastBold (false),
  219084. lastItalic (false)
  219085. {
  219086. if (FT_Init_FreeType (&ftLib) != 0)
  219087. {
  219088. ftLib = 0;
  219089. DBG ("Failed to initialize FreeType");
  219090. }
  219091. StringArray fontDirs;
  219092. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219093. fontDirs.removeEmptyStrings (true);
  219094. if (fontDirs.size() == 0)
  219095. {
  219096. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  219097. if (fontsInfo != 0)
  219098. {
  219099. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219100. {
  219101. fontDirs.add (e->getAllSubText().trim());
  219102. }
  219103. }
  219104. }
  219105. if (fontDirs.size() == 0)
  219106. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219107. for (int i = 0; i < fontDirs.size(); ++i)
  219108. enumerateFaces (fontDirs[i]);
  219109. }
  219110. ~FreeTypeInterface()
  219111. {
  219112. if (lastFace != 0)
  219113. FT_Done_Face (lastFace);
  219114. if (ftLib != 0)
  219115. FT_Done_FreeType (ftLib);
  219116. clearSingletonInstance();
  219117. }
  219118. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219119. {
  219120. for (int i = 0; i < faces.size(); i++)
  219121. if (faces[i]->getFamilyName() == familyName)
  219122. return faces[i];
  219123. if (! create)
  219124. return 0;
  219125. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219126. faces.add (newFace);
  219127. return newFace;
  219128. }
  219129. // Enumerate all font faces available in a given directory
  219130. void enumerateFaces (const String& path)
  219131. {
  219132. File dirPath (path);
  219133. if (path.isEmpty() || ! dirPath.isDirectory())
  219134. return;
  219135. DirectoryIterator di (dirPath, true);
  219136. while (di.next())
  219137. {
  219138. File possible (di.getFile());
  219139. if (possible.hasFileExtension ("ttf")
  219140. || possible.hasFileExtension ("pfb")
  219141. || possible.hasFileExtension ("pcf"))
  219142. {
  219143. FT_Face face;
  219144. int faceIndex = 0;
  219145. int numFaces = 0;
  219146. do
  219147. {
  219148. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219149. faceIndex, &face) == 0)
  219150. {
  219151. if (faceIndex == 0)
  219152. numFaces = face->num_faces;
  219153. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219154. {
  219155. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219156. int style = (int) FreeTypeFontFace::Plain;
  219157. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219158. style |= (int) FreeTypeFontFace::Bold;
  219159. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219160. style |= (int) FreeTypeFontFace::Italic;
  219161. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219162. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219163. // Surely there must be a better way to do this?
  219164. const String name (face->family_name);
  219165. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219166. || name.containsIgnoreCase ("Verdana")
  219167. || name.containsIgnoreCase ("Arial")));
  219168. }
  219169. FT_Done_Face (face);
  219170. }
  219171. ++faceIndex;
  219172. }
  219173. while (faceIndex < numFaces);
  219174. }
  219175. }
  219176. }
  219177. // Create a FreeType face object for a given font
  219178. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219179. {
  219180. FT_Face face = 0;
  219181. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219182. {
  219183. face = lastFace;
  219184. }
  219185. else
  219186. {
  219187. if (lastFace != 0)
  219188. {
  219189. FT_Done_Face (lastFace);
  219190. lastFace = 0;
  219191. }
  219192. lastFontName = fontName;
  219193. lastBold = bold;
  219194. lastItalic = italic;
  219195. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219196. if (ftFace != 0)
  219197. {
  219198. int style = (int) FreeTypeFontFace::Plain;
  219199. if (bold)
  219200. style |= (int) FreeTypeFontFace::Bold;
  219201. if (italic)
  219202. style |= (int) FreeTypeFontFace::Italic;
  219203. int faceIndex;
  219204. String fileName (ftFace->getFileName (style, faceIndex));
  219205. if (fileName.isEmpty())
  219206. {
  219207. style ^= (int) FreeTypeFontFace::Bold;
  219208. fileName = ftFace->getFileName (style, faceIndex);
  219209. if (fileName.isEmpty())
  219210. {
  219211. style ^= (int) FreeTypeFontFace::Bold;
  219212. style ^= (int) FreeTypeFontFace::Italic;
  219213. fileName = ftFace->getFileName (style, faceIndex);
  219214. if (! fileName.length())
  219215. {
  219216. style ^= (int) FreeTypeFontFace::Bold;
  219217. fileName = ftFace->getFileName (style, faceIndex);
  219218. }
  219219. }
  219220. }
  219221. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219222. {
  219223. face = lastFace;
  219224. // If there isn't a unicode charmap then select the first one.
  219225. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219226. FT_Set_Charmap (face, face->charmaps[0]);
  219227. }
  219228. }
  219229. }
  219230. return face;
  219231. }
  219232. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219233. {
  219234. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219235. const float height = (float) (face->ascender - face->descender);
  219236. const float scaleX = 1.0f / height;
  219237. const float scaleY = -1.0f / height;
  219238. Path destShape;
  219239. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219240. || face->glyph->format != ft_glyph_format_outline)
  219241. {
  219242. return false;
  219243. }
  219244. const FT_Outline* const outline = &face->glyph->outline;
  219245. const short* const contours = outline->contours;
  219246. const char* const tags = outline->tags;
  219247. FT_Vector* const points = outline->points;
  219248. for (int c = 0; c < outline->n_contours; c++)
  219249. {
  219250. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219251. const int endPoint = contours[c];
  219252. for (int p = startPoint; p <= endPoint; p++)
  219253. {
  219254. const float x = scaleX * points[p].x;
  219255. const float y = scaleY * points[p].y;
  219256. if (p == startPoint)
  219257. {
  219258. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219259. {
  219260. float x2 = scaleX * points [endPoint].x;
  219261. float y2 = scaleY * points [endPoint].y;
  219262. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219263. {
  219264. x2 = (x + x2) * 0.5f;
  219265. y2 = (y + y2) * 0.5f;
  219266. }
  219267. destShape.startNewSubPath (x2, y2);
  219268. }
  219269. else
  219270. {
  219271. destShape.startNewSubPath (x, y);
  219272. }
  219273. }
  219274. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219275. {
  219276. if (p != startPoint)
  219277. destShape.lineTo (x, y);
  219278. }
  219279. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219280. {
  219281. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219282. float x2 = scaleX * points [nextIndex].x;
  219283. float y2 = scaleY * points [nextIndex].y;
  219284. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219285. {
  219286. x2 = (x + x2) * 0.5f;
  219287. y2 = (y + y2) * 0.5f;
  219288. }
  219289. else
  219290. {
  219291. ++p;
  219292. }
  219293. destShape.quadraticTo (x, y, x2, y2);
  219294. }
  219295. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219296. {
  219297. if (p >= endPoint)
  219298. return false;
  219299. const int next1 = p + 1;
  219300. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219301. const float x2 = scaleX * points [next1].x;
  219302. const float y2 = scaleY * points [next1].y;
  219303. const float x3 = scaleX * points [next2].x;
  219304. const float y3 = scaleY * points [next2].y;
  219305. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219306. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219307. return false;
  219308. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219309. p += 2;
  219310. }
  219311. }
  219312. destShape.closeSubPath();
  219313. }
  219314. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219315. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219316. addKerning (face, dest, character, glyphIndex);
  219317. return true;
  219318. }
  219319. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219320. {
  219321. const float height = (float) (face->ascender - face->descender);
  219322. uint32 rightGlyphIndex;
  219323. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219324. while (rightGlyphIndex != 0)
  219325. {
  219326. FT_Vector kerning;
  219327. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219328. {
  219329. if (kerning.x != 0)
  219330. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219331. }
  219332. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219333. }
  219334. }
  219335. // Add a glyph to a font
  219336. bool addGlyphToFont (const uint32 character, const String& fontName,
  219337. bool bold, bool italic, CustomTypeface& dest)
  219338. {
  219339. FT_Face face = createFT_Face (fontName, bold, italic);
  219340. return face != 0 && addGlyph (face, dest, character);
  219341. }
  219342. void getFamilyNames (StringArray& familyNames) const
  219343. {
  219344. for (int i = 0; i < faces.size(); i++)
  219345. familyNames.add (faces[i]->getFamilyName());
  219346. }
  219347. void getMonospacedNames (StringArray& monoSpaced) const
  219348. {
  219349. for (int i = 0; i < faces.size(); i++)
  219350. if (faces[i]->getMonospaced())
  219351. monoSpaced.add (faces[i]->getFamilyName());
  219352. }
  219353. void getSerifNames (StringArray& serif) const
  219354. {
  219355. for (int i = 0; i < faces.size(); i++)
  219356. if (faces[i]->getSerif())
  219357. serif.add (faces[i]->getFamilyName());
  219358. }
  219359. void getSansSerifNames (StringArray& sansSerif) const
  219360. {
  219361. for (int i = 0; i < faces.size(); i++)
  219362. if (! faces[i]->getSerif())
  219363. sansSerif.add (faces[i]->getFamilyName());
  219364. }
  219365. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219366. private:
  219367. FT_Library ftLib;
  219368. FT_Face lastFace;
  219369. String lastFontName;
  219370. bool lastBold, lastItalic;
  219371. OwnedArray<FreeTypeFontFace> faces;
  219372. };
  219373. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219374. class FreetypeTypeface : public CustomTypeface
  219375. {
  219376. public:
  219377. FreetypeTypeface (const Font& font)
  219378. {
  219379. FT_Face face = FreeTypeInterface::getInstance()
  219380. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219381. if (face == 0)
  219382. {
  219383. #if JUCE_DEBUG
  219384. String msg ("Failed to create typeface: ");
  219385. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219386. DBG (msg);
  219387. #endif
  219388. }
  219389. else
  219390. {
  219391. setCharacteristics (font.getTypefaceName(),
  219392. face->ascender / (float) (face->ascender - face->descender),
  219393. font.isBold(), font.isItalic(),
  219394. L' ');
  219395. }
  219396. }
  219397. bool loadGlyphIfPossible (juce_wchar character)
  219398. {
  219399. return FreeTypeInterface::getInstance()
  219400. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219401. }
  219402. };
  219403. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219404. {
  219405. return new FreetypeTypeface (font);
  219406. }
  219407. const StringArray Font::findAllTypefaceNames()
  219408. {
  219409. StringArray s;
  219410. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219411. s.sort (true);
  219412. return s;
  219413. }
  219414. namespace
  219415. {
  219416. const String pickBestFont (const StringArray& names,
  219417. const char* const choicesString)
  219418. {
  219419. StringArray choices;
  219420. choices.addTokens (String (choicesString), ",", String::empty);
  219421. choices.trim();
  219422. choices.removeEmptyStrings();
  219423. int i, j;
  219424. for (j = 0; j < choices.size(); ++j)
  219425. if (names.contains (choices[j], true))
  219426. return choices[j];
  219427. for (j = 0; j < choices.size(); ++j)
  219428. for (i = 0; i < names.size(); i++)
  219429. if (names[i].startsWithIgnoreCase (choices[j]))
  219430. return names[i];
  219431. for (j = 0; j < choices.size(); ++j)
  219432. for (i = 0; i < names.size(); i++)
  219433. if (names[i].containsIgnoreCase (choices[j]))
  219434. return names[i];
  219435. return names[0];
  219436. }
  219437. const String linux_getDefaultSansSerifFontName()
  219438. {
  219439. StringArray allFonts;
  219440. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219441. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219442. }
  219443. const String linux_getDefaultSerifFontName()
  219444. {
  219445. StringArray allFonts;
  219446. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219447. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219448. }
  219449. const String linux_getDefaultMonospacedFontName()
  219450. {
  219451. StringArray allFonts;
  219452. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219453. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219454. }
  219455. }
  219456. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  219457. {
  219458. defaultSans = linux_getDefaultSansSerifFontName();
  219459. defaultSerif = linux_getDefaultSerifFontName();
  219460. defaultFixed = linux_getDefaultMonospacedFontName();
  219461. }
  219462. #endif
  219463. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219464. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219465. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219466. // compiled on its own).
  219467. #if JUCE_INCLUDED_FILE
  219468. // These are defined in juce_linux_Messaging.cpp
  219469. extern Display* display;
  219470. extern XContext windowHandleXContext;
  219471. namespace Atoms
  219472. {
  219473. enum ProtocolItems
  219474. {
  219475. TAKE_FOCUS = 0,
  219476. DELETE_WINDOW = 1,
  219477. PING = 2
  219478. };
  219479. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219480. ActiveWin, Pid, WindowType, WindowState,
  219481. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219482. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219483. XdndActionDescription, XdndActionCopy,
  219484. allowedActions[5],
  219485. allowedMimeTypes[2];
  219486. const unsigned long DndVersion = 3;
  219487. static void initialiseAtoms()
  219488. {
  219489. static bool atomsInitialised = false;
  219490. if (! atomsInitialised)
  219491. {
  219492. atomsInitialised = true;
  219493. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219494. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219495. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219496. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219497. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219498. State = XInternAtom (display, "WM_STATE", True);
  219499. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219500. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219501. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219502. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219503. XdndAware = XInternAtom (display, "XdndAware", False);
  219504. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219505. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219506. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219507. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219508. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219509. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219510. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219511. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219512. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219513. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219514. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219515. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219516. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219517. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219518. allowedActions[1] = XdndActionCopy;
  219519. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219520. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219521. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219522. }
  219523. }
  219524. }
  219525. namespace Keys
  219526. {
  219527. enum MouseButtons
  219528. {
  219529. NoButton = 0,
  219530. LeftButton = 1,
  219531. MiddleButton = 2,
  219532. RightButton = 3,
  219533. WheelUp = 4,
  219534. WheelDown = 5
  219535. };
  219536. static int AltMask = 0;
  219537. static int NumLockMask = 0;
  219538. static bool numLock = false;
  219539. static bool capsLock = false;
  219540. static char keyStates [32];
  219541. static const int extendedKeyModifier = 0x10000000;
  219542. }
  219543. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219544. {
  219545. int keysym;
  219546. if (keyCode & Keys::extendedKeyModifier)
  219547. {
  219548. keysym = 0xff00 | (keyCode & 0xff);
  219549. }
  219550. else
  219551. {
  219552. keysym = keyCode;
  219553. if (keysym == (XK_Tab & 0xff)
  219554. || keysym == (XK_Return & 0xff)
  219555. || keysym == (XK_Escape & 0xff)
  219556. || keysym == (XK_BackSpace & 0xff))
  219557. {
  219558. keysym |= 0xff00;
  219559. }
  219560. }
  219561. ScopedXLock xlock;
  219562. const int keycode = XKeysymToKeycode (display, keysym);
  219563. const int keybyte = keycode >> 3;
  219564. const int keybit = (1 << (keycode & 7));
  219565. return (Keys::keyStates [keybyte] & keybit) != 0;
  219566. }
  219567. #if JUCE_USE_XSHM
  219568. namespace XSHMHelpers
  219569. {
  219570. static int trappedErrorCode = 0;
  219571. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219572. {
  219573. trappedErrorCode = err->error_code;
  219574. return 0;
  219575. }
  219576. static bool isShmAvailable() throw()
  219577. {
  219578. static bool isChecked = false;
  219579. static bool isAvailable = false;
  219580. if (! isChecked)
  219581. {
  219582. isChecked = true;
  219583. int major, minor;
  219584. Bool pixmaps;
  219585. ScopedXLock xlock;
  219586. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219587. {
  219588. trappedErrorCode = 0;
  219589. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219590. XShmSegmentInfo segmentInfo;
  219591. zerostruct (segmentInfo);
  219592. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219593. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219594. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219595. xImage->bytes_per_line * xImage->height,
  219596. IPC_CREAT | 0777)) >= 0)
  219597. {
  219598. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219599. if (segmentInfo.shmaddr != (void*) -1)
  219600. {
  219601. segmentInfo.readOnly = False;
  219602. xImage->data = segmentInfo.shmaddr;
  219603. XSync (display, False);
  219604. if (XShmAttach (display, &segmentInfo) != 0)
  219605. {
  219606. XSync (display, False);
  219607. XShmDetach (display, &segmentInfo);
  219608. isAvailable = true;
  219609. }
  219610. }
  219611. XFlush (display);
  219612. XDestroyImage (xImage);
  219613. shmdt (segmentInfo.shmaddr);
  219614. }
  219615. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219616. XSetErrorHandler (oldHandler);
  219617. if (trappedErrorCode != 0)
  219618. isAvailable = false;
  219619. }
  219620. }
  219621. return isAvailable;
  219622. }
  219623. }
  219624. #endif
  219625. #if JUCE_USE_XRENDER
  219626. namespace XRender
  219627. {
  219628. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219629. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219630. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219631. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219632. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219633. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219634. static tXRenderFindFormat xRenderFindFormat = 0;
  219635. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219636. static bool isAvailable()
  219637. {
  219638. static bool hasLoaded = false;
  219639. if (! hasLoaded)
  219640. {
  219641. ScopedXLock xlock;
  219642. hasLoaded = true;
  219643. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219644. if (h != 0)
  219645. {
  219646. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219647. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219648. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219649. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219650. }
  219651. if (xRenderQueryVersion != 0
  219652. && xRenderFindStandardFormat != 0
  219653. && xRenderFindFormat != 0
  219654. && xRenderFindVisualFormat != 0)
  219655. {
  219656. int major, minor;
  219657. if (xRenderQueryVersion (display, &major, &minor))
  219658. return true;
  219659. }
  219660. xRenderQueryVersion = 0;
  219661. }
  219662. return xRenderQueryVersion != 0;
  219663. }
  219664. static XRenderPictFormat* findPictureFormat()
  219665. {
  219666. ScopedXLock xlock;
  219667. XRenderPictFormat* pictFormat = 0;
  219668. if (isAvailable())
  219669. {
  219670. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219671. if (pictFormat == 0)
  219672. {
  219673. XRenderPictFormat desiredFormat;
  219674. desiredFormat.type = PictTypeDirect;
  219675. desiredFormat.depth = 32;
  219676. desiredFormat.direct.alphaMask = 0xff;
  219677. desiredFormat.direct.redMask = 0xff;
  219678. desiredFormat.direct.greenMask = 0xff;
  219679. desiredFormat.direct.blueMask = 0xff;
  219680. desiredFormat.direct.alpha = 24;
  219681. desiredFormat.direct.red = 16;
  219682. desiredFormat.direct.green = 8;
  219683. desiredFormat.direct.blue = 0;
  219684. pictFormat = xRenderFindFormat (display,
  219685. PictFormatType | PictFormatDepth
  219686. | PictFormatRedMask | PictFormatRed
  219687. | PictFormatGreenMask | PictFormatGreen
  219688. | PictFormatBlueMask | PictFormatBlue
  219689. | PictFormatAlphaMask | PictFormatAlpha,
  219690. &desiredFormat,
  219691. 0);
  219692. }
  219693. }
  219694. return pictFormat;
  219695. }
  219696. }
  219697. #endif
  219698. namespace Visuals
  219699. {
  219700. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219701. {
  219702. ScopedXLock xlock;
  219703. Visual* visual = 0;
  219704. int numVisuals = 0;
  219705. long desiredMask = VisualNoMask;
  219706. XVisualInfo desiredVisual;
  219707. desiredVisual.screen = DefaultScreen (display);
  219708. desiredVisual.depth = desiredDepth;
  219709. desiredMask = VisualScreenMask | VisualDepthMask;
  219710. if (desiredDepth == 32)
  219711. {
  219712. desiredVisual.c_class = TrueColor;
  219713. desiredVisual.red_mask = 0x00FF0000;
  219714. desiredVisual.green_mask = 0x0000FF00;
  219715. desiredVisual.blue_mask = 0x000000FF;
  219716. desiredVisual.bits_per_rgb = 8;
  219717. desiredMask |= VisualClassMask;
  219718. desiredMask |= VisualRedMaskMask;
  219719. desiredMask |= VisualGreenMaskMask;
  219720. desiredMask |= VisualBlueMaskMask;
  219721. desiredMask |= VisualBitsPerRGBMask;
  219722. }
  219723. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219724. desiredMask,
  219725. &desiredVisual,
  219726. &numVisuals);
  219727. if (xvinfos != 0)
  219728. {
  219729. for (int i = 0; i < numVisuals; i++)
  219730. {
  219731. if (xvinfos[i].depth == desiredDepth)
  219732. {
  219733. visual = xvinfos[i].visual;
  219734. break;
  219735. }
  219736. }
  219737. XFree (xvinfos);
  219738. }
  219739. return visual;
  219740. }
  219741. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219742. {
  219743. Visual* visual = 0;
  219744. if (desiredDepth == 32)
  219745. {
  219746. #if JUCE_USE_XSHM
  219747. if (XSHMHelpers::isShmAvailable())
  219748. {
  219749. #if JUCE_USE_XRENDER
  219750. if (XRender::isAvailable())
  219751. {
  219752. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219753. if (pictFormat != 0)
  219754. {
  219755. int numVisuals = 0;
  219756. XVisualInfo desiredVisual;
  219757. desiredVisual.screen = DefaultScreen (display);
  219758. desiredVisual.depth = 32;
  219759. desiredVisual.bits_per_rgb = 8;
  219760. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219761. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219762. &desiredVisual, &numVisuals);
  219763. if (xvinfos != 0)
  219764. {
  219765. for (int i = 0; i < numVisuals; ++i)
  219766. {
  219767. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219768. if (pictVisualFormat != 0
  219769. && pictVisualFormat->type == PictTypeDirect
  219770. && pictVisualFormat->direct.alphaMask)
  219771. {
  219772. visual = xvinfos[i].visual;
  219773. matchedDepth = 32;
  219774. break;
  219775. }
  219776. }
  219777. XFree (xvinfos);
  219778. }
  219779. }
  219780. }
  219781. #endif
  219782. if (visual == 0)
  219783. {
  219784. visual = findVisualWithDepth (32);
  219785. if (visual != 0)
  219786. matchedDepth = 32;
  219787. }
  219788. }
  219789. #endif
  219790. }
  219791. if (visual == 0 && desiredDepth >= 24)
  219792. {
  219793. visual = findVisualWithDepth (24);
  219794. if (visual != 0)
  219795. matchedDepth = 24;
  219796. }
  219797. if (visual == 0 && desiredDepth >= 16)
  219798. {
  219799. visual = findVisualWithDepth (16);
  219800. if (visual != 0)
  219801. matchedDepth = 16;
  219802. }
  219803. return visual;
  219804. }
  219805. }
  219806. class XBitmapImage : public Image::SharedImage
  219807. {
  219808. public:
  219809. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219810. const bool clearImage, const int imageDepth_, Visual* visual)
  219811. : Image::SharedImage (format_, w, h),
  219812. imageDepth (imageDepth_),
  219813. gc (None)
  219814. {
  219815. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219816. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219817. lineStride = ((w * pixelStride + 3) & ~3);
  219818. ScopedXLock xlock;
  219819. #if JUCE_USE_XSHM
  219820. usingXShm = false;
  219821. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219822. {
  219823. zerostruct (segmentInfo);
  219824. segmentInfo.shmid = -1;
  219825. segmentInfo.shmaddr = (char *) -1;
  219826. segmentInfo.readOnly = False;
  219827. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219828. if (xImage != 0)
  219829. {
  219830. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219831. xImage->bytes_per_line * xImage->height,
  219832. IPC_CREAT | 0777)) >= 0)
  219833. {
  219834. if (segmentInfo.shmid != -1)
  219835. {
  219836. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219837. if (segmentInfo.shmaddr != (void*) -1)
  219838. {
  219839. segmentInfo.readOnly = False;
  219840. xImage->data = segmentInfo.shmaddr;
  219841. imageData = (uint8*) segmentInfo.shmaddr;
  219842. if (XShmAttach (display, &segmentInfo) != 0)
  219843. usingXShm = true;
  219844. else
  219845. jassertfalse;
  219846. }
  219847. else
  219848. {
  219849. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219850. }
  219851. }
  219852. }
  219853. }
  219854. }
  219855. if (! usingXShm)
  219856. #endif
  219857. {
  219858. imageDataAllocated.malloc (lineStride * h);
  219859. imageData = imageDataAllocated;
  219860. if (format_ == Image::ARGB && clearImage)
  219861. zeromem (imageData, h * lineStride);
  219862. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219863. xImage->width = w;
  219864. xImage->height = h;
  219865. xImage->xoffset = 0;
  219866. xImage->format = ZPixmap;
  219867. xImage->data = (char*) imageData;
  219868. xImage->byte_order = ImageByteOrder (display);
  219869. xImage->bitmap_unit = BitmapUnit (display);
  219870. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219871. xImage->bitmap_pad = 32;
  219872. xImage->depth = pixelStride * 8;
  219873. xImage->bytes_per_line = lineStride;
  219874. xImage->bits_per_pixel = pixelStride * 8;
  219875. xImage->red_mask = 0x00FF0000;
  219876. xImage->green_mask = 0x0000FF00;
  219877. xImage->blue_mask = 0x000000FF;
  219878. if (imageDepth == 16)
  219879. {
  219880. const int pixelStride = 2;
  219881. const int lineStride = ((w * pixelStride + 3) & ~3);
  219882. imageData16Bit.malloc (lineStride * h);
  219883. xImage->data = imageData16Bit;
  219884. xImage->bitmap_pad = 16;
  219885. xImage->depth = pixelStride * 8;
  219886. xImage->bytes_per_line = lineStride;
  219887. xImage->bits_per_pixel = pixelStride * 8;
  219888. xImage->red_mask = visual->red_mask;
  219889. xImage->green_mask = visual->green_mask;
  219890. xImage->blue_mask = visual->blue_mask;
  219891. }
  219892. if (! XInitImage (xImage))
  219893. jassertfalse;
  219894. }
  219895. }
  219896. ~XBitmapImage()
  219897. {
  219898. ScopedXLock xlock;
  219899. if (gc != None)
  219900. XFreeGC (display, gc);
  219901. #if JUCE_USE_XSHM
  219902. if (usingXShm)
  219903. {
  219904. XShmDetach (display, &segmentInfo);
  219905. XFlush (display);
  219906. XDestroyImage (xImage);
  219907. shmdt (segmentInfo.shmaddr);
  219908. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219909. }
  219910. else
  219911. #endif
  219912. {
  219913. xImage->data = 0;
  219914. XDestroyImage (xImage);
  219915. }
  219916. }
  219917. Image::ImageType getType() const { return Image::NativeImage; }
  219918. LowLevelGraphicsContext* createLowLevelContext()
  219919. {
  219920. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219921. }
  219922. SharedImage* clone()
  219923. {
  219924. jassertfalse;
  219925. return 0;
  219926. }
  219927. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219928. {
  219929. ScopedXLock xlock;
  219930. if (gc == None)
  219931. {
  219932. XGCValues gcvalues;
  219933. gcvalues.foreground = None;
  219934. gcvalues.background = None;
  219935. gcvalues.function = GXcopy;
  219936. gcvalues.plane_mask = AllPlanes;
  219937. gcvalues.clip_mask = None;
  219938. gcvalues.graphics_exposures = False;
  219939. gc = XCreateGC (display, window,
  219940. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219941. &gcvalues);
  219942. }
  219943. if (imageDepth == 16)
  219944. {
  219945. const uint32 rMask = xImage->red_mask;
  219946. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219947. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219948. const uint32 gMask = xImage->green_mask;
  219949. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219950. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219951. const uint32 bMask = xImage->blue_mask;
  219952. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219953. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219954. const Image::BitmapData srcData (Image (this), false);
  219955. for (int y = sy; y < sy + dh; ++y)
  219956. {
  219957. const uint8* p = srcData.getPixelPointer (sx, y);
  219958. for (int x = sx; x < sx + dw; ++x)
  219959. {
  219960. const PixelRGB* const pixel = (const PixelRGB*) p;
  219961. p += srcData.pixelStride;
  219962. XPutPixel (xImage, x, y,
  219963. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219964. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219965. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219966. }
  219967. }
  219968. }
  219969. // blit results to screen.
  219970. #if JUCE_USE_XSHM
  219971. if (usingXShm)
  219972. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219973. else
  219974. #endif
  219975. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219976. }
  219977. private:
  219978. XImage* xImage;
  219979. const int imageDepth;
  219980. HeapBlock <uint8> imageDataAllocated;
  219981. HeapBlock <char> imageData16Bit;
  219982. GC gc;
  219983. #if JUCE_USE_XSHM
  219984. XShmSegmentInfo segmentInfo;
  219985. bool usingXShm;
  219986. #endif
  219987. static int getShiftNeeded (const uint32 mask) throw()
  219988. {
  219989. for (int i = 32; --i >= 0;)
  219990. if (((mask >> i) & 1) != 0)
  219991. return i - 7;
  219992. jassertfalse;
  219993. return 0;
  219994. }
  219995. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219996. };
  219997. class LinuxComponentPeer : public ComponentPeer
  219998. {
  219999. public:
  220000. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220001. : ComponentPeer (component, windowStyleFlags),
  220002. windowH (0),
  220003. parentWindow (0),
  220004. wx (0),
  220005. wy (0),
  220006. ww (0),
  220007. wh (0),
  220008. fullScreen (false),
  220009. mapped (false),
  220010. visual (0),
  220011. depth (0)
  220012. {
  220013. // it's dangerous to create a window on a thread other than the message thread..
  220014. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220015. repainter = new LinuxRepaintManager (this);
  220016. createWindow();
  220017. setTitle (component->getName());
  220018. }
  220019. ~LinuxComponentPeer()
  220020. {
  220021. // it's dangerous to delete a window on a thread other than the message thread..
  220022. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220023. deleteIconPixmaps();
  220024. destroyWindow();
  220025. windowH = 0;
  220026. }
  220027. void* getNativeHandle() const
  220028. {
  220029. return (void*) windowH;
  220030. }
  220031. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220032. {
  220033. XPointer peer = 0;
  220034. ScopedXLock xlock;
  220035. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220036. {
  220037. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220038. peer = 0;
  220039. }
  220040. return (LinuxComponentPeer*) peer;
  220041. }
  220042. void setVisible (bool shouldBeVisible)
  220043. {
  220044. ScopedXLock xlock;
  220045. if (shouldBeVisible)
  220046. XMapWindow (display, windowH);
  220047. else
  220048. XUnmapWindow (display, windowH);
  220049. }
  220050. void setTitle (const String& title)
  220051. {
  220052. setWindowTitle (windowH, title);
  220053. }
  220054. void setPosition (int x, int y)
  220055. {
  220056. setBounds (x, y, ww, wh, false);
  220057. }
  220058. void setSize (int w, int h)
  220059. {
  220060. setBounds (wx, wy, w, h, false);
  220061. }
  220062. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220063. {
  220064. fullScreen = isNowFullScreen;
  220065. if (windowH != 0)
  220066. {
  220067. Component::SafePointer<Component> deletionChecker (component);
  220068. wx = x;
  220069. wy = y;
  220070. ww = jmax (1, w);
  220071. wh = jmax (1, h);
  220072. ScopedXLock xlock;
  220073. // Make sure the Window manager does what we want
  220074. XSizeHints* hints = XAllocSizeHints();
  220075. hints->flags = USSize | USPosition;
  220076. hints->width = ww;
  220077. hints->height = wh;
  220078. hints->x = wx;
  220079. hints->y = wy;
  220080. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220081. {
  220082. hints->min_width = hints->max_width = hints->width;
  220083. hints->min_height = hints->max_height = hints->height;
  220084. hints->flags |= PMinSize | PMaxSize;
  220085. }
  220086. XSetWMNormalHints (display, windowH, hints);
  220087. XFree (hints);
  220088. XMoveResizeWindow (display, windowH,
  220089. wx - windowBorder.getLeft(),
  220090. wy - windowBorder.getTop(), ww, wh);
  220091. if (deletionChecker != 0)
  220092. {
  220093. updateBorderSize();
  220094. handleMovedOrResized();
  220095. }
  220096. }
  220097. }
  220098. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220099. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220100. const Point<int> localToGlobal (const Point<int>& relativePosition)
  220101. {
  220102. return relativePosition + getScreenPosition();
  220103. }
  220104. const Point<int> globalToLocal (const Point<int>& screenPosition)
  220105. {
  220106. return screenPosition - getScreenPosition();
  220107. }
  220108. void setAlpha (float newAlpha)
  220109. {
  220110. //xxx todo!
  220111. }
  220112. void setMinimised (bool shouldBeMinimised)
  220113. {
  220114. if (shouldBeMinimised)
  220115. {
  220116. Window root = RootWindow (display, DefaultScreen (display));
  220117. XClientMessageEvent clientMsg;
  220118. clientMsg.display = display;
  220119. clientMsg.window = windowH;
  220120. clientMsg.type = ClientMessage;
  220121. clientMsg.format = 32;
  220122. clientMsg.message_type = Atoms::ChangeState;
  220123. clientMsg.data.l[0] = IconicState;
  220124. ScopedXLock xlock;
  220125. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220126. }
  220127. else
  220128. {
  220129. setVisible (true);
  220130. }
  220131. }
  220132. bool isMinimised() const
  220133. {
  220134. bool minimised = false;
  220135. unsigned char* stateProp;
  220136. unsigned long nitems, bytesLeft;
  220137. Atom actualType;
  220138. int actualFormat;
  220139. ScopedXLock xlock;
  220140. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220141. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220142. &stateProp) == Success
  220143. && actualType == Atoms::State
  220144. && actualFormat == 32
  220145. && nitems > 0)
  220146. {
  220147. if (((unsigned long*) stateProp)[0] == IconicState)
  220148. minimised = true;
  220149. XFree (stateProp);
  220150. }
  220151. return minimised;
  220152. }
  220153. void setFullScreen (const bool shouldBeFullScreen)
  220154. {
  220155. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220156. setMinimised (false);
  220157. if (fullScreen != shouldBeFullScreen)
  220158. {
  220159. if (shouldBeFullScreen)
  220160. r = Desktop::getInstance().getMainMonitorArea();
  220161. if (! r.isEmpty())
  220162. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220163. getComponent()->repaint();
  220164. }
  220165. }
  220166. bool isFullScreen() const
  220167. {
  220168. return fullScreen;
  220169. }
  220170. bool isChildWindowOf (Window possibleParent) const
  220171. {
  220172. Window* windowList = 0;
  220173. uint32 windowListSize = 0;
  220174. Window parent, root;
  220175. ScopedXLock xlock;
  220176. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220177. {
  220178. if (windowList != 0)
  220179. XFree (windowList);
  220180. return parent == possibleParent;
  220181. }
  220182. return false;
  220183. }
  220184. bool isFrontWindow() const
  220185. {
  220186. Window* windowList = 0;
  220187. uint32 windowListSize = 0;
  220188. bool result = false;
  220189. ScopedXLock xlock;
  220190. Window parent, root = RootWindow (display, DefaultScreen (display));
  220191. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220192. {
  220193. for (int i = windowListSize; --i >= 0;)
  220194. {
  220195. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220196. if (peer != 0)
  220197. {
  220198. result = (peer == this);
  220199. break;
  220200. }
  220201. }
  220202. }
  220203. if (windowList != 0)
  220204. XFree (windowList);
  220205. return result;
  220206. }
  220207. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220208. {
  220209. if (((unsigned int) position.getX()) >= (unsigned int) ww
  220210. || ((unsigned int) position.getY()) >= (unsigned int) wh)
  220211. return false;
  220212. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  220213. {
  220214. Component* const c = Desktop::getInstance().getComponent (i);
  220215. if (c == getComponent())
  220216. break;
  220217. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  220218. return false;
  220219. }
  220220. if (trueIfInAChildWindow)
  220221. return true;
  220222. ::Window root, child;
  220223. unsigned int bw, depth;
  220224. int wx, wy, w, h;
  220225. ScopedXLock xlock;
  220226. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220227. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220228. &bw, &depth))
  220229. {
  220230. return false;
  220231. }
  220232. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  220233. return false;
  220234. return child == None;
  220235. }
  220236. const BorderSize getFrameSize() const
  220237. {
  220238. return BorderSize();
  220239. }
  220240. bool setAlwaysOnTop (bool alwaysOnTop)
  220241. {
  220242. return false;
  220243. }
  220244. void toFront (bool makeActive)
  220245. {
  220246. if (makeActive)
  220247. {
  220248. setVisible (true);
  220249. grabFocus();
  220250. }
  220251. XEvent ev;
  220252. ev.xclient.type = ClientMessage;
  220253. ev.xclient.serial = 0;
  220254. ev.xclient.send_event = True;
  220255. ev.xclient.message_type = Atoms::ActiveWin;
  220256. ev.xclient.window = windowH;
  220257. ev.xclient.format = 32;
  220258. ev.xclient.data.l[0] = 2;
  220259. ev.xclient.data.l[1] = CurrentTime;
  220260. ev.xclient.data.l[2] = 0;
  220261. ev.xclient.data.l[3] = 0;
  220262. ev.xclient.data.l[4] = 0;
  220263. {
  220264. ScopedXLock xlock;
  220265. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220266. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220267. XWindowAttributes attr;
  220268. XGetWindowAttributes (display, windowH, &attr);
  220269. if (component->isAlwaysOnTop())
  220270. XRaiseWindow (display, windowH);
  220271. XSync (display, False);
  220272. }
  220273. handleBroughtToFront();
  220274. }
  220275. void toBehind (ComponentPeer* other)
  220276. {
  220277. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220278. jassert (otherPeer != 0); // wrong type of window?
  220279. if (otherPeer != 0)
  220280. {
  220281. setMinimised (false);
  220282. Window newStack[] = { otherPeer->windowH, windowH };
  220283. ScopedXLock xlock;
  220284. XRestackWindows (display, newStack, 2);
  220285. }
  220286. }
  220287. bool isFocused() const
  220288. {
  220289. int revert = 0;
  220290. Window focusedWindow = 0;
  220291. ScopedXLock xlock;
  220292. XGetInputFocus (display, &focusedWindow, &revert);
  220293. return focusedWindow == windowH;
  220294. }
  220295. void grabFocus()
  220296. {
  220297. XWindowAttributes atts;
  220298. ScopedXLock xlock;
  220299. if (windowH != 0
  220300. && XGetWindowAttributes (display, windowH, &atts)
  220301. && atts.map_state == IsViewable
  220302. && ! isFocused())
  220303. {
  220304. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220305. isActiveApplication = true;
  220306. }
  220307. }
  220308. void textInputRequired (const Point<int>&)
  220309. {
  220310. }
  220311. void repaint (const Rectangle<int>& area)
  220312. {
  220313. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220314. }
  220315. void performAnyPendingRepaintsNow()
  220316. {
  220317. repainter->performAnyPendingRepaintsNow();
  220318. }
  220319. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220320. {
  220321. ScopedXLock xlock;
  220322. const int width = image.getWidth();
  220323. const int height = image.getHeight();
  220324. HeapBlock <uint32> colour (width * height);
  220325. int index = 0;
  220326. for (int y = 0; y < height; ++y)
  220327. for (int x = 0; x < width; ++x)
  220328. colour[index++] = image.getPixelAt (x, y).getARGB();
  220329. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220330. 0, reinterpret_cast<char*> (colour.getData()),
  220331. width, height, 32, 0);
  220332. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220333. width, height, 24);
  220334. GC gc = XCreateGC (display, pixmap, 0, 0);
  220335. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220336. XFreeGC (display, gc);
  220337. return pixmap;
  220338. }
  220339. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220340. {
  220341. ScopedXLock xlock;
  220342. const int width = image.getWidth();
  220343. const int height = image.getHeight();
  220344. const int stride = (width + 7) >> 3;
  220345. HeapBlock <char> mask;
  220346. mask.calloc (stride * height);
  220347. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220348. for (int y = 0; y < height; ++y)
  220349. {
  220350. for (int x = 0; x < width; ++x)
  220351. {
  220352. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220353. const int offset = y * stride + (x >> 3);
  220354. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220355. mask[offset] |= bit;
  220356. }
  220357. }
  220358. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220359. mask.getData(), width, height, 1, 0, 1);
  220360. }
  220361. void setIcon (const Image& newIcon)
  220362. {
  220363. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220364. HeapBlock <unsigned long> data (dataSize);
  220365. int index = 0;
  220366. data[index++] = newIcon.getWidth();
  220367. data[index++] = newIcon.getHeight();
  220368. for (int y = 0; y < newIcon.getHeight(); ++y)
  220369. for (int x = 0; x < newIcon.getWidth(); ++x)
  220370. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220371. ScopedXLock xlock;
  220372. XChangeProperty (display, windowH,
  220373. XInternAtom (display, "_NET_WM_ICON", False),
  220374. XA_CARDINAL, 32, PropModeReplace,
  220375. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220376. deleteIconPixmaps();
  220377. XWMHints* wmHints = XGetWMHints (display, windowH);
  220378. if (wmHints == 0)
  220379. wmHints = XAllocWMHints();
  220380. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220381. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220382. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220383. XSetWMHints (display, windowH, wmHints);
  220384. XFree (wmHints);
  220385. XSync (display, False);
  220386. }
  220387. void deleteIconPixmaps()
  220388. {
  220389. ScopedXLock xlock;
  220390. XWMHints* wmHints = XGetWMHints (display, windowH);
  220391. if (wmHints != 0)
  220392. {
  220393. if ((wmHints->flags & IconPixmapHint) != 0)
  220394. {
  220395. wmHints->flags &= ~IconPixmapHint;
  220396. XFreePixmap (display, wmHints->icon_pixmap);
  220397. }
  220398. if ((wmHints->flags & IconMaskHint) != 0)
  220399. {
  220400. wmHints->flags &= ~IconMaskHint;
  220401. XFreePixmap (display, wmHints->icon_mask);
  220402. }
  220403. XSetWMHints (display, windowH, wmHints);
  220404. XFree (wmHints);
  220405. }
  220406. }
  220407. void handleWindowMessage (XEvent* event)
  220408. {
  220409. switch (event->xany.type)
  220410. {
  220411. case 2: // 'KeyPress'
  220412. {
  220413. ScopedXLock xlock;
  220414. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220415. updateKeyStates (keyEvent->keycode, true);
  220416. char utf8 [64];
  220417. zeromem (utf8, sizeof (utf8));
  220418. KeySym sym;
  220419. {
  220420. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220421. ::setlocale (LC_ALL, "");
  220422. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220423. ::setlocale (LC_ALL, oldLocale);
  220424. }
  220425. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220426. int keyCode = (int) unicodeChar;
  220427. if (keyCode < 0x20)
  220428. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220429. const ModifierKeys oldMods (currentModifiers);
  220430. bool keyPressed = false;
  220431. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220432. if ((sym & 0xff00) == 0xff00)
  220433. {
  220434. // Translate keypad
  220435. if (sym == XK_KP_Divide)
  220436. keyCode = XK_slash;
  220437. else if (sym == XK_KP_Multiply)
  220438. keyCode = XK_asterisk;
  220439. else if (sym == XK_KP_Subtract)
  220440. keyCode = XK_hyphen;
  220441. else if (sym == XK_KP_Add)
  220442. keyCode = XK_plus;
  220443. else if (sym == XK_KP_Enter)
  220444. keyCode = XK_Return;
  220445. else if (sym == XK_KP_Decimal)
  220446. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220447. else if (sym == XK_KP_0)
  220448. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220449. else if (sym == XK_KP_1)
  220450. keyCode = Keys::numLock ? XK_1 : XK_End;
  220451. else if (sym == XK_KP_2)
  220452. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220453. else if (sym == XK_KP_3)
  220454. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220455. else if (sym == XK_KP_4)
  220456. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220457. else if (sym == XK_KP_5)
  220458. keyCode = XK_5;
  220459. else if (sym == XK_KP_6)
  220460. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220461. else if (sym == XK_KP_7)
  220462. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220463. else if (sym == XK_KP_8)
  220464. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220465. else if (sym == XK_KP_9)
  220466. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220467. switch (sym)
  220468. {
  220469. case XK_Left:
  220470. case XK_Right:
  220471. case XK_Up:
  220472. case XK_Down:
  220473. case XK_Page_Up:
  220474. case XK_Page_Down:
  220475. case XK_End:
  220476. case XK_Home:
  220477. case XK_Delete:
  220478. case XK_Insert:
  220479. keyPressed = true;
  220480. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220481. break;
  220482. case XK_Tab:
  220483. case XK_Return:
  220484. case XK_Escape:
  220485. case XK_BackSpace:
  220486. keyPressed = true;
  220487. keyCode &= 0xff;
  220488. break;
  220489. default:
  220490. {
  220491. if (sym >= XK_F1 && sym <= XK_F16)
  220492. {
  220493. keyPressed = true;
  220494. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220495. }
  220496. break;
  220497. }
  220498. }
  220499. }
  220500. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220501. keyPressed = true;
  220502. if (oldMods != currentModifiers)
  220503. handleModifierKeysChange();
  220504. if (keyDownChange)
  220505. handleKeyUpOrDown (true);
  220506. if (keyPressed)
  220507. handleKeyPress (keyCode, unicodeChar);
  220508. break;
  220509. }
  220510. case KeyRelease:
  220511. {
  220512. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220513. updateKeyStates (keyEvent->keycode, false);
  220514. KeySym sym;
  220515. {
  220516. ScopedXLock xlock;
  220517. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220518. }
  220519. const ModifierKeys oldMods (currentModifiers);
  220520. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220521. if (oldMods != currentModifiers)
  220522. handleModifierKeysChange();
  220523. if (keyDownChange)
  220524. handleKeyUpOrDown (false);
  220525. break;
  220526. }
  220527. case ButtonPress:
  220528. {
  220529. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220530. updateKeyModifiers (buttonPressEvent->state);
  220531. bool buttonMsg = false;
  220532. const int map = pointerMap [buttonPressEvent->button - Button1];
  220533. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220534. {
  220535. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220536. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220537. }
  220538. if (map == Keys::LeftButton)
  220539. {
  220540. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220541. buttonMsg = true;
  220542. }
  220543. else if (map == Keys::RightButton)
  220544. {
  220545. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220546. buttonMsg = true;
  220547. }
  220548. else if (map == Keys::MiddleButton)
  220549. {
  220550. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220551. buttonMsg = true;
  220552. }
  220553. if (buttonMsg)
  220554. {
  220555. toFront (true);
  220556. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220557. getEventTime (buttonPressEvent->time));
  220558. }
  220559. clearLastMousePos();
  220560. break;
  220561. }
  220562. case ButtonRelease:
  220563. {
  220564. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220565. updateKeyModifiers (buttonRelEvent->state);
  220566. const int map = pointerMap [buttonRelEvent->button - Button1];
  220567. if (map == Keys::LeftButton)
  220568. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220569. else if (map == Keys::RightButton)
  220570. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220571. else if (map == Keys::MiddleButton)
  220572. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220573. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220574. getEventTime (buttonRelEvent->time));
  220575. clearLastMousePos();
  220576. break;
  220577. }
  220578. case MotionNotify:
  220579. {
  220580. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220581. updateKeyModifiers (movedEvent->state);
  220582. const Point<int> mousePos (Desktop::getMousePosition());
  220583. if (lastMousePos != mousePos)
  220584. {
  220585. lastMousePos = mousePos;
  220586. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220587. {
  220588. Window wRoot = 0, wParent = 0;
  220589. {
  220590. ScopedXLock xlock;
  220591. unsigned int numChildren;
  220592. Window* wChild = 0;
  220593. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220594. }
  220595. if (wParent != 0
  220596. && wParent != windowH
  220597. && wParent != wRoot)
  220598. {
  220599. parentWindow = wParent;
  220600. updateBounds();
  220601. }
  220602. else
  220603. {
  220604. parentWindow = 0;
  220605. }
  220606. }
  220607. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220608. }
  220609. break;
  220610. }
  220611. case EnterNotify:
  220612. {
  220613. clearLastMousePos();
  220614. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220615. if (! currentModifiers.isAnyMouseButtonDown())
  220616. {
  220617. updateKeyModifiers (enterEvent->state);
  220618. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220619. }
  220620. break;
  220621. }
  220622. case LeaveNotify:
  220623. {
  220624. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220625. // Suppress the normal leave if we've got a pointer grab, or if
  220626. // it's a bogus one caused by clicking a mouse button when running
  220627. // in a Window manager
  220628. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220629. || leaveEvent->mode == NotifyUngrab)
  220630. {
  220631. updateKeyModifiers (leaveEvent->state);
  220632. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220633. }
  220634. break;
  220635. }
  220636. case FocusIn:
  220637. {
  220638. isActiveApplication = true;
  220639. if (isFocused())
  220640. handleFocusGain();
  220641. break;
  220642. }
  220643. case FocusOut:
  220644. {
  220645. isActiveApplication = false;
  220646. if (! isFocused())
  220647. handleFocusLoss();
  220648. break;
  220649. }
  220650. case Expose:
  220651. {
  220652. // Batch together all pending expose events
  220653. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  220654. XEvent nextEvent;
  220655. ScopedXLock xlock;
  220656. if (exposeEvent->window != windowH)
  220657. {
  220658. Window child;
  220659. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220660. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220661. &child);
  220662. }
  220663. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220664. exposeEvent->width, exposeEvent->height));
  220665. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220666. {
  220667. XPeekEvent (display, (XEvent*) &nextEvent);
  220668. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  220669. break;
  220670. XNextEvent (display, (XEvent*) &nextEvent);
  220671. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220672. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220673. nextExposeEvent->width, nextExposeEvent->height));
  220674. }
  220675. break;
  220676. }
  220677. case CirculateNotify:
  220678. case CreateNotify:
  220679. case DestroyNotify:
  220680. // Think we can ignore these
  220681. break;
  220682. case ConfigureNotify:
  220683. {
  220684. updateBounds();
  220685. updateBorderSize();
  220686. handleMovedOrResized();
  220687. // if the native title bar is dragged, need to tell any active menus, etc.
  220688. if ((styleFlags & windowHasTitleBar) != 0
  220689. && component->isCurrentlyBlockedByAnotherModalComponent())
  220690. {
  220691. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220692. if (currentModalComp != 0)
  220693. currentModalComp->inputAttemptWhenModal();
  220694. }
  220695. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  220696. if (confEvent->window == windowH
  220697. && confEvent->above != 0
  220698. && isFrontWindow())
  220699. {
  220700. handleBroughtToFront();
  220701. }
  220702. break;
  220703. }
  220704. case ReparentNotify:
  220705. {
  220706. parentWindow = 0;
  220707. Window wRoot = 0;
  220708. Window* wChild = 0;
  220709. unsigned int numChildren;
  220710. {
  220711. ScopedXLock xlock;
  220712. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220713. }
  220714. if (parentWindow == windowH || parentWindow == wRoot)
  220715. parentWindow = 0;
  220716. updateBounds();
  220717. updateBorderSize();
  220718. handleMovedOrResized();
  220719. break;
  220720. }
  220721. case GravityNotify:
  220722. {
  220723. updateBounds();
  220724. updateBorderSize();
  220725. handleMovedOrResized();
  220726. break;
  220727. }
  220728. case MapNotify:
  220729. mapped = true;
  220730. handleBroughtToFront();
  220731. break;
  220732. case UnmapNotify:
  220733. mapped = false;
  220734. break;
  220735. case MappingNotify:
  220736. {
  220737. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  220738. if (mappingEvent->request != MappingPointer)
  220739. {
  220740. // Deal with modifier/keyboard mapping
  220741. ScopedXLock xlock;
  220742. XRefreshKeyboardMapping (mappingEvent);
  220743. updateModifierMappings();
  220744. }
  220745. break;
  220746. }
  220747. case ClientMessage:
  220748. {
  220749. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  220750. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220751. {
  220752. const Atom atom = (Atom) clientMsg->data.l[0];
  220753. if (atom == Atoms::ProtocolList [Atoms::PING])
  220754. {
  220755. Window root = RootWindow (display, DefaultScreen (display));
  220756. event->xclient.window = root;
  220757. XSendEvent (display, root, False, NoEventMask, event);
  220758. XFlush (display);
  220759. }
  220760. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220761. {
  220762. XWindowAttributes atts;
  220763. ScopedXLock xlock;
  220764. if (clientMsg->window != 0
  220765. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220766. {
  220767. if (atts.map_state == IsViewable)
  220768. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220769. }
  220770. }
  220771. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220772. {
  220773. handleUserClosingWindow();
  220774. }
  220775. }
  220776. else if (clientMsg->message_type == Atoms::XdndEnter)
  220777. {
  220778. handleDragAndDropEnter (clientMsg);
  220779. }
  220780. else if (clientMsg->message_type == Atoms::XdndLeave)
  220781. {
  220782. resetDragAndDrop();
  220783. }
  220784. else if (clientMsg->message_type == Atoms::XdndPosition)
  220785. {
  220786. handleDragAndDropPosition (clientMsg);
  220787. }
  220788. else if (clientMsg->message_type == Atoms::XdndDrop)
  220789. {
  220790. handleDragAndDropDrop (clientMsg);
  220791. }
  220792. else if (clientMsg->message_type == Atoms::XdndStatus)
  220793. {
  220794. handleDragAndDropStatus (clientMsg);
  220795. }
  220796. else if (clientMsg->message_type == Atoms::XdndFinished)
  220797. {
  220798. resetDragAndDrop();
  220799. }
  220800. break;
  220801. }
  220802. case SelectionNotify:
  220803. handleDragAndDropSelection (event);
  220804. break;
  220805. case SelectionClear:
  220806. case SelectionRequest:
  220807. break;
  220808. default:
  220809. #if JUCE_USE_XSHM
  220810. {
  220811. ScopedXLock xlock;
  220812. if (event->xany.type == XShmGetEventBase (display))
  220813. repainter->notifyPaintCompleted();
  220814. }
  220815. #endif
  220816. break;
  220817. }
  220818. }
  220819. void showMouseCursor (Cursor cursor) throw()
  220820. {
  220821. ScopedXLock xlock;
  220822. XDefineCursor (display, windowH, cursor);
  220823. }
  220824. void setTaskBarIcon (const Image& image)
  220825. {
  220826. ScopedXLock xlock;
  220827. taskbarImage = image;
  220828. Screen* const screen = XDefaultScreenOfDisplay (display);
  220829. const int screenNumber = XScreenNumberOfScreen (screen);
  220830. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220831. screenAtom << screenNumber;
  220832. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220833. XGrabServer (display);
  220834. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220835. if (managerWin != None)
  220836. XSelectInput (display, managerWin, StructureNotifyMask);
  220837. XUngrabServer (display);
  220838. XFlush (display);
  220839. if (managerWin != None)
  220840. {
  220841. XEvent ev;
  220842. zerostruct (ev);
  220843. ev.xclient.type = ClientMessage;
  220844. ev.xclient.window = managerWin;
  220845. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220846. ev.xclient.format = 32;
  220847. ev.xclient.data.l[0] = CurrentTime;
  220848. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220849. ev.xclient.data.l[2] = windowH;
  220850. ev.xclient.data.l[3] = 0;
  220851. ev.xclient.data.l[4] = 0;
  220852. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220853. XSync (display, False);
  220854. }
  220855. // For older KDE's ...
  220856. long atomData = 1;
  220857. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220858. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220859. // For more recent KDE's...
  220860. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220861. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220862. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220863. XSizeHints* hints = XAllocSizeHints();
  220864. hints->flags = PMinSize;
  220865. hints->min_width = 22;
  220866. hints->min_height = 22;
  220867. XSetWMNormalHints (display, windowH, hints);
  220868. XFree (hints);
  220869. }
  220870. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220871. bool dontRepaint;
  220872. static ModifierKeys currentModifiers;
  220873. static bool isActiveApplication;
  220874. private:
  220875. class LinuxRepaintManager : public Timer
  220876. {
  220877. public:
  220878. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220879. : peer (peer_),
  220880. lastTimeImageUsed (0)
  220881. {
  220882. #if JUCE_USE_XSHM
  220883. shmCompletedDrawing = true;
  220884. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220885. if (useARGBImagesForRendering)
  220886. {
  220887. ScopedXLock xlock;
  220888. XShmSegmentInfo segmentinfo;
  220889. XImage* const testImage
  220890. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220891. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220892. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220893. XDestroyImage (testImage);
  220894. }
  220895. #endif
  220896. }
  220897. ~LinuxRepaintManager()
  220898. {
  220899. }
  220900. void timerCallback()
  220901. {
  220902. #if JUCE_USE_XSHM
  220903. if (! shmCompletedDrawing)
  220904. return;
  220905. #endif
  220906. if (! regionsNeedingRepaint.isEmpty())
  220907. {
  220908. stopTimer();
  220909. performAnyPendingRepaintsNow();
  220910. }
  220911. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220912. {
  220913. stopTimer();
  220914. image = Image::null;
  220915. }
  220916. }
  220917. void repaint (const Rectangle<int>& area)
  220918. {
  220919. if (! isTimerRunning())
  220920. startTimer (repaintTimerPeriod);
  220921. regionsNeedingRepaint.add (area);
  220922. }
  220923. void performAnyPendingRepaintsNow()
  220924. {
  220925. #if JUCE_USE_XSHM
  220926. if (! shmCompletedDrawing)
  220927. {
  220928. startTimer (repaintTimerPeriod);
  220929. return;
  220930. }
  220931. #endif
  220932. peer->clearMaskedRegion();
  220933. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220934. regionsNeedingRepaint.clear();
  220935. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220936. if (! totalArea.isEmpty())
  220937. {
  220938. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220939. || image.getHeight() < totalArea.getHeight())
  220940. {
  220941. #if JUCE_USE_XSHM
  220942. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220943. : Image::RGB,
  220944. #else
  220945. image = Image (new XBitmapImage (Image::RGB,
  220946. #endif
  220947. (totalArea.getWidth() + 31) & ~31,
  220948. (totalArea.getHeight() + 31) & ~31,
  220949. false, peer->depth, peer->visual));
  220950. }
  220951. startTimer (repaintTimerPeriod);
  220952. RectangleList adjustedList (originalRepaintRegion);
  220953. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220954. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220955. if (peer->depth == 32)
  220956. {
  220957. RectangleList::Iterator i (originalRepaintRegion);
  220958. while (i.next())
  220959. image.clear (*i.getRectangle() - totalArea.getPosition());
  220960. }
  220961. peer->handlePaint (context);
  220962. if (! peer->maskedRegion.isEmpty())
  220963. originalRepaintRegion.subtract (peer->maskedRegion);
  220964. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220965. {
  220966. #if JUCE_USE_XSHM
  220967. shmCompletedDrawing = false;
  220968. #endif
  220969. const Rectangle<int>& r = *i.getRectangle();
  220970. static_cast<XBitmapImage*> (image.getSharedImage())
  220971. ->blitToWindow (peer->windowH,
  220972. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220973. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220974. }
  220975. }
  220976. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220977. startTimer (repaintTimerPeriod);
  220978. }
  220979. #if JUCE_USE_XSHM
  220980. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220981. #endif
  220982. private:
  220983. enum { repaintTimerPeriod = 1000 / 100 };
  220984. LinuxComponentPeer* const peer;
  220985. Image image;
  220986. uint32 lastTimeImageUsed;
  220987. RectangleList regionsNeedingRepaint;
  220988. #if JUCE_USE_XSHM
  220989. bool useARGBImagesForRendering, shmCompletedDrawing;
  220990. #endif
  220991. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220992. };
  220993. ScopedPointer <LinuxRepaintManager> repainter;
  220994. friend class LinuxRepaintManager;
  220995. Window windowH, parentWindow;
  220996. int wx, wy, ww, wh;
  220997. Image taskbarImage;
  220998. bool fullScreen, mapped;
  220999. Visual* visual;
  221000. int depth;
  221001. BorderSize windowBorder;
  221002. struct MotifWmHints
  221003. {
  221004. unsigned long flags;
  221005. unsigned long functions;
  221006. unsigned long decorations;
  221007. long input_mode;
  221008. unsigned long status;
  221009. };
  221010. static void updateKeyStates (const int keycode, const bool press) throw()
  221011. {
  221012. const int keybyte = keycode >> 3;
  221013. const int keybit = (1 << (keycode & 7));
  221014. if (press)
  221015. Keys::keyStates [keybyte] |= keybit;
  221016. else
  221017. Keys::keyStates [keybyte] &= ~keybit;
  221018. }
  221019. static void updateKeyModifiers (const int status) throw()
  221020. {
  221021. int keyMods = 0;
  221022. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221023. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221024. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221025. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221026. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221027. Keys::capsLock = ((status & LockMask) != 0);
  221028. }
  221029. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221030. {
  221031. int modifier = 0;
  221032. bool isModifier = true;
  221033. switch (sym)
  221034. {
  221035. case XK_Shift_L:
  221036. case XK_Shift_R:
  221037. modifier = ModifierKeys::shiftModifier;
  221038. break;
  221039. case XK_Control_L:
  221040. case XK_Control_R:
  221041. modifier = ModifierKeys::ctrlModifier;
  221042. break;
  221043. case XK_Alt_L:
  221044. case XK_Alt_R:
  221045. modifier = ModifierKeys::altModifier;
  221046. break;
  221047. case XK_Num_Lock:
  221048. if (press)
  221049. Keys::numLock = ! Keys::numLock;
  221050. break;
  221051. case XK_Caps_Lock:
  221052. if (press)
  221053. Keys::capsLock = ! Keys::capsLock;
  221054. break;
  221055. case XK_Scroll_Lock:
  221056. break;
  221057. default:
  221058. isModifier = false;
  221059. break;
  221060. }
  221061. if (modifier != 0)
  221062. {
  221063. if (press)
  221064. currentModifiers = currentModifiers.withFlags (modifier);
  221065. else
  221066. currentModifiers = currentModifiers.withoutFlags (modifier);
  221067. }
  221068. return isModifier;
  221069. }
  221070. // Alt and Num lock are not defined by standard X
  221071. // modifier constants: check what they're mapped to
  221072. static void updateModifierMappings() throw()
  221073. {
  221074. ScopedXLock xlock;
  221075. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221076. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221077. Keys::AltMask = 0;
  221078. Keys::NumLockMask = 0;
  221079. XModifierKeymap* mapping = XGetModifierMapping (display);
  221080. if (mapping)
  221081. {
  221082. for (int i = 0; i < 8; i++)
  221083. {
  221084. if (mapping->modifiermap [i << 1] == altLeftCode)
  221085. Keys::AltMask = 1 << i;
  221086. else if (mapping->modifiermap [i << 1] == numLockCode)
  221087. Keys::NumLockMask = 1 << i;
  221088. }
  221089. XFreeModifiermap (mapping);
  221090. }
  221091. }
  221092. void removeWindowDecorations (Window wndH)
  221093. {
  221094. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221095. if (hints != None)
  221096. {
  221097. MotifWmHints motifHints;
  221098. zerostruct (motifHints);
  221099. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221100. motifHints.decorations = 0;
  221101. ScopedXLock xlock;
  221102. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221103. (unsigned char*) &motifHints, 4);
  221104. }
  221105. hints = XInternAtom (display, "_WIN_HINTS", True);
  221106. if (hints != None)
  221107. {
  221108. long gnomeHints = 0;
  221109. ScopedXLock xlock;
  221110. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221111. (unsigned char*) &gnomeHints, 1);
  221112. }
  221113. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221114. if (hints != None)
  221115. {
  221116. long kwmHints = 2; /*KDE_tinyDecoration*/
  221117. ScopedXLock xlock;
  221118. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221119. (unsigned char*) &kwmHints, 1);
  221120. }
  221121. }
  221122. void addWindowButtons (Window wndH)
  221123. {
  221124. ScopedXLock xlock;
  221125. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221126. if (hints != None)
  221127. {
  221128. MotifWmHints motifHints;
  221129. zerostruct (motifHints);
  221130. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221131. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221132. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221133. if ((styleFlags & windowHasCloseButton) != 0)
  221134. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221135. if ((styleFlags & windowHasMinimiseButton) != 0)
  221136. {
  221137. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221138. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221139. }
  221140. if ((styleFlags & windowHasMaximiseButton) != 0)
  221141. {
  221142. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221143. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221144. }
  221145. if ((styleFlags & windowIsResizable) != 0)
  221146. {
  221147. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221148. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221149. }
  221150. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221151. }
  221152. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221153. if (hints != None)
  221154. {
  221155. int netHints [6];
  221156. int num = 0;
  221157. if ((styleFlags & windowIsResizable) != 0)
  221158. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221159. if ((styleFlags & windowHasMaximiseButton) != 0)
  221160. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221161. if ((styleFlags & windowHasMinimiseButton) != 0)
  221162. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221163. if ((styleFlags & windowHasCloseButton) != 0)
  221164. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221165. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221166. }
  221167. }
  221168. void setWindowType()
  221169. {
  221170. int netHints [2];
  221171. int numHints = 0;
  221172. if ((styleFlags & windowIsTemporary) != 0
  221173. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221174. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221175. else
  221176. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221177. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221178. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221179. (unsigned char*) &netHints, numHints);
  221180. numHints = 0;
  221181. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221182. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221183. if (component->isAlwaysOnTop())
  221184. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221185. if (numHints > 0)
  221186. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221187. (unsigned char*) &netHints, numHints);
  221188. }
  221189. void createWindow()
  221190. {
  221191. ScopedXLock xlock;
  221192. Atoms::initialiseAtoms();
  221193. resetDragAndDrop();
  221194. // Get defaults for various properties
  221195. const int screen = DefaultScreen (display);
  221196. Window root = RootWindow (display, screen);
  221197. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221198. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221199. if (visual == 0)
  221200. {
  221201. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221202. Process::terminate();
  221203. }
  221204. // Create and install a colormap suitable fr our visual
  221205. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221206. XInstallColormap (display, colormap);
  221207. // Set up the window attributes
  221208. XSetWindowAttributes swa;
  221209. swa.border_pixel = 0;
  221210. swa.background_pixmap = None;
  221211. swa.colormap = colormap;
  221212. swa.event_mask = getAllEventsMask();
  221213. windowH = XCreateWindow (display, root,
  221214. 0, 0, 1, 1,
  221215. 0, depth, InputOutput, visual,
  221216. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221217. &swa);
  221218. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221219. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221220. GrabModeAsync, GrabModeAsync, None, None);
  221221. // Set the window context to identify the window handle object
  221222. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221223. {
  221224. // Failed
  221225. jassertfalse;
  221226. Logger::outputDebugString ("Failed to create context information for window.\n");
  221227. XDestroyWindow (display, windowH);
  221228. windowH = 0;
  221229. return;
  221230. }
  221231. // Set window manager hints
  221232. XWMHints* wmHints = XAllocWMHints();
  221233. wmHints->flags = InputHint | StateHint;
  221234. wmHints->input = True; // Locally active input model
  221235. wmHints->initial_state = NormalState;
  221236. XSetWMHints (display, windowH, wmHints);
  221237. XFree (wmHints);
  221238. // Set the window type
  221239. setWindowType();
  221240. // Define decoration
  221241. if ((styleFlags & windowHasTitleBar) == 0)
  221242. removeWindowDecorations (windowH);
  221243. else
  221244. addWindowButtons (windowH);
  221245. // Set window name
  221246. setWindowTitle (windowH, getComponent()->getName());
  221247. // Associate the PID, allowing to be shut down when something goes wrong
  221248. unsigned long pid = getpid();
  221249. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221250. (unsigned char*) &pid, 1);
  221251. // Set window manager protocols
  221252. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221253. (unsigned char*) Atoms::ProtocolList, 2);
  221254. // Set drag and drop flags
  221255. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221256. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221257. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221258. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221259. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221260. (const unsigned char*) "", 0);
  221261. unsigned long dndVersion = Atoms::DndVersion;
  221262. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221263. (const unsigned char*) &dndVersion, 1);
  221264. // Initialise the pointer and keyboard mapping
  221265. // This is not the same as the logical pointer mapping the X server uses:
  221266. // we don't mess with this.
  221267. static bool mappingInitialised = false;
  221268. if (! mappingInitialised)
  221269. {
  221270. mappingInitialised = true;
  221271. const int numButtons = XGetPointerMapping (display, 0, 0);
  221272. if (numButtons == 2)
  221273. {
  221274. pointerMap[0] = Keys::LeftButton;
  221275. pointerMap[1] = Keys::RightButton;
  221276. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221277. }
  221278. else if (numButtons >= 3)
  221279. {
  221280. pointerMap[0] = Keys::LeftButton;
  221281. pointerMap[1] = Keys::MiddleButton;
  221282. pointerMap[2] = Keys::RightButton;
  221283. if (numButtons >= 5)
  221284. {
  221285. pointerMap[3] = Keys::WheelUp;
  221286. pointerMap[4] = Keys::WheelDown;
  221287. }
  221288. }
  221289. updateModifierMappings();
  221290. }
  221291. }
  221292. void destroyWindow()
  221293. {
  221294. ScopedXLock xlock;
  221295. XPointer handlePointer;
  221296. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221297. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221298. XDestroyWindow (display, windowH);
  221299. // Wait for it to complete and then remove any events for this
  221300. // window from the event queue.
  221301. XSync (display, false);
  221302. XEvent event;
  221303. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221304. {}
  221305. }
  221306. static int getAllEventsMask() throw()
  221307. {
  221308. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221309. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221310. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221311. }
  221312. static int64 getEventTime (::Time t)
  221313. {
  221314. static int64 eventTimeOffset = 0x12345678;
  221315. const int64 thisMessageTime = t;
  221316. if (eventTimeOffset == 0x12345678)
  221317. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221318. return eventTimeOffset + thisMessageTime;
  221319. }
  221320. static void setWindowTitle (Window xwin, const String& title)
  221321. {
  221322. XTextProperty nameProperty;
  221323. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221324. ScopedXLock xlock;
  221325. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221326. {
  221327. XSetWMName (display, xwin, &nameProperty);
  221328. XSetWMIconName (display, xwin, &nameProperty);
  221329. XFree (nameProperty.value);
  221330. }
  221331. }
  221332. void updateBorderSize()
  221333. {
  221334. if ((styleFlags & windowHasTitleBar) == 0)
  221335. {
  221336. windowBorder = BorderSize (0);
  221337. }
  221338. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221339. {
  221340. ScopedXLock xlock;
  221341. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221342. if (hints != None)
  221343. {
  221344. unsigned char* data = 0;
  221345. unsigned long nitems, bytesLeft;
  221346. Atom actualType;
  221347. int actualFormat;
  221348. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221349. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221350. &data) == Success)
  221351. {
  221352. const unsigned long* const sizes = (const unsigned long*) data;
  221353. if (actualFormat == 32)
  221354. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221355. (int) sizes[3], (int) sizes[1]);
  221356. XFree (data);
  221357. }
  221358. }
  221359. }
  221360. }
  221361. void updateBounds()
  221362. {
  221363. jassert (windowH != 0);
  221364. if (windowH != 0)
  221365. {
  221366. Window root, child;
  221367. unsigned int bw, depth;
  221368. ScopedXLock xlock;
  221369. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221370. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221371. &bw, &depth))
  221372. {
  221373. wx = wy = ww = wh = 0;
  221374. }
  221375. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221376. {
  221377. wx = wy = 0;
  221378. }
  221379. }
  221380. }
  221381. void resetDragAndDrop()
  221382. {
  221383. dragAndDropFiles.clear();
  221384. lastDropPos = Point<int> (-1, -1);
  221385. dragAndDropCurrentMimeType = 0;
  221386. dragAndDropSourceWindow = 0;
  221387. srcMimeTypeAtomList.clear();
  221388. }
  221389. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221390. {
  221391. msg.type = ClientMessage;
  221392. msg.display = display;
  221393. msg.window = dragAndDropSourceWindow;
  221394. msg.format = 32;
  221395. msg.data.l[0] = windowH;
  221396. ScopedXLock xlock;
  221397. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221398. }
  221399. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221400. {
  221401. XClientMessageEvent msg;
  221402. zerostruct (msg);
  221403. msg.message_type = Atoms::XdndStatus;
  221404. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221405. msg.data.l[4] = dropAction;
  221406. sendDragAndDropMessage (msg);
  221407. }
  221408. void sendDragAndDropLeave()
  221409. {
  221410. XClientMessageEvent msg;
  221411. zerostruct (msg);
  221412. msg.message_type = Atoms::XdndLeave;
  221413. sendDragAndDropMessage (msg);
  221414. }
  221415. void sendDragAndDropFinish()
  221416. {
  221417. XClientMessageEvent msg;
  221418. zerostruct (msg);
  221419. msg.message_type = Atoms::XdndFinished;
  221420. sendDragAndDropMessage (msg);
  221421. }
  221422. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221423. {
  221424. if ((clientMsg->data.l[1] & 1) == 0)
  221425. {
  221426. sendDragAndDropLeave();
  221427. if (dragAndDropFiles.size() > 0)
  221428. handleFileDragExit (dragAndDropFiles);
  221429. dragAndDropFiles.clear();
  221430. }
  221431. }
  221432. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221433. {
  221434. if (dragAndDropSourceWindow == 0)
  221435. return;
  221436. dragAndDropSourceWindow = clientMsg->data.l[0];
  221437. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221438. (int) clientMsg->data.l[2] & 0xffff);
  221439. dropPos -= getScreenPosition();
  221440. if (lastDropPos != dropPos)
  221441. {
  221442. lastDropPos = dropPos;
  221443. dragAndDropTimestamp = clientMsg->data.l[3];
  221444. Atom targetAction = Atoms::XdndActionCopy;
  221445. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221446. {
  221447. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221448. {
  221449. targetAction = Atoms::allowedActions[i];
  221450. break;
  221451. }
  221452. }
  221453. sendDragAndDropStatus (true, targetAction);
  221454. if (dragAndDropFiles.size() == 0)
  221455. updateDraggedFileList (clientMsg);
  221456. if (dragAndDropFiles.size() > 0)
  221457. handleFileDragMove (dragAndDropFiles, dropPos);
  221458. }
  221459. }
  221460. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221461. {
  221462. if (dragAndDropFiles.size() == 0)
  221463. updateDraggedFileList (clientMsg);
  221464. const StringArray files (dragAndDropFiles);
  221465. const Point<int> lastPos (lastDropPos);
  221466. sendDragAndDropFinish();
  221467. resetDragAndDrop();
  221468. if (files.size() > 0)
  221469. handleFileDragDrop (files, lastPos);
  221470. }
  221471. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221472. {
  221473. dragAndDropFiles.clear();
  221474. srcMimeTypeAtomList.clear();
  221475. dragAndDropCurrentMimeType = 0;
  221476. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221477. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221478. {
  221479. dragAndDropSourceWindow = 0;
  221480. return;
  221481. }
  221482. dragAndDropSourceWindow = clientMsg->data.l[0];
  221483. if ((clientMsg->data.l[1] & 1) != 0)
  221484. {
  221485. Atom actual;
  221486. int format;
  221487. unsigned long count = 0, remaining = 0;
  221488. unsigned char* data = 0;
  221489. ScopedXLock xlock;
  221490. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221491. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221492. &count, &remaining, &data);
  221493. if (data != 0)
  221494. {
  221495. if (actual == XA_ATOM && format == 32 && count != 0)
  221496. {
  221497. const unsigned long* const types = (const unsigned long*) data;
  221498. for (unsigned int i = 0; i < count; ++i)
  221499. if (types[i] != None)
  221500. srcMimeTypeAtomList.add (types[i]);
  221501. }
  221502. XFree (data);
  221503. }
  221504. }
  221505. if (srcMimeTypeAtomList.size() == 0)
  221506. {
  221507. for (int i = 2; i < 5; ++i)
  221508. if (clientMsg->data.l[i] != None)
  221509. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221510. if (srcMimeTypeAtomList.size() == 0)
  221511. {
  221512. dragAndDropSourceWindow = 0;
  221513. return;
  221514. }
  221515. }
  221516. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221517. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221518. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221519. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221520. handleDragAndDropPosition (clientMsg);
  221521. }
  221522. void handleDragAndDropSelection (const XEvent* const evt)
  221523. {
  221524. dragAndDropFiles.clear();
  221525. if (evt->xselection.property != 0)
  221526. {
  221527. StringArray lines;
  221528. {
  221529. MemoryBlock dropData;
  221530. for (;;)
  221531. {
  221532. Atom actual;
  221533. uint8* data = 0;
  221534. unsigned long count = 0, remaining = 0;
  221535. int format = 0;
  221536. ScopedXLock xlock;
  221537. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221538. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221539. &format, &count, &remaining, &data) == Success)
  221540. {
  221541. dropData.append (data, count * format / 8);
  221542. XFree (data);
  221543. if (remaining == 0)
  221544. break;
  221545. }
  221546. else
  221547. {
  221548. XFree (data);
  221549. break;
  221550. }
  221551. }
  221552. lines.addLines (dropData.toString());
  221553. }
  221554. for (int i = 0; i < lines.size(); ++i)
  221555. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221556. dragAndDropFiles.trim();
  221557. dragAndDropFiles.removeEmptyStrings();
  221558. }
  221559. }
  221560. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221561. {
  221562. dragAndDropFiles.clear();
  221563. if (dragAndDropSourceWindow != None
  221564. && dragAndDropCurrentMimeType != 0)
  221565. {
  221566. dragAndDropTimestamp = clientMsg->data.l[2];
  221567. ScopedXLock xlock;
  221568. XConvertSelection (display,
  221569. Atoms::XdndSelection,
  221570. dragAndDropCurrentMimeType,
  221571. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221572. windowH,
  221573. dragAndDropTimestamp);
  221574. }
  221575. }
  221576. StringArray dragAndDropFiles;
  221577. int dragAndDropTimestamp;
  221578. Point<int> lastDropPos;
  221579. Atom dragAndDropCurrentMimeType;
  221580. Window dragAndDropSourceWindow;
  221581. Array <Atom> srcMimeTypeAtomList;
  221582. static int pointerMap[5];
  221583. static Point<int> lastMousePos;
  221584. static void clearLastMousePos() throw()
  221585. {
  221586. lastMousePos = Point<int> (0x100000, 0x100000);
  221587. }
  221588. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  221589. };
  221590. ModifierKeys LinuxComponentPeer::currentModifiers;
  221591. bool LinuxComponentPeer::isActiveApplication = false;
  221592. int LinuxComponentPeer::pointerMap[5];
  221593. Point<int> LinuxComponentPeer::lastMousePos;
  221594. bool Process::isForegroundProcess()
  221595. {
  221596. return LinuxComponentPeer::isActiveApplication;
  221597. }
  221598. void ModifierKeys::updateCurrentModifiers() throw()
  221599. {
  221600. currentModifiers = LinuxComponentPeer::currentModifiers;
  221601. }
  221602. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221603. {
  221604. Window root, child;
  221605. int x, y, winx, winy;
  221606. unsigned int mask;
  221607. int mouseMods = 0;
  221608. ScopedXLock xlock;
  221609. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221610. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221611. {
  221612. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221613. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221614. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221615. }
  221616. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221617. return LinuxComponentPeer::currentModifiers;
  221618. }
  221619. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221620. {
  221621. if (enableOrDisable)
  221622. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221623. }
  221624. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221625. {
  221626. return new LinuxComponentPeer (this, styleFlags);
  221627. }
  221628. // (this callback is hooked up in the messaging code)
  221629. void juce_windowMessageReceive (XEvent* event)
  221630. {
  221631. if (event->xany.window != None)
  221632. {
  221633. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221634. if (ComponentPeer::isValidPeer (peer))
  221635. peer->handleWindowMessage (event);
  221636. }
  221637. else
  221638. {
  221639. switch (event->xany.type)
  221640. {
  221641. case KeymapNotify:
  221642. {
  221643. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221644. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221645. break;
  221646. }
  221647. default:
  221648. break;
  221649. }
  221650. }
  221651. }
  221652. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221653. {
  221654. if (display == 0)
  221655. return;
  221656. #if JUCE_USE_XINERAMA
  221657. int major_opcode, first_event, first_error;
  221658. ScopedXLock xlock;
  221659. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221660. {
  221661. typedef Bool (*tXineramaIsActive) (Display*);
  221662. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221663. static tXineramaIsActive xXineramaIsActive = 0;
  221664. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221665. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221666. {
  221667. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221668. if (h == 0)
  221669. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221670. if (h != 0)
  221671. {
  221672. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221673. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221674. }
  221675. }
  221676. if (xXineramaIsActive != 0
  221677. && xXineramaQueryScreens != 0
  221678. && xXineramaIsActive (display))
  221679. {
  221680. int numMonitors = 0;
  221681. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221682. if (screens != 0)
  221683. {
  221684. for (int i = numMonitors; --i >= 0;)
  221685. {
  221686. int index = screens[i].screen_number;
  221687. if (index >= 0)
  221688. {
  221689. while (monitorCoords.size() < index)
  221690. monitorCoords.add (Rectangle<int>());
  221691. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221692. screens[i].y_org,
  221693. screens[i].width,
  221694. screens[i].height));
  221695. }
  221696. }
  221697. XFree (screens);
  221698. }
  221699. }
  221700. }
  221701. if (monitorCoords.size() == 0)
  221702. #endif
  221703. {
  221704. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221705. if (hints != None)
  221706. {
  221707. const int numMonitors = ScreenCount (display);
  221708. for (int i = 0; i < numMonitors; ++i)
  221709. {
  221710. Window root = RootWindow (display, i);
  221711. unsigned long nitems, bytesLeft;
  221712. Atom actualType;
  221713. int actualFormat;
  221714. unsigned char* data = 0;
  221715. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221716. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221717. &data) == Success)
  221718. {
  221719. const long* const position = (const long*) data;
  221720. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221721. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221722. position[2], position[3]));
  221723. XFree (data);
  221724. }
  221725. }
  221726. }
  221727. if (monitorCoords.size() == 0)
  221728. {
  221729. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221730. DisplayHeight (display, DefaultScreen (display))));
  221731. }
  221732. }
  221733. }
  221734. void Desktop::createMouseInputSources()
  221735. {
  221736. mouseSources.add (new MouseInputSource (0, true));
  221737. }
  221738. bool Desktop::canUseSemiTransparentWindows() throw()
  221739. {
  221740. int matchedDepth = 0;
  221741. const int desiredDepth = 32;
  221742. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221743. && (matchedDepth == desiredDepth);
  221744. }
  221745. const Point<int> Desktop::getMousePosition()
  221746. {
  221747. Window root, child;
  221748. int x, y, winx, winy;
  221749. unsigned int mask;
  221750. ScopedXLock xlock;
  221751. if (XQueryPointer (display,
  221752. RootWindow (display, DefaultScreen (display)),
  221753. &root, &child,
  221754. &x, &y, &winx, &winy, &mask) == False)
  221755. {
  221756. // Pointer not on the default screen
  221757. x = y = -1;
  221758. }
  221759. return Point<int> (x, y);
  221760. }
  221761. void Desktop::setMousePosition (const Point<int>& newPosition)
  221762. {
  221763. ScopedXLock xlock;
  221764. Window root = RootWindow (display, DefaultScreen (display));
  221765. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221766. }
  221767. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  221768. {
  221769. return upright;
  221770. }
  221771. static bool screenSaverAllowed = true;
  221772. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221773. {
  221774. if (screenSaverAllowed != isEnabled)
  221775. {
  221776. screenSaverAllowed = isEnabled;
  221777. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221778. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221779. if (xScreenSaverSuspend == 0)
  221780. {
  221781. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221782. if (h != 0)
  221783. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221784. }
  221785. ScopedXLock xlock;
  221786. if (xScreenSaverSuspend != 0)
  221787. xScreenSaverSuspend (display, ! isEnabled);
  221788. }
  221789. }
  221790. bool Desktop::isScreenSaverEnabled()
  221791. {
  221792. return screenSaverAllowed;
  221793. }
  221794. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221795. {
  221796. ScopedXLock xlock;
  221797. const unsigned int imageW = image.getWidth();
  221798. const unsigned int imageH = image.getHeight();
  221799. #if JUCE_USE_XCURSOR
  221800. {
  221801. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221802. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221803. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221804. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221805. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221806. static tXcursorImageCreate xXcursorImageCreate = 0;
  221807. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221808. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221809. static bool hasBeenLoaded = false;
  221810. if (! hasBeenLoaded)
  221811. {
  221812. hasBeenLoaded = true;
  221813. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221814. if (h != 0)
  221815. {
  221816. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221817. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221818. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221819. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221820. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221821. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221822. || ! xXcursorSupportsARGB (display))
  221823. xXcursorSupportsARGB = 0;
  221824. }
  221825. }
  221826. if (xXcursorSupportsARGB != 0)
  221827. {
  221828. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221829. if (xcImage != 0)
  221830. {
  221831. xcImage->xhot = hotspotX;
  221832. xcImage->yhot = hotspotY;
  221833. XcursorPixel* dest = xcImage->pixels;
  221834. for (int y = 0; y < (int) imageH; ++y)
  221835. for (int x = 0; x < (int) imageW; ++x)
  221836. *dest++ = image.getPixelAt (x, y).getARGB();
  221837. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221838. xXcursorImageDestroy (xcImage);
  221839. if (result != 0)
  221840. return result;
  221841. }
  221842. }
  221843. }
  221844. #endif
  221845. Window root = RootWindow (display, DefaultScreen (display));
  221846. unsigned int cursorW, cursorH;
  221847. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221848. return 0;
  221849. Image im (Image::ARGB, cursorW, cursorH, true);
  221850. {
  221851. Graphics g (im);
  221852. if (imageW > cursorW || imageH > cursorH)
  221853. {
  221854. hotspotX = (hotspotX * cursorW) / imageW;
  221855. hotspotY = (hotspotY * cursorH) / imageH;
  221856. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221857. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221858. false);
  221859. }
  221860. else
  221861. {
  221862. g.drawImageAt (image, 0, 0);
  221863. }
  221864. }
  221865. const int stride = (cursorW + 7) >> 3;
  221866. HeapBlock <char> maskPlane, sourcePlane;
  221867. maskPlane.calloc (stride * cursorH);
  221868. sourcePlane.calloc (stride * cursorH);
  221869. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221870. for (int y = cursorH; --y >= 0;)
  221871. {
  221872. for (int x = cursorW; --x >= 0;)
  221873. {
  221874. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221875. const int offset = y * stride + (x >> 3);
  221876. const Colour c (im.getPixelAt (x, y));
  221877. if (c.getAlpha() >= 128)
  221878. maskPlane[offset] |= mask;
  221879. if (c.getBrightness() >= 0.5f)
  221880. sourcePlane[offset] |= mask;
  221881. }
  221882. }
  221883. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221884. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221885. XColor white, black;
  221886. black.red = black.green = black.blue = 0;
  221887. white.red = white.green = white.blue = 0xffff;
  221888. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221889. XFreePixmap (display, sourcePixmap);
  221890. XFreePixmap (display, maskPixmap);
  221891. return result;
  221892. }
  221893. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221894. {
  221895. ScopedXLock xlock;
  221896. if (cursorHandle != 0)
  221897. XFreeCursor (display, (Cursor) cursorHandle);
  221898. }
  221899. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221900. {
  221901. unsigned int shape;
  221902. switch (type)
  221903. {
  221904. case NormalCursor: return None; // Use parent cursor
  221905. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221906. case WaitCursor: shape = XC_watch; break;
  221907. case IBeamCursor: shape = XC_xterm; break;
  221908. case PointingHandCursor: shape = XC_hand2; break;
  221909. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221910. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221911. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221912. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221913. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221914. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221915. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221916. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221917. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221918. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221919. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221920. case CrosshairCursor: shape = XC_crosshair; break;
  221921. case DraggingHandCursor:
  221922. {
  221923. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221924. 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,
  221925. 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 };
  221926. const int dragHandDataSize = 99;
  221927. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221928. }
  221929. case CopyingCursor:
  221930. {
  221931. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221932. 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,
  221933. 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,
  221934. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221935. const int copyCursorSize = 119;
  221936. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221937. }
  221938. default:
  221939. jassertfalse;
  221940. return None;
  221941. }
  221942. ScopedXLock xlock;
  221943. return (void*) XCreateFontCursor (display, shape);
  221944. }
  221945. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221946. {
  221947. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221948. if (lp != 0)
  221949. lp->showMouseCursor ((Cursor) getHandle());
  221950. }
  221951. void MouseCursor::showInAllWindows() const
  221952. {
  221953. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221954. showInWindow (ComponentPeer::getPeer (i));
  221955. }
  221956. const Image juce_createIconForFile (const File& file)
  221957. {
  221958. return Image::null;
  221959. }
  221960. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221961. {
  221962. return createSoftwareImage (format, width, height, clearImage);
  221963. }
  221964. #if JUCE_OPENGL
  221965. class WindowedGLContext : public OpenGLContext
  221966. {
  221967. public:
  221968. WindowedGLContext (Component* const component,
  221969. const OpenGLPixelFormat& pixelFormat_,
  221970. GLXContext sharedContext)
  221971. : renderContext (0),
  221972. embeddedWindow (0),
  221973. pixelFormat (pixelFormat_),
  221974. swapInterval (0)
  221975. {
  221976. jassert (component != 0);
  221977. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221978. if (peer == 0)
  221979. return;
  221980. ScopedXLock xlock;
  221981. XSync (display, False);
  221982. GLint attribs [64];
  221983. int n = 0;
  221984. attribs[n++] = GLX_RGBA;
  221985. attribs[n++] = GLX_DOUBLEBUFFER;
  221986. attribs[n++] = GLX_RED_SIZE;
  221987. attribs[n++] = pixelFormat.redBits;
  221988. attribs[n++] = GLX_GREEN_SIZE;
  221989. attribs[n++] = pixelFormat.greenBits;
  221990. attribs[n++] = GLX_BLUE_SIZE;
  221991. attribs[n++] = pixelFormat.blueBits;
  221992. attribs[n++] = GLX_ALPHA_SIZE;
  221993. attribs[n++] = pixelFormat.alphaBits;
  221994. attribs[n++] = GLX_DEPTH_SIZE;
  221995. attribs[n++] = pixelFormat.depthBufferBits;
  221996. attribs[n++] = GLX_STENCIL_SIZE;
  221997. attribs[n++] = pixelFormat.stencilBufferBits;
  221998. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221999. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222000. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222001. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222002. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222003. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222004. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222005. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222006. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222007. attribs[n++] = None;
  222008. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222009. if (bestVisual == 0)
  222010. return;
  222011. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222012. Window windowH = (Window) peer->getNativeHandle();
  222013. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222014. XSetWindowAttributes swa;
  222015. swa.colormap = colourMap;
  222016. swa.border_pixel = 0;
  222017. swa.event_mask = ExposureMask | StructureNotifyMask;
  222018. embeddedWindow = XCreateWindow (display, windowH,
  222019. 0, 0, 1, 1, 0,
  222020. bestVisual->depth,
  222021. InputOutput,
  222022. bestVisual->visual,
  222023. CWBorderPixel | CWColormap | CWEventMask,
  222024. &swa);
  222025. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222026. XMapWindow (display, embeddedWindow);
  222027. XFreeColormap (display, colourMap);
  222028. XFree (bestVisual);
  222029. XSync (display, False);
  222030. }
  222031. ~WindowedGLContext()
  222032. {
  222033. ScopedXLock xlock;
  222034. deleteContext();
  222035. XUnmapWindow (display, embeddedWindow);
  222036. XDestroyWindow (display, embeddedWindow);
  222037. }
  222038. void deleteContext()
  222039. {
  222040. makeInactive();
  222041. if (renderContext != 0)
  222042. {
  222043. ScopedXLock xlock;
  222044. glXDestroyContext (display, renderContext);
  222045. renderContext = 0;
  222046. }
  222047. }
  222048. bool makeActive() const throw()
  222049. {
  222050. jassert (renderContext != 0);
  222051. ScopedXLock xlock;
  222052. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222053. && XSync (display, False);
  222054. }
  222055. bool makeInactive() const throw()
  222056. {
  222057. ScopedXLock xlock;
  222058. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222059. }
  222060. bool isActive() const throw()
  222061. {
  222062. ScopedXLock xlock;
  222063. return glXGetCurrentContext() == renderContext;
  222064. }
  222065. const OpenGLPixelFormat getPixelFormat() const
  222066. {
  222067. return pixelFormat;
  222068. }
  222069. void* getRawContext() const throw()
  222070. {
  222071. return renderContext;
  222072. }
  222073. void updateWindowPosition (int x, int y, int w, int h, int)
  222074. {
  222075. ScopedXLock xlock;
  222076. XMoveResizeWindow (display, embeddedWindow,
  222077. x, y, jmax (1, w), jmax (1, h));
  222078. }
  222079. void swapBuffers()
  222080. {
  222081. ScopedXLock xlock;
  222082. glXSwapBuffers (display, embeddedWindow);
  222083. }
  222084. bool setSwapInterval (const int numFramesPerSwap)
  222085. {
  222086. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222087. if (GLXSwapIntervalSGI != 0)
  222088. {
  222089. swapInterval = numFramesPerSwap;
  222090. GLXSwapIntervalSGI (numFramesPerSwap);
  222091. return true;
  222092. }
  222093. return false;
  222094. }
  222095. int getSwapInterval() const
  222096. {
  222097. return swapInterval;
  222098. }
  222099. void repaint()
  222100. {
  222101. }
  222102. GLXContext renderContext;
  222103. private:
  222104. Window embeddedWindow;
  222105. OpenGLPixelFormat pixelFormat;
  222106. int swapInterval;
  222107. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  222108. };
  222109. OpenGLContext* OpenGLComponent::createContext()
  222110. {
  222111. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222112. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222113. return (c->renderContext != 0) ? c.release() : 0;
  222114. }
  222115. void juce_glViewport (const int w, const int h)
  222116. {
  222117. glViewport (0, 0, w, h);
  222118. }
  222119. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222120. OwnedArray <OpenGLPixelFormat>& results)
  222121. {
  222122. results.add (new OpenGLPixelFormat()); // xxx
  222123. }
  222124. #endif
  222125. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222126. {
  222127. jassertfalse; // not implemented!
  222128. return false;
  222129. }
  222130. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222131. {
  222132. jassertfalse; // not implemented!
  222133. return false;
  222134. }
  222135. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222136. {
  222137. if (! isOnDesktop ())
  222138. addToDesktop (0);
  222139. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222140. if (wp != 0)
  222141. {
  222142. wp->setTaskBarIcon (newImage);
  222143. setVisible (true);
  222144. toFront (false);
  222145. repaint();
  222146. }
  222147. }
  222148. void SystemTrayIconComponent::paint (Graphics& g)
  222149. {
  222150. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222151. if (wp != 0)
  222152. {
  222153. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222154. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222155. false);
  222156. }
  222157. }
  222158. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222159. {
  222160. // xxx not yet implemented!
  222161. }
  222162. void PlatformUtilities::beep()
  222163. {
  222164. std::cout << "\a" << std::flush;
  222165. }
  222166. bool AlertWindow::showNativeDialogBox (const String& title,
  222167. const String& bodyText,
  222168. bool isOkCancel)
  222169. {
  222170. // use a non-native one for the time being..
  222171. if (isOkCancel)
  222172. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222173. else
  222174. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222175. return true;
  222176. }
  222177. const int KeyPress::spaceKey = XK_space & 0xff;
  222178. const int KeyPress::returnKey = XK_Return & 0xff;
  222179. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222180. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222181. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222182. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222183. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222184. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222185. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222186. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222187. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222188. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222189. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222190. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222191. const int KeyPress::tabKey = XK_Tab & 0xff;
  222192. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222193. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222194. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222195. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222196. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222197. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222198. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222199. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222200. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222201. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222202. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222203. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222204. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222205. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222206. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222207. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222208. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222209. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222210. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222211. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222212. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222213. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222214. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222215. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222216. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222217. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222218. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222219. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222220. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222221. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222222. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222223. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222224. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222225. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222226. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222227. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222228. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222229. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222230. #endif
  222231. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222232. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222233. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222234. // compiled on its own).
  222235. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222236. namespace
  222237. {
  222238. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222239. {
  222240. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222241. snd_pcm_hw_params_t* hwParams;
  222242. snd_pcm_hw_params_alloca (&hwParams);
  222243. for (int i = 0; ratesToTry[i] != 0; ++i)
  222244. {
  222245. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222246. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222247. {
  222248. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222249. }
  222250. }
  222251. }
  222252. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222253. {
  222254. snd_pcm_hw_params_t *params;
  222255. snd_pcm_hw_params_alloca (&params);
  222256. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222257. {
  222258. snd_pcm_hw_params_get_channels_min (params, minChans);
  222259. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222260. }
  222261. }
  222262. void getDeviceProperties (const String& deviceID,
  222263. unsigned int& minChansOut,
  222264. unsigned int& maxChansOut,
  222265. unsigned int& minChansIn,
  222266. unsigned int& maxChansIn,
  222267. Array <int>& rates)
  222268. {
  222269. if (deviceID.isEmpty())
  222270. return;
  222271. snd_ctl_t* handle;
  222272. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222273. {
  222274. snd_pcm_info_t* info;
  222275. snd_pcm_info_alloca (&info);
  222276. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222277. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222278. snd_pcm_info_set_subdevice (info, 0);
  222279. if (snd_ctl_pcm_info (handle, info) >= 0)
  222280. {
  222281. snd_pcm_t* pcmHandle;
  222282. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222283. {
  222284. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222285. getDeviceSampleRates (pcmHandle, rates);
  222286. snd_pcm_close (pcmHandle);
  222287. }
  222288. }
  222289. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222290. if (snd_ctl_pcm_info (handle, info) >= 0)
  222291. {
  222292. snd_pcm_t* pcmHandle;
  222293. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222294. {
  222295. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222296. if (rates.size() == 0)
  222297. getDeviceSampleRates (pcmHandle, rates);
  222298. snd_pcm_close (pcmHandle);
  222299. }
  222300. }
  222301. snd_ctl_close (handle);
  222302. }
  222303. }
  222304. }
  222305. class ALSADevice
  222306. {
  222307. public:
  222308. ALSADevice (const String& deviceID, bool forInput)
  222309. : handle (0),
  222310. bitDepth (16),
  222311. numChannelsRunning (0),
  222312. latency (0),
  222313. isInput (forInput),
  222314. isInterleaved (true)
  222315. {
  222316. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222317. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222318. SND_PCM_ASYNC));
  222319. }
  222320. ~ALSADevice()
  222321. {
  222322. if (handle != 0)
  222323. snd_pcm_close (handle);
  222324. }
  222325. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222326. {
  222327. if (handle == 0)
  222328. return false;
  222329. snd_pcm_hw_params_t* hwParams;
  222330. snd_pcm_hw_params_alloca (&hwParams);
  222331. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222332. return false;
  222333. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222334. isInterleaved = false;
  222335. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222336. isInterleaved = true;
  222337. else
  222338. {
  222339. jassertfalse;
  222340. return false;
  222341. }
  222342. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  222343. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  222344. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  222345. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  222346. SND_PCM_FORMAT_S32_BE, 32,
  222347. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  222348. SND_PCM_FORMAT_S24_3BE, 24,
  222349. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  222350. SND_PCM_FORMAT_S16_BE, 16 };
  222351. bitDepth = 0;
  222352. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  222353. {
  222354. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222355. {
  222356. bitDepth = formatsToTry [i + 1] & 255;
  222357. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  222358. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  222359. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  222360. break;
  222361. }
  222362. }
  222363. if (bitDepth == 0)
  222364. {
  222365. error = "device doesn't support a compatible PCM format";
  222366. DBG ("ALSA error: " + error + "\n");
  222367. return false;
  222368. }
  222369. int dir = 0;
  222370. unsigned int periods = 4;
  222371. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222372. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222373. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222374. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222375. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222376. || failed (snd_pcm_hw_params (handle, hwParams)))
  222377. {
  222378. return false;
  222379. }
  222380. snd_pcm_uframes_t frames = 0;
  222381. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222382. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222383. latency = 0;
  222384. else
  222385. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222386. snd_pcm_sw_params_t* swParams;
  222387. snd_pcm_sw_params_alloca (&swParams);
  222388. snd_pcm_uframes_t boundary;
  222389. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222390. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222391. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222392. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222393. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222394. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222395. || failed (snd_pcm_sw_params (handle, swParams)))
  222396. {
  222397. return false;
  222398. }
  222399. /*
  222400. #if JUCE_DEBUG
  222401. // enable this to dump the config of the devices that get opened
  222402. snd_output_t* out;
  222403. snd_output_stdio_attach (&out, stderr, 0);
  222404. snd_pcm_hw_params_dump (hwParams, out);
  222405. snd_pcm_sw_params_dump (swParams, out);
  222406. #endif
  222407. */
  222408. numChannelsRunning = numChannels;
  222409. return true;
  222410. }
  222411. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222412. {
  222413. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222414. float** const data = outputChannelBuffer.getArrayOfChannels();
  222415. snd_pcm_sframes_t numDone = 0;
  222416. if (isInterleaved)
  222417. {
  222418. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222419. for (int i = 0; i < numChannelsRunning; ++i)
  222420. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222421. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222422. }
  222423. else
  222424. {
  222425. for (int i = 0; i < numChannelsRunning; ++i)
  222426. converter->convertSamples (data[i], data[i], numSamples);
  222427. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222428. }
  222429. if (failed (numDone))
  222430. {
  222431. if (numDone == -EPIPE)
  222432. {
  222433. if (failed (snd_pcm_prepare (handle)))
  222434. return false;
  222435. }
  222436. else if (numDone != -ESTRPIPE)
  222437. return false;
  222438. }
  222439. return true;
  222440. }
  222441. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222442. {
  222443. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222444. float** const data = inputChannelBuffer.getArrayOfChannels();
  222445. if (isInterleaved)
  222446. {
  222447. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222448. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  222449. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222450. if (failed (num))
  222451. {
  222452. if (num == -EPIPE)
  222453. {
  222454. if (failed (snd_pcm_prepare (handle)))
  222455. return false;
  222456. }
  222457. else if (num != -ESTRPIPE)
  222458. return false;
  222459. }
  222460. for (int i = 0; i < numChannelsRunning; ++i)
  222461. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222462. }
  222463. else
  222464. {
  222465. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222466. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222467. return false;
  222468. for (int i = 0; i < numChannelsRunning; ++i)
  222469. converter->convertSamples (data[i], data[i], numSamples);
  222470. }
  222471. return true;
  222472. }
  222473. snd_pcm_t* handle;
  222474. String error;
  222475. int bitDepth, numChannelsRunning, latency;
  222476. private:
  222477. const bool isInput;
  222478. bool isInterleaved;
  222479. MemoryBlock scratch;
  222480. ScopedPointer<AudioData::Converter> converter;
  222481. template <class SampleType>
  222482. struct ConverterHelper
  222483. {
  222484. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222485. {
  222486. if (forInput)
  222487. {
  222488. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222489. if (isLittleEndian)
  222490. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222491. else
  222492. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222493. }
  222494. else
  222495. {
  222496. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222497. if (isLittleEndian)
  222498. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222499. else
  222500. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222501. }
  222502. }
  222503. };
  222504. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222505. {
  222506. switch (bitDepth)
  222507. {
  222508. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222509. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222510. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222511. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222512. default: jassertfalse; break; // unsupported format!
  222513. }
  222514. return 0;
  222515. }
  222516. bool failed (const int errorNum)
  222517. {
  222518. if (errorNum >= 0)
  222519. return false;
  222520. error = snd_strerror (errorNum);
  222521. DBG ("ALSA error: " + error + "\n");
  222522. return true;
  222523. }
  222524. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  222525. };
  222526. class ALSAThread : public Thread
  222527. {
  222528. public:
  222529. ALSAThread (const String& inputId_,
  222530. const String& outputId_)
  222531. : Thread ("Juce ALSA"),
  222532. sampleRate (0),
  222533. bufferSize (0),
  222534. outputLatency (0),
  222535. inputLatency (0),
  222536. callback (0),
  222537. inputId (inputId_),
  222538. outputId (outputId_),
  222539. numCallbacks (0),
  222540. inputChannelBuffer (1, 1),
  222541. outputChannelBuffer (1, 1)
  222542. {
  222543. initialiseRatesAndChannels();
  222544. }
  222545. ~ALSAThread()
  222546. {
  222547. close();
  222548. }
  222549. void open (BigInteger inputChannels,
  222550. BigInteger outputChannels,
  222551. const double sampleRate_,
  222552. const int bufferSize_)
  222553. {
  222554. close();
  222555. error = String::empty;
  222556. sampleRate = sampleRate_;
  222557. bufferSize = bufferSize_;
  222558. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222559. inputChannelBuffer.clear();
  222560. inputChannelDataForCallback.clear();
  222561. currentInputChans.clear();
  222562. if (inputChannels.getHighestBit() >= 0)
  222563. {
  222564. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222565. {
  222566. if (inputChannels[i])
  222567. {
  222568. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222569. currentInputChans.setBit (i);
  222570. }
  222571. }
  222572. }
  222573. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222574. outputChannelBuffer.clear();
  222575. outputChannelDataForCallback.clear();
  222576. currentOutputChans.clear();
  222577. if (outputChannels.getHighestBit() >= 0)
  222578. {
  222579. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222580. {
  222581. if (outputChannels[i])
  222582. {
  222583. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222584. currentOutputChans.setBit (i);
  222585. }
  222586. }
  222587. }
  222588. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222589. {
  222590. outputDevice = new ALSADevice (outputId, false);
  222591. if (outputDevice->error.isNotEmpty())
  222592. {
  222593. error = outputDevice->error;
  222594. outputDevice = 0;
  222595. return;
  222596. }
  222597. currentOutputChans.setRange (0, minChansOut, true);
  222598. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222599. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222600. bufferSize))
  222601. {
  222602. error = outputDevice->error;
  222603. outputDevice = 0;
  222604. return;
  222605. }
  222606. outputLatency = outputDevice->latency;
  222607. }
  222608. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222609. {
  222610. inputDevice = new ALSADevice (inputId, true);
  222611. if (inputDevice->error.isNotEmpty())
  222612. {
  222613. error = inputDevice->error;
  222614. inputDevice = 0;
  222615. return;
  222616. }
  222617. currentInputChans.setRange (0, minChansIn, true);
  222618. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222619. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222620. bufferSize))
  222621. {
  222622. error = inputDevice->error;
  222623. inputDevice = 0;
  222624. return;
  222625. }
  222626. inputLatency = inputDevice->latency;
  222627. }
  222628. if (outputDevice == 0 && inputDevice == 0)
  222629. {
  222630. error = "no channels";
  222631. return;
  222632. }
  222633. if (outputDevice != 0 && inputDevice != 0)
  222634. {
  222635. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222636. }
  222637. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222638. return;
  222639. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222640. return;
  222641. startThread (9);
  222642. int count = 1000;
  222643. while (numCallbacks == 0)
  222644. {
  222645. sleep (5);
  222646. if (--count < 0 || ! isThreadRunning())
  222647. {
  222648. error = "device didn't start";
  222649. break;
  222650. }
  222651. }
  222652. }
  222653. void close()
  222654. {
  222655. stopThread (6000);
  222656. inputDevice = 0;
  222657. outputDevice = 0;
  222658. inputChannelBuffer.setSize (1, 1);
  222659. outputChannelBuffer.setSize (1, 1);
  222660. numCallbacks = 0;
  222661. }
  222662. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222663. {
  222664. const ScopedLock sl (callbackLock);
  222665. callback = newCallback;
  222666. }
  222667. void run()
  222668. {
  222669. while (! threadShouldExit())
  222670. {
  222671. if (inputDevice != 0)
  222672. {
  222673. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222674. {
  222675. DBG ("ALSA: read failure");
  222676. break;
  222677. }
  222678. }
  222679. if (threadShouldExit())
  222680. break;
  222681. {
  222682. const ScopedLock sl (callbackLock);
  222683. ++numCallbacks;
  222684. if (callback != 0)
  222685. {
  222686. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222687. inputChannelDataForCallback.size(),
  222688. outputChannelDataForCallback.getRawDataPointer(),
  222689. outputChannelDataForCallback.size(),
  222690. bufferSize);
  222691. }
  222692. else
  222693. {
  222694. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222695. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222696. }
  222697. }
  222698. if (outputDevice != 0)
  222699. {
  222700. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222701. if (threadShouldExit())
  222702. break;
  222703. failed (snd_pcm_avail_update (outputDevice->handle));
  222704. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222705. {
  222706. DBG ("ALSA: write failure");
  222707. break;
  222708. }
  222709. }
  222710. }
  222711. }
  222712. int getBitDepth() const throw()
  222713. {
  222714. if (outputDevice != 0)
  222715. return outputDevice->bitDepth;
  222716. if (inputDevice != 0)
  222717. return inputDevice->bitDepth;
  222718. return 16;
  222719. }
  222720. String error;
  222721. double sampleRate;
  222722. int bufferSize, outputLatency, inputLatency;
  222723. BigInteger currentInputChans, currentOutputChans;
  222724. Array <int> sampleRates;
  222725. StringArray channelNamesOut, channelNamesIn;
  222726. AudioIODeviceCallback* callback;
  222727. private:
  222728. const String inputId, outputId;
  222729. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222730. int numCallbacks;
  222731. CriticalSection callbackLock;
  222732. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222733. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222734. unsigned int minChansOut, maxChansOut;
  222735. unsigned int minChansIn, maxChansIn;
  222736. bool failed (const int errorNum)
  222737. {
  222738. if (errorNum >= 0)
  222739. return false;
  222740. error = snd_strerror (errorNum);
  222741. DBG ("ALSA error: " + error + "\n");
  222742. return true;
  222743. }
  222744. void initialiseRatesAndChannels()
  222745. {
  222746. sampleRates.clear();
  222747. channelNamesOut.clear();
  222748. channelNamesIn.clear();
  222749. minChansOut = 0;
  222750. maxChansOut = 0;
  222751. minChansIn = 0;
  222752. maxChansIn = 0;
  222753. unsigned int dummy = 0;
  222754. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222755. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222756. unsigned int i;
  222757. for (i = 0; i < maxChansOut; ++i)
  222758. channelNamesOut.add ("channel " + String ((int) i + 1));
  222759. for (i = 0; i < maxChansIn; ++i)
  222760. channelNamesIn.add ("channel " + String ((int) i + 1));
  222761. }
  222762. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  222763. };
  222764. class ALSAAudioIODevice : public AudioIODevice
  222765. {
  222766. public:
  222767. ALSAAudioIODevice (const String& deviceName,
  222768. const String& inputId_,
  222769. const String& outputId_)
  222770. : AudioIODevice (deviceName, "ALSA"),
  222771. inputId (inputId_),
  222772. outputId (outputId_),
  222773. isOpen_ (false),
  222774. isStarted (false),
  222775. internal (inputId_, outputId_)
  222776. {
  222777. }
  222778. ~ALSAAudioIODevice()
  222779. {
  222780. }
  222781. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222782. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222783. int getNumSampleRates() { return internal.sampleRates.size(); }
  222784. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222785. int getDefaultBufferSize() { return 512; }
  222786. int getNumBufferSizesAvailable() { return 50; }
  222787. int getBufferSizeSamples (int index)
  222788. {
  222789. int n = 16;
  222790. for (int i = 0; i < index; ++i)
  222791. n += n < 64 ? 16
  222792. : (n < 512 ? 32
  222793. : (n < 1024 ? 64
  222794. : (n < 2048 ? 128 : 256)));
  222795. return n;
  222796. }
  222797. const String open (const BigInteger& inputChannels,
  222798. const BigInteger& outputChannels,
  222799. double sampleRate,
  222800. int bufferSizeSamples)
  222801. {
  222802. close();
  222803. if (bufferSizeSamples <= 0)
  222804. bufferSizeSamples = getDefaultBufferSize();
  222805. if (sampleRate <= 0)
  222806. {
  222807. for (int i = 0; i < getNumSampleRates(); ++i)
  222808. {
  222809. if (getSampleRate (i) >= 44100)
  222810. {
  222811. sampleRate = getSampleRate (i);
  222812. break;
  222813. }
  222814. }
  222815. }
  222816. internal.open (inputChannels, outputChannels,
  222817. sampleRate, bufferSizeSamples);
  222818. isOpen_ = internal.error.isEmpty();
  222819. return internal.error;
  222820. }
  222821. void close()
  222822. {
  222823. stop();
  222824. internal.close();
  222825. isOpen_ = false;
  222826. }
  222827. bool isOpen() { return isOpen_; }
  222828. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222829. const String getLastError() { return internal.error; }
  222830. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222831. double getCurrentSampleRate() { return internal.sampleRate; }
  222832. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222833. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222834. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222835. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222836. int getInputLatencyInSamples() { return internal.inputLatency; }
  222837. void start (AudioIODeviceCallback* callback)
  222838. {
  222839. if (! isOpen_)
  222840. callback = 0;
  222841. if (callback != 0)
  222842. callback->audioDeviceAboutToStart (this);
  222843. internal.setCallback (callback);
  222844. isStarted = (callback != 0);
  222845. }
  222846. void stop()
  222847. {
  222848. AudioIODeviceCallback* const oldCallback = internal.callback;
  222849. start (0);
  222850. if (oldCallback != 0)
  222851. oldCallback->audioDeviceStopped();
  222852. }
  222853. String inputId, outputId;
  222854. private:
  222855. bool isOpen_, isStarted;
  222856. ALSAThread internal;
  222857. };
  222858. class ALSAAudioIODeviceType : public AudioIODeviceType
  222859. {
  222860. public:
  222861. ALSAAudioIODeviceType()
  222862. : AudioIODeviceType ("ALSA"),
  222863. hasScanned (false)
  222864. {
  222865. }
  222866. ~ALSAAudioIODeviceType()
  222867. {
  222868. }
  222869. void scanForDevices()
  222870. {
  222871. if (hasScanned)
  222872. return;
  222873. hasScanned = true;
  222874. inputNames.clear();
  222875. inputIds.clear();
  222876. outputNames.clear();
  222877. outputIds.clear();
  222878. /* void** hints = 0;
  222879. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222880. {
  222881. for (void** hint = hints; *hint != 0; ++hint)
  222882. {
  222883. const String name (getHint (*hint, "NAME"));
  222884. if (name.isNotEmpty())
  222885. {
  222886. const String ioid (getHint (*hint, "IOID"));
  222887. String desc (getHint (*hint, "DESC"));
  222888. if (desc.isEmpty())
  222889. desc = name;
  222890. desc = desc.replaceCharacters ("\n\r", " ");
  222891. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222892. if (ioid.isEmpty() || ioid == "Input")
  222893. {
  222894. inputNames.add (desc);
  222895. inputIds.add (name);
  222896. }
  222897. if (ioid.isEmpty() || ioid == "Output")
  222898. {
  222899. outputNames.add (desc);
  222900. outputIds.add (name);
  222901. }
  222902. }
  222903. }
  222904. snd_device_name_free_hint (hints);
  222905. }
  222906. */
  222907. snd_ctl_t* handle = 0;
  222908. snd_ctl_card_info_t* info = 0;
  222909. snd_ctl_card_info_alloca (&info);
  222910. int cardNum = -1;
  222911. while (outputIds.size() + inputIds.size() <= 32)
  222912. {
  222913. snd_card_next (&cardNum);
  222914. if (cardNum < 0)
  222915. break;
  222916. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222917. {
  222918. if (snd_ctl_card_info (handle, info) >= 0)
  222919. {
  222920. String cardId (snd_ctl_card_info_get_id (info));
  222921. if (cardId.removeCharacters ("0123456789").isEmpty())
  222922. cardId = String (cardNum);
  222923. int device = -1;
  222924. for (;;)
  222925. {
  222926. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222927. break;
  222928. String id, name;
  222929. id << "hw:" << cardId << ',' << device;
  222930. bool isInput, isOutput;
  222931. if (testDevice (id, isInput, isOutput))
  222932. {
  222933. name << snd_ctl_card_info_get_name (info);
  222934. if (name.isEmpty())
  222935. name = id;
  222936. if (isInput)
  222937. {
  222938. inputNames.add (name);
  222939. inputIds.add (id);
  222940. }
  222941. if (isOutput)
  222942. {
  222943. outputNames.add (name);
  222944. outputIds.add (id);
  222945. }
  222946. }
  222947. }
  222948. }
  222949. snd_ctl_close (handle);
  222950. }
  222951. }
  222952. inputNames.appendNumbersToDuplicates (false, true);
  222953. outputNames.appendNumbersToDuplicates (false, true);
  222954. }
  222955. const StringArray getDeviceNames (bool wantInputNames) const
  222956. {
  222957. jassert (hasScanned); // need to call scanForDevices() before doing this
  222958. return wantInputNames ? inputNames : outputNames;
  222959. }
  222960. int getDefaultDeviceIndex (bool forInput) const
  222961. {
  222962. jassert (hasScanned); // need to call scanForDevices() before doing this
  222963. return 0;
  222964. }
  222965. bool hasSeparateInputsAndOutputs() const { return true; }
  222966. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222967. {
  222968. jassert (hasScanned); // need to call scanForDevices() before doing this
  222969. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222970. if (d == 0)
  222971. return -1;
  222972. return asInput ? inputIds.indexOf (d->inputId)
  222973. : outputIds.indexOf (d->outputId);
  222974. }
  222975. AudioIODevice* createDevice (const String& outputDeviceName,
  222976. const String& inputDeviceName)
  222977. {
  222978. jassert (hasScanned); // need to call scanForDevices() before doing this
  222979. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222980. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222981. String deviceName (outputIndex >= 0 ? outputDeviceName
  222982. : inputDeviceName);
  222983. if (inputIndex >= 0 || outputIndex >= 0)
  222984. return new ALSAAudioIODevice (deviceName,
  222985. inputIds [inputIndex],
  222986. outputIds [outputIndex]);
  222987. return 0;
  222988. }
  222989. private:
  222990. StringArray inputNames, outputNames, inputIds, outputIds;
  222991. bool hasScanned;
  222992. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222993. {
  222994. unsigned int minChansOut = 0, maxChansOut = 0;
  222995. unsigned int minChansIn = 0, maxChansIn = 0;
  222996. Array <int> rates;
  222997. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222998. DBG ("ALSA device: " + id
  222999. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  223000. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  223001. + " rates=" + String (rates.size()));
  223002. isInput = maxChansIn > 0;
  223003. isOutput = maxChansOut > 0;
  223004. return (isInput || isOutput) && rates.size() > 0;
  223005. }
  223006. /*static const String getHint (void* hint, const char* type)
  223007. {
  223008. char* const n = snd_device_name_get_hint (hint, type);
  223009. const String s ((const char*) n);
  223010. free (n);
  223011. return s;
  223012. }*/
  223013. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  223014. };
  223015. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  223016. {
  223017. return new ALSAAudioIODeviceType();
  223018. }
  223019. #endif
  223020. /*** End of inlined file: juce_linux_Audio.cpp ***/
  223021. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  223022. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223023. // compiled on its own).
  223024. #ifdef JUCE_INCLUDED_FILE
  223025. #if JUCE_JACK
  223026. static void* juce_libjack_handle = 0;
  223027. void* juce_load_jack_function (const char* const name)
  223028. {
  223029. if (juce_libjack_handle == 0)
  223030. return 0;
  223031. return dlsym (juce_libjack_handle, name);
  223032. }
  223033. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223034. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223035. return_type fn_name argument_types { \
  223036. static fn_name##_ptr_t fn = 0; \
  223037. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223038. if (fn) return (*fn)arguments; \
  223039. else return 0; \
  223040. }
  223041. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223042. typedef void (*fn_name##_ptr_t)argument_types; \
  223043. void fn_name argument_types { \
  223044. static fn_name##_ptr_t fn = 0; \
  223045. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223046. if (fn) (*fn)arguments; \
  223047. }
  223048. 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));
  223049. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223050. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223051. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223052. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223053. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223054. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223055. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223056. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223057. 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));
  223058. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223059. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223060. 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));
  223061. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223062. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223063. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223064. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223065. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223066. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223067. #if JUCE_DEBUG
  223068. #define JACK_LOGGING_ENABLED 1
  223069. #endif
  223070. #if JACK_LOGGING_ENABLED
  223071. namespace
  223072. {
  223073. void jack_Log (const String& s)
  223074. {
  223075. std::cerr << s << std::endl;
  223076. }
  223077. void dumpJackErrorMessage (const jack_status_t status)
  223078. {
  223079. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223080. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223081. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223082. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223083. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223084. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223085. }
  223086. }
  223087. #else
  223088. #define dumpJackErrorMessage(a) {}
  223089. #define jack_Log(...) {}
  223090. #endif
  223091. #ifndef JUCE_JACK_CLIENT_NAME
  223092. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223093. #endif
  223094. class JackAudioIODevice : public AudioIODevice
  223095. {
  223096. public:
  223097. JackAudioIODevice (const String& deviceName,
  223098. const String& inputId_,
  223099. const String& outputId_)
  223100. : AudioIODevice (deviceName, "JACK"),
  223101. inputId (inputId_),
  223102. outputId (outputId_),
  223103. isOpen_ (false),
  223104. callback (0),
  223105. totalNumberOfInputChannels (0),
  223106. totalNumberOfOutputChannels (0)
  223107. {
  223108. jassert (deviceName.isNotEmpty());
  223109. jack_status_t status;
  223110. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223111. if (client == 0)
  223112. {
  223113. dumpJackErrorMessage (status);
  223114. }
  223115. else
  223116. {
  223117. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223118. // open input ports
  223119. const StringArray inputChannels (getInputChannelNames());
  223120. for (int i = 0; i < inputChannels.size(); i++)
  223121. {
  223122. String inputName;
  223123. inputName << "in_" << ++totalNumberOfInputChannels;
  223124. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223125. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223126. }
  223127. // open output ports
  223128. const StringArray outputChannels (getOutputChannelNames());
  223129. for (int i = 0; i < outputChannels.size (); i++)
  223130. {
  223131. String outputName;
  223132. outputName << "out_" << ++totalNumberOfOutputChannels;
  223133. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223134. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223135. }
  223136. inChans.calloc (totalNumberOfInputChannels + 2);
  223137. outChans.calloc (totalNumberOfOutputChannels + 2);
  223138. }
  223139. }
  223140. ~JackAudioIODevice()
  223141. {
  223142. close();
  223143. if (client != 0)
  223144. {
  223145. JUCE_NAMESPACE::jack_client_close (client);
  223146. client = 0;
  223147. }
  223148. }
  223149. const StringArray getChannelNames (bool forInput) const
  223150. {
  223151. StringArray names;
  223152. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223153. forInput ? JackPortIsInput : JackPortIsOutput);
  223154. if (ports != 0)
  223155. {
  223156. int j = 0;
  223157. while (ports[j] != 0)
  223158. {
  223159. const String portName (ports [j++]);
  223160. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223161. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223162. }
  223163. free (ports);
  223164. }
  223165. return names;
  223166. }
  223167. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223168. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223169. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223170. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223171. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223172. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223173. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223174. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223175. double sampleRate, int bufferSizeSamples)
  223176. {
  223177. if (client == 0)
  223178. {
  223179. lastError = "No JACK client running";
  223180. return lastError;
  223181. }
  223182. lastError = String::empty;
  223183. close();
  223184. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223185. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223186. JUCE_NAMESPACE::jack_activate (client);
  223187. isOpen_ = true;
  223188. if (! inputChannels.isZero())
  223189. {
  223190. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223191. if (ports != 0)
  223192. {
  223193. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223194. for (int i = 0; i < numInputChannels; ++i)
  223195. {
  223196. const String portName (ports[i]);
  223197. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223198. {
  223199. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223200. if (error != 0)
  223201. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223202. }
  223203. }
  223204. free (ports);
  223205. }
  223206. }
  223207. if (! outputChannels.isZero())
  223208. {
  223209. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223210. if (ports != 0)
  223211. {
  223212. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223213. for (int i = 0; i < numOutputChannels; ++i)
  223214. {
  223215. const String portName (ports[i]);
  223216. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223217. {
  223218. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223219. if (error != 0)
  223220. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223221. }
  223222. }
  223223. free (ports);
  223224. }
  223225. }
  223226. return lastError;
  223227. }
  223228. void close()
  223229. {
  223230. stop();
  223231. if (client != 0)
  223232. {
  223233. JUCE_NAMESPACE::jack_deactivate (client);
  223234. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223235. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223236. }
  223237. isOpen_ = false;
  223238. }
  223239. void start (AudioIODeviceCallback* newCallback)
  223240. {
  223241. if (isOpen_ && newCallback != callback)
  223242. {
  223243. if (newCallback != 0)
  223244. newCallback->audioDeviceAboutToStart (this);
  223245. AudioIODeviceCallback* const oldCallback = callback;
  223246. {
  223247. const ScopedLock sl (callbackLock);
  223248. callback = newCallback;
  223249. }
  223250. if (oldCallback != 0)
  223251. oldCallback->audioDeviceStopped();
  223252. }
  223253. }
  223254. void stop()
  223255. {
  223256. start (0);
  223257. }
  223258. bool isOpen() { return isOpen_; }
  223259. bool isPlaying() { return callback != 0; }
  223260. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223261. double getCurrentSampleRate() { return getSampleRate (0); }
  223262. int getCurrentBitDepth() { return 32; }
  223263. const String getLastError() { return lastError; }
  223264. const BigInteger getActiveOutputChannels() const
  223265. {
  223266. BigInteger outputBits;
  223267. for (int i = 0; i < outputPorts.size(); i++)
  223268. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223269. outputBits.setBit (i);
  223270. return outputBits;
  223271. }
  223272. const BigInteger getActiveInputChannels() const
  223273. {
  223274. BigInteger inputBits;
  223275. for (int i = 0; i < inputPorts.size(); i++)
  223276. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223277. inputBits.setBit (i);
  223278. return inputBits;
  223279. }
  223280. int getOutputLatencyInSamples()
  223281. {
  223282. int latency = 0;
  223283. for (int i = 0; i < outputPorts.size(); i++)
  223284. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223285. return latency;
  223286. }
  223287. int getInputLatencyInSamples()
  223288. {
  223289. int latency = 0;
  223290. for (int i = 0; i < inputPorts.size(); i++)
  223291. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223292. return latency;
  223293. }
  223294. String inputId, outputId;
  223295. private:
  223296. void process (const int numSamples)
  223297. {
  223298. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223299. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223300. {
  223301. jack_default_audio_sample_t* in
  223302. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223303. if (in != 0)
  223304. inChans [numActiveInChans++] = (float*) in;
  223305. }
  223306. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223307. {
  223308. jack_default_audio_sample_t* out
  223309. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223310. if (out != 0)
  223311. outChans [numActiveOutChans++] = (float*) out;
  223312. }
  223313. const ScopedLock sl (callbackLock);
  223314. if (callback != 0)
  223315. {
  223316. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223317. outChans, numActiveOutChans, numSamples);
  223318. }
  223319. else
  223320. {
  223321. for (i = 0; i < numActiveOutChans; ++i)
  223322. zeromem (outChans[i], sizeof (float) * numSamples);
  223323. }
  223324. }
  223325. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223326. {
  223327. if (callbackArgument != 0)
  223328. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223329. return 0;
  223330. }
  223331. static void threadInitCallback (void* callbackArgument)
  223332. {
  223333. jack_Log ("JackAudioIODevice::initialise");
  223334. }
  223335. static void shutdownCallback (void* callbackArgument)
  223336. {
  223337. jack_Log ("JackAudioIODevice::shutdown");
  223338. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223339. if (device != 0)
  223340. {
  223341. device->client = 0;
  223342. device->close();
  223343. }
  223344. }
  223345. static void errorCallback (const char* msg)
  223346. {
  223347. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223348. }
  223349. bool isOpen_;
  223350. jack_client_t* client;
  223351. String lastError;
  223352. AudioIODeviceCallback* callback;
  223353. CriticalSection callbackLock;
  223354. HeapBlock <float*> inChans, outChans;
  223355. int totalNumberOfInputChannels;
  223356. int totalNumberOfOutputChannels;
  223357. Array<void*> inputPorts, outputPorts;
  223358. };
  223359. class JackAudioIODeviceType : public AudioIODeviceType
  223360. {
  223361. public:
  223362. JackAudioIODeviceType()
  223363. : AudioIODeviceType ("JACK"),
  223364. hasScanned (false)
  223365. {
  223366. }
  223367. ~JackAudioIODeviceType()
  223368. {
  223369. }
  223370. void scanForDevices()
  223371. {
  223372. hasScanned = true;
  223373. inputNames.clear();
  223374. inputIds.clear();
  223375. outputNames.clear();
  223376. outputIds.clear();
  223377. if (juce_libjack_handle == 0)
  223378. {
  223379. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223380. if (juce_libjack_handle == 0)
  223381. return;
  223382. }
  223383. // open a dummy client
  223384. jack_status_t status;
  223385. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223386. if (client == 0)
  223387. {
  223388. dumpJackErrorMessage (status);
  223389. }
  223390. else
  223391. {
  223392. // scan for output devices
  223393. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223394. if (ports != 0)
  223395. {
  223396. int j = 0;
  223397. while (ports[j] != 0)
  223398. {
  223399. String clientName (ports[j]);
  223400. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223401. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223402. && ! inputNames.contains (clientName))
  223403. {
  223404. inputNames.add (clientName);
  223405. inputIds.add (ports [j]);
  223406. }
  223407. ++j;
  223408. }
  223409. free (ports);
  223410. }
  223411. // scan for input devices
  223412. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223413. if (ports != 0)
  223414. {
  223415. int j = 0;
  223416. while (ports[j] != 0)
  223417. {
  223418. String clientName (ports[j]);
  223419. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223420. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223421. && ! outputNames.contains (clientName))
  223422. {
  223423. outputNames.add (clientName);
  223424. outputIds.add (ports [j]);
  223425. }
  223426. ++j;
  223427. }
  223428. free (ports);
  223429. }
  223430. JUCE_NAMESPACE::jack_client_close (client);
  223431. }
  223432. }
  223433. const StringArray getDeviceNames (bool wantInputNames) const
  223434. {
  223435. jassert (hasScanned); // need to call scanForDevices() before doing this
  223436. return wantInputNames ? inputNames : outputNames;
  223437. }
  223438. int getDefaultDeviceIndex (bool forInput) const
  223439. {
  223440. jassert (hasScanned); // need to call scanForDevices() before doing this
  223441. return 0;
  223442. }
  223443. bool hasSeparateInputsAndOutputs() const { return true; }
  223444. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223445. {
  223446. jassert (hasScanned); // need to call scanForDevices() before doing this
  223447. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223448. if (d == 0)
  223449. return -1;
  223450. return asInput ? inputIds.indexOf (d->inputId)
  223451. : outputIds.indexOf (d->outputId);
  223452. }
  223453. AudioIODevice* createDevice (const String& outputDeviceName,
  223454. const String& inputDeviceName)
  223455. {
  223456. jassert (hasScanned); // need to call scanForDevices() before doing this
  223457. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223458. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223459. if (inputIndex >= 0 || outputIndex >= 0)
  223460. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223461. : inputDeviceName,
  223462. inputIds [inputIndex],
  223463. outputIds [outputIndex]);
  223464. return 0;
  223465. }
  223466. private:
  223467. StringArray inputNames, outputNames, inputIds, outputIds;
  223468. bool hasScanned;
  223469. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  223470. };
  223471. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223472. {
  223473. return new JackAudioIODeviceType();
  223474. }
  223475. #else // if JACK is turned off..
  223476. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223477. #endif
  223478. #endif
  223479. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223480. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223481. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223482. // compiled on its own).
  223483. #if JUCE_INCLUDED_FILE
  223484. #if JUCE_ALSA
  223485. namespace
  223486. {
  223487. snd_seq_t* iterateMidiDevices (const bool forInput,
  223488. StringArray& deviceNamesFound,
  223489. const int deviceIndexToOpen)
  223490. {
  223491. snd_seq_t* returnedHandle = 0;
  223492. snd_seq_t* seqHandle;
  223493. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223494. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223495. {
  223496. snd_seq_system_info_t* systemInfo;
  223497. snd_seq_client_info_t* clientInfo;
  223498. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223499. {
  223500. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223501. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223502. {
  223503. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223504. while (--numClients >= 0 && returnedHandle == 0)
  223505. {
  223506. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223507. {
  223508. snd_seq_port_info_t* portInfo;
  223509. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223510. {
  223511. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223512. const int client = snd_seq_client_info_get_client (clientInfo);
  223513. snd_seq_port_info_set_client (portInfo, client);
  223514. snd_seq_port_info_set_port (portInfo, -1);
  223515. while (--numPorts >= 0)
  223516. {
  223517. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223518. && (snd_seq_port_info_get_capability (portInfo)
  223519. & (forInput ? SND_SEQ_PORT_CAP_READ
  223520. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223521. {
  223522. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223523. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223524. {
  223525. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223526. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223527. if (sourcePort != -1)
  223528. {
  223529. snd_seq_set_client_name (seqHandle,
  223530. forInput ? "Juce Midi Input"
  223531. : "Juce Midi Output");
  223532. const int portId
  223533. = snd_seq_create_simple_port (seqHandle,
  223534. forInput ? "Juce Midi In Port"
  223535. : "Juce Midi Out Port",
  223536. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223537. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223538. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223539. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223540. returnedHandle = seqHandle;
  223541. }
  223542. }
  223543. }
  223544. }
  223545. snd_seq_port_info_free (portInfo);
  223546. }
  223547. }
  223548. }
  223549. snd_seq_client_info_free (clientInfo);
  223550. }
  223551. snd_seq_system_info_free (systemInfo);
  223552. }
  223553. if (returnedHandle == 0)
  223554. snd_seq_close (seqHandle);
  223555. }
  223556. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223557. return returnedHandle;
  223558. }
  223559. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  223560. {
  223561. snd_seq_t* seqHandle = 0;
  223562. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223563. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223564. {
  223565. snd_seq_set_client_name (seqHandle,
  223566. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223567. const int portId
  223568. = snd_seq_create_simple_port (seqHandle,
  223569. forInput ? "in"
  223570. : "out",
  223571. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223572. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223573. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223574. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223575. if (portId < 0)
  223576. {
  223577. snd_seq_close (seqHandle);
  223578. seqHandle = 0;
  223579. }
  223580. }
  223581. return seqHandle;
  223582. }
  223583. }
  223584. class MidiOutputDevice
  223585. {
  223586. public:
  223587. MidiOutputDevice (MidiOutput* const midiOutput_,
  223588. snd_seq_t* const seqHandle_)
  223589. :
  223590. midiOutput (midiOutput_),
  223591. seqHandle (seqHandle_),
  223592. maxEventSize (16 * 1024)
  223593. {
  223594. jassert (seqHandle != 0 && midiOutput != 0);
  223595. snd_midi_event_new (maxEventSize, &midiParser);
  223596. }
  223597. ~MidiOutputDevice()
  223598. {
  223599. snd_midi_event_free (midiParser);
  223600. snd_seq_close (seqHandle);
  223601. }
  223602. void sendMessageNow (const MidiMessage& message)
  223603. {
  223604. if (message.getRawDataSize() > maxEventSize)
  223605. {
  223606. maxEventSize = message.getRawDataSize();
  223607. snd_midi_event_free (midiParser);
  223608. snd_midi_event_new (maxEventSize, &midiParser);
  223609. }
  223610. snd_seq_event_t event;
  223611. snd_seq_ev_clear (&event);
  223612. snd_midi_event_encode (midiParser,
  223613. message.getRawData(),
  223614. message.getRawDataSize(),
  223615. &event);
  223616. snd_midi_event_reset_encode (midiParser);
  223617. snd_seq_ev_set_source (&event, 0);
  223618. snd_seq_ev_set_subs (&event);
  223619. snd_seq_ev_set_direct (&event);
  223620. snd_seq_event_output (seqHandle, &event);
  223621. snd_seq_drain_output (seqHandle);
  223622. }
  223623. private:
  223624. MidiOutput* const midiOutput;
  223625. snd_seq_t* const seqHandle;
  223626. snd_midi_event_t* midiParser;
  223627. int maxEventSize;
  223628. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  223629. };
  223630. const StringArray MidiOutput::getDevices()
  223631. {
  223632. StringArray devices;
  223633. iterateMidiDevices (false, devices, -1);
  223634. return devices;
  223635. }
  223636. int MidiOutput::getDefaultDeviceIndex()
  223637. {
  223638. return 0;
  223639. }
  223640. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223641. {
  223642. MidiOutput* newDevice = 0;
  223643. StringArray devices;
  223644. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223645. if (handle != 0)
  223646. {
  223647. newDevice = new MidiOutput();
  223648. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223649. }
  223650. return newDevice;
  223651. }
  223652. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223653. {
  223654. MidiOutput* newDevice = 0;
  223655. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223656. if (handle != 0)
  223657. {
  223658. newDevice = new MidiOutput();
  223659. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223660. }
  223661. return newDevice;
  223662. }
  223663. MidiOutput::~MidiOutput()
  223664. {
  223665. delete static_cast <MidiOutputDevice*> (internal);
  223666. }
  223667. void MidiOutput::reset()
  223668. {
  223669. }
  223670. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223671. {
  223672. return false;
  223673. }
  223674. void MidiOutput::setVolume (float leftVol, float rightVol)
  223675. {
  223676. }
  223677. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223678. {
  223679. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223680. }
  223681. class MidiInputThread : public Thread
  223682. {
  223683. public:
  223684. MidiInputThread (MidiInput* const midiInput_,
  223685. snd_seq_t* const seqHandle_,
  223686. MidiInputCallback* const callback_)
  223687. : Thread ("Juce MIDI Input"),
  223688. midiInput (midiInput_),
  223689. seqHandle (seqHandle_),
  223690. callback (callback_)
  223691. {
  223692. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223693. }
  223694. ~MidiInputThread()
  223695. {
  223696. snd_seq_close (seqHandle);
  223697. }
  223698. void run()
  223699. {
  223700. const int maxEventSize = 16 * 1024;
  223701. snd_midi_event_t* midiParser;
  223702. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223703. {
  223704. HeapBlock <uint8> buffer (maxEventSize);
  223705. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223706. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223707. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223708. while (! threadShouldExit())
  223709. {
  223710. if (poll (pfd, numPfds, 500) > 0)
  223711. {
  223712. snd_seq_event_t* inputEvent = 0;
  223713. snd_seq_nonblock (seqHandle, 1);
  223714. do
  223715. {
  223716. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223717. {
  223718. // xxx what about SYSEXes that are too big for the buffer?
  223719. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223720. snd_midi_event_reset_decode (midiParser);
  223721. if (numBytes > 0)
  223722. {
  223723. const MidiMessage message ((const uint8*) buffer,
  223724. numBytes,
  223725. Time::getMillisecondCounter() * 0.001);
  223726. callback->handleIncomingMidiMessage (midiInput, message);
  223727. }
  223728. snd_seq_free_event (inputEvent);
  223729. }
  223730. }
  223731. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223732. snd_seq_free_event (inputEvent);
  223733. }
  223734. }
  223735. snd_midi_event_free (midiParser);
  223736. }
  223737. };
  223738. private:
  223739. MidiInput* const midiInput;
  223740. snd_seq_t* const seqHandle;
  223741. MidiInputCallback* const callback;
  223742. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  223743. };
  223744. MidiInput::MidiInput (const String& name_)
  223745. : name (name_),
  223746. internal (0)
  223747. {
  223748. }
  223749. MidiInput::~MidiInput()
  223750. {
  223751. stop();
  223752. delete static_cast <MidiInputThread*> (internal);
  223753. }
  223754. void MidiInput::start()
  223755. {
  223756. static_cast <MidiInputThread*> (internal)->startThread();
  223757. }
  223758. void MidiInput::stop()
  223759. {
  223760. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223761. }
  223762. int MidiInput::getDefaultDeviceIndex()
  223763. {
  223764. return 0;
  223765. }
  223766. const StringArray MidiInput::getDevices()
  223767. {
  223768. StringArray devices;
  223769. iterateMidiDevices (true, devices, -1);
  223770. return devices;
  223771. }
  223772. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223773. {
  223774. MidiInput* newDevice = 0;
  223775. StringArray devices;
  223776. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223777. if (handle != 0)
  223778. {
  223779. newDevice = new MidiInput (devices [deviceIndex]);
  223780. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223781. }
  223782. return newDevice;
  223783. }
  223784. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223785. {
  223786. MidiInput* newDevice = 0;
  223787. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223788. if (handle != 0)
  223789. {
  223790. newDevice = new MidiInput (deviceName);
  223791. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223792. }
  223793. return newDevice;
  223794. }
  223795. #else
  223796. // (These are just stub functions if ALSA is unavailable...)
  223797. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223798. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223799. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223800. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223801. MidiOutput::~MidiOutput() {}
  223802. void MidiOutput::reset() {}
  223803. bool MidiOutput::getVolume (float&, float&) { return false; }
  223804. void MidiOutput::setVolume (float, float) {}
  223805. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223806. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223807. MidiInput::~MidiInput() {}
  223808. void MidiInput::start() {}
  223809. void MidiInput::stop() {}
  223810. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223811. const StringArray MidiInput::getDevices() { return StringArray(); }
  223812. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223813. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223814. #endif
  223815. #endif
  223816. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223817. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223818. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223819. // compiled on its own).
  223820. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223821. AudioCDReader::AudioCDReader()
  223822. : AudioFormatReader (0, "CD Audio")
  223823. {
  223824. }
  223825. const StringArray AudioCDReader::getAvailableCDNames()
  223826. {
  223827. StringArray names;
  223828. return names;
  223829. }
  223830. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223831. {
  223832. return 0;
  223833. }
  223834. AudioCDReader::~AudioCDReader()
  223835. {
  223836. }
  223837. void AudioCDReader::refreshTrackLengths()
  223838. {
  223839. }
  223840. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223841. int64 startSampleInFile, int numSamples)
  223842. {
  223843. return false;
  223844. }
  223845. bool AudioCDReader::isCDStillPresent() const
  223846. {
  223847. return false;
  223848. }
  223849. bool AudioCDReader::isTrackAudio (int trackNum) const
  223850. {
  223851. return false;
  223852. }
  223853. void AudioCDReader::enableIndexScanning (bool b)
  223854. {
  223855. }
  223856. int AudioCDReader::getLastIndex() const
  223857. {
  223858. return 0;
  223859. }
  223860. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223861. {
  223862. return Array<int>();
  223863. }
  223864. #endif
  223865. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223866. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223867. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223868. // compiled on its own).
  223869. #if JUCE_INCLUDED_FILE
  223870. void FileChooser::showPlatformDialog (Array<File>& results,
  223871. const String& title,
  223872. const File& file,
  223873. const String& filters,
  223874. bool isDirectory,
  223875. bool selectsFiles,
  223876. bool isSave,
  223877. bool warnAboutOverwritingExistingFiles,
  223878. bool selectMultipleFiles,
  223879. FilePreviewComponent* previewComponent)
  223880. {
  223881. const String separator (":");
  223882. String command ("zenity --file-selection");
  223883. if (title.isNotEmpty())
  223884. command << " --title=\"" << title << "\"";
  223885. if (file != File::nonexistent)
  223886. command << " --filename=\"" << file.getFullPathName () << "\"";
  223887. if (isDirectory)
  223888. command << " --directory";
  223889. if (isSave)
  223890. command << " --save";
  223891. if (selectMultipleFiles)
  223892. command << " --multiple --separator=\"" << separator << "\"";
  223893. command << " 2>&1";
  223894. MemoryOutputStream result;
  223895. int status = -1;
  223896. FILE* stream = popen (command.toUTF8(), "r");
  223897. if (stream != 0)
  223898. {
  223899. for (;;)
  223900. {
  223901. char buffer [1024];
  223902. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223903. if (bytesRead <= 0)
  223904. break;
  223905. result.write (buffer, bytesRead);
  223906. }
  223907. status = pclose (stream);
  223908. }
  223909. if (status == 0)
  223910. {
  223911. StringArray tokens;
  223912. if (selectMultipleFiles)
  223913. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223914. else
  223915. tokens.add (result.toUTF8());
  223916. for (int i = 0; i < tokens.size(); i++)
  223917. results.add (File (tokens[i]));
  223918. return;
  223919. }
  223920. //xxx ain't got one!
  223921. jassertfalse;
  223922. }
  223923. #endif
  223924. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223925. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223926. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223927. // compiled on its own).
  223928. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223929. /*
  223930. Sorry.. This class isn't implemented on Linux!
  223931. */
  223932. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223933. : browser (0),
  223934. blankPageShown (false),
  223935. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223936. {
  223937. setOpaque (true);
  223938. }
  223939. WebBrowserComponent::~WebBrowserComponent()
  223940. {
  223941. }
  223942. void WebBrowserComponent::goToURL (const String& url,
  223943. const StringArray* headers,
  223944. const MemoryBlock* postData)
  223945. {
  223946. lastURL = url;
  223947. lastHeaders.clear();
  223948. if (headers != 0)
  223949. lastHeaders = *headers;
  223950. lastPostData.setSize (0);
  223951. if (postData != 0)
  223952. lastPostData = *postData;
  223953. blankPageShown = false;
  223954. }
  223955. void WebBrowserComponent::stop()
  223956. {
  223957. }
  223958. void WebBrowserComponent::goBack()
  223959. {
  223960. lastURL = String::empty;
  223961. blankPageShown = false;
  223962. }
  223963. void WebBrowserComponent::goForward()
  223964. {
  223965. lastURL = String::empty;
  223966. }
  223967. void WebBrowserComponent::refresh()
  223968. {
  223969. }
  223970. void WebBrowserComponent::paint (Graphics& g)
  223971. {
  223972. g.fillAll (Colours::white);
  223973. }
  223974. void WebBrowserComponent::checkWindowAssociation()
  223975. {
  223976. }
  223977. void WebBrowserComponent::reloadLastURL()
  223978. {
  223979. if (lastURL.isNotEmpty())
  223980. {
  223981. goToURL (lastURL, &lastHeaders, &lastPostData);
  223982. lastURL = String::empty;
  223983. }
  223984. }
  223985. void WebBrowserComponent::parentHierarchyChanged()
  223986. {
  223987. checkWindowAssociation();
  223988. }
  223989. void WebBrowserComponent::resized()
  223990. {
  223991. }
  223992. void WebBrowserComponent::visibilityChanged()
  223993. {
  223994. checkWindowAssociation();
  223995. }
  223996. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223997. {
  223998. return true;
  223999. }
  224000. #endif
  224001. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224002. #endif
  224003. END_JUCE_NAMESPACE
  224004. #endif
  224005. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  224006. #endif
  224007. #if JUCE_MAC || JUCE_IPHONE
  224008. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  224009. /*
  224010. This file wraps together all the mac-specific code, so that
  224011. we can include all the native headers just once, and compile all our
  224012. platform-specific stuff in one big lump, keeping it out of the way of
  224013. the rest of the codebase.
  224014. */
  224015. #if JUCE_MAC || JUCE_IOS
  224016. BEGIN_JUCE_NAMESPACE
  224017. #undef Point
  224018. namespace
  224019. {
  224020. template <class RectType>
  224021. const Rectangle<int> convertToRectInt (const RectType& r)
  224022. {
  224023. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  224024. }
  224025. template <class RectType>
  224026. const Rectangle<float> convertToRectFloat (const RectType& r)
  224027. {
  224028. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  224029. }
  224030. template <class RectType>
  224031. CGRect convertToCGRect (const RectType& r)
  224032. {
  224033. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  224034. }
  224035. }
  224036. #define JUCE_INCLUDED_FILE 1
  224037. // Now include the actual code files..
  224038. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  224039. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  224040. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  224041. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  224042. cross-linked so that when you make a call to a class that you thought was private, it ends up
  224043. actually calling into a similarly named class in the other module's address space.
  224044. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224045. have unique names, and should avoid this problem.
  224046. If you're using the amalgamated version, you can just set this macro to something unique before
  224047. you include juce_amalgamated.cpp.
  224048. */
  224049. #ifndef JUCE_ObjCExtraSuffix
  224050. #define JUCE_ObjCExtraSuffix 3
  224051. #endif
  224052. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224053. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224054. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224055. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224056. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224057. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224058. // compiled on its own).
  224059. #if JUCE_INCLUDED_FILE
  224060. namespace
  224061. {
  224062. const String nsStringToJuce (NSString* s)
  224063. {
  224064. return String::fromUTF8 ([s UTF8String]);
  224065. }
  224066. NSString* juceStringToNS (const String& s)
  224067. {
  224068. return [NSString stringWithUTF8String: s.toUTF8()];
  224069. }
  224070. const String convertUTF16ToString (const UniChar* utf16)
  224071. {
  224072. String s;
  224073. while (*utf16 != 0)
  224074. s += (juce_wchar) *utf16++;
  224075. return s;
  224076. }
  224077. }
  224078. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224079. {
  224080. String result;
  224081. if (cfString != 0)
  224082. {
  224083. CFRange range = { 0, CFStringGetLength (cfString) };
  224084. HeapBlock <UniChar> u (range.length + 1);
  224085. CFStringGetCharacters (cfString, range, u);
  224086. u[range.length] = 0;
  224087. result = convertUTF16ToString (u);
  224088. }
  224089. return result;
  224090. }
  224091. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224092. {
  224093. const int len = s.length();
  224094. HeapBlock <UniChar> temp (len + 2);
  224095. for (int i = 0; i <= len; ++i)
  224096. temp[i] = s[i];
  224097. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224098. }
  224099. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224100. {
  224101. #if JUCE_IOS
  224102. const ScopedAutoReleasePool pool;
  224103. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224104. #else
  224105. UnicodeMapping map;
  224106. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224107. kUnicodeNoSubset,
  224108. kTextEncodingDefaultFormat);
  224109. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224110. kUnicodeCanonicalCompVariant,
  224111. kTextEncodingDefaultFormat);
  224112. map.mappingVersion = kUnicodeUseLatestMapping;
  224113. UnicodeToTextInfo conversionInfo = 0;
  224114. String result;
  224115. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224116. {
  224117. const int len = s.length();
  224118. HeapBlock <UniChar> tempIn, tempOut;
  224119. tempIn.calloc (len + 2);
  224120. tempOut.calloc (len + 2);
  224121. for (int i = 0; i <= len; ++i)
  224122. tempIn[i] = s[i];
  224123. ByteCount bytesRead = 0;
  224124. ByteCount outputBufferSize = 0;
  224125. if (ConvertFromUnicodeToText (conversionInfo,
  224126. len * sizeof (UniChar), tempIn,
  224127. kUnicodeDefaultDirectionMask,
  224128. 0, 0, 0, 0,
  224129. len * sizeof (UniChar), &bytesRead,
  224130. &outputBufferSize, tempOut) == noErr)
  224131. {
  224132. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224133. juce_wchar* t = result;
  224134. unsigned int i;
  224135. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224136. t[i] = (juce_wchar) tempOut[i];
  224137. t[i] = 0;
  224138. }
  224139. DisposeUnicodeToTextInfo (&conversionInfo);
  224140. }
  224141. return result;
  224142. #endif
  224143. }
  224144. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224145. void SystemClipboard::copyTextToClipboard (const String& text)
  224146. {
  224147. #if JUCE_IOS
  224148. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224149. forPasteboardType: @"public.text"];
  224150. #else
  224151. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224152. owner: nil];
  224153. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224154. forType: NSStringPboardType];
  224155. #endif
  224156. }
  224157. const String SystemClipboard::getTextFromClipboard()
  224158. {
  224159. #if JUCE_IOS
  224160. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224161. #else
  224162. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224163. #endif
  224164. return text == 0 ? String::empty
  224165. : nsStringToJuce (text);
  224166. }
  224167. #endif
  224168. #endif
  224169. /*** End of inlined file: juce_mac_Strings.mm ***/
  224170. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224171. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224172. // compiled on its own).
  224173. #if JUCE_INCLUDED_FILE
  224174. namespace SystemStatsHelpers
  224175. {
  224176. static int64 highResTimerFrequency = 0;
  224177. static double highResTimerToMillisecRatio = 0;
  224178. #if JUCE_INTEL
  224179. static void juce_getCpuVendor (char* const v) throw()
  224180. {
  224181. int vendor[4];
  224182. zerostruct (vendor);
  224183. int dummy = 0;
  224184. asm ("mov %%ebx, %%esi \n\t"
  224185. "cpuid \n\t"
  224186. "xchg %%esi, %%ebx"
  224187. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224188. memcpy (v, vendor, 16);
  224189. }
  224190. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224191. {
  224192. unsigned int cpu = 0;
  224193. unsigned int ext = 0;
  224194. unsigned int family = 0;
  224195. unsigned int dummy = 0;
  224196. asm ("mov %%ebx, %%esi \n\t"
  224197. "cpuid \n\t"
  224198. "xchg %%esi, %%ebx"
  224199. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224200. familyModel = family;
  224201. extFeatures = ext;
  224202. return cpu;
  224203. }
  224204. #endif
  224205. }
  224206. void SystemStats::initialiseStats()
  224207. {
  224208. using namespace SystemStatsHelpers;
  224209. static bool initialised = false;
  224210. if (! initialised)
  224211. {
  224212. initialised = true;
  224213. #if JUCE_MAC
  224214. [NSApplication sharedApplication];
  224215. #endif
  224216. #if JUCE_INTEL
  224217. unsigned int familyModel, extFeatures;
  224218. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224219. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224220. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224221. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224222. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224223. #else
  224224. cpuFlags.hasMMX = false;
  224225. cpuFlags.hasSSE = false;
  224226. cpuFlags.hasSSE2 = false;
  224227. cpuFlags.has3DNow = false;
  224228. #endif
  224229. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224230. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224231. #else
  224232. cpuFlags.numCpus = (int) MPProcessors();
  224233. #endif
  224234. mach_timebase_info_data_t timebase;
  224235. (void) mach_timebase_info (&timebase);
  224236. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224237. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224238. String s (SystemStats::getJUCEVersion());
  224239. rlimit lim;
  224240. getrlimit (RLIMIT_NOFILE, &lim);
  224241. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224242. setrlimit (RLIMIT_NOFILE, &lim);
  224243. }
  224244. }
  224245. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224246. {
  224247. return MacOSX;
  224248. }
  224249. const String SystemStats::getOperatingSystemName()
  224250. {
  224251. return "Mac OS X";
  224252. }
  224253. #if ! JUCE_IOS
  224254. int PlatformUtilities::getOSXMinorVersionNumber()
  224255. {
  224256. SInt32 versionMinor = 0;
  224257. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224258. (void) err;
  224259. jassert (err == noErr);
  224260. return (int) versionMinor;
  224261. }
  224262. #endif
  224263. bool SystemStats::isOperatingSystem64Bit()
  224264. {
  224265. #if JUCE_IOS
  224266. return false;
  224267. #elif JUCE_64BIT
  224268. return true;
  224269. #else
  224270. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224271. #endif
  224272. }
  224273. int SystemStats::getMemorySizeInMegabytes()
  224274. {
  224275. uint64 mem = 0;
  224276. size_t memSize = sizeof (mem);
  224277. int mib[] = { CTL_HW, HW_MEMSIZE };
  224278. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224279. return (int) (mem / (1024 * 1024));
  224280. }
  224281. const String SystemStats::getCpuVendor()
  224282. {
  224283. #if JUCE_INTEL
  224284. char v [16];
  224285. SystemStatsHelpers::juce_getCpuVendor (v);
  224286. return String (v, 16);
  224287. #else
  224288. return String::empty;
  224289. #endif
  224290. }
  224291. int SystemStats::getCpuSpeedInMegaherz()
  224292. {
  224293. uint64 speedHz = 0;
  224294. size_t speedSize = sizeof (speedHz);
  224295. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224296. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224297. #if JUCE_BIG_ENDIAN
  224298. if (speedSize == 4)
  224299. speedHz >>= 32;
  224300. #endif
  224301. return (int) (speedHz / 1000000);
  224302. }
  224303. const String SystemStats::getLogonName()
  224304. {
  224305. return nsStringToJuce (NSUserName());
  224306. }
  224307. const String SystemStats::getFullUserName()
  224308. {
  224309. return nsStringToJuce (NSFullUserName());
  224310. }
  224311. uint32 juce_millisecondsSinceStartup() throw()
  224312. {
  224313. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224314. }
  224315. double Time::getMillisecondCounterHiRes() throw()
  224316. {
  224317. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224318. }
  224319. int64 Time::getHighResolutionTicks() throw()
  224320. {
  224321. return (int64) mach_absolute_time();
  224322. }
  224323. int64 Time::getHighResolutionTicksPerSecond() throw()
  224324. {
  224325. return SystemStatsHelpers::highResTimerFrequency;
  224326. }
  224327. bool Time::setSystemTimeToThisTime() const
  224328. {
  224329. jassertfalse;
  224330. return false;
  224331. }
  224332. int SystemStats::getPageSize()
  224333. {
  224334. return (int) NSPageSize();
  224335. }
  224336. void PlatformUtilities::fpuReset()
  224337. {
  224338. }
  224339. #endif
  224340. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224341. /*** Start of inlined file: juce_mac_Network.mm ***/
  224342. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224343. // compiled on its own).
  224344. #if JUCE_INCLUDED_FILE
  224345. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  224346. {
  224347. ifaddrs* addrs = 0;
  224348. if (getifaddrs (&addrs) == 0)
  224349. {
  224350. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  224351. {
  224352. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224353. if (sto->ss_family == AF_LINK)
  224354. {
  224355. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224356. #ifndef IFT_ETHER
  224357. #define IFT_ETHER 6
  224358. #endif
  224359. if (sadd->sdl_type == IFT_ETHER)
  224360. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  224361. }
  224362. }
  224363. freeifaddrs (addrs);
  224364. }
  224365. }
  224366. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224367. const String& emailSubject,
  224368. const String& bodyText,
  224369. const StringArray& filesToAttach)
  224370. {
  224371. #if JUCE_IOS
  224372. //xxx probably need to use MFMailComposeViewController
  224373. jassertfalse;
  224374. return false;
  224375. #else
  224376. const ScopedAutoReleasePool pool;
  224377. String script;
  224378. script << "tell application \"Mail\"\r\n"
  224379. "set newMessage to make new outgoing message with properties {subject:\""
  224380. << emailSubject.replace ("\"", "\\\"")
  224381. << "\", content:\""
  224382. << bodyText.replace ("\"", "\\\"")
  224383. << "\" & return & return}\r\n"
  224384. "tell newMessage\r\n"
  224385. "set visible to true\r\n"
  224386. "set sender to \"sdfsdfsdfewf\"\r\n"
  224387. "make new to recipient at end of to recipients with properties {address:\""
  224388. << targetEmailAddress
  224389. << "\"}\r\n";
  224390. for (int i = 0; i < filesToAttach.size(); ++i)
  224391. {
  224392. script << "tell content\r\n"
  224393. "make new attachment with properties {file name:\""
  224394. << filesToAttach[i].replace ("\"", "\\\"")
  224395. << "\"} at after the last paragraph\r\n"
  224396. "end tell\r\n";
  224397. }
  224398. script << "end tell\r\n"
  224399. "end tell\r\n";
  224400. NSAppleScript* s = [[NSAppleScript alloc]
  224401. initWithSource: juceStringToNS (script)];
  224402. NSDictionary* error = 0;
  224403. const bool ok = [s executeAndReturnError: &error] != nil;
  224404. [s release];
  224405. return ok;
  224406. #endif
  224407. }
  224408. END_JUCE_NAMESPACE
  224409. using namespace JUCE_NAMESPACE;
  224410. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224411. @interface JuceURLConnection : NSObject
  224412. {
  224413. @public
  224414. NSURLRequest* request;
  224415. NSURLConnection* connection;
  224416. NSMutableData* data;
  224417. Thread* runLoopThread;
  224418. bool initialised, hasFailed, hasFinished;
  224419. int position;
  224420. int64 contentLength;
  224421. NSDictionary* headers;
  224422. NSLock* dataLock;
  224423. }
  224424. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224425. - (void) dealloc;
  224426. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224427. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224428. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224429. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224430. - (BOOL) isOpen;
  224431. - (int) read: (char*) dest numBytes: (int) num;
  224432. - (int) readPosition;
  224433. - (void) stop;
  224434. - (void) createConnection;
  224435. @end
  224436. class JuceURLConnectionMessageThread : public Thread
  224437. {
  224438. JuceURLConnection* owner;
  224439. public:
  224440. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224441. : Thread ("http connection"),
  224442. owner (owner_)
  224443. {
  224444. }
  224445. ~JuceURLConnectionMessageThread()
  224446. {
  224447. stopThread (10000);
  224448. }
  224449. void run()
  224450. {
  224451. [owner createConnection];
  224452. while (! threadShouldExit())
  224453. {
  224454. const ScopedAutoReleasePool pool;
  224455. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224456. }
  224457. }
  224458. };
  224459. @implementation JuceURLConnection
  224460. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224461. withCallback: (URL::OpenStreamProgressCallback*) callback
  224462. withContext: (void*) context;
  224463. {
  224464. [super init];
  224465. request = req;
  224466. [request retain];
  224467. data = [[NSMutableData data] retain];
  224468. dataLock = [[NSLock alloc] init];
  224469. connection = 0;
  224470. initialised = false;
  224471. hasFailed = false;
  224472. hasFinished = false;
  224473. contentLength = -1;
  224474. headers = 0;
  224475. runLoopThread = new JuceURLConnectionMessageThread (self);
  224476. runLoopThread->startThread();
  224477. while (runLoopThread->isThreadRunning() && ! initialised)
  224478. {
  224479. if (callback != 0)
  224480. callback (context, -1, (int) [[request HTTPBody] length]);
  224481. Thread::sleep (1);
  224482. }
  224483. return self;
  224484. }
  224485. - (void) dealloc
  224486. {
  224487. [self stop];
  224488. deleteAndZero (runLoopThread);
  224489. [connection release];
  224490. [data release];
  224491. [dataLock release];
  224492. [request release];
  224493. [headers release];
  224494. [super dealloc];
  224495. }
  224496. - (void) createConnection
  224497. {
  224498. NSUInteger oldRetainCount = [self retainCount];
  224499. connection = [[NSURLConnection alloc] initWithRequest: request
  224500. delegate: self];
  224501. if (oldRetainCount == [self retainCount])
  224502. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224503. if (connection == nil)
  224504. runLoopThread->signalThreadShouldExit();
  224505. }
  224506. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224507. {
  224508. (void) conn;
  224509. [dataLock lock];
  224510. [data setLength: 0];
  224511. [dataLock unlock];
  224512. initialised = true;
  224513. contentLength = [response expectedContentLength];
  224514. [headers release];
  224515. headers = 0;
  224516. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224517. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224518. }
  224519. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224520. {
  224521. (void) conn;
  224522. DBG (nsStringToJuce ([error description]));
  224523. hasFailed = true;
  224524. initialised = true;
  224525. if (runLoopThread != 0)
  224526. runLoopThread->signalThreadShouldExit();
  224527. }
  224528. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224529. {
  224530. (void) conn;
  224531. [dataLock lock];
  224532. [data appendData: newData];
  224533. [dataLock unlock];
  224534. initialised = true;
  224535. }
  224536. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224537. {
  224538. (void) conn;
  224539. hasFinished = true;
  224540. initialised = true;
  224541. if (runLoopThread != 0)
  224542. runLoopThread->signalThreadShouldExit();
  224543. }
  224544. - (BOOL) isOpen
  224545. {
  224546. return connection != 0 && ! hasFailed;
  224547. }
  224548. - (int) readPosition
  224549. {
  224550. return position;
  224551. }
  224552. - (int) read: (char*) dest numBytes: (int) numNeeded
  224553. {
  224554. int numDone = 0;
  224555. while (numNeeded > 0)
  224556. {
  224557. int available = jmin (numNeeded, (int) [data length]);
  224558. if (available > 0)
  224559. {
  224560. [dataLock lock];
  224561. [data getBytes: dest length: available];
  224562. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224563. [dataLock unlock];
  224564. numDone += available;
  224565. numNeeded -= available;
  224566. dest += available;
  224567. }
  224568. else
  224569. {
  224570. if (hasFailed || hasFinished)
  224571. break;
  224572. Thread::sleep (1);
  224573. }
  224574. }
  224575. position += numDone;
  224576. return numDone;
  224577. }
  224578. - (void) stop
  224579. {
  224580. [connection cancel];
  224581. if (runLoopThread != 0)
  224582. runLoopThread->stopThread (10000);
  224583. }
  224584. @end
  224585. BEGIN_JUCE_NAMESPACE
  224586. void* juce_openInternetFile (const String& url,
  224587. const String& headers,
  224588. const MemoryBlock& postData,
  224589. const bool isPost,
  224590. URL::OpenStreamProgressCallback* callback,
  224591. void* callbackContext,
  224592. int timeOutMs)
  224593. {
  224594. const ScopedAutoReleasePool pool;
  224595. NSMutableURLRequest* req = [NSMutableURLRequest
  224596. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224597. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224598. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224599. if (req == nil)
  224600. return 0;
  224601. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224602. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224603. StringArray headerLines;
  224604. headerLines.addLines (headers);
  224605. headerLines.removeEmptyStrings (true);
  224606. for (int i = 0; i < headerLines.size(); ++i)
  224607. {
  224608. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224609. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224610. if (key.isNotEmpty() && value.isNotEmpty())
  224611. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224612. }
  224613. if (isPost && postData.getSize() > 0)
  224614. {
  224615. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224616. length: postData.getSize()]];
  224617. }
  224618. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224619. withCallback: callback
  224620. withContext: callbackContext];
  224621. if ([s isOpen])
  224622. return s;
  224623. [s release];
  224624. return 0;
  224625. }
  224626. void juce_closeInternetFile (void* handle)
  224627. {
  224628. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224629. if (s != 0)
  224630. {
  224631. const ScopedAutoReleasePool pool;
  224632. [s stop];
  224633. [s release];
  224634. }
  224635. }
  224636. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224637. {
  224638. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224639. if (s != 0)
  224640. {
  224641. const ScopedAutoReleasePool pool;
  224642. return [s read: (char*) buffer numBytes: bytesToRead];
  224643. }
  224644. return 0;
  224645. }
  224646. int64 juce_getInternetFileContentLength (void* handle)
  224647. {
  224648. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224649. if (s != 0)
  224650. return s->contentLength;
  224651. return -1;
  224652. }
  224653. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224654. {
  224655. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224656. if (s != 0 && s->headers != 0)
  224657. {
  224658. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224659. NSString* key;
  224660. while ((key = [enumerator nextObject]) != nil)
  224661. headers.set (nsStringToJuce (key),
  224662. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224663. }
  224664. }
  224665. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224666. {
  224667. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224668. if (s != 0)
  224669. return [s readPosition];
  224670. return 0;
  224671. }
  224672. #endif
  224673. /*** End of inlined file: juce_mac_Network.mm ***/
  224674. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224675. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224676. // compiled on its own).
  224677. #if JUCE_INCLUDED_FILE
  224678. struct NamedPipeInternal
  224679. {
  224680. String pipeInName, pipeOutName;
  224681. int pipeIn, pipeOut;
  224682. bool volatile createdPipe, blocked, stopReadOperation;
  224683. static void signalHandler (int) {}
  224684. };
  224685. void NamedPipe::cancelPendingReads()
  224686. {
  224687. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224688. {
  224689. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224690. intern->stopReadOperation = true;
  224691. char buffer [1] = { 0 };
  224692. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224693. (void) bytesWritten;
  224694. int timeout = 2000;
  224695. while (intern->blocked && --timeout >= 0)
  224696. Thread::sleep (2);
  224697. intern->stopReadOperation = false;
  224698. }
  224699. }
  224700. void NamedPipe::close()
  224701. {
  224702. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224703. if (intern != 0)
  224704. {
  224705. internal = 0;
  224706. if (intern->pipeIn != -1)
  224707. ::close (intern->pipeIn);
  224708. if (intern->pipeOut != -1)
  224709. ::close (intern->pipeOut);
  224710. if (intern->createdPipe)
  224711. {
  224712. unlink (intern->pipeInName.toUTF8());
  224713. unlink (intern->pipeOutName.toUTF8());
  224714. }
  224715. delete intern;
  224716. }
  224717. }
  224718. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224719. {
  224720. close();
  224721. NamedPipeInternal* const intern = new NamedPipeInternal();
  224722. internal = intern;
  224723. intern->createdPipe = createPipe;
  224724. intern->blocked = false;
  224725. intern->stopReadOperation = false;
  224726. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224727. siginterrupt (SIGPIPE, 1);
  224728. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224729. intern->pipeInName = pipePath + "_in";
  224730. intern->pipeOutName = pipePath + "_out";
  224731. intern->pipeIn = -1;
  224732. intern->pipeOut = -1;
  224733. if (createPipe)
  224734. {
  224735. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224736. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224737. {
  224738. delete intern;
  224739. internal = 0;
  224740. return false;
  224741. }
  224742. }
  224743. return true;
  224744. }
  224745. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224746. {
  224747. int bytesRead = -1;
  224748. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224749. if (intern != 0)
  224750. {
  224751. intern->blocked = true;
  224752. if (intern->pipeIn == -1)
  224753. {
  224754. if (intern->createdPipe)
  224755. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224756. else
  224757. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224758. if (intern->pipeIn == -1)
  224759. {
  224760. intern->blocked = false;
  224761. return -1;
  224762. }
  224763. }
  224764. bytesRead = 0;
  224765. char* p = static_cast<char*> (destBuffer);
  224766. while (bytesRead < maxBytesToRead)
  224767. {
  224768. const int bytesThisTime = maxBytesToRead - bytesRead;
  224769. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224770. if (numRead <= 0 || intern->stopReadOperation)
  224771. {
  224772. bytesRead = -1;
  224773. break;
  224774. }
  224775. bytesRead += numRead;
  224776. p += bytesRead;
  224777. }
  224778. intern->blocked = false;
  224779. }
  224780. return bytesRead;
  224781. }
  224782. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224783. {
  224784. int bytesWritten = -1;
  224785. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224786. if (intern != 0)
  224787. {
  224788. if (intern->pipeOut == -1)
  224789. {
  224790. if (intern->createdPipe)
  224791. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224792. else
  224793. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224794. if (intern->pipeOut == -1)
  224795. {
  224796. return -1;
  224797. }
  224798. }
  224799. const char* p = static_cast<const char*> (sourceBuffer);
  224800. bytesWritten = 0;
  224801. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224802. while (bytesWritten < numBytesToWrite
  224803. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224804. {
  224805. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224806. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224807. if (numWritten <= 0)
  224808. {
  224809. bytesWritten = -1;
  224810. break;
  224811. }
  224812. bytesWritten += numWritten;
  224813. p += bytesWritten;
  224814. }
  224815. }
  224816. return bytesWritten;
  224817. }
  224818. #endif
  224819. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224820. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224821. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224822. // compiled on its own).
  224823. #if JUCE_INCLUDED_FILE
  224824. /*
  224825. Note that a lot of methods that you'd expect to find in this file actually
  224826. live in juce_posix_SharedCode.h!
  224827. */
  224828. bool Process::isForegroundProcess()
  224829. {
  224830. #if JUCE_MAC
  224831. return [NSApp isActive];
  224832. #else
  224833. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224834. #endif
  224835. }
  224836. void Process::raisePrivilege()
  224837. {
  224838. jassertfalse;
  224839. }
  224840. void Process::lowerPrivilege()
  224841. {
  224842. jassertfalse;
  224843. }
  224844. void Process::terminate()
  224845. {
  224846. exit (0);
  224847. }
  224848. void Process::setPriority (ProcessPriority)
  224849. {
  224850. // xxx
  224851. }
  224852. #endif
  224853. /*** End of inlined file: juce_mac_Threads.mm ***/
  224854. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224855. /*
  224856. This file contains posix routines that are common to both the Linux and Mac builds.
  224857. It gets included directly in the cpp files for these platforms.
  224858. */
  224859. CriticalSection::CriticalSection() throw()
  224860. {
  224861. pthread_mutexattr_t atts;
  224862. pthread_mutexattr_init (&atts);
  224863. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224864. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224865. pthread_mutex_init (&internal, &atts);
  224866. }
  224867. CriticalSection::~CriticalSection() throw()
  224868. {
  224869. pthread_mutex_destroy (&internal);
  224870. }
  224871. void CriticalSection::enter() const throw()
  224872. {
  224873. pthread_mutex_lock (&internal);
  224874. }
  224875. bool CriticalSection::tryEnter() const throw()
  224876. {
  224877. return pthread_mutex_trylock (&internal) == 0;
  224878. }
  224879. void CriticalSection::exit() const throw()
  224880. {
  224881. pthread_mutex_unlock (&internal);
  224882. }
  224883. class WaitableEventImpl
  224884. {
  224885. public:
  224886. WaitableEventImpl (const bool manualReset_)
  224887. : triggered (false),
  224888. manualReset (manualReset_)
  224889. {
  224890. pthread_cond_init (&condition, 0);
  224891. pthread_mutexattr_t atts;
  224892. pthread_mutexattr_init (&atts);
  224893. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224894. pthread_mutex_init (&mutex, &atts);
  224895. }
  224896. ~WaitableEventImpl()
  224897. {
  224898. pthread_cond_destroy (&condition);
  224899. pthread_mutex_destroy (&mutex);
  224900. }
  224901. bool wait (const int timeOutMillisecs) throw()
  224902. {
  224903. pthread_mutex_lock (&mutex);
  224904. if (! triggered)
  224905. {
  224906. if (timeOutMillisecs < 0)
  224907. {
  224908. do
  224909. {
  224910. pthread_cond_wait (&condition, &mutex);
  224911. }
  224912. while (! triggered);
  224913. }
  224914. else
  224915. {
  224916. struct timeval now;
  224917. gettimeofday (&now, 0);
  224918. struct timespec time;
  224919. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224920. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224921. if (time.tv_nsec >= 1000000000)
  224922. {
  224923. time.tv_nsec -= 1000000000;
  224924. time.tv_sec++;
  224925. }
  224926. do
  224927. {
  224928. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224929. {
  224930. pthread_mutex_unlock (&mutex);
  224931. return false;
  224932. }
  224933. }
  224934. while (! triggered);
  224935. }
  224936. }
  224937. if (! manualReset)
  224938. triggered = false;
  224939. pthread_mutex_unlock (&mutex);
  224940. return true;
  224941. }
  224942. void signal() throw()
  224943. {
  224944. pthread_mutex_lock (&mutex);
  224945. triggered = true;
  224946. pthread_cond_broadcast (&condition);
  224947. pthread_mutex_unlock (&mutex);
  224948. }
  224949. void reset() throw()
  224950. {
  224951. pthread_mutex_lock (&mutex);
  224952. triggered = false;
  224953. pthread_mutex_unlock (&mutex);
  224954. }
  224955. private:
  224956. pthread_cond_t condition;
  224957. pthread_mutex_t mutex;
  224958. bool triggered;
  224959. const bool manualReset;
  224960. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224961. };
  224962. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224963. : internal (new WaitableEventImpl (manualReset))
  224964. {
  224965. }
  224966. WaitableEvent::~WaitableEvent() throw()
  224967. {
  224968. delete static_cast <WaitableEventImpl*> (internal);
  224969. }
  224970. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224971. {
  224972. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224973. }
  224974. void WaitableEvent::signal() const throw()
  224975. {
  224976. static_cast <WaitableEventImpl*> (internal)->signal();
  224977. }
  224978. void WaitableEvent::reset() const throw()
  224979. {
  224980. static_cast <WaitableEventImpl*> (internal)->reset();
  224981. }
  224982. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224983. {
  224984. struct timespec time;
  224985. time.tv_sec = millisecs / 1000;
  224986. time.tv_nsec = (millisecs % 1000) * 1000000;
  224987. nanosleep (&time, 0);
  224988. }
  224989. const juce_wchar File::separator = '/';
  224990. const String File::separatorString ("/");
  224991. const File File::getCurrentWorkingDirectory()
  224992. {
  224993. HeapBlock<char> heapBuffer;
  224994. char localBuffer [1024];
  224995. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224996. int bufferSize = 4096;
  224997. while (cwd == 0 && errno == ERANGE)
  224998. {
  224999. heapBuffer.malloc (bufferSize);
  225000. cwd = getcwd (heapBuffer, bufferSize - 1);
  225001. bufferSize += 1024;
  225002. }
  225003. return File (String::fromUTF8 (cwd));
  225004. }
  225005. bool File::setAsCurrentWorkingDirectory() const
  225006. {
  225007. return chdir (getFullPathName().toUTF8()) == 0;
  225008. }
  225009. namespace
  225010. {
  225011. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225012. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  225013. #else
  225014. typedef struct stat juce_statStruct;
  225015. #endif
  225016. bool juce_stat (const String& fileName, juce_statStruct& info)
  225017. {
  225018. return fileName.isNotEmpty()
  225019. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225020. && (stat64 (fileName.toUTF8(), &info) == 0);
  225021. #else
  225022. && (stat (fileName.toUTF8(), &info) == 0);
  225023. #endif
  225024. }
  225025. // if this file doesn't exist, find a parent of it that does..
  225026. bool juce_doStatFS (File f, struct statfs& result)
  225027. {
  225028. for (int i = 5; --i >= 0;)
  225029. {
  225030. if (f.exists())
  225031. break;
  225032. f = f.getParentDirectory();
  225033. }
  225034. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225035. }
  225036. }
  225037. bool File::isDirectory() const
  225038. {
  225039. juce_statStruct info;
  225040. return fullPath.isEmpty()
  225041. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  225042. }
  225043. bool File::exists() const
  225044. {
  225045. juce_statStruct info;
  225046. return fullPath.isNotEmpty()
  225047. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225048. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  225049. #else
  225050. && (lstat (fullPath.toUTF8(), &info) == 0);
  225051. #endif
  225052. }
  225053. bool File::existsAsFile() const
  225054. {
  225055. return exists() && ! isDirectory();
  225056. }
  225057. int64 File::getSize() const
  225058. {
  225059. juce_statStruct info;
  225060. return juce_stat (fullPath, info) ? info.st_size : 0;
  225061. }
  225062. bool File::hasWriteAccess() const
  225063. {
  225064. if (exists())
  225065. return access (fullPath.toUTF8(), W_OK) == 0;
  225066. if ((! isDirectory()) && fullPath.containsChar (separator))
  225067. return getParentDirectory().hasWriteAccess();
  225068. return false;
  225069. }
  225070. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225071. {
  225072. juce_statStruct info;
  225073. if (! juce_stat (fullPath, info))
  225074. return false;
  225075. info.st_mode &= 0777; // Just permissions
  225076. if (shouldBeReadOnly)
  225077. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225078. else
  225079. // Give everybody write permission?
  225080. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225081. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225082. }
  225083. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225084. {
  225085. modificationTime = 0;
  225086. accessTime = 0;
  225087. creationTime = 0;
  225088. juce_statStruct info;
  225089. if (juce_stat (fullPath, info))
  225090. {
  225091. modificationTime = (int64) info.st_mtime * 1000;
  225092. accessTime = (int64) info.st_atime * 1000;
  225093. creationTime = (int64) info.st_ctime * 1000;
  225094. }
  225095. }
  225096. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225097. {
  225098. struct utimbuf times;
  225099. times.actime = (time_t) (accessTime / 1000);
  225100. times.modtime = (time_t) (modificationTime / 1000);
  225101. return utime (fullPath.toUTF8(), &times) == 0;
  225102. }
  225103. bool File::deleteFile() const
  225104. {
  225105. if (! exists())
  225106. return true;
  225107. else if (isDirectory())
  225108. return rmdir (fullPath.toUTF8()) == 0;
  225109. else
  225110. return remove (fullPath.toUTF8()) == 0;
  225111. }
  225112. bool File::moveInternal (const File& dest) const
  225113. {
  225114. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225115. return true;
  225116. if (hasWriteAccess() && copyInternal (dest))
  225117. {
  225118. if (deleteFile())
  225119. return true;
  225120. dest.deleteFile();
  225121. }
  225122. return false;
  225123. }
  225124. void File::createDirectoryInternal (const String& fileName) const
  225125. {
  225126. mkdir (fileName.toUTF8(), 0777);
  225127. }
  225128. int64 juce_fileSetPosition (void* handle, int64 pos)
  225129. {
  225130. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225131. return pos;
  225132. return -1;
  225133. }
  225134. void FileInputStream::openHandle()
  225135. {
  225136. totalSize = file.getSize();
  225137. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225138. if (f != -1)
  225139. fileHandle = (void*) f;
  225140. }
  225141. void FileInputStream::closeHandle()
  225142. {
  225143. if (fileHandle != 0)
  225144. {
  225145. close ((int) (pointer_sized_int) fileHandle);
  225146. fileHandle = 0;
  225147. }
  225148. }
  225149. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225150. {
  225151. if (fileHandle != 0)
  225152. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225153. return 0;
  225154. }
  225155. void FileOutputStream::openHandle()
  225156. {
  225157. if (file.exists())
  225158. {
  225159. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225160. if (f != -1)
  225161. {
  225162. currentPosition = lseek (f, 0, SEEK_END);
  225163. if (currentPosition >= 0)
  225164. fileHandle = (void*) f;
  225165. else
  225166. close (f);
  225167. }
  225168. }
  225169. else
  225170. {
  225171. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225172. if (f != -1)
  225173. fileHandle = (void*) f;
  225174. }
  225175. }
  225176. void FileOutputStream::closeHandle()
  225177. {
  225178. if (fileHandle != 0)
  225179. {
  225180. close ((int) (pointer_sized_int) fileHandle);
  225181. fileHandle = 0;
  225182. }
  225183. }
  225184. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225185. {
  225186. if (fileHandle != 0)
  225187. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225188. return 0;
  225189. }
  225190. void FileOutputStream::flushInternal()
  225191. {
  225192. if (fileHandle != 0)
  225193. fsync ((int) (pointer_sized_int) fileHandle);
  225194. }
  225195. const File juce_getExecutableFile()
  225196. {
  225197. Dl_info exeInfo;
  225198. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225199. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225200. }
  225201. int64 File::getBytesFreeOnVolume() const
  225202. {
  225203. struct statfs buf;
  225204. if (juce_doStatFS (*this, buf))
  225205. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225206. return 0;
  225207. }
  225208. int64 File::getVolumeTotalSize() const
  225209. {
  225210. struct statfs buf;
  225211. if (juce_doStatFS (*this, buf))
  225212. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225213. return 0;
  225214. }
  225215. const String File::getVolumeLabel() const
  225216. {
  225217. #if JUCE_MAC
  225218. struct VolAttrBuf
  225219. {
  225220. u_int32_t length;
  225221. attrreference_t mountPointRef;
  225222. char mountPointSpace [MAXPATHLEN];
  225223. } attrBuf;
  225224. struct attrlist attrList;
  225225. zerostruct (attrList);
  225226. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225227. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225228. File f (*this);
  225229. for (;;)
  225230. {
  225231. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225232. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225233. (int) attrBuf.mountPointRef.attr_length);
  225234. const File parent (f.getParentDirectory());
  225235. if (f == parent)
  225236. break;
  225237. f = parent;
  225238. }
  225239. #endif
  225240. return String::empty;
  225241. }
  225242. int File::getVolumeSerialNumber() const
  225243. {
  225244. return 0; // xxx
  225245. }
  225246. void juce_runSystemCommand (const String& command)
  225247. {
  225248. int result = system (command.toUTF8());
  225249. (void) result;
  225250. }
  225251. const String juce_getOutputFromCommand (const String& command)
  225252. {
  225253. // slight bodge here, as we just pipe the output into a temp file and read it...
  225254. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225255. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225256. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225257. String result (tempFile.loadFileAsString());
  225258. tempFile.deleteFile();
  225259. return result;
  225260. }
  225261. class InterProcessLock::Pimpl
  225262. {
  225263. public:
  225264. Pimpl (const String& name, const int timeOutMillisecs)
  225265. : handle (0), refCount (1)
  225266. {
  225267. #if JUCE_MAC
  225268. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225269. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225270. #else
  225271. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225272. #endif
  225273. temp.create();
  225274. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225275. if (handle != 0)
  225276. {
  225277. struct flock fl;
  225278. zerostruct (fl);
  225279. fl.l_whence = SEEK_SET;
  225280. fl.l_type = F_WRLCK;
  225281. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225282. for (;;)
  225283. {
  225284. const int result = fcntl (handle, F_SETLK, &fl);
  225285. if (result >= 0)
  225286. return;
  225287. if (errno != EINTR)
  225288. {
  225289. if (timeOutMillisecs == 0
  225290. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225291. break;
  225292. Thread::sleep (10);
  225293. }
  225294. }
  225295. }
  225296. closeFile();
  225297. }
  225298. ~Pimpl()
  225299. {
  225300. closeFile();
  225301. }
  225302. void closeFile()
  225303. {
  225304. if (handle != 0)
  225305. {
  225306. struct flock fl;
  225307. zerostruct (fl);
  225308. fl.l_whence = SEEK_SET;
  225309. fl.l_type = F_UNLCK;
  225310. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225311. {}
  225312. close (handle);
  225313. handle = 0;
  225314. }
  225315. }
  225316. int handle, refCount;
  225317. };
  225318. InterProcessLock::InterProcessLock (const String& name_)
  225319. : name (name_)
  225320. {
  225321. }
  225322. InterProcessLock::~InterProcessLock()
  225323. {
  225324. }
  225325. bool InterProcessLock::enter (const int timeOutMillisecs)
  225326. {
  225327. const ScopedLock sl (lock);
  225328. if (pimpl == 0)
  225329. {
  225330. pimpl = new Pimpl (name, timeOutMillisecs);
  225331. if (pimpl->handle == 0)
  225332. pimpl = 0;
  225333. }
  225334. else
  225335. {
  225336. pimpl->refCount++;
  225337. }
  225338. return pimpl != 0;
  225339. }
  225340. void InterProcessLock::exit()
  225341. {
  225342. const ScopedLock sl (lock);
  225343. // Trying to release the lock too many times!
  225344. jassert (pimpl != 0);
  225345. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225346. pimpl = 0;
  225347. }
  225348. void JUCE_API juce_threadEntryPoint (void*);
  225349. void* threadEntryProc (void* userData)
  225350. {
  225351. JUCE_AUTORELEASEPOOL
  225352. juce_threadEntryPoint (userData);
  225353. return 0;
  225354. }
  225355. void* juce_createThread (void* userData)
  225356. {
  225357. pthread_t handle = 0;
  225358. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225359. {
  225360. pthread_detach (handle);
  225361. return (void*) handle;
  225362. }
  225363. return 0;
  225364. }
  225365. void juce_killThread (void* handle)
  225366. {
  225367. if (handle != 0)
  225368. pthread_cancel ((pthread_t) handle);
  225369. }
  225370. void juce_setCurrentThreadName (const String& /*name*/)
  225371. {
  225372. }
  225373. bool juce_setThreadPriority (void* handle, int priority)
  225374. {
  225375. struct sched_param param;
  225376. int policy;
  225377. priority = jlimit (0, 10, priority);
  225378. if (handle == 0)
  225379. handle = (void*) pthread_self();
  225380. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225381. return false;
  225382. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225383. const int minPriority = sched_get_priority_min (policy);
  225384. const int maxPriority = sched_get_priority_max (policy);
  225385. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225386. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225387. }
  225388. Thread::ThreadID Thread::getCurrentThreadId()
  225389. {
  225390. return (ThreadID) pthread_self();
  225391. }
  225392. void Thread::yield()
  225393. {
  225394. sched_yield();
  225395. }
  225396. /* Remove this macro if you're having problems compiling the cpu affinity
  225397. calls (the API for these has changed about quite a bit in various Linux
  225398. versions, and a lot of distros seem to ship with obsolete versions)
  225399. */
  225400. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225401. #define SUPPORT_AFFINITIES 1
  225402. #endif
  225403. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225404. {
  225405. #if SUPPORT_AFFINITIES
  225406. cpu_set_t affinity;
  225407. CPU_ZERO (&affinity);
  225408. for (int i = 0; i < 32; ++i)
  225409. if ((affinityMask & (1 << i)) != 0)
  225410. CPU_SET (i, &affinity);
  225411. /*
  225412. N.B. If this line causes a compile error, then you've probably not got the latest
  225413. version of glibc installed.
  225414. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225415. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225416. */
  225417. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225418. sched_yield();
  225419. #else
  225420. /* affinities aren't supported because either the appropriate header files weren't found,
  225421. or the SUPPORT_AFFINITIES macro was turned off
  225422. */
  225423. jassertfalse;
  225424. #endif
  225425. }
  225426. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225427. /*** Start of inlined file: juce_mac_Files.mm ***/
  225428. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225429. // compiled on its own).
  225430. #if JUCE_INCLUDED_FILE
  225431. /*
  225432. Note that a lot of methods that you'd expect to find in this file actually
  225433. live in juce_posix_SharedCode.h!
  225434. */
  225435. bool File::copyInternal (const File& dest) const
  225436. {
  225437. const ScopedAutoReleasePool pool;
  225438. NSFileManager* fm = [NSFileManager defaultManager];
  225439. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225440. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225441. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225442. toPath: juceStringToNS (dest.getFullPathName())
  225443. error: nil];
  225444. #else
  225445. && [fm copyPath: juceStringToNS (fullPath)
  225446. toPath: juceStringToNS (dest.getFullPathName())
  225447. handler: nil];
  225448. #endif
  225449. }
  225450. void File::findFileSystemRoots (Array<File>& destArray)
  225451. {
  225452. destArray.add (File ("/"));
  225453. }
  225454. namespace
  225455. {
  225456. bool isFileOnDriveType (const File& f, const char* const* types)
  225457. {
  225458. struct statfs buf;
  225459. if (juce_doStatFS (f, buf))
  225460. {
  225461. const String type (buf.f_fstypename);
  225462. while (*types != 0)
  225463. if (type.equalsIgnoreCase (*types++))
  225464. return true;
  225465. }
  225466. return false;
  225467. }
  225468. bool juce_isHiddenFile (const String& path)
  225469. {
  225470. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225471. const ScopedAutoReleasePool pool;
  225472. NSNumber* hidden = nil;
  225473. NSError* err = nil;
  225474. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225475. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225476. && [hidden boolValue];
  225477. #else
  225478. #if JUCE_IOS
  225479. return File (path).getFileName().startsWithChar ('.');
  225480. #else
  225481. FSRef ref;
  225482. LSItemInfoRecord info;
  225483. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225484. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225485. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225486. #endif
  225487. #endif
  225488. }
  225489. #if JUCE_IOS
  225490. const String getIOSSystemLocation (NSSearchPathDirectory type)
  225491. {
  225492. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  225493. objectAtIndex: 0]);
  225494. }
  225495. #endif
  225496. }
  225497. bool File::isOnCDRomDrive() const
  225498. {
  225499. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225500. return isFileOnDriveType (*this, cdTypes);
  225501. }
  225502. bool File::isOnHardDisk() const
  225503. {
  225504. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225505. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225506. }
  225507. bool File::isOnRemovableDrive() const
  225508. {
  225509. #if JUCE_IOS
  225510. return false; // xxx is this possible?
  225511. #else
  225512. const ScopedAutoReleasePool pool;
  225513. BOOL removable = false;
  225514. [[NSWorkspace sharedWorkspace]
  225515. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225516. isRemovable: &removable
  225517. isWritable: nil
  225518. isUnmountable: nil
  225519. description: nil
  225520. type: nil];
  225521. return removable;
  225522. #endif
  225523. }
  225524. bool File::isHidden() const
  225525. {
  225526. return juce_isHiddenFile (getFullPathName());
  225527. }
  225528. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225529. const File File::getSpecialLocation (const SpecialLocationType type)
  225530. {
  225531. const ScopedAutoReleasePool pool;
  225532. String resultPath;
  225533. switch (type)
  225534. {
  225535. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225536. #if JUCE_IOS
  225537. case userDocumentsDirectory: resultPath = getIOSSystemLocation (NSDocumentDirectory); break;
  225538. case userDesktopDirectory: resultPath = getIOSSystemLocation (NSDesktopDirectory); break;
  225539. case tempDirectory:
  225540. {
  225541. File tmp (getIOSSystemLocation (NSCachesDirectory));
  225542. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  225543. tmp.createDirectory();
  225544. return tmp.getFullPathName();
  225545. }
  225546. #else
  225547. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225548. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225549. case tempDirectory:
  225550. {
  225551. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225552. tmp.createDirectory();
  225553. return tmp.getFullPathName();
  225554. }
  225555. #endif
  225556. case userMusicDirectory: resultPath = "~/Music"; break;
  225557. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225558. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225559. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225560. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225561. case invokedExecutableFile:
  225562. if (juce_Argv0 != 0)
  225563. return File (String::fromUTF8 (juce_Argv0));
  225564. // deliberate fall-through...
  225565. case currentExecutableFile:
  225566. return juce_getExecutableFile();
  225567. case currentApplicationFile:
  225568. {
  225569. const File exe (juce_getExecutableFile());
  225570. const File parent (exe.getParentDirectory());
  225571. #if JUCE_IOS
  225572. return parent;
  225573. #else
  225574. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225575. ? parent.getParentDirectory().getParentDirectory()
  225576. : exe;
  225577. #endif
  225578. }
  225579. case hostApplicationPath:
  225580. {
  225581. unsigned int size = 8192;
  225582. HeapBlock<char> buffer;
  225583. buffer.calloc (size + 8);
  225584. _NSGetExecutablePath (buffer.getData(), &size);
  225585. return String::fromUTF8 (buffer, size);
  225586. }
  225587. default:
  225588. jassertfalse; // unknown type?
  225589. break;
  225590. }
  225591. if (resultPath.isNotEmpty())
  225592. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225593. return File::nonexistent;
  225594. }
  225595. const String File::getVersion() const
  225596. {
  225597. const ScopedAutoReleasePool pool;
  225598. String result;
  225599. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225600. if (bundle != 0)
  225601. {
  225602. NSDictionary* info = [bundle infoDictionary];
  225603. if (info != 0)
  225604. {
  225605. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225606. if (name != nil)
  225607. result = nsStringToJuce (name);
  225608. }
  225609. }
  225610. return result;
  225611. }
  225612. const File File::getLinkedTarget() const
  225613. {
  225614. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225615. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225616. #else
  225617. // (the cast here avoids a deprecation warning)
  225618. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225619. #endif
  225620. if (dest != nil)
  225621. return File (nsStringToJuce (dest));
  225622. return *this;
  225623. }
  225624. bool File::moveToTrash() const
  225625. {
  225626. if (! exists())
  225627. return true;
  225628. #if JUCE_IOS
  225629. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225630. #else
  225631. const ScopedAutoReleasePool pool;
  225632. NSString* p = juceStringToNS (getFullPathName());
  225633. return [[NSWorkspace sharedWorkspace]
  225634. performFileOperation: NSWorkspaceRecycleOperation
  225635. source: [p stringByDeletingLastPathComponent]
  225636. destination: @""
  225637. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225638. tag: nil ];
  225639. #endif
  225640. }
  225641. class DirectoryIterator::NativeIterator::Pimpl
  225642. {
  225643. public:
  225644. Pimpl (const File& directory, const String& wildCard_)
  225645. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225646. wildCard (wildCard_),
  225647. enumerator (0)
  225648. {
  225649. const ScopedAutoReleasePool pool;
  225650. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225651. wildcardUTF8 = wildCard.toUTF8();
  225652. }
  225653. ~Pimpl()
  225654. {
  225655. [enumerator release];
  225656. }
  225657. bool next (String& filenameFound,
  225658. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225659. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225660. {
  225661. const ScopedAutoReleasePool pool;
  225662. for (;;)
  225663. {
  225664. NSString* file;
  225665. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225666. return false;
  225667. [enumerator skipDescendents];
  225668. filenameFound = nsStringToJuce (file);
  225669. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225670. continue;
  225671. const String path (parentDir + filenameFound);
  225672. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225673. {
  225674. juce_statStruct info;
  225675. const bool statOk = juce_stat (path, info);
  225676. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225677. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225678. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225679. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225680. }
  225681. if (isHidden != 0)
  225682. *isHidden = juce_isHiddenFile (path);
  225683. if (isReadOnly != 0)
  225684. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225685. return true;
  225686. }
  225687. }
  225688. private:
  225689. String parentDir, wildCard;
  225690. const char* wildcardUTF8;
  225691. NSDirectoryEnumerator* enumerator;
  225692. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  225693. };
  225694. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225695. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225696. {
  225697. }
  225698. DirectoryIterator::NativeIterator::~NativeIterator()
  225699. {
  225700. }
  225701. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225702. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225703. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225704. {
  225705. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225706. }
  225707. bool juce_launchExecutable (const String& pathAndArguments)
  225708. {
  225709. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225710. const int cpid = fork();
  225711. if (cpid == 0)
  225712. {
  225713. // Child process
  225714. if (execve (argv[0], (char**) argv, 0) < 0)
  225715. exit (0);
  225716. }
  225717. else
  225718. {
  225719. if (cpid < 0)
  225720. return false;
  225721. }
  225722. return true;
  225723. }
  225724. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225725. {
  225726. #if JUCE_IOS
  225727. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225728. #else
  225729. const ScopedAutoReleasePool pool;
  225730. if (parameters.isEmpty())
  225731. {
  225732. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225733. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225734. }
  225735. bool ok = false;
  225736. if (PlatformUtilities::isBundle (fileName))
  225737. {
  225738. NSMutableArray* urls = [NSMutableArray array];
  225739. StringArray docs;
  225740. docs.addTokens (parameters, true);
  225741. for (int i = 0; i < docs.size(); ++i)
  225742. [urls addObject: juceStringToNS (docs[i])];
  225743. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225744. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225745. options: 0
  225746. additionalEventParamDescriptor: nil
  225747. launchIdentifiers: nil];
  225748. }
  225749. else if (File (fileName).exists())
  225750. {
  225751. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  225752. }
  225753. return ok;
  225754. #endif
  225755. }
  225756. void File::revealToUser() const
  225757. {
  225758. #if ! JUCE_IOS
  225759. if (exists())
  225760. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225761. else if (getParentDirectory().exists())
  225762. getParentDirectory().revealToUser();
  225763. #endif
  225764. }
  225765. #if ! JUCE_IOS
  225766. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225767. {
  225768. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225769. }
  225770. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225771. {
  225772. char path [2048];
  225773. zerostruct (path);
  225774. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225775. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225776. return String::empty;
  225777. }
  225778. #endif
  225779. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225780. {
  225781. const ScopedAutoReleasePool pool;
  225782. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225783. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225784. #else
  225785. // (the cast here avoids a deprecation warning)
  225786. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225787. #endif
  225788. return [fileDict fileHFSTypeCode];
  225789. }
  225790. bool PlatformUtilities::isBundle (const String& filename)
  225791. {
  225792. #if JUCE_IOS
  225793. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225794. #else
  225795. const ScopedAutoReleasePool pool;
  225796. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225797. #endif
  225798. }
  225799. #endif
  225800. /*** End of inlined file: juce_mac_Files.mm ***/
  225801. #if JUCE_IOS
  225802. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225803. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225804. // compiled on its own).
  225805. #if JUCE_INCLUDED_FILE
  225806. END_JUCE_NAMESPACE
  225807. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225808. {
  225809. }
  225810. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225811. - (void) applicationWillTerminate: (UIApplication*) application;
  225812. @end
  225813. @implementation JuceAppStartupDelegate
  225814. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225815. {
  225816. initialiseJuce_GUI();
  225817. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225818. exit (0);
  225819. }
  225820. - (void) applicationWillTerminate: (UIApplication*) application
  225821. {
  225822. JUCEApplication::appWillTerminateByForce();
  225823. }
  225824. @end
  225825. BEGIN_JUCE_NAMESPACE
  225826. int juce_iOSMain (int argc, const char* argv[])
  225827. {
  225828. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225829. }
  225830. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225831. {
  225832. pool = [[NSAutoreleasePool alloc] init];
  225833. }
  225834. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225835. {
  225836. [((NSAutoreleasePool*) pool) release];
  225837. }
  225838. void PlatformUtilities::beep()
  225839. {
  225840. //xxx
  225841. //AudioServicesPlaySystemSound ();
  225842. }
  225843. void PlatformUtilities::addItemToDock (const File& file)
  225844. {
  225845. }
  225846. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225847. END_JUCE_NAMESPACE
  225848. @interface JuceAlertBoxDelegate : NSObject
  225849. {
  225850. @public
  225851. bool clickedOk;
  225852. }
  225853. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225854. @end
  225855. @implementation JuceAlertBoxDelegate
  225856. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225857. {
  225858. clickedOk = (buttonIndex == 0);
  225859. alertView.hidden = true;
  225860. }
  225861. @end
  225862. BEGIN_JUCE_NAMESPACE
  225863. // (This function is used directly by other bits of code)
  225864. bool juce_iPhoneShowModalAlert (const String& title,
  225865. const String& bodyText,
  225866. NSString* okButtonText,
  225867. NSString* cancelButtonText)
  225868. {
  225869. const ScopedAutoReleasePool pool;
  225870. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225871. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225872. message: juceStringToNS (bodyText)
  225873. delegate: callback
  225874. cancelButtonTitle: okButtonText
  225875. otherButtonTitles: cancelButtonText, nil];
  225876. [alert retain];
  225877. [alert show];
  225878. while (! alert.hidden && alert.superview != nil)
  225879. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225880. const bool result = callback->clickedOk;
  225881. [alert release];
  225882. [callback release];
  225883. return result;
  225884. }
  225885. bool AlertWindow::showNativeDialogBox (const String& title,
  225886. const String& bodyText,
  225887. bool isOkCancel)
  225888. {
  225889. return juce_iPhoneShowModalAlert (title, bodyText,
  225890. @"OK",
  225891. isOkCancel ? @"Cancel" : nil);
  225892. }
  225893. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225894. {
  225895. jassertfalse; // no such thing on the iphone!
  225896. return false;
  225897. }
  225898. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225899. {
  225900. jassertfalse; // no such thing on the iphone!
  225901. return false;
  225902. }
  225903. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225904. {
  225905. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225906. }
  225907. bool Desktop::isScreenSaverEnabled()
  225908. {
  225909. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225910. }
  225911. #endif
  225912. #endif
  225913. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  225914. #else
  225915. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225916. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225917. // compiled on its own).
  225918. #if JUCE_INCLUDED_FILE
  225919. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225920. {
  225921. pool = [[NSAutoreleasePool alloc] init];
  225922. }
  225923. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225924. {
  225925. [((NSAutoreleasePool*) pool) release];
  225926. }
  225927. void PlatformUtilities::beep()
  225928. {
  225929. NSBeep();
  225930. }
  225931. void PlatformUtilities::addItemToDock (const File& file)
  225932. {
  225933. // check that it's not already there...
  225934. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225935. .containsIgnoreCase (file.getFullPathName()))
  225936. {
  225937. 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>"
  225938. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225939. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225940. }
  225941. }
  225942. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225943. bool AlertWindow::showNativeDialogBox (const String& title,
  225944. const String& bodyText,
  225945. bool isOkCancel)
  225946. {
  225947. const ScopedAutoReleasePool pool;
  225948. return NSRunAlertPanel (juceStringToNS (title),
  225949. juceStringToNS (bodyText),
  225950. @"Ok",
  225951. isOkCancel ? @"Cancel" : nil,
  225952. nil) == NSAlertDefaultReturn;
  225953. }
  225954. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225955. {
  225956. if (files.size() == 0)
  225957. return false;
  225958. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225959. if (draggingSource == 0)
  225960. {
  225961. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225962. return false;
  225963. }
  225964. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225965. if (sourceComp == 0)
  225966. {
  225967. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225968. return false;
  225969. }
  225970. const ScopedAutoReleasePool pool;
  225971. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225972. if (view == 0)
  225973. return false;
  225974. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225975. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225976. owner: nil];
  225977. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225978. for (int i = 0; i < files.size(); ++i)
  225979. [filesArray addObject: juceStringToNS (files[i])];
  225980. [pboard setPropertyList: filesArray
  225981. forType: NSFilenamesPboardType];
  225982. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225983. fromView: nil];
  225984. dragPosition.x -= 16;
  225985. dragPosition.y -= 16;
  225986. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225987. at: dragPosition
  225988. offset: NSMakeSize (0, 0)
  225989. event: [[view window] currentEvent]
  225990. pasteboard: pboard
  225991. source: view
  225992. slideBack: YES];
  225993. return true;
  225994. }
  225995. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225996. {
  225997. jassertfalse; // not implemented!
  225998. return false;
  225999. }
  226000. bool Desktop::canUseSemiTransparentWindows() throw()
  226001. {
  226002. return true;
  226003. }
  226004. const Point<int> Desktop::getMousePosition()
  226005. {
  226006. const ScopedAutoReleasePool pool;
  226007. const NSPoint p ([NSEvent mouseLocation]);
  226008. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  226009. }
  226010. void Desktop::setMousePosition (const Point<int>& newPosition)
  226011. {
  226012. // this rubbish needs to be done around the warp call, to avoid causing a
  226013. // bizarre glitch..
  226014. CGAssociateMouseAndMouseCursorPosition (false);
  226015. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  226016. CGAssociateMouseAndMouseCursorPosition (true);
  226017. }
  226018. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  226019. {
  226020. return upright;
  226021. }
  226022. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226023. class ScreenSaverDefeater : public Timer,
  226024. public DeletedAtShutdown
  226025. {
  226026. public:
  226027. ScreenSaverDefeater()
  226028. {
  226029. startTimer (10000);
  226030. timerCallback();
  226031. }
  226032. ~ScreenSaverDefeater() {}
  226033. void timerCallback()
  226034. {
  226035. if (Process::isForegroundProcess())
  226036. UpdateSystemActivity (UsrActivity);
  226037. }
  226038. };
  226039. static ScreenSaverDefeater* screenSaverDefeater = 0;
  226040. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226041. {
  226042. if (isEnabled)
  226043. deleteAndZero (screenSaverDefeater);
  226044. else if (screenSaverDefeater == 0)
  226045. screenSaverDefeater = new ScreenSaverDefeater();
  226046. }
  226047. bool Desktop::isScreenSaverEnabled()
  226048. {
  226049. return screenSaverDefeater == 0;
  226050. }
  226051. #else
  226052. static IOPMAssertionID screenSaverDisablerID = 0;
  226053. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226054. {
  226055. if (isEnabled)
  226056. {
  226057. if (screenSaverDisablerID != 0)
  226058. {
  226059. IOPMAssertionRelease (screenSaverDisablerID);
  226060. screenSaverDisablerID = 0;
  226061. }
  226062. }
  226063. else
  226064. {
  226065. if (screenSaverDisablerID == 0)
  226066. {
  226067. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226068. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226069. CFSTR ("Juce"), &screenSaverDisablerID);
  226070. #else
  226071. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226072. &screenSaverDisablerID);
  226073. #endif
  226074. }
  226075. }
  226076. }
  226077. bool Desktop::isScreenSaverEnabled()
  226078. {
  226079. return screenSaverDisablerID == 0;
  226080. }
  226081. #endif
  226082. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226083. {
  226084. const ScopedAutoReleasePool pool;
  226085. monitorCoords.clear();
  226086. NSArray* screens = [NSScreen screens];
  226087. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226088. for (unsigned int i = 0; i < [screens count]; ++i)
  226089. {
  226090. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226091. NSRect r = clipToWorkArea ? [s visibleFrame]
  226092. : [s frame];
  226093. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  226094. monitorCoords.add (convertToRectInt (r));
  226095. }
  226096. jassert (monitorCoords.size() > 0);
  226097. }
  226098. #endif
  226099. #endif
  226100. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226101. #endif
  226102. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226103. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226104. // compiled on its own).
  226105. #if JUCE_INCLUDED_FILE
  226106. void Logger::outputDebugString (const String& text)
  226107. {
  226108. std::cerr << text << std::endl;
  226109. }
  226110. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  226111. {
  226112. static char testResult = 0;
  226113. if (testResult == 0)
  226114. {
  226115. struct kinfo_proc info;
  226116. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226117. size_t sz = sizeof (info);
  226118. sysctl (m, 4, &info, &sz, 0, 0);
  226119. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226120. }
  226121. return testResult > 0;
  226122. }
  226123. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226124. {
  226125. return juce_isRunningUnderDebugger();
  226126. }
  226127. #endif
  226128. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226129. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226130. #if JUCE_IOS
  226131. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226132. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226133. // compiled on its own).
  226134. #if JUCE_INCLUDED_FILE
  226135. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226136. #define SUPPORT_10_4_FONTS 1
  226137. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226138. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226139. #define SUPPORT_ONLY_10_4_FONTS 1
  226140. #endif
  226141. END_JUCE_NAMESPACE
  226142. @interface NSFont (PrivateHack)
  226143. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226144. @end
  226145. BEGIN_JUCE_NAMESPACE
  226146. #endif
  226147. class MacTypeface : public Typeface
  226148. {
  226149. public:
  226150. MacTypeface (const Font& font)
  226151. : Typeface (font.getTypefaceName())
  226152. {
  226153. const ScopedAutoReleasePool pool;
  226154. renderingTransform = CGAffineTransformIdentity;
  226155. bool needsItalicTransform = false;
  226156. #if JUCE_IOS
  226157. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226158. if (font.isItalic() || font.isBold())
  226159. {
  226160. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226161. for (NSString* i in familyFonts)
  226162. {
  226163. const String fn (nsStringToJuce (i));
  226164. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226165. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226166. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226167. || afterDash.containsIgnoreCase ("italic")
  226168. || fn.endsWithIgnoreCase ("oblique")
  226169. || fn.endsWithIgnoreCase ("italic");
  226170. if (probablyBold == font.isBold()
  226171. && probablyItalic == font.isItalic())
  226172. {
  226173. fontName = i;
  226174. needsItalicTransform = false;
  226175. break;
  226176. }
  226177. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226178. {
  226179. fontName = i;
  226180. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226181. }
  226182. }
  226183. if (needsItalicTransform)
  226184. renderingTransform.c = 0.15f;
  226185. }
  226186. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226187. const int ascender = abs (CGFontGetAscent (fontRef));
  226188. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226189. ascent = ascender / totalHeight;
  226190. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226191. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226192. #else
  226193. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226194. if (font.isItalic())
  226195. {
  226196. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226197. toHaveTrait: NSItalicFontMask];
  226198. if (newFont == nsFont)
  226199. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226200. nsFont = newFont;
  226201. }
  226202. if (font.isBold())
  226203. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226204. [nsFont retain];
  226205. ascent = std::abs ((float) [nsFont ascender]);
  226206. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226207. ascent /= totalSize;
  226208. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226209. if (needsItalicTransform)
  226210. {
  226211. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226212. renderingTransform.c = 0.15f;
  226213. }
  226214. #if SUPPORT_ONLY_10_4_FONTS
  226215. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226216. if (atsFont == 0)
  226217. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226218. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226219. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226220. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226221. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226222. #else
  226223. #if SUPPORT_10_4_FONTS
  226224. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226225. {
  226226. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226227. if (atsFont == 0)
  226228. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226229. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226230. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226231. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226232. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226233. }
  226234. else
  226235. #endif
  226236. {
  226237. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226238. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226239. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226240. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226241. }
  226242. #endif
  226243. #endif
  226244. }
  226245. ~MacTypeface()
  226246. {
  226247. #if ! JUCE_IOS
  226248. [nsFont release];
  226249. #endif
  226250. if (fontRef != 0)
  226251. CGFontRelease (fontRef);
  226252. }
  226253. float getAscent() const
  226254. {
  226255. return ascent;
  226256. }
  226257. float getDescent() const
  226258. {
  226259. return 1.0f - ascent;
  226260. }
  226261. float getStringWidth (const String& text)
  226262. {
  226263. if (fontRef == 0 || text.isEmpty())
  226264. return 0;
  226265. const int length = text.length();
  226266. HeapBlock <CGGlyph> glyphs;
  226267. createGlyphsForString (text, length, glyphs);
  226268. float x = 0;
  226269. #if SUPPORT_ONLY_10_4_FONTS
  226270. HeapBlock <NSSize> advances (length);
  226271. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226272. for (int i = 0; i < length; ++i)
  226273. x += advances[i].width;
  226274. #else
  226275. #if SUPPORT_10_4_FONTS
  226276. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226277. {
  226278. HeapBlock <NSSize> advances (length);
  226279. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226280. for (int i = 0; i < length; ++i)
  226281. x += advances[i].width;
  226282. }
  226283. else
  226284. #endif
  226285. {
  226286. HeapBlock <int> advances (length);
  226287. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226288. for (int i = 0; i < length; ++i)
  226289. x += advances[i];
  226290. }
  226291. #endif
  226292. return x * unitsToHeightScaleFactor;
  226293. }
  226294. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226295. {
  226296. xOffsets.add (0);
  226297. if (fontRef == 0 || text.isEmpty())
  226298. return;
  226299. const int length = text.length();
  226300. HeapBlock <CGGlyph> glyphs;
  226301. createGlyphsForString (text, length, glyphs);
  226302. #if SUPPORT_ONLY_10_4_FONTS
  226303. HeapBlock <NSSize> advances (length);
  226304. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226305. int x = 0;
  226306. for (int i = 0; i < length; ++i)
  226307. {
  226308. x += advances[i].width;
  226309. xOffsets.add (x * unitsToHeightScaleFactor);
  226310. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226311. }
  226312. #else
  226313. #if SUPPORT_10_4_FONTS
  226314. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226315. {
  226316. HeapBlock <NSSize> advances (length);
  226317. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226318. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226319. float x = 0;
  226320. for (int i = 0; i < length; ++i)
  226321. {
  226322. x += advances[i].width;
  226323. xOffsets.add (x * unitsToHeightScaleFactor);
  226324. resultGlyphs.add (nsGlyphs[i]);
  226325. }
  226326. }
  226327. else
  226328. #endif
  226329. {
  226330. HeapBlock <int> advances (length);
  226331. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226332. {
  226333. int x = 0;
  226334. for (int i = 0; i < length; ++i)
  226335. {
  226336. x += advances [i];
  226337. xOffsets.add (x * unitsToHeightScaleFactor);
  226338. resultGlyphs.add (glyphs[i]);
  226339. }
  226340. }
  226341. }
  226342. #endif
  226343. }
  226344. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226345. {
  226346. #if JUCE_IOS
  226347. return false;
  226348. #else
  226349. if (nsFont == 0)
  226350. return false;
  226351. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226352. jassert (path.isEmpty());
  226353. const ScopedAutoReleasePool pool;
  226354. NSBezierPath* bez = [NSBezierPath bezierPath];
  226355. [bez moveToPoint: NSMakePoint (0, 0)];
  226356. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226357. inFont: nsFont];
  226358. for (int i = 0; i < [bez elementCount]; ++i)
  226359. {
  226360. NSPoint p[3];
  226361. switch ([bez elementAtIndex: i associatedPoints: p])
  226362. {
  226363. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  226364. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  226365. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  226366. (float) p[1].x, (float) -p[1].y,
  226367. (float) p[2].x, (float) -p[2].y); break;
  226368. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  226369. default: jassertfalse; break;
  226370. }
  226371. }
  226372. path.applyTransform (pathTransform);
  226373. return true;
  226374. #endif
  226375. }
  226376. CGFontRef fontRef;
  226377. float fontHeightToCGSizeFactor;
  226378. CGAffineTransform renderingTransform;
  226379. private:
  226380. float ascent, unitsToHeightScaleFactor;
  226381. #if JUCE_IOS
  226382. #else
  226383. NSFont* nsFont;
  226384. AffineTransform pathTransform;
  226385. #endif
  226386. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226387. {
  226388. #if SUPPORT_10_4_FONTS
  226389. #if ! SUPPORT_ONLY_10_4_FONTS
  226390. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226391. #endif
  226392. {
  226393. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226394. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226395. for (int i = 0; i < length; ++i)
  226396. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226397. return;
  226398. }
  226399. #endif
  226400. #if ! SUPPORT_ONLY_10_4_FONTS
  226401. if (charToGlyphMapper == 0)
  226402. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226403. glyphs.malloc (length);
  226404. for (int i = 0; i < length; ++i)
  226405. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226406. #endif
  226407. }
  226408. #if ! SUPPORT_ONLY_10_4_FONTS
  226409. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226410. class CharToGlyphMapper
  226411. {
  226412. public:
  226413. CharToGlyphMapper (CGFontRef fontRef)
  226414. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226415. idRangeOffset (0), glyphIndexes (0)
  226416. {
  226417. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226418. if (cmapTable != 0)
  226419. {
  226420. const int numSubtables = getValue16 (cmapTable, 2);
  226421. for (int i = 0; i < numSubtables; ++i)
  226422. {
  226423. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226424. {
  226425. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226426. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226427. {
  226428. const int length = getValue16 (cmapTable, offset + 2);
  226429. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226430. segCount = segCountX2 / 2;
  226431. const int endCodeOffset = offset + 14;
  226432. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226433. const int idDeltaOffset = startCodeOffset + segCountX2;
  226434. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226435. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226436. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226437. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226438. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226439. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226440. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226441. }
  226442. break;
  226443. }
  226444. }
  226445. CFRelease (cmapTable);
  226446. }
  226447. }
  226448. ~CharToGlyphMapper()
  226449. {
  226450. if (endCode != 0)
  226451. {
  226452. CFRelease (endCode);
  226453. CFRelease (startCode);
  226454. CFRelease (idDelta);
  226455. CFRelease (idRangeOffset);
  226456. CFRelease (glyphIndexes);
  226457. }
  226458. }
  226459. int getGlyphForCharacter (const juce_wchar c) const
  226460. {
  226461. for (int i = 0; i < segCount; ++i)
  226462. {
  226463. if (getValue16 (endCode, i * 2) >= c)
  226464. {
  226465. const int start = getValue16 (startCode, i * 2);
  226466. if (start > c)
  226467. break;
  226468. const int delta = getValue16 (idDelta, i * 2);
  226469. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226470. if (rangeOffset == 0)
  226471. return delta + c;
  226472. else
  226473. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226474. }
  226475. }
  226476. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226477. return jmax (-1, (int) c - 29);
  226478. }
  226479. private:
  226480. int segCount;
  226481. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226482. static uint16 getValue16 (CFDataRef data, const int index)
  226483. {
  226484. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226485. }
  226486. static uint32 getValue32 (CFDataRef data, const int index)
  226487. {
  226488. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226489. }
  226490. };
  226491. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226492. #endif
  226493. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  226494. };
  226495. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226496. {
  226497. return new MacTypeface (font);
  226498. }
  226499. const StringArray Font::findAllTypefaceNames()
  226500. {
  226501. StringArray names;
  226502. const ScopedAutoReleasePool pool;
  226503. #if JUCE_IOS
  226504. NSArray* fonts = [UIFont familyNames];
  226505. #else
  226506. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226507. #endif
  226508. for (unsigned int i = 0; i < [fonts count]; ++i)
  226509. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226510. names.sort (true);
  226511. return names;
  226512. }
  226513. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  226514. {
  226515. #if JUCE_IOS
  226516. defaultSans = "Helvetica";
  226517. defaultSerif = "Times New Roman";
  226518. defaultFixed = "Courier New";
  226519. #else
  226520. defaultSans = "Lucida Grande";
  226521. defaultSerif = "Times New Roman";
  226522. defaultFixed = "Monaco";
  226523. #endif
  226524. defaultFallback = "Arial Unicode MS";
  226525. }
  226526. #endif
  226527. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226528. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226529. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226530. // compiled on its own).
  226531. #if JUCE_INCLUDED_FILE
  226532. class CoreGraphicsImage : public Image::SharedImage
  226533. {
  226534. public:
  226535. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226536. : Image::SharedImage (format_, width_, height_)
  226537. {
  226538. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226539. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226540. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226541. imageData = imageDataAllocated;
  226542. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226543. : CGColorSpaceCreateDeviceRGB();
  226544. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226545. colourSpace, getCGImageFlags (format_));
  226546. CGColorSpaceRelease (colourSpace);
  226547. }
  226548. ~CoreGraphicsImage()
  226549. {
  226550. CGContextRelease (context);
  226551. }
  226552. Image::ImageType getType() const { return Image::NativeImage; }
  226553. LowLevelGraphicsContext* createLowLevelContext();
  226554. SharedImage* clone()
  226555. {
  226556. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226557. memcpy (im->imageData, imageData, lineStride * height);
  226558. return im;
  226559. }
  226560. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226561. {
  226562. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226563. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226564. {
  226565. return CGBitmapContextCreateImage (nativeImage->context);
  226566. }
  226567. else
  226568. {
  226569. const Image::BitmapData srcData (juceImage, false);
  226570. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226571. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226572. 8, srcData.pixelStride * 8, srcData.lineStride,
  226573. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226574. 0, true, kCGRenderingIntentDefault);
  226575. CGDataProviderRelease (provider);
  226576. return imageRef;
  226577. }
  226578. }
  226579. #if JUCE_MAC
  226580. static NSImage* createNSImage (const Image& image)
  226581. {
  226582. const ScopedAutoReleasePool pool;
  226583. NSImage* im = [[NSImage alloc] init];
  226584. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226585. [im lockFocus];
  226586. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226587. CGImageRef imageRef = createImage (image, false, colourSpace);
  226588. CGColorSpaceRelease (colourSpace);
  226589. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226590. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226591. CGImageRelease (imageRef);
  226592. [im unlockFocus];
  226593. return im;
  226594. }
  226595. #endif
  226596. CGContextRef context;
  226597. HeapBlock<uint8> imageDataAllocated;
  226598. private:
  226599. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226600. {
  226601. #if JUCE_BIG_ENDIAN
  226602. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226603. #else
  226604. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226605. #endif
  226606. }
  226607. };
  226608. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226609. {
  226610. #if USE_COREGRAPHICS_RENDERING
  226611. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226612. #else
  226613. return createSoftwareImage (format, width, height, clearImage);
  226614. #endif
  226615. }
  226616. class CoreGraphicsContext : public LowLevelGraphicsContext
  226617. {
  226618. public:
  226619. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226620. : context (context_),
  226621. flipHeight (flipHeight_),
  226622. lastClipRectIsValid (false),
  226623. state (new SavedState()),
  226624. numGradientLookupEntries (0)
  226625. {
  226626. CGContextRetain (context);
  226627. CGContextSaveGState(context);
  226628. CGContextSetShouldSmoothFonts (context, true);
  226629. CGContextSetShouldAntialias (context, true);
  226630. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226631. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226632. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226633. gradientCallbacks.version = 0;
  226634. gradientCallbacks.evaluate = gradientCallback;
  226635. gradientCallbacks.releaseInfo = 0;
  226636. setFont (Font());
  226637. }
  226638. ~CoreGraphicsContext()
  226639. {
  226640. CGContextRestoreGState (context);
  226641. CGContextRelease (context);
  226642. CGColorSpaceRelease (rgbColourSpace);
  226643. CGColorSpaceRelease (greyColourSpace);
  226644. }
  226645. bool isVectorDevice() const { return false; }
  226646. void setOrigin (int x, int y)
  226647. {
  226648. CGContextTranslateCTM (context, x, -y);
  226649. if (lastClipRectIsValid)
  226650. lastClipRect.translate (-x, -y);
  226651. }
  226652. void addTransform (const AffineTransform& transform)
  226653. {
  226654. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  226655. .translated (0, flipHeight)
  226656. .followedBy (transform)
  226657. .translated (0, -flipHeight)
  226658. .scaled (1.0f, -1.0f));
  226659. lastClipRectIsValid = false;
  226660. }
  226661. bool clipToRectangle (const Rectangle<int>& r)
  226662. {
  226663. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226664. if (lastClipRectIsValid)
  226665. {
  226666. // This is actually incorrect, because the actual clip region may be complex, and
  226667. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226668. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226669. // when calculating the resultant clip bounds, and makes the same mistake!
  226670. lastClipRect = lastClipRect.getIntersection (r);
  226671. return ! lastClipRect.isEmpty();
  226672. }
  226673. return ! isClipEmpty();
  226674. }
  226675. bool clipToRectangleList (const RectangleList& clipRegion)
  226676. {
  226677. if (clipRegion.isEmpty())
  226678. {
  226679. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226680. lastClipRectIsValid = true;
  226681. lastClipRect = Rectangle<int>();
  226682. return false;
  226683. }
  226684. else
  226685. {
  226686. const int numRects = clipRegion.getNumRectangles();
  226687. HeapBlock <CGRect> rects (numRects);
  226688. for (int i = 0; i < numRects; ++i)
  226689. {
  226690. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226691. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226692. }
  226693. CGContextClipToRects (context, rects, numRects);
  226694. lastClipRectIsValid = false;
  226695. return ! isClipEmpty();
  226696. }
  226697. }
  226698. void excludeClipRectangle (const Rectangle<int>& r)
  226699. {
  226700. RectangleList remaining (getClipBounds());
  226701. remaining.subtract (r);
  226702. clipToRectangleList (remaining);
  226703. lastClipRectIsValid = false;
  226704. }
  226705. void clipToPath (const Path& path, const AffineTransform& transform)
  226706. {
  226707. createPath (path, transform);
  226708. CGContextClip (context);
  226709. lastClipRectIsValid = false;
  226710. }
  226711. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226712. {
  226713. if (! transform.isSingularity())
  226714. {
  226715. Image singleChannelImage (sourceImage);
  226716. if (sourceImage.getFormat() != Image::SingleChannel)
  226717. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226718. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226719. flip();
  226720. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226721. applyTransform (t);
  226722. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226723. CGContextClipToMask (context, r, image);
  226724. applyTransform (t.inverted());
  226725. flip();
  226726. CGImageRelease (image);
  226727. lastClipRectIsValid = false;
  226728. }
  226729. }
  226730. bool clipRegionIntersects (const Rectangle<int>& r)
  226731. {
  226732. return getClipBounds().intersects (r);
  226733. }
  226734. const Rectangle<int> getClipBounds() const
  226735. {
  226736. if (! lastClipRectIsValid)
  226737. {
  226738. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226739. lastClipRectIsValid = true;
  226740. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226741. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226742. roundToInt (bounds.size.width),
  226743. roundToInt (bounds.size.height));
  226744. }
  226745. return lastClipRect;
  226746. }
  226747. bool isClipEmpty() const
  226748. {
  226749. return getClipBounds().isEmpty();
  226750. }
  226751. void saveState()
  226752. {
  226753. CGContextSaveGState (context);
  226754. stateStack.add (new SavedState (*state));
  226755. }
  226756. void restoreState()
  226757. {
  226758. CGContextRestoreGState (context);
  226759. SavedState* const top = stateStack.getLast();
  226760. if (top != 0)
  226761. {
  226762. state = top;
  226763. stateStack.removeLast (1, false);
  226764. lastClipRectIsValid = false;
  226765. }
  226766. else
  226767. {
  226768. jassertfalse; // trying to pop with an empty stack!
  226769. }
  226770. }
  226771. void beginTransparencyLayer (float opacity)
  226772. {
  226773. saveState();
  226774. CGContextSetAlpha (context, opacity);
  226775. CGContextBeginTransparencyLayer (context, 0);
  226776. }
  226777. void endTransparencyLayer()
  226778. {
  226779. CGContextEndTransparencyLayer (context);
  226780. restoreState();
  226781. }
  226782. void setFill (const FillType& fillType)
  226783. {
  226784. state->fillType = fillType;
  226785. if (fillType.isColour())
  226786. {
  226787. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226788. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226789. CGContextSetAlpha (context, 1.0f);
  226790. }
  226791. }
  226792. void setOpacity (float newOpacity)
  226793. {
  226794. state->fillType.setOpacity (newOpacity);
  226795. setFill (state->fillType);
  226796. }
  226797. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226798. {
  226799. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226800. ? kCGInterpolationLow
  226801. : kCGInterpolationHigh);
  226802. }
  226803. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226804. {
  226805. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226806. }
  226807. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226808. {
  226809. if (replaceExistingContents)
  226810. {
  226811. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226812. CGContextClearRect (context, cgRect);
  226813. #else
  226814. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226815. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226816. CGContextClearRect (context, cgRect);
  226817. else
  226818. #endif
  226819. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226820. #endif
  226821. fillCGRect (cgRect, false);
  226822. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226823. }
  226824. else
  226825. {
  226826. if (state->fillType.isColour())
  226827. {
  226828. CGContextFillRect (context, cgRect);
  226829. }
  226830. else if (state->fillType.isGradient())
  226831. {
  226832. CGContextSaveGState (context);
  226833. CGContextClipToRect (context, cgRect);
  226834. drawGradient();
  226835. CGContextRestoreGState (context);
  226836. }
  226837. else
  226838. {
  226839. CGContextSaveGState (context);
  226840. CGContextClipToRect (context, cgRect);
  226841. drawImage (state->fillType.image, state->fillType.transform, true);
  226842. CGContextRestoreGState (context);
  226843. }
  226844. }
  226845. }
  226846. void fillPath (const Path& path, const AffineTransform& transform)
  226847. {
  226848. CGContextSaveGState (context);
  226849. if (state->fillType.isColour())
  226850. {
  226851. flip();
  226852. applyTransform (transform);
  226853. createPath (path);
  226854. if (path.isUsingNonZeroWinding())
  226855. CGContextFillPath (context);
  226856. else
  226857. CGContextEOFillPath (context);
  226858. }
  226859. else
  226860. {
  226861. createPath (path, transform);
  226862. if (path.isUsingNonZeroWinding())
  226863. CGContextClip (context);
  226864. else
  226865. CGContextEOClip (context);
  226866. if (state->fillType.isGradient())
  226867. drawGradient();
  226868. else
  226869. drawImage (state->fillType.image, state->fillType.transform, true);
  226870. }
  226871. CGContextRestoreGState (context);
  226872. }
  226873. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226874. {
  226875. const int iw = sourceImage.getWidth();
  226876. const int ih = sourceImage.getHeight();
  226877. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226878. CGContextSaveGState (context);
  226879. CGContextSetAlpha (context, state->fillType.getOpacity());
  226880. flip();
  226881. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226882. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226883. if (fillEntireClipAsTiles)
  226884. {
  226885. #if JUCE_IOS
  226886. CGContextDrawTiledImage (context, imageRect, image);
  226887. #else
  226888. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226889. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226890. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226891. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226892. CGContextDrawTiledImage (context, imageRect, image);
  226893. else
  226894. #endif
  226895. {
  226896. // Fallback to manually doing a tiled fill on 10.4
  226897. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226898. int x = 0, y = 0;
  226899. while (x > clip.origin.x) x -= iw;
  226900. while (y > clip.origin.y) y -= ih;
  226901. const int right = (int) (clip.origin.x + clip.size.width);
  226902. const int bottom = (int) (clip.origin.y + clip.size.height);
  226903. while (y < bottom)
  226904. {
  226905. for (int x2 = x; x2 < right; x2 += iw)
  226906. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226907. y += ih;
  226908. }
  226909. }
  226910. #endif
  226911. }
  226912. else
  226913. {
  226914. CGContextDrawImage (context, imageRect, image);
  226915. }
  226916. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226917. CGContextRestoreGState (context);
  226918. }
  226919. void drawLine (const Line<float>& line)
  226920. {
  226921. if (state->fillType.isColour())
  226922. {
  226923. CGContextSetLineCap (context, kCGLineCapSquare);
  226924. CGContextSetLineWidth (context, 1.0f);
  226925. CGContextSetRGBStrokeColor (context,
  226926. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226927. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226928. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226929. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226930. CGContextStrokeLineSegments (context, cgLine, 1);
  226931. }
  226932. else
  226933. {
  226934. Path p;
  226935. p.addLineSegment (line, 1.0f);
  226936. fillPath (p, AffineTransform::identity);
  226937. }
  226938. }
  226939. void drawVerticalLine (const int x, float top, float bottom)
  226940. {
  226941. if (state->fillType.isColour())
  226942. {
  226943. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226944. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226945. #else
  226946. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226947. // the x co-ord slightly to trick it..
  226948. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226949. #endif
  226950. }
  226951. else
  226952. {
  226953. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226954. }
  226955. }
  226956. void drawHorizontalLine (const int y, float left, float right)
  226957. {
  226958. if (state->fillType.isColour())
  226959. {
  226960. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226961. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226962. #else
  226963. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226964. // the x co-ord slightly to trick it..
  226965. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226966. #endif
  226967. }
  226968. else
  226969. {
  226970. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226971. }
  226972. }
  226973. void setFont (const Font& newFont)
  226974. {
  226975. if (state->font != newFont)
  226976. {
  226977. state->fontRef = 0;
  226978. state->font = newFont;
  226979. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226980. if (mf != 0)
  226981. {
  226982. state->fontRef = mf->fontRef;
  226983. CGContextSetFont (context, state->fontRef);
  226984. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226985. state->fontTransform = mf->renderingTransform;
  226986. state->fontTransform.a *= state->font.getHorizontalScale();
  226987. CGContextSetTextMatrix (context, state->fontTransform);
  226988. }
  226989. }
  226990. }
  226991. const Font getFont()
  226992. {
  226993. return state->font;
  226994. }
  226995. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226996. {
  226997. if (state->fontRef != 0 && state->fillType.isColour())
  226998. {
  226999. if (transform.isOnlyTranslation())
  227000. {
  227001. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  227002. CGGlyph g = glyphNumber;
  227003. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227004. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227005. }
  227006. else
  227007. {
  227008. CGContextSaveGState (context);
  227009. flip();
  227010. applyTransform (transform);
  227011. CGAffineTransform t = state->fontTransform;
  227012. t.d = -t.d;
  227013. CGContextSetTextMatrix (context, t);
  227014. CGGlyph g = glyphNumber;
  227015. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227016. CGContextRestoreGState (context);
  227017. }
  227018. }
  227019. else
  227020. {
  227021. Path p;
  227022. Font& f = state->font;
  227023. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227024. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227025. .followedBy (transform));
  227026. }
  227027. }
  227028. private:
  227029. CGContextRef context;
  227030. const CGFloat flipHeight;
  227031. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227032. CGFunctionCallbacks gradientCallbacks;
  227033. mutable Rectangle<int> lastClipRect;
  227034. mutable bool lastClipRectIsValid;
  227035. struct SavedState
  227036. {
  227037. SavedState()
  227038. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227039. {
  227040. }
  227041. SavedState (const SavedState& other)
  227042. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227043. fontTransform (other.fontTransform)
  227044. {
  227045. }
  227046. ~SavedState()
  227047. {
  227048. }
  227049. FillType fillType;
  227050. Font font;
  227051. CGFontRef fontRef;
  227052. CGAffineTransform fontTransform;
  227053. };
  227054. ScopedPointer <SavedState> state;
  227055. OwnedArray <SavedState> stateStack;
  227056. HeapBlock <PixelARGB> gradientLookupTable;
  227057. int numGradientLookupEntries;
  227058. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227059. {
  227060. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227061. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227062. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227063. colour.unpremultiply();
  227064. outData[0] = colour.getRed() / 255.0f;
  227065. outData[1] = colour.getGreen() / 255.0f;
  227066. outData[2] = colour.getBlue() / 255.0f;
  227067. outData[3] = colour.getAlpha() / 255.0f;
  227068. }
  227069. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227070. {
  227071. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227072. --numGradientLookupEntries;
  227073. CGShadingRef result = 0;
  227074. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227075. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227076. if (gradient.isRadial)
  227077. {
  227078. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227079. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227080. function, true, true);
  227081. }
  227082. else
  227083. {
  227084. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227085. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227086. function, true, true);
  227087. }
  227088. CGFunctionRelease (function);
  227089. return result;
  227090. }
  227091. void drawGradient()
  227092. {
  227093. flip();
  227094. applyTransform (state->fillType.transform);
  227095. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227096. // you draw a gradient with high quality interp enabled).
  227097. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227098. CGContextSetAlpha (context, state->fillType.getOpacity());
  227099. CGContextDrawShading (context, shading);
  227100. CGShadingRelease (shading);
  227101. }
  227102. void createPath (const Path& path) const
  227103. {
  227104. CGContextBeginPath (context);
  227105. Path::Iterator i (path);
  227106. while (i.next())
  227107. {
  227108. switch (i.elementType)
  227109. {
  227110. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227111. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227112. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227113. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227114. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227115. default: jassertfalse; break;
  227116. }
  227117. }
  227118. }
  227119. void createPath (const Path& path, const AffineTransform& transform) const
  227120. {
  227121. CGContextBeginPath (context);
  227122. Path::Iterator i (path);
  227123. while (i.next())
  227124. {
  227125. switch (i.elementType)
  227126. {
  227127. case Path::Iterator::startNewSubPath:
  227128. transform.transformPoint (i.x1, i.y1);
  227129. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227130. break;
  227131. case Path::Iterator::lineTo:
  227132. transform.transformPoint (i.x1, i.y1);
  227133. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227134. break;
  227135. case Path::Iterator::quadraticTo:
  227136. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227137. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227138. break;
  227139. case Path::Iterator::cubicTo:
  227140. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227141. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227142. break;
  227143. case Path::Iterator::closePath:
  227144. CGContextClosePath (context); break;
  227145. default:
  227146. jassertfalse;
  227147. break;
  227148. }
  227149. }
  227150. }
  227151. void flip() const
  227152. {
  227153. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227154. }
  227155. void applyTransform (const AffineTransform& transform) const
  227156. {
  227157. CGAffineTransform t;
  227158. t.a = transform.mat00;
  227159. t.b = transform.mat10;
  227160. t.c = transform.mat01;
  227161. t.d = transform.mat11;
  227162. t.tx = transform.mat02;
  227163. t.ty = transform.mat12;
  227164. CGContextConcatCTM (context, t);
  227165. }
  227166. JUCE_DECLARE_NON_COPYABLE (CoreGraphicsContext);
  227167. };
  227168. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227169. {
  227170. return new CoreGraphicsContext (context, height);
  227171. }
  227172. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227173. const Image juce_loadWithCoreImage (InputStream& input)
  227174. {
  227175. MemoryBlock data;
  227176. input.readIntoMemoryBlock (data, -1);
  227177. #if JUCE_IOS
  227178. JUCE_AUTORELEASEPOOL
  227179. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  227180. length: data.getSize()
  227181. freeWhenDone: NO]];
  227182. if (image != nil)
  227183. {
  227184. CGImageRef loadedImage = image.CGImage;
  227185. #else
  227186. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227187. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227188. CGDataProviderRelease (provider);
  227189. if (imageSource != 0)
  227190. {
  227191. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227192. CFRelease (imageSource);
  227193. #endif
  227194. if (loadedImage != 0)
  227195. {
  227196. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  227197. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  227198. && alphaInfo != kCGImageAlphaNoneSkipLast
  227199. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  227200. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  227201. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227202. hasAlphaChan, Image::NativeImage);
  227203. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227204. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227205. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227206. CGContextFlush (cgImage->context);
  227207. #if ! JUCE_IOS
  227208. CFRelease (loadedImage);
  227209. #endif
  227210. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  227211. // to find out whether the file they just loaded the image from had an alpha channel or not.
  227212. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  227213. return image;
  227214. }
  227215. }
  227216. return Image::null;
  227217. }
  227218. #endif
  227219. #endif
  227220. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227221. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227222. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227223. // compiled on its own).
  227224. #if JUCE_INCLUDED_FILE
  227225. class UIViewComponentPeer;
  227226. END_JUCE_NAMESPACE
  227227. #define JuceUIView MakeObjCClassName(JuceUIView)
  227228. @interface JuceUIView : UIView <UITextViewDelegate>
  227229. {
  227230. @public
  227231. UIViewComponentPeer* owner;
  227232. UITextView* hiddenTextView;
  227233. }
  227234. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227235. - (void) dealloc;
  227236. - (void) drawRect: (CGRect) r;
  227237. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227238. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227239. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227240. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227241. - (BOOL) becomeFirstResponder;
  227242. - (BOOL) resignFirstResponder;
  227243. - (BOOL) canBecomeFirstResponder;
  227244. - (void) asyncRepaint: (id) rect;
  227245. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227246. @end
  227247. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  227248. @interface JuceUIViewController : UIViewController
  227249. {
  227250. }
  227251. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  227252. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  227253. @end
  227254. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227255. @interface JuceUIWindow : UIWindow
  227256. {
  227257. @private
  227258. UIViewComponentPeer* owner;
  227259. bool isZooming;
  227260. }
  227261. - (void) setOwner: (UIViewComponentPeer*) owner;
  227262. - (void) becomeKeyWindow;
  227263. @end
  227264. BEGIN_JUCE_NAMESPACE
  227265. class UIViewComponentPeer : public ComponentPeer,
  227266. public FocusChangeListener
  227267. {
  227268. public:
  227269. UIViewComponentPeer (Component* const component,
  227270. const int windowStyleFlags,
  227271. UIView* viewToAttachTo);
  227272. ~UIViewComponentPeer();
  227273. void* getNativeHandle() const;
  227274. void setVisible (bool shouldBeVisible);
  227275. void setTitle (const String& title);
  227276. void setPosition (int x, int y);
  227277. void setSize (int w, int h);
  227278. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227279. const Rectangle<int> getBounds() const;
  227280. const Rectangle<int> getBounds (const bool global) const;
  227281. const Point<int> getScreenPosition() const;
  227282. const Point<int> localToGlobal (const Point<int>& relativePosition);
  227283. const Point<int> globalToLocal (const Point<int>& screenPosition);
  227284. void setAlpha (float newAlpha);
  227285. void setMinimised (bool shouldBeMinimised);
  227286. bool isMinimised() const;
  227287. void setFullScreen (bool shouldBeFullScreen);
  227288. bool isFullScreen() const;
  227289. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227290. const BorderSize getFrameSize() const;
  227291. bool setAlwaysOnTop (bool alwaysOnTop);
  227292. void toFront (bool makeActiveWindow);
  227293. void toBehind (ComponentPeer* other);
  227294. void setIcon (const Image& newIcon);
  227295. virtual void drawRect (CGRect r);
  227296. virtual bool canBecomeKeyWindow();
  227297. virtual bool windowShouldClose();
  227298. virtual void redirectMovedOrResized();
  227299. virtual CGRect constrainRect (CGRect r);
  227300. virtual void viewFocusGain();
  227301. virtual void viewFocusLoss();
  227302. bool isFocused() const;
  227303. void grabFocus();
  227304. void textInputRequired (const Point<int>& position);
  227305. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227306. void updateHiddenTextContent (TextInputTarget* target);
  227307. void globalFocusChanged (Component*);
  227308. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  227309. virtual void displayRotated();
  227310. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227311. void repaint (const Rectangle<int>& area);
  227312. void performAnyPendingRepaintsNow();
  227313. UIWindow* window;
  227314. JuceUIView* view;
  227315. JuceUIViewController* controller;
  227316. bool isSharedWindow, fullScreen, insideDrawRect;
  227317. static ModifierKeys currentModifiers;
  227318. static int64 getMouseTime (UIEvent* e)
  227319. {
  227320. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227321. + (int64) ([e timestamp] * 1000.0);
  227322. }
  227323. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  227324. {
  227325. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227326. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227327. {
  227328. case UIInterfaceOrientationPortrait:
  227329. return r;
  227330. case UIInterfaceOrientationPortraitUpsideDown:
  227331. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227332. r.getWidth(), r.getHeight());
  227333. case UIInterfaceOrientationLandscapeLeft:
  227334. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  227335. r.getHeight(), r.getWidth());
  227336. case UIInterfaceOrientationLandscapeRight:
  227337. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  227338. r.getHeight(), r.getWidth());
  227339. default: jassertfalse; // unknown orientation!
  227340. }
  227341. return r;
  227342. }
  227343. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  227344. {
  227345. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227346. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227347. {
  227348. case UIInterfaceOrientationPortrait:
  227349. return r;
  227350. case UIInterfaceOrientationPortraitUpsideDown:
  227351. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227352. r.getWidth(), r.getHeight());
  227353. case UIInterfaceOrientationLandscapeLeft:
  227354. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  227355. r.getHeight(), r.getWidth());
  227356. case UIInterfaceOrientationLandscapeRight:
  227357. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  227358. r.getHeight(), r.getWidth());
  227359. default: jassertfalse; // unknown orientation!
  227360. }
  227361. return r;
  227362. }
  227363. Array <UITouch*> currentTouches;
  227364. private:
  227365. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  227366. };
  227367. END_JUCE_NAMESPACE
  227368. @implementation JuceUIViewController
  227369. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  227370. {
  227371. JuceUIView* juceView = (JuceUIView*) [self view];
  227372. jassert (juceView != 0 && juceView->owner != 0);
  227373. return juceView->owner->shouldRotate (interfaceOrientation);
  227374. }
  227375. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  227376. {
  227377. JuceUIView* juceView = (JuceUIView*) [self view];
  227378. jassert (juceView != 0 && juceView->owner != 0);
  227379. juceView->owner->displayRotated();
  227380. }
  227381. @end
  227382. @implementation JuceUIView
  227383. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227384. withFrame: (CGRect) frame
  227385. {
  227386. [super initWithFrame: frame];
  227387. owner = owner_;
  227388. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227389. [self addSubview: hiddenTextView];
  227390. hiddenTextView.delegate = self;
  227391. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227392. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227393. return self;
  227394. }
  227395. - (void) dealloc
  227396. {
  227397. [hiddenTextView removeFromSuperview];
  227398. [hiddenTextView release];
  227399. [super dealloc];
  227400. }
  227401. - (void) drawRect: (CGRect) r
  227402. {
  227403. if (owner != 0)
  227404. owner->drawRect (r);
  227405. }
  227406. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227407. {
  227408. return false;
  227409. }
  227410. ModifierKeys UIViewComponentPeer::currentModifiers;
  227411. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227412. {
  227413. return UIViewComponentPeer::currentModifiers;
  227414. }
  227415. void ModifierKeys::updateCurrentModifiers() throw()
  227416. {
  227417. currentModifiers = UIViewComponentPeer::currentModifiers;
  227418. }
  227419. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227420. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227421. {
  227422. if (owner != 0)
  227423. owner->handleTouches (event, true, false, false);
  227424. }
  227425. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227426. {
  227427. if (owner != 0)
  227428. owner->handleTouches (event, false, false, false);
  227429. }
  227430. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227431. {
  227432. if (owner != 0)
  227433. owner->handleTouches (event, false, true, false);
  227434. }
  227435. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227436. {
  227437. if (owner != 0)
  227438. owner->handleTouches (event, false, true, true);
  227439. [self touchesEnded: touches withEvent: event];
  227440. }
  227441. - (BOOL) becomeFirstResponder
  227442. {
  227443. if (owner != 0)
  227444. owner->viewFocusGain();
  227445. return true;
  227446. }
  227447. - (BOOL) resignFirstResponder
  227448. {
  227449. if (owner != 0)
  227450. owner->viewFocusLoss();
  227451. return true;
  227452. }
  227453. - (BOOL) canBecomeFirstResponder
  227454. {
  227455. return owner != 0 && owner->canBecomeKeyWindow();
  227456. }
  227457. - (void) asyncRepaint: (id) rect
  227458. {
  227459. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227460. [self setNeedsDisplayInRect: *r];
  227461. }
  227462. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227463. {
  227464. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227465. nsStringToJuce (text));
  227466. }
  227467. @end
  227468. @implementation JuceUIWindow
  227469. - (void) setOwner: (UIViewComponentPeer*) owner_
  227470. {
  227471. owner = owner_;
  227472. isZooming = false;
  227473. }
  227474. - (void) becomeKeyWindow
  227475. {
  227476. [super becomeKeyWindow];
  227477. if (owner != 0)
  227478. owner->grabFocus();
  227479. }
  227480. @end
  227481. BEGIN_JUCE_NAMESPACE
  227482. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227483. const int windowStyleFlags,
  227484. UIView* viewToAttachTo)
  227485. : ComponentPeer (component, windowStyleFlags),
  227486. window (0),
  227487. view (0), controller (0),
  227488. isSharedWindow (viewToAttachTo != 0),
  227489. fullScreen (false),
  227490. insideDrawRect (false)
  227491. {
  227492. CGRect r = convertToCGRect (component->getLocalBounds());
  227493. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227494. if (isSharedWindow)
  227495. {
  227496. window = [viewToAttachTo window];
  227497. [viewToAttachTo addSubview: view];
  227498. setVisible (component->isVisible());
  227499. }
  227500. else
  227501. {
  227502. controller = [[JuceUIViewController alloc] init];
  227503. controller.view = view;
  227504. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  227505. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227506. window = [[JuceUIWindow alloc] init];
  227507. window.frame = r;
  227508. window.opaque = component->isOpaque();
  227509. view.opaque = component->isOpaque();
  227510. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227511. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227512. [((JuceUIWindow*) window) setOwner: this];
  227513. if (component->isAlwaysOnTop())
  227514. window.windowLevel = UIWindowLevelAlert;
  227515. [window addSubview: view];
  227516. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227517. view.hidden = ! component->isVisible();
  227518. window.hidden = ! component->isVisible();
  227519. view.multipleTouchEnabled = YES;
  227520. }
  227521. setTitle (component->getName());
  227522. Desktop::getInstance().addFocusChangeListener (this);
  227523. }
  227524. UIViewComponentPeer::~UIViewComponentPeer()
  227525. {
  227526. Desktop::getInstance().removeFocusChangeListener (this);
  227527. view->owner = 0;
  227528. [view removeFromSuperview];
  227529. [view release];
  227530. [controller release];
  227531. if (! isSharedWindow)
  227532. {
  227533. [((JuceUIWindow*) window) setOwner: 0];
  227534. [window release];
  227535. }
  227536. }
  227537. void* UIViewComponentPeer::getNativeHandle() const
  227538. {
  227539. return view;
  227540. }
  227541. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227542. {
  227543. view.hidden = ! shouldBeVisible;
  227544. if (! isSharedWindow)
  227545. window.hidden = ! shouldBeVisible;
  227546. }
  227547. void UIViewComponentPeer::setTitle (const String& title)
  227548. {
  227549. // xxx is this possible?
  227550. }
  227551. void UIViewComponentPeer::setPosition (int x, int y)
  227552. {
  227553. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227554. }
  227555. void UIViewComponentPeer::setSize (int w, int h)
  227556. {
  227557. setBounds (component->getX(), component->getY(), w, h, false);
  227558. }
  227559. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227560. {
  227561. fullScreen = isNowFullScreen;
  227562. w = jmax (0, w);
  227563. h = jmax (0, h);
  227564. if (isSharedWindow)
  227565. {
  227566. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  227567. if ([view frame].size.width != r.size.width
  227568. || [view frame].size.height != r.size.height)
  227569. [view setNeedsDisplay];
  227570. view.frame = r;
  227571. }
  227572. else
  227573. {
  227574. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  227575. window.frame = convertToCGRect (bounds);
  227576. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  227577. handleMovedOrResized();
  227578. }
  227579. }
  227580. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227581. {
  227582. CGRect r = [view frame];
  227583. if (global && [view window] != 0)
  227584. {
  227585. r = [view convertRect: r toView: nil];
  227586. CGRect wr = [[view window] frame];
  227587. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  227588. r.origin.x = windowBounds.getX();
  227589. r.origin.y = windowBounds.getY();
  227590. }
  227591. return convertToRectInt (r);
  227592. }
  227593. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227594. {
  227595. return getBounds (! isSharedWindow);
  227596. }
  227597. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227598. {
  227599. return getBounds (true).getPosition();
  227600. }
  227601. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  227602. {
  227603. return relativePosition + getScreenPosition();
  227604. }
  227605. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  227606. {
  227607. return screenPosition - getScreenPosition();
  227608. }
  227609. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227610. {
  227611. if (constrainer != 0)
  227612. {
  227613. CGRect current = [window frame];
  227614. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227615. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227616. Rectangle<int> pos (convertToRectInt (r));
  227617. Rectangle<int> original (convertToRectInt (current));
  227618. constrainer->checkBounds (pos, original,
  227619. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227620. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227621. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227622. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227623. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227624. r.origin.x = pos.getX();
  227625. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227626. r.size.width = pos.getWidth();
  227627. r.size.height = pos.getHeight();
  227628. }
  227629. return r;
  227630. }
  227631. void UIViewComponentPeer::setAlpha (float newAlpha)
  227632. {
  227633. [[view window] setAlpha: (CGFloat) newAlpha];
  227634. }
  227635. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227636. {
  227637. }
  227638. bool UIViewComponentPeer::isMinimised() const
  227639. {
  227640. return false;
  227641. }
  227642. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227643. {
  227644. if (! isSharedWindow)
  227645. {
  227646. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  227647. : lastNonFullscreenBounds);
  227648. if ((! shouldBeFullScreen) && r.isEmpty())
  227649. r = getBounds();
  227650. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227651. if (! r.isEmpty())
  227652. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227653. component->repaint();
  227654. }
  227655. }
  227656. bool UIViewComponentPeer::isFullScreen() const
  227657. {
  227658. return fullScreen;
  227659. }
  227660. namespace
  227661. {
  227662. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  227663. {
  227664. switch (interfaceOrientation)
  227665. {
  227666. case UIInterfaceOrientationPortrait: return Desktop::upright;
  227667. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  227668. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  227669. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  227670. default: jassertfalse; // unknown orientation!
  227671. }
  227672. return Desktop::upright;
  227673. }
  227674. }
  227675. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  227676. {
  227677. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  227678. }
  227679. void UIViewComponentPeer::displayRotated()
  227680. {
  227681. const Rectangle<int> oldArea (component->getBounds());
  227682. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  227683. Desktop::getInstance().refreshMonitorSizes();
  227684. if (fullScreen)
  227685. {
  227686. fullScreen = false;
  227687. setFullScreen (true);
  227688. }
  227689. else
  227690. {
  227691. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  227692. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  227693. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  227694. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  227695. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  227696. setBounds ((int) (l * newDesktop.getWidth()),
  227697. (int) (t * newDesktop.getHeight()),
  227698. (int) ((r - l) * newDesktop.getWidth()),
  227699. (int) ((b - t) * newDesktop.getHeight()),
  227700. false);
  227701. }
  227702. }
  227703. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227704. {
  227705. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227706. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227707. return false;
  227708. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  227709. withEvent: nil];
  227710. if (trueIfInAChildWindow)
  227711. return v != nil;
  227712. return v == view;
  227713. }
  227714. const BorderSize UIViewComponentPeer::getFrameSize() const
  227715. {
  227716. return BorderSize();
  227717. }
  227718. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227719. {
  227720. if (! isSharedWindow)
  227721. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227722. return true;
  227723. }
  227724. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227725. {
  227726. if (isSharedWindow)
  227727. [[view superview] bringSubviewToFront: view];
  227728. if (window != 0 && component->isVisible())
  227729. [window makeKeyAndVisible];
  227730. }
  227731. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227732. {
  227733. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227734. jassert (otherPeer != 0); // wrong type of window?
  227735. if (otherPeer != 0)
  227736. {
  227737. if (isSharedWindow)
  227738. {
  227739. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227740. }
  227741. else
  227742. {
  227743. jassertfalse; // don't know how to do this
  227744. }
  227745. }
  227746. }
  227747. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227748. {
  227749. // to do..
  227750. }
  227751. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227752. {
  227753. NSArray* touches = [[event touchesForView: view] allObjects];
  227754. for (unsigned int i = 0; i < [touches count]; ++i)
  227755. {
  227756. UITouch* touch = [touches objectAtIndex: i];
  227757. CGPoint p = [touch locationInView: view];
  227758. const Point<int> pos ((int) p.x, (int) p.y);
  227759. juce_lastMousePos = pos + getScreenPosition();
  227760. const int64 time = getMouseTime (event);
  227761. int touchIndex = currentTouches.indexOf (touch);
  227762. if (touchIndex < 0)
  227763. {
  227764. touchIndex = currentTouches.size();
  227765. currentTouches.add (touch);
  227766. }
  227767. if (isDown)
  227768. {
  227769. currentModifiers = currentModifiers.withoutMouseButtons();
  227770. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227771. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227772. }
  227773. else if (isUp)
  227774. {
  227775. currentModifiers = currentModifiers.withoutMouseButtons();
  227776. currentTouches.remove (touchIndex);
  227777. }
  227778. if (isCancel)
  227779. currentTouches.clear();
  227780. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227781. }
  227782. }
  227783. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227784. void UIViewComponentPeer::viewFocusGain()
  227785. {
  227786. if (currentlyFocusedPeer != this)
  227787. {
  227788. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227789. currentlyFocusedPeer->handleFocusLoss();
  227790. currentlyFocusedPeer = this;
  227791. handleFocusGain();
  227792. }
  227793. }
  227794. void UIViewComponentPeer::viewFocusLoss()
  227795. {
  227796. if (currentlyFocusedPeer == this)
  227797. {
  227798. currentlyFocusedPeer = 0;
  227799. handleFocusLoss();
  227800. }
  227801. }
  227802. void juce_HandleProcessFocusChange()
  227803. {
  227804. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227805. {
  227806. if (Process::isForegroundProcess())
  227807. {
  227808. currentlyFocusedPeer->handleFocusGain();
  227809. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  227810. }
  227811. else
  227812. {
  227813. currentlyFocusedPeer->handleFocusLoss();
  227814. // turn kiosk mode off if we lose focus..
  227815. Desktop::getInstance().setKioskModeComponent (0);
  227816. }
  227817. }
  227818. }
  227819. bool UIViewComponentPeer::isFocused() const
  227820. {
  227821. return isSharedWindow ? this == currentlyFocusedPeer
  227822. : (window != 0 && [window isKeyWindow]);
  227823. }
  227824. void UIViewComponentPeer::grabFocus()
  227825. {
  227826. if (window != 0)
  227827. {
  227828. [window makeKeyWindow];
  227829. viewFocusGain();
  227830. }
  227831. }
  227832. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227833. {
  227834. }
  227835. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227836. {
  227837. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227838. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227839. }
  227840. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227841. {
  227842. TextInputTarget* const target = findCurrentTextInputTarget();
  227843. if (target != 0)
  227844. {
  227845. const Range<int> currentSelection (target->getHighlightedRegion());
  227846. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227847. if (currentSelection.isEmpty())
  227848. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227849. target->insertTextAtCaret (text);
  227850. updateHiddenTextContent (target);
  227851. }
  227852. return NO;
  227853. }
  227854. void UIViewComponentPeer::globalFocusChanged (Component*)
  227855. {
  227856. TextInputTarget* const target = findCurrentTextInputTarget();
  227857. if (target != 0)
  227858. {
  227859. Component* comp = dynamic_cast<Component*> (target);
  227860. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227861. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227862. updateHiddenTextContent (target);
  227863. [view->hiddenTextView becomeFirstResponder];
  227864. }
  227865. else
  227866. {
  227867. [view->hiddenTextView resignFirstResponder];
  227868. }
  227869. }
  227870. void UIViewComponentPeer::drawRect (CGRect r)
  227871. {
  227872. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227873. return;
  227874. CGContextRef cg = UIGraphicsGetCurrentContext();
  227875. if (! component->isOpaque())
  227876. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227877. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227878. CoreGraphicsContext g (cg, view.bounds.size.height);
  227879. insideDrawRect = true;
  227880. handlePaint (g);
  227881. insideDrawRect = false;
  227882. }
  227883. bool UIViewComponentPeer::canBecomeKeyWindow()
  227884. {
  227885. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227886. }
  227887. bool UIViewComponentPeer::windowShouldClose()
  227888. {
  227889. if (! isValidPeer (this))
  227890. return YES;
  227891. handleUserClosingWindow();
  227892. return NO;
  227893. }
  227894. void UIViewComponentPeer::redirectMovedOrResized()
  227895. {
  227896. handleMovedOrResized();
  227897. }
  227898. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227899. {
  227900. }
  227901. class AsyncRepaintMessage : public CallbackMessage
  227902. {
  227903. public:
  227904. UIViewComponentPeer* const peer;
  227905. const Rectangle<int> rect;
  227906. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227907. : peer (peer_), rect (rect_)
  227908. {
  227909. }
  227910. void messageCallback()
  227911. {
  227912. if (ComponentPeer::isValidPeer (peer))
  227913. peer->repaint (rect);
  227914. }
  227915. };
  227916. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227917. {
  227918. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227919. {
  227920. (new AsyncRepaintMessage (this, area))->post();
  227921. }
  227922. else
  227923. {
  227924. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227925. }
  227926. }
  227927. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227928. {
  227929. }
  227930. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227931. {
  227932. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227933. }
  227934. const Image juce_createIconForFile (const File& file)
  227935. {
  227936. return Image::null;
  227937. }
  227938. void Desktop::createMouseInputSources()
  227939. {
  227940. for (int i = 0; i < 10; ++i)
  227941. mouseSources.add (new MouseInputSource (i, false));
  227942. }
  227943. bool Desktop::canUseSemiTransparentWindows() throw()
  227944. {
  227945. return true;
  227946. }
  227947. const Point<int> Desktop::getMousePosition()
  227948. {
  227949. return juce_lastMousePos;
  227950. }
  227951. void Desktop::setMousePosition (const Point<int>&)
  227952. {
  227953. }
  227954. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227955. {
  227956. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227957. }
  227958. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227959. {
  227960. const ScopedAutoReleasePool pool;
  227961. monitorCoords.clear();
  227962. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227963. : [[UIScreen mainScreen] bounds];
  227964. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227965. }
  227966. const int KeyPress::spaceKey = ' ';
  227967. const int KeyPress::returnKey = 0x0d;
  227968. const int KeyPress::escapeKey = 0x1b;
  227969. const int KeyPress::backspaceKey = 0x7f;
  227970. const int KeyPress::leftKey = 0x1000;
  227971. const int KeyPress::rightKey = 0x1001;
  227972. const int KeyPress::upKey = 0x1002;
  227973. const int KeyPress::downKey = 0x1003;
  227974. const int KeyPress::pageUpKey = 0x1004;
  227975. const int KeyPress::pageDownKey = 0x1005;
  227976. const int KeyPress::endKey = 0x1006;
  227977. const int KeyPress::homeKey = 0x1007;
  227978. const int KeyPress::deleteKey = 0x1008;
  227979. const int KeyPress::insertKey = -1;
  227980. const int KeyPress::tabKey = 9;
  227981. const int KeyPress::F1Key = 0x2001;
  227982. const int KeyPress::F2Key = 0x2002;
  227983. const int KeyPress::F3Key = 0x2003;
  227984. const int KeyPress::F4Key = 0x2004;
  227985. const int KeyPress::F5Key = 0x2005;
  227986. const int KeyPress::F6Key = 0x2006;
  227987. const int KeyPress::F7Key = 0x2007;
  227988. const int KeyPress::F8Key = 0x2008;
  227989. const int KeyPress::F9Key = 0x2009;
  227990. const int KeyPress::F10Key = 0x200a;
  227991. const int KeyPress::F11Key = 0x200b;
  227992. const int KeyPress::F12Key = 0x200c;
  227993. const int KeyPress::F13Key = 0x200d;
  227994. const int KeyPress::F14Key = 0x200e;
  227995. const int KeyPress::F15Key = 0x200f;
  227996. const int KeyPress::F16Key = 0x2010;
  227997. const int KeyPress::numberPad0 = 0x30020;
  227998. const int KeyPress::numberPad1 = 0x30021;
  227999. const int KeyPress::numberPad2 = 0x30022;
  228000. const int KeyPress::numberPad3 = 0x30023;
  228001. const int KeyPress::numberPad4 = 0x30024;
  228002. const int KeyPress::numberPad5 = 0x30025;
  228003. const int KeyPress::numberPad6 = 0x30026;
  228004. const int KeyPress::numberPad7 = 0x30027;
  228005. const int KeyPress::numberPad8 = 0x30028;
  228006. const int KeyPress::numberPad9 = 0x30029;
  228007. const int KeyPress::numberPadAdd = 0x3002a;
  228008. const int KeyPress::numberPadSubtract = 0x3002b;
  228009. const int KeyPress::numberPadMultiply = 0x3002c;
  228010. const int KeyPress::numberPadDivide = 0x3002d;
  228011. const int KeyPress::numberPadSeparator = 0x3002e;
  228012. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228013. const int KeyPress::numberPadEquals = 0x30030;
  228014. const int KeyPress::numberPadDelete = 0x30031;
  228015. const int KeyPress::playKey = 0x30000;
  228016. const int KeyPress::stopKey = 0x30001;
  228017. const int KeyPress::fastForwardKey = 0x30002;
  228018. const int KeyPress::rewindKey = 0x30003;
  228019. #endif
  228020. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  228021. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  228022. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228023. // compiled on its own).
  228024. #if JUCE_INCLUDED_FILE
  228025. struct CallbackMessagePayload
  228026. {
  228027. MessageCallbackFunction* function;
  228028. void* parameter;
  228029. void* volatile result;
  228030. bool volatile hasBeenExecuted;
  228031. };
  228032. END_JUCE_NAMESPACE
  228033. @interface JuceCustomMessageHandler : NSObject
  228034. {
  228035. }
  228036. - (void) performCallback: (id) info;
  228037. @end
  228038. @implementation JuceCustomMessageHandler
  228039. - (void) performCallback: (id) info
  228040. {
  228041. if ([info isKindOfClass: [NSData class]])
  228042. {
  228043. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  228044. if (pl != 0)
  228045. {
  228046. pl->result = (*pl->function) (pl->parameter);
  228047. pl->hasBeenExecuted = true;
  228048. }
  228049. }
  228050. else
  228051. {
  228052. jassertfalse; // should never get here!
  228053. }
  228054. }
  228055. @end
  228056. BEGIN_JUCE_NAMESPACE
  228057. void MessageManager::runDispatchLoop()
  228058. {
  228059. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228060. runDispatchLoopUntil (-1);
  228061. }
  228062. void MessageManager::stopDispatchLoop()
  228063. {
  228064. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  228065. exit (0); // iPhone apps get no mercy..
  228066. }
  228067. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  228068. {
  228069. const ScopedAutoReleasePool pool;
  228070. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228071. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  228072. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  228073. while (! quitMessagePosted)
  228074. {
  228075. const ScopedAutoReleasePool pool;
  228076. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228077. beforeDate: endDate];
  228078. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  228079. break;
  228080. }
  228081. return ! quitMessagePosted;
  228082. }
  228083. namespace iOSMessageLoopHelpers
  228084. {
  228085. static CFRunLoopRef runLoop = 0;
  228086. static CFRunLoopSourceRef runLoopSource = 0;
  228087. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  228088. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  228089. void runLoopSourceCallback (void*)
  228090. {
  228091. if (pendingMessages != 0)
  228092. {
  228093. int numDispatched = 0;
  228094. do
  228095. {
  228096. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  228097. if (nextMessage == 0)
  228098. return;
  228099. const ScopedAutoReleasePool pool;
  228100. MessageManager::getInstance()->deliverMessage (nextMessage);
  228101. } while (++numDispatched <= 4);
  228102. CFRunLoopSourceSignal (runLoopSource);
  228103. CFRunLoopWakeUp (runLoop);
  228104. }
  228105. }
  228106. }
  228107. void MessageManager::doPlatformSpecificInitialisation()
  228108. {
  228109. using namespace iOSMessageLoopHelpers;
  228110. pendingMessages = new OwnedArray <Message, CriticalSection>();
  228111. runLoop = CFRunLoopGetCurrent();
  228112. CFRunLoopSourceContext sourceContext;
  228113. zerostruct (sourceContext);
  228114. sourceContext.perform = runLoopSourceCallback;
  228115. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  228116. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  228117. if (juceCustomMessageHandler == 0)
  228118. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  228119. }
  228120. void MessageManager::doPlatformSpecificShutdown()
  228121. {
  228122. using namespace iOSMessageLoopHelpers;
  228123. CFRunLoopSourceInvalidate (runLoopSource);
  228124. CFRelease (runLoopSource);
  228125. runLoopSource = 0;
  228126. deleteAndZero (pendingMessages);
  228127. if (juceCustomMessageHandler != 0)
  228128. {
  228129. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  228130. [juceCustomMessageHandler release];
  228131. juceCustomMessageHandler = 0;
  228132. }
  228133. }
  228134. bool juce_postMessageToSystemQueue (Message* message)
  228135. {
  228136. using namespace iOSMessageLoopHelpers;
  228137. if (pendingMessages != 0)
  228138. {
  228139. pendingMessages->add (message);
  228140. CFRunLoopSourceSignal (runLoopSource);
  228141. CFRunLoopWakeUp (runLoop);
  228142. }
  228143. return true;
  228144. }
  228145. void MessageManager::broadcastMessage (const String& value)
  228146. {
  228147. }
  228148. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  228149. {
  228150. using namespace iOSMessageLoopHelpers;
  228151. if (isThisTheMessageThread())
  228152. {
  228153. return (*callback) (data);
  228154. }
  228155. else
  228156. {
  228157. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  228158. // deadlock because the message manager is blocked from running, so can never
  228159. // call your function..
  228160. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  228161. const ScopedAutoReleasePool pool;
  228162. CallbackMessagePayload cmp;
  228163. cmp.function = callback;
  228164. cmp.parameter = data;
  228165. cmp.result = 0;
  228166. cmp.hasBeenExecuted = false;
  228167. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  228168. withObject: [NSData dataWithBytesNoCopy: &cmp
  228169. length: sizeof (cmp)
  228170. freeWhenDone: NO]
  228171. waitUntilDone: YES];
  228172. return cmp.result;
  228173. }
  228174. }
  228175. #endif
  228176. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  228177. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  228178. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228179. // compiled on its own).
  228180. #if JUCE_INCLUDED_FILE
  228181. #if JUCE_MAC
  228182. END_JUCE_NAMESPACE
  228183. using namespace JUCE_NAMESPACE;
  228184. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  228185. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228186. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  228187. #else
  228188. @interface JuceFileChooserDelegate : NSObject
  228189. #endif
  228190. {
  228191. StringArray* filters;
  228192. }
  228193. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  228194. - (void) dealloc;
  228195. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  228196. @end
  228197. @implementation JuceFileChooserDelegate
  228198. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  228199. {
  228200. [super init];
  228201. filters = filters_;
  228202. return self;
  228203. }
  228204. - (void) dealloc
  228205. {
  228206. delete filters;
  228207. [super dealloc];
  228208. }
  228209. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  228210. {
  228211. (void) sender;
  228212. const File f (nsStringToJuce (filename));
  228213. for (int i = filters->size(); --i >= 0;)
  228214. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228215. return true;
  228216. return f.isDirectory();
  228217. }
  228218. @end
  228219. BEGIN_JUCE_NAMESPACE
  228220. void FileChooser::showPlatformDialog (Array<File>& results,
  228221. const String& title,
  228222. const File& currentFileOrDirectory,
  228223. const String& filter,
  228224. bool selectsDirectory,
  228225. bool selectsFiles,
  228226. bool isSaveDialogue,
  228227. bool warnAboutOverwritingExistingFiles,
  228228. bool selectMultipleFiles,
  228229. FilePreviewComponent* extraInfoComponent)
  228230. {
  228231. const ScopedAutoReleasePool pool;
  228232. StringArray* filters = new StringArray();
  228233. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228234. filters->trim();
  228235. filters->removeEmptyStrings();
  228236. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228237. [delegate autorelease];
  228238. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228239. : [NSOpenPanel openPanel];
  228240. [panel setTitle: juceStringToNS (title)];
  228241. if (! isSaveDialogue)
  228242. {
  228243. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228244. [openPanel setCanChooseDirectories: selectsDirectory];
  228245. [openPanel setCanChooseFiles: selectsFiles];
  228246. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228247. }
  228248. [panel setDelegate: delegate];
  228249. if (isSaveDialogue || selectsDirectory)
  228250. [panel setCanCreateDirectories: YES];
  228251. String directory, filename;
  228252. if (currentFileOrDirectory.isDirectory())
  228253. {
  228254. directory = currentFileOrDirectory.getFullPathName();
  228255. }
  228256. else
  228257. {
  228258. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228259. filename = currentFileOrDirectory.getFileName();
  228260. }
  228261. if ([panel runModalForDirectory: juceStringToNS (directory)
  228262. file: juceStringToNS (filename)]
  228263. == NSOKButton)
  228264. {
  228265. if (isSaveDialogue)
  228266. {
  228267. results.add (File (nsStringToJuce ([panel filename])));
  228268. }
  228269. else
  228270. {
  228271. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228272. NSArray* urls = [openPanel filenames];
  228273. for (unsigned int i = 0; i < [urls count]; ++i)
  228274. {
  228275. NSString* f = [urls objectAtIndex: i];
  228276. results.add (File (nsStringToJuce (f)));
  228277. }
  228278. }
  228279. }
  228280. [panel setDelegate: nil];
  228281. }
  228282. #else
  228283. void FileChooser::showPlatformDialog (Array<File>& results,
  228284. const String& title,
  228285. const File& currentFileOrDirectory,
  228286. const String& filter,
  228287. bool selectsDirectory,
  228288. bool selectsFiles,
  228289. bool isSaveDialogue,
  228290. bool warnAboutOverwritingExistingFiles,
  228291. bool selectMultipleFiles,
  228292. FilePreviewComponent* extraInfoComponent)
  228293. {
  228294. const ScopedAutoReleasePool pool;
  228295. jassertfalse; //xxx to do
  228296. }
  228297. #endif
  228298. #endif
  228299. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228300. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228301. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228302. // compiled on its own).
  228303. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228304. #if JUCE_MAC
  228305. END_JUCE_NAMESPACE
  228306. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228307. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228308. {
  228309. CriticalSection* contextLock;
  228310. bool needsUpdate;
  228311. }
  228312. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228313. - (bool) makeActive;
  228314. - (void) makeInactive;
  228315. - (void) reshape;
  228316. @end
  228317. @implementation ThreadSafeNSOpenGLView
  228318. - (id) initWithFrame: (NSRect) frameRect
  228319. pixelFormat: (NSOpenGLPixelFormat*) format
  228320. {
  228321. contextLock = new CriticalSection();
  228322. self = [super initWithFrame: frameRect pixelFormat: format];
  228323. if (self != nil)
  228324. [[NSNotificationCenter defaultCenter] addObserver: self
  228325. selector: @selector (_surfaceNeedsUpdate:)
  228326. name: NSViewGlobalFrameDidChangeNotification
  228327. object: self];
  228328. return self;
  228329. }
  228330. - (void) dealloc
  228331. {
  228332. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228333. delete contextLock;
  228334. [super dealloc];
  228335. }
  228336. - (bool) makeActive
  228337. {
  228338. const ScopedLock sl (*contextLock);
  228339. if ([self openGLContext] == 0)
  228340. return false;
  228341. [[self openGLContext] makeCurrentContext];
  228342. if (needsUpdate)
  228343. {
  228344. [super update];
  228345. needsUpdate = false;
  228346. }
  228347. return true;
  228348. }
  228349. - (void) makeInactive
  228350. {
  228351. const ScopedLock sl (*contextLock);
  228352. [NSOpenGLContext clearCurrentContext];
  228353. }
  228354. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228355. {
  228356. const ScopedLock sl (*contextLock);
  228357. needsUpdate = true;
  228358. }
  228359. - (void) update
  228360. {
  228361. const ScopedLock sl (*contextLock);
  228362. needsUpdate = true;
  228363. }
  228364. - (void) reshape
  228365. {
  228366. const ScopedLock sl (*contextLock);
  228367. needsUpdate = true;
  228368. }
  228369. @end
  228370. BEGIN_JUCE_NAMESPACE
  228371. class WindowedGLContext : public OpenGLContext
  228372. {
  228373. public:
  228374. WindowedGLContext (Component* const component,
  228375. const OpenGLPixelFormat& pixelFormat_,
  228376. NSOpenGLContext* sharedContext)
  228377. : renderContext (0),
  228378. pixelFormat (pixelFormat_)
  228379. {
  228380. jassert (component != 0);
  228381. NSOpenGLPixelFormatAttribute attribs [64];
  228382. int n = 0;
  228383. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228384. attribs[n++] = NSOpenGLPFAAccelerated;
  228385. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228386. attribs[n++] = NSOpenGLPFAColorSize;
  228387. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228388. pixelFormat.greenBits,
  228389. pixelFormat.blueBits);
  228390. attribs[n++] = NSOpenGLPFAAlphaSize;
  228391. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228392. attribs[n++] = NSOpenGLPFADepthSize;
  228393. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228394. attribs[n++] = NSOpenGLPFAStencilSize;
  228395. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228396. attribs[n++] = NSOpenGLPFAAccumSize;
  228397. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228398. pixelFormat.accumulationBufferGreenBits,
  228399. pixelFormat.accumulationBufferBlueBits,
  228400. pixelFormat.accumulationBufferAlphaBits);
  228401. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228402. attribs[n++] = NSOpenGLPFASampleBuffers;
  228403. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228404. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228405. attribs[n++] = NSOpenGLPFANoRecovery;
  228406. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228407. NSOpenGLPixelFormat* format
  228408. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228409. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228410. pixelFormat: format];
  228411. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228412. shareContext: sharedContext] autorelease];
  228413. const GLint swapInterval = 1;
  228414. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228415. [view setOpenGLContext: renderContext];
  228416. [format release];
  228417. viewHolder = new NSViewComponentInternal (view, component);
  228418. }
  228419. ~WindowedGLContext()
  228420. {
  228421. deleteContext();
  228422. viewHolder = 0;
  228423. }
  228424. void deleteContext()
  228425. {
  228426. makeInactive();
  228427. [renderContext clearDrawable];
  228428. [renderContext setView: nil];
  228429. [view setOpenGLContext: nil];
  228430. renderContext = nil;
  228431. }
  228432. bool makeActive() const throw()
  228433. {
  228434. jassert (renderContext != 0);
  228435. if ([renderContext view] != view)
  228436. [renderContext setView: view];
  228437. [view makeActive];
  228438. return isActive();
  228439. }
  228440. bool makeInactive() const throw()
  228441. {
  228442. [view makeInactive];
  228443. return true;
  228444. }
  228445. bool isActive() const throw()
  228446. {
  228447. return [NSOpenGLContext currentContext] == renderContext;
  228448. }
  228449. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228450. void* getRawContext() const throw() { return renderContext; }
  228451. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228452. {
  228453. }
  228454. void swapBuffers()
  228455. {
  228456. [renderContext flushBuffer];
  228457. }
  228458. bool setSwapInterval (const int numFramesPerSwap)
  228459. {
  228460. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228461. forParameter: NSOpenGLCPSwapInterval];
  228462. return true;
  228463. }
  228464. int getSwapInterval() const
  228465. {
  228466. GLint numFrames = 0;
  228467. [renderContext getValues: &numFrames
  228468. forParameter: NSOpenGLCPSwapInterval];
  228469. return numFrames;
  228470. }
  228471. void repaint()
  228472. {
  228473. // we need to invalidate the juce view that holds this gl view, to make it
  228474. // cause a repaint callback
  228475. NSView* v = (NSView*) viewHolder->view;
  228476. NSRect r = [v frame];
  228477. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228478. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228479. // repaint message, thus never causing our paint() callback, and never repainting
  228480. // the comp. So invalidating just a little bit around the edge helps..
  228481. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228482. }
  228483. void* getNativeWindowHandle() const { return viewHolder->view; }
  228484. NSOpenGLContext* renderContext;
  228485. ThreadSafeNSOpenGLView* view;
  228486. private:
  228487. OpenGLPixelFormat pixelFormat;
  228488. ScopedPointer <NSViewComponentInternal> viewHolder;
  228489. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  228490. };
  228491. OpenGLContext* OpenGLComponent::createContext()
  228492. {
  228493. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228494. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228495. return (c->renderContext != 0) ? c.release() : 0;
  228496. }
  228497. void* OpenGLComponent::getNativeWindowHandle() const
  228498. {
  228499. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228500. : 0;
  228501. }
  228502. void juce_glViewport (const int w, const int h)
  228503. {
  228504. glViewport (0, 0, w, h);
  228505. }
  228506. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228507. OwnedArray <OpenGLPixelFormat>& results)
  228508. {
  228509. /* GLint attribs [64];
  228510. int n = 0;
  228511. attribs[n++] = AGL_RGBA;
  228512. attribs[n++] = AGL_DOUBLEBUFFER;
  228513. attribs[n++] = AGL_ACCELERATED;
  228514. attribs[n++] = AGL_NO_RECOVERY;
  228515. attribs[n++] = AGL_NONE;
  228516. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228517. while (p != 0)
  228518. {
  228519. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228520. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228521. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228522. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228523. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228524. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228525. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228526. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228527. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228528. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228529. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228530. results.add (pf);
  228531. p = aglNextPixelFormat (p);
  228532. }*/
  228533. //jassertfalse // can't see how you do this in cocoa!
  228534. }
  228535. #else
  228536. END_JUCE_NAMESPACE
  228537. @interface JuceGLView : UIView
  228538. {
  228539. }
  228540. + (Class) layerClass;
  228541. @end
  228542. @implementation JuceGLView
  228543. + (Class) layerClass
  228544. {
  228545. return [CAEAGLLayer class];
  228546. }
  228547. @end
  228548. BEGIN_JUCE_NAMESPACE
  228549. class GLESContext : public OpenGLContext
  228550. {
  228551. public:
  228552. GLESContext (UIViewComponentPeer* peer,
  228553. Component* const component_,
  228554. const OpenGLPixelFormat& pixelFormat_,
  228555. const GLESContext* const sharedContext,
  228556. NSUInteger apiType)
  228557. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228558. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228559. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228560. {
  228561. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228562. view.opaque = YES;
  228563. view.hidden = NO;
  228564. view.backgroundColor = [UIColor blackColor];
  228565. view.userInteractionEnabled = NO;
  228566. glLayer = (CAEAGLLayer*) [view layer];
  228567. [peer->view addSubview: view];
  228568. if (sharedContext != 0)
  228569. context = [[EAGLContext alloc] initWithAPI: apiType
  228570. sharegroup: [sharedContext->context sharegroup]];
  228571. else
  228572. context = [[EAGLContext alloc] initWithAPI: apiType];
  228573. createGLBuffers();
  228574. }
  228575. ~GLESContext()
  228576. {
  228577. deleteContext();
  228578. [view removeFromSuperview];
  228579. [view release];
  228580. freeGLBuffers();
  228581. }
  228582. void deleteContext()
  228583. {
  228584. makeInactive();
  228585. [context release];
  228586. context = nil;
  228587. }
  228588. bool makeActive() const throw()
  228589. {
  228590. jassert (context != 0);
  228591. [EAGLContext setCurrentContext: context];
  228592. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228593. return true;
  228594. }
  228595. void swapBuffers()
  228596. {
  228597. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228598. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228599. }
  228600. bool makeInactive() const throw()
  228601. {
  228602. return [EAGLContext setCurrentContext: nil];
  228603. }
  228604. bool isActive() const throw()
  228605. {
  228606. return [EAGLContext currentContext] == context;
  228607. }
  228608. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228609. void* getRawContext() const throw() { return glLayer; }
  228610. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228611. {
  228612. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228613. if (lastWidth != w || lastHeight != h)
  228614. {
  228615. lastWidth = w;
  228616. lastHeight = h;
  228617. freeGLBuffers();
  228618. createGLBuffers();
  228619. }
  228620. }
  228621. bool setSwapInterval (const int numFramesPerSwap)
  228622. {
  228623. numFrames = numFramesPerSwap;
  228624. return true;
  228625. }
  228626. int getSwapInterval() const
  228627. {
  228628. return numFrames;
  228629. }
  228630. void repaint()
  228631. {
  228632. }
  228633. void createGLBuffers()
  228634. {
  228635. makeActive();
  228636. glGenFramebuffersOES (1, &frameBufferHandle);
  228637. glGenRenderbuffersOES (1, &colorBufferHandle);
  228638. glGenRenderbuffersOES (1, &depthBufferHandle);
  228639. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228640. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228641. GLint width, height;
  228642. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228643. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228644. if (useDepthBuffer)
  228645. {
  228646. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228647. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228648. }
  228649. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228650. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228651. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228652. if (useDepthBuffer)
  228653. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228654. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228655. }
  228656. void freeGLBuffers()
  228657. {
  228658. if (frameBufferHandle != 0)
  228659. {
  228660. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228661. frameBufferHandle = 0;
  228662. }
  228663. if (colorBufferHandle != 0)
  228664. {
  228665. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228666. colorBufferHandle = 0;
  228667. }
  228668. if (depthBufferHandle != 0)
  228669. {
  228670. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228671. depthBufferHandle = 0;
  228672. }
  228673. }
  228674. private:
  228675. Component::SafePointer<Component> component;
  228676. OpenGLPixelFormat pixelFormat;
  228677. JuceGLView* view;
  228678. CAEAGLLayer* glLayer;
  228679. EAGLContext* context;
  228680. bool useDepthBuffer;
  228681. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228682. int numFrames;
  228683. int lastWidth, lastHeight;
  228684. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  228685. };
  228686. OpenGLContext* OpenGLComponent::createContext()
  228687. {
  228688. ScopedAutoReleasePool pool;
  228689. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228690. if (peer != 0)
  228691. return new GLESContext (peer, this, preferredPixelFormat,
  228692. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228693. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228694. return 0;
  228695. }
  228696. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228697. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228698. {
  228699. }
  228700. void juce_glViewport (const int w, const int h)
  228701. {
  228702. glViewport (0, 0, w, h);
  228703. }
  228704. #endif
  228705. #endif
  228706. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228707. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228708. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228709. // compiled on its own).
  228710. #if JUCE_INCLUDED_FILE
  228711. #if JUCE_MAC
  228712. namespace MouseCursorHelpers
  228713. {
  228714. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228715. {
  228716. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228717. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228718. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228719. [im release];
  228720. return c;
  228721. }
  228722. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228723. {
  228724. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228725. BufferedInputStream buf (fileStream, 4096);
  228726. PNGImageFormat pngFormat;
  228727. Image im (pngFormat.decodeImage (buf));
  228728. if (im.isValid())
  228729. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228730. jassertfalse;
  228731. return 0;
  228732. }
  228733. }
  228734. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228735. {
  228736. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228737. }
  228738. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228739. {
  228740. const ScopedAutoReleasePool pool;
  228741. NSCursor* c = 0;
  228742. switch (type)
  228743. {
  228744. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228745. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228746. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228747. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228748. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228749. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228750. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228751. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228752. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228753. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228754. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228755. case UpDownResizeCursor:
  228756. case TopEdgeResizeCursor:
  228757. case BottomEdgeResizeCursor:
  228758. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228759. case TopLeftCornerResizeCursor:
  228760. case BottomRightCornerResizeCursor:
  228761. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228762. case TopRightCornerResizeCursor:
  228763. case BottomLeftCornerResizeCursor:
  228764. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228765. case UpDownLeftRightResizeCursor:
  228766. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228767. default:
  228768. jassertfalse;
  228769. break;
  228770. }
  228771. [c retain];
  228772. return c;
  228773. }
  228774. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228775. {
  228776. [((NSCursor*) cursorHandle) release];
  228777. }
  228778. void MouseCursor::showInAllWindows() const
  228779. {
  228780. showInWindow (0);
  228781. }
  228782. void MouseCursor::showInWindow (ComponentPeer*) const
  228783. {
  228784. NSCursor* c = (NSCursor*) getHandle();
  228785. if (c == 0)
  228786. c = [NSCursor arrowCursor];
  228787. [c set];
  228788. }
  228789. #else
  228790. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228791. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228792. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228793. void MouseCursor::showInAllWindows() const {}
  228794. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228795. #endif
  228796. #endif
  228797. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228798. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228799. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228800. // compiled on its own).
  228801. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228802. #if JUCE_MAC
  228803. END_JUCE_NAMESPACE
  228804. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228805. @interface DownloadClickDetector : NSObject
  228806. {
  228807. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228808. }
  228809. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228810. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228811. request: (NSURLRequest*) request
  228812. frame: (WebFrame*) frame
  228813. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228814. @end
  228815. @implementation DownloadClickDetector
  228816. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228817. {
  228818. [super init];
  228819. ownerComponent = ownerComponent_;
  228820. return self;
  228821. }
  228822. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228823. request: (NSURLRequest*) request
  228824. frame: (WebFrame*) frame
  228825. decisionListener: (id <WebPolicyDecisionListener>) listener
  228826. {
  228827. (void) sender;
  228828. (void) request;
  228829. (void) frame;
  228830. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228831. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228832. [listener use];
  228833. else
  228834. [listener ignore];
  228835. }
  228836. @end
  228837. BEGIN_JUCE_NAMESPACE
  228838. class WebBrowserComponentInternal : public NSViewComponent
  228839. {
  228840. public:
  228841. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228842. {
  228843. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228844. frameName: @""
  228845. groupName: @""];
  228846. setView (webView);
  228847. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228848. [webView setPolicyDelegate: clickListener];
  228849. }
  228850. ~WebBrowserComponentInternal()
  228851. {
  228852. [webView setPolicyDelegate: nil];
  228853. [clickListener release];
  228854. setView (0);
  228855. }
  228856. void goToURL (const String& url,
  228857. const StringArray* headers,
  228858. const MemoryBlock* postData)
  228859. {
  228860. NSMutableURLRequest* r
  228861. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228862. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228863. timeoutInterval: 30.0];
  228864. if (postData != 0 && postData->getSize() > 0)
  228865. {
  228866. [r setHTTPMethod: @"POST"];
  228867. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228868. length: postData->getSize()]];
  228869. }
  228870. if (headers != 0)
  228871. {
  228872. for (int i = 0; i < headers->size(); ++i)
  228873. {
  228874. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228875. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228876. [r setValue: juceStringToNS (headerValue)
  228877. forHTTPHeaderField: juceStringToNS (headerName)];
  228878. }
  228879. }
  228880. stop();
  228881. [[webView mainFrame] loadRequest: r];
  228882. }
  228883. void goBack()
  228884. {
  228885. [webView goBack];
  228886. }
  228887. void goForward()
  228888. {
  228889. [webView goForward];
  228890. }
  228891. void stop()
  228892. {
  228893. [webView stopLoading: nil];
  228894. }
  228895. void refresh()
  228896. {
  228897. [webView reload: nil];
  228898. }
  228899. void mouseMove (const MouseEvent&)
  228900. {
  228901. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228902. // them work is to push them via this non-public method..
  228903. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228904. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228905. }
  228906. private:
  228907. WebView* webView;
  228908. DownloadClickDetector* clickListener;
  228909. };
  228910. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228911. : browser (0),
  228912. blankPageShown (false),
  228913. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228914. {
  228915. setOpaque (true);
  228916. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228917. }
  228918. WebBrowserComponent::~WebBrowserComponent()
  228919. {
  228920. deleteAndZero (browser);
  228921. }
  228922. void WebBrowserComponent::goToURL (const String& url,
  228923. const StringArray* headers,
  228924. const MemoryBlock* postData)
  228925. {
  228926. lastURL = url;
  228927. lastHeaders.clear();
  228928. if (headers != 0)
  228929. lastHeaders = *headers;
  228930. lastPostData.setSize (0);
  228931. if (postData != 0)
  228932. lastPostData = *postData;
  228933. blankPageShown = false;
  228934. browser->goToURL (url, headers, postData);
  228935. }
  228936. void WebBrowserComponent::stop()
  228937. {
  228938. browser->stop();
  228939. }
  228940. void WebBrowserComponent::goBack()
  228941. {
  228942. lastURL = String::empty;
  228943. blankPageShown = false;
  228944. browser->goBack();
  228945. }
  228946. void WebBrowserComponent::goForward()
  228947. {
  228948. lastURL = String::empty;
  228949. browser->goForward();
  228950. }
  228951. void WebBrowserComponent::refresh()
  228952. {
  228953. browser->refresh();
  228954. }
  228955. void WebBrowserComponent::paint (Graphics&)
  228956. {
  228957. }
  228958. void WebBrowserComponent::checkWindowAssociation()
  228959. {
  228960. if (isShowing())
  228961. {
  228962. if (blankPageShown)
  228963. goBack();
  228964. }
  228965. else
  228966. {
  228967. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228968. {
  228969. // when the component becomes invisible, some stuff like flash
  228970. // carries on playing audio, so we need to force it onto a blank
  228971. // page to avoid this, (and send it back when it's made visible again).
  228972. blankPageShown = true;
  228973. browser->goToURL ("about:blank", 0, 0);
  228974. }
  228975. }
  228976. }
  228977. void WebBrowserComponent::reloadLastURL()
  228978. {
  228979. if (lastURL.isNotEmpty())
  228980. {
  228981. goToURL (lastURL, &lastHeaders, &lastPostData);
  228982. lastURL = String::empty;
  228983. }
  228984. }
  228985. void WebBrowserComponent::parentHierarchyChanged()
  228986. {
  228987. checkWindowAssociation();
  228988. }
  228989. void WebBrowserComponent::resized()
  228990. {
  228991. browser->setSize (getWidth(), getHeight());
  228992. }
  228993. void WebBrowserComponent::visibilityChanged()
  228994. {
  228995. checkWindowAssociation();
  228996. }
  228997. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228998. {
  228999. return true;
  229000. }
  229001. #else
  229002. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229003. {
  229004. }
  229005. WebBrowserComponent::~WebBrowserComponent()
  229006. {
  229007. }
  229008. void WebBrowserComponent::goToURL (const String& url,
  229009. const StringArray* headers,
  229010. const MemoryBlock* postData)
  229011. {
  229012. }
  229013. void WebBrowserComponent::stop()
  229014. {
  229015. }
  229016. void WebBrowserComponent::goBack()
  229017. {
  229018. }
  229019. void WebBrowserComponent::goForward()
  229020. {
  229021. }
  229022. void WebBrowserComponent::refresh()
  229023. {
  229024. }
  229025. void WebBrowserComponent::paint (Graphics& g)
  229026. {
  229027. }
  229028. void WebBrowserComponent::checkWindowAssociation()
  229029. {
  229030. }
  229031. void WebBrowserComponent::reloadLastURL()
  229032. {
  229033. }
  229034. void WebBrowserComponent::parentHierarchyChanged()
  229035. {
  229036. }
  229037. void WebBrowserComponent::resized()
  229038. {
  229039. }
  229040. void WebBrowserComponent::visibilityChanged()
  229041. {
  229042. }
  229043. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  229044. {
  229045. return true;
  229046. }
  229047. #endif
  229048. #endif
  229049. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229050. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  229051. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229052. // compiled on its own).
  229053. #if JUCE_INCLUDED_FILE
  229054. class IPhoneAudioIODevice : public AudioIODevice
  229055. {
  229056. public:
  229057. IPhoneAudioIODevice (const String& deviceName)
  229058. : AudioIODevice (deviceName, "Audio"),
  229059. actualBufferSize (0),
  229060. isRunning (false),
  229061. audioUnit (0),
  229062. callback (0),
  229063. floatData (1, 2)
  229064. {
  229065. numInputChannels = 2;
  229066. numOutputChannels = 2;
  229067. preferredBufferSize = 0;
  229068. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  229069. updateDeviceInfo();
  229070. }
  229071. ~IPhoneAudioIODevice()
  229072. {
  229073. close();
  229074. }
  229075. const StringArray getOutputChannelNames()
  229076. {
  229077. StringArray s;
  229078. s.add ("Left");
  229079. s.add ("Right");
  229080. return s;
  229081. }
  229082. const StringArray getInputChannelNames()
  229083. {
  229084. StringArray s;
  229085. if (audioInputIsAvailable)
  229086. {
  229087. s.add ("Left");
  229088. s.add ("Right");
  229089. }
  229090. return s;
  229091. }
  229092. int getNumSampleRates()
  229093. {
  229094. return 1;
  229095. }
  229096. double getSampleRate (int index)
  229097. {
  229098. return sampleRate;
  229099. }
  229100. int getNumBufferSizesAvailable()
  229101. {
  229102. return 1;
  229103. }
  229104. int getBufferSizeSamples (int index)
  229105. {
  229106. return getDefaultBufferSize();
  229107. }
  229108. int getDefaultBufferSize()
  229109. {
  229110. return 1024;
  229111. }
  229112. const String open (const BigInteger& inputChannels,
  229113. const BigInteger& outputChannels,
  229114. double sampleRate,
  229115. int bufferSize)
  229116. {
  229117. close();
  229118. lastError = String::empty;
  229119. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  229120. // xxx set up channel mapping
  229121. activeOutputChans = outputChannels;
  229122. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  229123. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  229124. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  229125. activeInputChans = inputChannels;
  229126. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  229127. numInputChannels = activeInputChans.countNumberOfSetBits();
  229128. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  229129. AudioSessionSetActive (true);
  229130. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  229131. : kAudioSessionCategory_MediaPlayback;
  229132. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  229133. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  229134. fixAudioRouteIfSetToReceiver();
  229135. updateDeviceInfo();
  229136. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229137. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  229138. actualBufferSize = preferredBufferSize;
  229139. prepareFloatBuffers();
  229140. isRunning = true;
  229141. propertyChanged (0, 0, 0); // creates and starts the AU
  229142. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  229143. return lastError;
  229144. }
  229145. void close()
  229146. {
  229147. if (isRunning)
  229148. {
  229149. isRunning = false;
  229150. AudioSessionSetActive (false);
  229151. if (audioUnit != 0)
  229152. {
  229153. AudioComponentInstanceDispose (audioUnit);
  229154. audioUnit = 0;
  229155. }
  229156. }
  229157. }
  229158. bool isOpen()
  229159. {
  229160. return isRunning;
  229161. }
  229162. int getCurrentBufferSizeSamples()
  229163. {
  229164. return actualBufferSize;
  229165. }
  229166. double getCurrentSampleRate()
  229167. {
  229168. return sampleRate;
  229169. }
  229170. int getCurrentBitDepth()
  229171. {
  229172. return 16;
  229173. }
  229174. const BigInteger getActiveOutputChannels() const
  229175. {
  229176. return activeOutputChans;
  229177. }
  229178. const BigInteger getActiveInputChannels() const
  229179. {
  229180. return activeInputChans;
  229181. }
  229182. int getOutputLatencyInSamples()
  229183. {
  229184. return 0; //xxx
  229185. }
  229186. int getInputLatencyInSamples()
  229187. {
  229188. return 0; //xxx
  229189. }
  229190. void start (AudioIODeviceCallback* callback_)
  229191. {
  229192. if (isRunning && callback != callback_)
  229193. {
  229194. if (callback_ != 0)
  229195. callback_->audioDeviceAboutToStart (this);
  229196. const ScopedLock sl (callbackLock);
  229197. callback = callback_;
  229198. }
  229199. }
  229200. void stop()
  229201. {
  229202. if (isRunning)
  229203. {
  229204. AudioIODeviceCallback* lastCallback;
  229205. {
  229206. const ScopedLock sl (callbackLock);
  229207. lastCallback = callback;
  229208. callback = 0;
  229209. }
  229210. if (lastCallback != 0)
  229211. lastCallback->audioDeviceStopped();
  229212. }
  229213. }
  229214. bool isPlaying()
  229215. {
  229216. return isRunning && callback != 0;
  229217. }
  229218. const String getLastError()
  229219. {
  229220. return lastError;
  229221. }
  229222. private:
  229223. CriticalSection callbackLock;
  229224. Float64 sampleRate;
  229225. int numInputChannels, numOutputChannels;
  229226. int preferredBufferSize;
  229227. int actualBufferSize;
  229228. bool isRunning;
  229229. String lastError;
  229230. AudioStreamBasicDescription format;
  229231. AudioUnit audioUnit;
  229232. UInt32 audioInputIsAvailable;
  229233. AudioIODeviceCallback* callback;
  229234. BigInteger activeOutputChans, activeInputChans;
  229235. AudioSampleBuffer floatData;
  229236. float* inputChannels[3];
  229237. float* outputChannels[3];
  229238. bool monoInputChannelNumber, monoOutputChannelNumber;
  229239. void prepareFloatBuffers()
  229240. {
  229241. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229242. zerostruct (inputChannels);
  229243. zerostruct (outputChannels);
  229244. for (int i = 0; i < numInputChannels; ++i)
  229245. inputChannels[i] = floatData.getSampleData (i);
  229246. for (int i = 0; i < numOutputChannels; ++i)
  229247. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229248. }
  229249. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229250. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229251. {
  229252. OSStatus err = noErr;
  229253. if (audioInputIsAvailable)
  229254. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229255. const ScopedLock sl (callbackLock);
  229256. if (callback != 0)
  229257. {
  229258. if (audioInputIsAvailable && numInputChannels > 0)
  229259. {
  229260. short* shortData = (short*) ioData->mBuffers[0].mData;
  229261. if (numInputChannels >= 2)
  229262. {
  229263. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229264. {
  229265. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229266. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229267. }
  229268. }
  229269. else
  229270. {
  229271. if (monoInputChannelNumber > 0)
  229272. ++shortData;
  229273. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229274. {
  229275. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229276. ++shortData;
  229277. }
  229278. }
  229279. }
  229280. else
  229281. {
  229282. for (int i = numInputChannels; --i >= 0;)
  229283. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229284. }
  229285. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229286. outputChannels, numOutputChannels,
  229287. (int) inNumberFrames);
  229288. short* shortData = (short*) ioData->mBuffers[0].mData;
  229289. int n = 0;
  229290. if (numOutputChannels >= 2)
  229291. {
  229292. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229293. {
  229294. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229295. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229296. }
  229297. }
  229298. else if (numOutputChannels == 1)
  229299. {
  229300. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229301. {
  229302. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229303. shortData [n++] = s;
  229304. shortData [n++] = s;
  229305. }
  229306. }
  229307. else
  229308. {
  229309. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229310. }
  229311. }
  229312. else
  229313. {
  229314. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229315. }
  229316. return err;
  229317. }
  229318. void updateDeviceInfo()
  229319. {
  229320. UInt32 size = sizeof (sampleRate);
  229321. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229322. size = sizeof (audioInputIsAvailable);
  229323. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229324. }
  229325. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229326. {
  229327. if (! isRunning)
  229328. return;
  229329. if (inPropertyValue != 0)
  229330. {
  229331. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229332. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229333. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229334. SInt32 routeChangeReason;
  229335. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229336. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229337. fixAudioRouteIfSetToReceiver();
  229338. }
  229339. updateDeviceInfo();
  229340. createAudioUnit();
  229341. AudioSessionSetActive (true);
  229342. if (audioUnit != 0)
  229343. {
  229344. UInt32 formatSize = sizeof (format);
  229345. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229346. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229347. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229348. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229349. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229350. AudioOutputUnitStart (audioUnit);
  229351. }
  229352. }
  229353. void interruptionListener (UInt32 inInterruption)
  229354. {
  229355. /*if (inInterruption == kAudioSessionBeginInterruption)
  229356. {
  229357. isRunning = false;
  229358. AudioOutputUnitStop (audioUnit);
  229359. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229360. "This could have been interrupted by another application or by unplugging a headset",
  229361. @"Resume",
  229362. @"Cancel"))
  229363. {
  229364. isRunning = true;
  229365. propertyChanged (0, 0, 0);
  229366. }
  229367. }*/
  229368. if (inInterruption == kAudioSessionEndInterruption)
  229369. {
  229370. isRunning = true;
  229371. AudioSessionSetActive (true);
  229372. AudioOutputUnitStart (audioUnit);
  229373. }
  229374. }
  229375. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229376. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229377. {
  229378. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229379. }
  229380. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229381. {
  229382. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229383. }
  229384. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229385. {
  229386. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229387. }
  229388. void resetFormat (const int numChannels)
  229389. {
  229390. memset (&format, 0, sizeof (format));
  229391. format.mFormatID = kAudioFormatLinearPCM;
  229392. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229393. format.mBitsPerChannel = 8 * sizeof (short);
  229394. format.mChannelsPerFrame = 2;
  229395. format.mFramesPerPacket = 1;
  229396. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229397. }
  229398. bool createAudioUnit()
  229399. {
  229400. if (audioUnit != 0)
  229401. {
  229402. AudioComponentInstanceDispose (audioUnit);
  229403. audioUnit = 0;
  229404. }
  229405. resetFormat (2);
  229406. AudioComponentDescription desc;
  229407. desc.componentType = kAudioUnitType_Output;
  229408. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229409. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229410. desc.componentFlags = 0;
  229411. desc.componentFlagsMask = 0;
  229412. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229413. AudioComponentInstanceNew (comp, &audioUnit);
  229414. if (audioUnit == 0)
  229415. return false;
  229416. const UInt32 one = 1;
  229417. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229418. AudioChannelLayout layout;
  229419. layout.mChannelBitmap = 0;
  229420. layout.mNumberChannelDescriptions = 0;
  229421. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229422. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229423. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229424. AURenderCallbackStruct inputProc;
  229425. inputProc.inputProc = processStatic;
  229426. inputProc.inputProcRefCon = this;
  229427. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229428. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229429. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229430. AudioUnitInitialize (audioUnit);
  229431. return true;
  229432. }
  229433. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229434. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229435. static void fixAudioRouteIfSetToReceiver()
  229436. {
  229437. CFStringRef audioRoute = 0;
  229438. UInt32 propertySize = sizeof (audioRoute);
  229439. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229440. {
  229441. NSString* route = (NSString*) audioRoute;
  229442. //DBG ("audio route: " + nsStringToJuce (route));
  229443. if ([route hasPrefix: @"Receiver"])
  229444. {
  229445. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229446. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229447. }
  229448. CFRelease (audioRoute);
  229449. }
  229450. }
  229451. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  229452. };
  229453. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229454. {
  229455. public:
  229456. IPhoneAudioIODeviceType()
  229457. : AudioIODeviceType ("iPhone Audio")
  229458. {
  229459. }
  229460. void scanForDevices()
  229461. {
  229462. }
  229463. const StringArray getDeviceNames (bool wantInputNames) const
  229464. {
  229465. StringArray s;
  229466. s.add ("iPhone Audio");
  229467. return s;
  229468. }
  229469. int getDefaultDeviceIndex (bool forInput) const
  229470. {
  229471. return 0;
  229472. }
  229473. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229474. {
  229475. return device != 0 ? 0 : -1;
  229476. }
  229477. bool hasSeparateInputsAndOutputs() const { return false; }
  229478. AudioIODevice* createDevice (const String& outputDeviceName,
  229479. const String& inputDeviceName)
  229480. {
  229481. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229482. {
  229483. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229484. : inputDeviceName);
  229485. }
  229486. return 0;
  229487. }
  229488. private:
  229489. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  229490. };
  229491. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229492. {
  229493. return new IPhoneAudioIODeviceType();
  229494. }
  229495. #endif
  229496. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229497. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229498. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229499. // compiled on its own).
  229500. #if JUCE_INCLUDED_FILE
  229501. #if JUCE_MAC
  229502. namespace CoreMidiHelpers
  229503. {
  229504. static bool logError (const OSStatus err, const int lineNum)
  229505. {
  229506. if (err == noErr)
  229507. return true;
  229508. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229509. jassertfalse;
  229510. return false;
  229511. }
  229512. #undef CHECK_ERROR
  229513. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229514. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229515. {
  229516. String result;
  229517. CFStringRef str = 0;
  229518. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229519. if (str != 0)
  229520. {
  229521. result = PlatformUtilities::cfStringToJuceString (str);
  229522. CFRelease (str);
  229523. str = 0;
  229524. }
  229525. MIDIEntityRef entity = 0;
  229526. MIDIEndpointGetEntity (endpoint, &entity);
  229527. if (entity == 0)
  229528. return result; // probably virtual
  229529. if (result.isEmpty())
  229530. {
  229531. // endpoint name has zero length - try the entity
  229532. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229533. if (str != 0)
  229534. {
  229535. result += PlatformUtilities::cfStringToJuceString (str);
  229536. CFRelease (str);
  229537. str = 0;
  229538. }
  229539. }
  229540. // now consider the device's name
  229541. MIDIDeviceRef device = 0;
  229542. MIDIEntityGetDevice (entity, &device);
  229543. if (device == 0)
  229544. return result;
  229545. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229546. if (str != 0)
  229547. {
  229548. const String s (PlatformUtilities::cfStringToJuceString (str));
  229549. CFRelease (str);
  229550. // if an external device has only one entity, throw away
  229551. // the endpoint name and just use the device name
  229552. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229553. {
  229554. result = s;
  229555. }
  229556. else if (! result.startsWithIgnoreCase (s))
  229557. {
  229558. // prepend the device name to the entity name
  229559. result = (s + " " + result).trimEnd();
  229560. }
  229561. }
  229562. return result;
  229563. }
  229564. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229565. {
  229566. String result;
  229567. // Does the endpoint have connections?
  229568. CFDataRef connections = 0;
  229569. int numConnections = 0;
  229570. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229571. if (connections != 0)
  229572. {
  229573. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229574. if (numConnections > 0)
  229575. {
  229576. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229577. for (int i = 0; i < numConnections; ++i, ++pid)
  229578. {
  229579. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229580. MIDIObjectRef connObject;
  229581. MIDIObjectType connObjectType;
  229582. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229583. if (err == noErr)
  229584. {
  229585. String s;
  229586. if (connObjectType == kMIDIObjectType_ExternalSource
  229587. || connObjectType == kMIDIObjectType_ExternalDestination)
  229588. {
  229589. // Connected to an external device's endpoint (10.3 and later).
  229590. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229591. }
  229592. else
  229593. {
  229594. // Connected to an external device (10.2) (or something else, catch-all)
  229595. CFStringRef str = 0;
  229596. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229597. if (str != 0)
  229598. {
  229599. s = PlatformUtilities::cfStringToJuceString (str);
  229600. CFRelease (str);
  229601. }
  229602. }
  229603. if (s.isNotEmpty())
  229604. {
  229605. if (result.isNotEmpty())
  229606. result += ", ";
  229607. result += s;
  229608. }
  229609. }
  229610. }
  229611. }
  229612. CFRelease (connections);
  229613. }
  229614. if (result.isNotEmpty())
  229615. return result;
  229616. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229617. return getEndpointName (endpoint, false);
  229618. }
  229619. static MIDIClientRef getGlobalMidiClient()
  229620. {
  229621. static MIDIClientRef globalMidiClient = 0;
  229622. if (globalMidiClient == 0)
  229623. {
  229624. String name ("JUCE");
  229625. if (JUCEApplication::getInstance() != 0)
  229626. name = JUCEApplication::getInstance()->getApplicationName();
  229627. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229628. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229629. CFRelease (appName);
  229630. }
  229631. return globalMidiClient;
  229632. }
  229633. class MidiPortAndEndpoint
  229634. {
  229635. public:
  229636. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229637. : port (port_), endPoint (endPoint_)
  229638. {
  229639. }
  229640. ~MidiPortAndEndpoint()
  229641. {
  229642. if (port != 0)
  229643. MIDIPortDispose (port);
  229644. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229645. MIDIEndpointDispose (endPoint);
  229646. }
  229647. void send (const MIDIPacketList* const packets)
  229648. {
  229649. if (port != 0)
  229650. MIDISend (port, endPoint, packets);
  229651. else
  229652. MIDIReceived (endPoint, packets);
  229653. }
  229654. MIDIPortRef port;
  229655. MIDIEndpointRef endPoint;
  229656. };
  229657. class MidiPortAndCallback;
  229658. static CriticalSection callbackLock;
  229659. static Array<MidiPortAndCallback*> activeCallbacks;
  229660. class MidiPortAndCallback
  229661. {
  229662. public:
  229663. MidiPortAndCallback (MidiInputCallback& callback_)
  229664. : input (0), active (false), callback (callback_), concatenator (2048)
  229665. {
  229666. }
  229667. ~MidiPortAndCallback()
  229668. {
  229669. active = false;
  229670. {
  229671. const ScopedLock sl (callbackLock);
  229672. activeCallbacks.removeValue (this);
  229673. }
  229674. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229675. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229676. }
  229677. void handlePackets (const MIDIPacketList* const pktlist)
  229678. {
  229679. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229680. const ScopedLock sl (callbackLock);
  229681. if (activeCallbacks.contains (this) && active)
  229682. {
  229683. const MIDIPacket* packet = &pktlist->packet[0];
  229684. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229685. {
  229686. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229687. input, callback);
  229688. packet = MIDIPacketNext (packet);
  229689. }
  229690. }
  229691. }
  229692. MidiInput* input;
  229693. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229694. volatile bool active;
  229695. private:
  229696. MidiInputCallback& callback;
  229697. MidiDataConcatenator concatenator;
  229698. };
  229699. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229700. {
  229701. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229702. }
  229703. }
  229704. const StringArray MidiOutput::getDevices()
  229705. {
  229706. StringArray s;
  229707. const ItemCount num = MIDIGetNumberOfDestinations();
  229708. for (ItemCount i = 0; i < num; ++i)
  229709. {
  229710. MIDIEndpointRef dest = MIDIGetDestination (i);
  229711. if (dest != 0)
  229712. {
  229713. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229714. if (name.isEmpty())
  229715. name = "<error>";
  229716. s.add (name);
  229717. }
  229718. else
  229719. {
  229720. s.add ("<error>");
  229721. }
  229722. }
  229723. return s;
  229724. }
  229725. int MidiOutput::getDefaultDeviceIndex()
  229726. {
  229727. return 0;
  229728. }
  229729. MidiOutput* MidiOutput::openDevice (int index)
  229730. {
  229731. MidiOutput* mo = 0;
  229732. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229733. {
  229734. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229735. CFStringRef pname;
  229736. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229737. {
  229738. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229739. MIDIPortRef port;
  229740. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229741. {
  229742. mo = new MidiOutput();
  229743. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229744. }
  229745. CFRelease (pname);
  229746. }
  229747. }
  229748. return mo;
  229749. }
  229750. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229751. {
  229752. MidiOutput* mo = 0;
  229753. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229754. MIDIEndpointRef endPoint;
  229755. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229756. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229757. {
  229758. mo = new MidiOutput();
  229759. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229760. }
  229761. CFRelease (name);
  229762. return mo;
  229763. }
  229764. MidiOutput::~MidiOutput()
  229765. {
  229766. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229767. }
  229768. void MidiOutput::reset()
  229769. {
  229770. }
  229771. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229772. {
  229773. return false;
  229774. }
  229775. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229776. {
  229777. }
  229778. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229779. {
  229780. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229781. if (message.isSysEx())
  229782. {
  229783. const int maxPacketSize = 256;
  229784. int pos = 0, bytesLeft = message.getRawDataSize();
  229785. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229786. HeapBlock <MIDIPacketList> packets;
  229787. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229788. packets->numPackets = numPackets;
  229789. MIDIPacket* p = packets->packet;
  229790. for (int i = 0; i < numPackets; ++i)
  229791. {
  229792. p->timeStamp = 0;
  229793. p->length = jmin (maxPacketSize, bytesLeft);
  229794. memcpy (p->data, message.getRawData() + pos, p->length);
  229795. pos += p->length;
  229796. bytesLeft -= p->length;
  229797. p = MIDIPacketNext (p);
  229798. }
  229799. mpe->send (packets);
  229800. }
  229801. else
  229802. {
  229803. MIDIPacketList packets;
  229804. packets.numPackets = 1;
  229805. packets.packet[0].timeStamp = 0;
  229806. packets.packet[0].length = message.getRawDataSize();
  229807. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229808. mpe->send (&packets);
  229809. }
  229810. }
  229811. const StringArray MidiInput::getDevices()
  229812. {
  229813. StringArray s;
  229814. const ItemCount num = MIDIGetNumberOfSources();
  229815. for (ItemCount i = 0; i < num; ++i)
  229816. {
  229817. MIDIEndpointRef source = MIDIGetSource (i);
  229818. if (source != 0)
  229819. {
  229820. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229821. if (name.isEmpty())
  229822. name = "<error>";
  229823. s.add (name);
  229824. }
  229825. else
  229826. {
  229827. s.add ("<error>");
  229828. }
  229829. }
  229830. return s;
  229831. }
  229832. int MidiInput::getDefaultDeviceIndex()
  229833. {
  229834. return 0;
  229835. }
  229836. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229837. {
  229838. jassert (callback != 0);
  229839. using namespace CoreMidiHelpers;
  229840. MidiInput* newInput = 0;
  229841. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  229842. {
  229843. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229844. if (endPoint != 0)
  229845. {
  229846. CFStringRef name;
  229847. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229848. {
  229849. MIDIClientRef client = getGlobalMidiClient();
  229850. if (client != 0)
  229851. {
  229852. MIDIPortRef port;
  229853. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229854. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229855. {
  229856. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229857. {
  229858. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229859. newInput = new MidiInput (getDevices() [index]);
  229860. mpc->input = newInput;
  229861. newInput->internal = mpc;
  229862. const ScopedLock sl (callbackLock);
  229863. activeCallbacks.add (mpc.release());
  229864. }
  229865. else
  229866. {
  229867. CHECK_ERROR (MIDIPortDispose (port));
  229868. }
  229869. }
  229870. }
  229871. }
  229872. CFRelease (name);
  229873. }
  229874. }
  229875. return newInput;
  229876. }
  229877. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229878. {
  229879. jassert (callback != 0);
  229880. using namespace CoreMidiHelpers;
  229881. MidiInput* mi = 0;
  229882. MIDIClientRef client = getGlobalMidiClient();
  229883. if (client != 0)
  229884. {
  229885. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229886. mpc->active = false;
  229887. MIDIEndpointRef endPoint;
  229888. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229889. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229890. {
  229891. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229892. mi = new MidiInput (deviceName);
  229893. mpc->input = mi;
  229894. mi->internal = mpc;
  229895. const ScopedLock sl (callbackLock);
  229896. activeCallbacks.add (mpc.release());
  229897. }
  229898. CFRelease (name);
  229899. }
  229900. return mi;
  229901. }
  229902. MidiInput::MidiInput (const String& name_)
  229903. : name (name_)
  229904. {
  229905. }
  229906. MidiInput::~MidiInput()
  229907. {
  229908. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229909. }
  229910. void MidiInput::start()
  229911. {
  229912. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229913. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229914. }
  229915. void MidiInput::stop()
  229916. {
  229917. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229918. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229919. }
  229920. #undef CHECK_ERROR
  229921. #else // Stubs for iOS...
  229922. MidiOutput::~MidiOutput() {}
  229923. void MidiOutput::reset() {}
  229924. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229925. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229926. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229927. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229928. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229929. const StringArray MidiInput::getDevices() { return StringArray(); }
  229930. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229931. #endif
  229932. #endif
  229933. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229934. #else
  229935. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229936. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229937. // compiled on its own).
  229938. #if JUCE_INCLUDED_FILE
  229939. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229940. #define SUPPORT_10_4_FONTS 1
  229941. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229942. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229943. #define SUPPORT_ONLY_10_4_FONTS 1
  229944. #endif
  229945. END_JUCE_NAMESPACE
  229946. @interface NSFont (PrivateHack)
  229947. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229948. @end
  229949. BEGIN_JUCE_NAMESPACE
  229950. #endif
  229951. class MacTypeface : public Typeface
  229952. {
  229953. public:
  229954. MacTypeface (const Font& font)
  229955. : Typeface (font.getTypefaceName())
  229956. {
  229957. const ScopedAutoReleasePool pool;
  229958. renderingTransform = CGAffineTransformIdentity;
  229959. bool needsItalicTransform = false;
  229960. #if JUCE_IOS
  229961. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229962. if (font.isItalic() || font.isBold())
  229963. {
  229964. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229965. for (NSString* i in familyFonts)
  229966. {
  229967. const String fn (nsStringToJuce (i));
  229968. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229969. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229970. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229971. || afterDash.containsIgnoreCase ("italic")
  229972. || fn.endsWithIgnoreCase ("oblique")
  229973. || fn.endsWithIgnoreCase ("italic");
  229974. if (probablyBold == font.isBold()
  229975. && probablyItalic == font.isItalic())
  229976. {
  229977. fontName = i;
  229978. needsItalicTransform = false;
  229979. break;
  229980. }
  229981. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229982. {
  229983. fontName = i;
  229984. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229985. }
  229986. }
  229987. if (needsItalicTransform)
  229988. renderingTransform.c = 0.15f;
  229989. }
  229990. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229991. const int ascender = abs (CGFontGetAscent (fontRef));
  229992. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229993. ascent = ascender / totalHeight;
  229994. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229995. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229996. #else
  229997. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229998. if (font.isItalic())
  229999. {
  230000. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  230001. toHaveTrait: NSItalicFontMask];
  230002. if (newFont == nsFont)
  230003. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  230004. nsFont = newFont;
  230005. }
  230006. if (font.isBold())
  230007. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  230008. [nsFont retain];
  230009. ascent = std::abs ((float) [nsFont ascender]);
  230010. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  230011. ascent /= totalSize;
  230012. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  230013. if (needsItalicTransform)
  230014. {
  230015. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  230016. renderingTransform.c = 0.15f;
  230017. }
  230018. #if SUPPORT_ONLY_10_4_FONTS
  230019. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230020. if (atsFont == 0)
  230021. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230022. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230023. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230024. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230025. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230026. #else
  230027. #if SUPPORT_10_4_FONTS
  230028. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230029. {
  230030. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230031. if (atsFont == 0)
  230032. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230033. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230034. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230035. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230036. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230037. }
  230038. else
  230039. #endif
  230040. {
  230041. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  230042. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  230043. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230044. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  230045. }
  230046. #endif
  230047. #endif
  230048. }
  230049. ~MacTypeface()
  230050. {
  230051. #if ! JUCE_IOS
  230052. [nsFont release];
  230053. #endif
  230054. if (fontRef != 0)
  230055. CGFontRelease (fontRef);
  230056. }
  230057. float getAscent() const
  230058. {
  230059. return ascent;
  230060. }
  230061. float getDescent() const
  230062. {
  230063. return 1.0f - ascent;
  230064. }
  230065. float getStringWidth (const String& text)
  230066. {
  230067. if (fontRef == 0 || text.isEmpty())
  230068. return 0;
  230069. const int length = text.length();
  230070. HeapBlock <CGGlyph> glyphs;
  230071. createGlyphsForString (text, length, glyphs);
  230072. float x = 0;
  230073. #if SUPPORT_ONLY_10_4_FONTS
  230074. HeapBlock <NSSize> advances (length);
  230075. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230076. for (int i = 0; i < length; ++i)
  230077. x += advances[i].width;
  230078. #else
  230079. #if SUPPORT_10_4_FONTS
  230080. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230081. {
  230082. HeapBlock <NSSize> advances (length);
  230083. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  230084. for (int i = 0; i < length; ++i)
  230085. x += advances[i].width;
  230086. }
  230087. else
  230088. #endif
  230089. {
  230090. HeapBlock <int> advances (length);
  230091. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230092. for (int i = 0; i < length; ++i)
  230093. x += advances[i];
  230094. }
  230095. #endif
  230096. return x * unitsToHeightScaleFactor;
  230097. }
  230098. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  230099. {
  230100. xOffsets.add (0);
  230101. if (fontRef == 0 || text.isEmpty())
  230102. return;
  230103. const int length = text.length();
  230104. HeapBlock <CGGlyph> glyphs;
  230105. createGlyphsForString (text, length, glyphs);
  230106. #if SUPPORT_ONLY_10_4_FONTS
  230107. HeapBlock <NSSize> advances (length);
  230108. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230109. int x = 0;
  230110. for (int i = 0; i < length; ++i)
  230111. {
  230112. x += advances[i].width;
  230113. xOffsets.add (x * unitsToHeightScaleFactor);
  230114. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230115. }
  230116. #else
  230117. #if SUPPORT_10_4_FONTS
  230118. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230119. {
  230120. HeapBlock <NSSize> advances (length);
  230121. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230122. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230123. float x = 0;
  230124. for (int i = 0; i < length; ++i)
  230125. {
  230126. x += advances[i].width;
  230127. xOffsets.add (x * unitsToHeightScaleFactor);
  230128. resultGlyphs.add (nsGlyphs[i]);
  230129. }
  230130. }
  230131. else
  230132. #endif
  230133. {
  230134. HeapBlock <int> advances (length);
  230135. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230136. {
  230137. int x = 0;
  230138. for (int i = 0; i < length; ++i)
  230139. {
  230140. x += advances [i];
  230141. xOffsets.add (x * unitsToHeightScaleFactor);
  230142. resultGlyphs.add (glyphs[i]);
  230143. }
  230144. }
  230145. }
  230146. #endif
  230147. }
  230148. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230149. {
  230150. #if JUCE_IOS
  230151. return false;
  230152. #else
  230153. if (nsFont == 0)
  230154. return false;
  230155. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230156. jassert (path.isEmpty());
  230157. const ScopedAutoReleasePool pool;
  230158. NSBezierPath* bez = [NSBezierPath bezierPath];
  230159. [bez moveToPoint: NSMakePoint (0, 0)];
  230160. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230161. inFont: nsFont];
  230162. for (int i = 0; i < [bez elementCount]; ++i)
  230163. {
  230164. NSPoint p[3];
  230165. switch ([bez elementAtIndex: i associatedPoints: p])
  230166. {
  230167. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  230168. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  230169. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  230170. (float) p[1].x, (float) -p[1].y,
  230171. (float) p[2].x, (float) -p[2].y); break;
  230172. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  230173. default: jassertfalse; break;
  230174. }
  230175. }
  230176. path.applyTransform (pathTransform);
  230177. return true;
  230178. #endif
  230179. }
  230180. CGFontRef fontRef;
  230181. float fontHeightToCGSizeFactor;
  230182. CGAffineTransform renderingTransform;
  230183. private:
  230184. float ascent, unitsToHeightScaleFactor;
  230185. #if JUCE_IOS
  230186. #else
  230187. NSFont* nsFont;
  230188. AffineTransform pathTransform;
  230189. #endif
  230190. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230191. {
  230192. #if SUPPORT_10_4_FONTS
  230193. #if ! SUPPORT_ONLY_10_4_FONTS
  230194. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230195. #endif
  230196. {
  230197. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230198. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230199. for (int i = 0; i < length; ++i)
  230200. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230201. return;
  230202. }
  230203. #endif
  230204. #if ! SUPPORT_ONLY_10_4_FONTS
  230205. if (charToGlyphMapper == 0)
  230206. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230207. glyphs.malloc (length);
  230208. for (int i = 0; i < length; ++i)
  230209. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230210. #endif
  230211. }
  230212. #if ! SUPPORT_ONLY_10_4_FONTS
  230213. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230214. class CharToGlyphMapper
  230215. {
  230216. public:
  230217. CharToGlyphMapper (CGFontRef fontRef)
  230218. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230219. idRangeOffset (0), glyphIndexes (0)
  230220. {
  230221. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230222. if (cmapTable != 0)
  230223. {
  230224. const int numSubtables = getValue16 (cmapTable, 2);
  230225. for (int i = 0; i < numSubtables; ++i)
  230226. {
  230227. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230228. {
  230229. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230230. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230231. {
  230232. const int length = getValue16 (cmapTable, offset + 2);
  230233. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230234. segCount = segCountX2 / 2;
  230235. const int endCodeOffset = offset + 14;
  230236. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230237. const int idDeltaOffset = startCodeOffset + segCountX2;
  230238. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230239. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230240. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230241. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230242. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230243. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230244. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230245. }
  230246. break;
  230247. }
  230248. }
  230249. CFRelease (cmapTable);
  230250. }
  230251. }
  230252. ~CharToGlyphMapper()
  230253. {
  230254. if (endCode != 0)
  230255. {
  230256. CFRelease (endCode);
  230257. CFRelease (startCode);
  230258. CFRelease (idDelta);
  230259. CFRelease (idRangeOffset);
  230260. CFRelease (glyphIndexes);
  230261. }
  230262. }
  230263. int getGlyphForCharacter (const juce_wchar c) const
  230264. {
  230265. for (int i = 0; i < segCount; ++i)
  230266. {
  230267. if (getValue16 (endCode, i * 2) >= c)
  230268. {
  230269. const int start = getValue16 (startCode, i * 2);
  230270. if (start > c)
  230271. break;
  230272. const int delta = getValue16 (idDelta, i * 2);
  230273. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230274. if (rangeOffset == 0)
  230275. return delta + c;
  230276. else
  230277. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230278. }
  230279. }
  230280. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230281. return jmax (-1, (int) c - 29);
  230282. }
  230283. private:
  230284. int segCount;
  230285. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230286. static uint16 getValue16 (CFDataRef data, const int index)
  230287. {
  230288. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230289. }
  230290. static uint32 getValue32 (CFDataRef data, const int index)
  230291. {
  230292. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230293. }
  230294. };
  230295. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230296. #endif
  230297. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  230298. };
  230299. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230300. {
  230301. return new MacTypeface (font);
  230302. }
  230303. const StringArray Font::findAllTypefaceNames()
  230304. {
  230305. StringArray names;
  230306. const ScopedAutoReleasePool pool;
  230307. #if JUCE_IOS
  230308. NSArray* fonts = [UIFont familyNames];
  230309. #else
  230310. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230311. #endif
  230312. for (unsigned int i = 0; i < [fonts count]; ++i)
  230313. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230314. names.sort (true);
  230315. return names;
  230316. }
  230317. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  230318. {
  230319. #if JUCE_IOS
  230320. defaultSans = "Helvetica";
  230321. defaultSerif = "Times New Roman";
  230322. defaultFixed = "Courier New";
  230323. #else
  230324. defaultSans = "Lucida Grande";
  230325. defaultSerif = "Times New Roman";
  230326. defaultFixed = "Monaco";
  230327. #endif
  230328. defaultFallback = "Arial Unicode MS";
  230329. }
  230330. #endif
  230331. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230332. // (must go before juce_mac_CoreGraphicsContext.mm)
  230333. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230334. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230335. // compiled on its own).
  230336. #if JUCE_INCLUDED_FILE
  230337. class CoreGraphicsImage : public Image::SharedImage
  230338. {
  230339. public:
  230340. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230341. : Image::SharedImage (format_, width_, height_)
  230342. {
  230343. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230344. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230345. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230346. imageData = imageDataAllocated;
  230347. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230348. : CGColorSpaceCreateDeviceRGB();
  230349. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230350. colourSpace, getCGImageFlags (format_));
  230351. CGColorSpaceRelease (colourSpace);
  230352. }
  230353. ~CoreGraphicsImage()
  230354. {
  230355. CGContextRelease (context);
  230356. }
  230357. Image::ImageType getType() const { return Image::NativeImage; }
  230358. LowLevelGraphicsContext* createLowLevelContext();
  230359. SharedImage* clone()
  230360. {
  230361. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230362. memcpy (im->imageData, imageData, lineStride * height);
  230363. return im;
  230364. }
  230365. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230366. {
  230367. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230368. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230369. {
  230370. return CGBitmapContextCreateImage (nativeImage->context);
  230371. }
  230372. else
  230373. {
  230374. const Image::BitmapData srcData (juceImage, false);
  230375. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230376. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230377. 8, srcData.pixelStride * 8, srcData.lineStride,
  230378. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230379. 0, true, kCGRenderingIntentDefault);
  230380. CGDataProviderRelease (provider);
  230381. return imageRef;
  230382. }
  230383. }
  230384. #if JUCE_MAC
  230385. static NSImage* createNSImage (const Image& image)
  230386. {
  230387. const ScopedAutoReleasePool pool;
  230388. NSImage* im = [[NSImage alloc] init];
  230389. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230390. [im lockFocus];
  230391. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230392. CGImageRef imageRef = createImage (image, false, colourSpace);
  230393. CGColorSpaceRelease (colourSpace);
  230394. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230395. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230396. CGImageRelease (imageRef);
  230397. [im unlockFocus];
  230398. return im;
  230399. }
  230400. #endif
  230401. CGContextRef context;
  230402. HeapBlock<uint8> imageDataAllocated;
  230403. private:
  230404. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230405. {
  230406. #if JUCE_BIG_ENDIAN
  230407. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230408. #else
  230409. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230410. #endif
  230411. }
  230412. };
  230413. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230414. {
  230415. #if USE_COREGRAPHICS_RENDERING
  230416. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230417. #else
  230418. return createSoftwareImage (format, width, height, clearImage);
  230419. #endif
  230420. }
  230421. class CoreGraphicsContext : public LowLevelGraphicsContext
  230422. {
  230423. public:
  230424. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230425. : context (context_),
  230426. flipHeight (flipHeight_),
  230427. lastClipRectIsValid (false),
  230428. state (new SavedState()),
  230429. numGradientLookupEntries (0)
  230430. {
  230431. CGContextRetain (context);
  230432. CGContextSaveGState(context);
  230433. CGContextSetShouldSmoothFonts (context, true);
  230434. CGContextSetShouldAntialias (context, true);
  230435. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230436. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230437. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230438. gradientCallbacks.version = 0;
  230439. gradientCallbacks.evaluate = gradientCallback;
  230440. gradientCallbacks.releaseInfo = 0;
  230441. setFont (Font());
  230442. }
  230443. ~CoreGraphicsContext()
  230444. {
  230445. CGContextRestoreGState (context);
  230446. CGContextRelease (context);
  230447. CGColorSpaceRelease (rgbColourSpace);
  230448. CGColorSpaceRelease (greyColourSpace);
  230449. }
  230450. bool isVectorDevice() const { return false; }
  230451. void setOrigin (int x, int y)
  230452. {
  230453. CGContextTranslateCTM (context, x, -y);
  230454. if (lastClipRectIsValid)
  230455. lastClipRect.translate (-x, -y);
  230456. }
  230457. void addTransform (const AffineTransform& transform)
  230458. {
  230459. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  230460. .translated (0, flipHeight)
  230461. .followedBy (transform)
  230462. .translated (0, -flipHeight)
  230463. .scaled (1.0f, -1.0f));
  230464. lastClipRectIsValid = false;
  230465. }
  230466. bool clipToRectangle (const Rectangle<int>& r)
  230467. {
  230468. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230469. if (lastClipRectIsValid)
  230470. {
  230471. // This is actually incorrect, because the actual clip region may be complex, and
  230472. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230473. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230474. // when calculating the resultant clip bounds, and makes the same mistake!
  230475. lastClipRect = lastClipRect.getIntersection (r);
  230476. return ! lastClipRect.isEmpty();
  230477. }
  230478. return ! isClipEmpty();
  230479. }
  230480. bool clipToRectangleList (const RectangleList& clipRegion)
  230481. {
  230482. if (clipRegion.isEmpty())
  230483. {
  230484. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230485. lastClipRectIsValid = true;
  230486. lastClipRect = Rectangle<int>();
  230487. return false;
  230488. }
  230489. else
  230490. {
  230491. const int numRects = clipRegion.getNumRectangles();
  230492. HeapBlock <CGRect> rects (numRects);
  230493. for (int i = 0; i < numRects; ++i)
  230494. {
  230495. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230496. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230497. }
  230498. CGContextClipToRects (context, rects, numRects);
  230499. lastClipRectIsValid = false;
  230500. return ! isClipEmpty();
  230501. }
  230502. }
  230503. void excludeClipRectangle (const Rectangle<int>& r)
  230504. {
  230505. RectangleList remaining (getClipBounds());
  230506. remaining.subtract (r);
  230507. clipToRectangleList (remaining);
  230508. lastClipRectIsValid = false;
  230509. }
  230510. void clipToPath (const Path& path, const AffineTransform& transform)
  230511. {
  230512. createPath (path, transform);
  230513. CGContextClip (context);
  230514. lastClipRectIsValid = false;
  230515. }
  230516. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230517. {
  230518. if (! transform.isSingularity())
  230519. {
  230520. Image singleChannelImage (sourceImage);
  230521. if (sourceImage.getFormat() != Image::SingleChannel)
  230522. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230523. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230524. flip();
  230525. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230526. applyTransform (t);
  230527. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230528. CGContextClipToMask (context, r, image);
  230529. applyTransform (t.inverted());
  230530. flip();
  230531. CGImageRelease (image);
  230532. lastClipRectIsValid = false;
  230533. }
  230534. }
  230535. bool clipRegionIntersects (const Rectangle<int>& r)
  230536. {
  230537. return getClipBounds().intersects (r);
  230538. }
  230539. const Rectangle<int> getClipBounds() const
  230540. {
  230541. if (! lastClipRectIsValid)
  230542. {
  230543. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230544. lastClipRectIsValid = true;
  230545. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230546. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230547. roundToInt (bounds.size.width),
  230548. roundToInt (bounds.size.height));
  230549. }
  230550. return lastClipRect;
  230551. }
  230552. bool isClipEmpty() const
  230553. {
  230554. return getClipBounds().isEmpty();
  230555. }
  230556. void saveState()
  230557. {
  230558. CGContextSaveGState (context);
  230559. stateStack.add (new SavedState (*state));
  230560. }
  230561. void restoreState()
  230562. {
  230563. CGContextRestoreGState (context);
  230564. SavedState* const top = stateStack.getLast();
  230565. if (top != 0)
  230566. {
  230567. state = top;
  230568. stateStack.removeLast (1, false);
  230569. lastClipRectIsValid = false;
  230570. }
  230571. else
  230572. {
  230573. jassertfalse; // trying to pop with an empty stack!
  230574. }
  230575. }
  230576. void beginTransparencyLayer (float opacity)
  230577. {
  230578. saveState();
  230579. CGContextSetAlpha (context, opacity);
  230580. CGContextBeginTransparencyLayer (context, 0);
  230581. }
  230582. void endTransparencyLayer()
  230583. {
  230584. CGContextEndTransparencyLayer (context);
  230585. restoreState();
  230586. }
  230587. void setFill (const FillType& fillType)
  230588. {
  230589. state->fillType = fillType;
  230590. if (fillType.isColour())
  230591. {
  230592. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230593. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230594. CGContextSetAlpha (context, 1.0f);
  230595. }
  230596. }
  230597. void setOpacity (float newOpacity)
  230598. {
  230599. state->fillType.setOpacity (newOpacity);
  230600. setFill (state->fillType);
  230601. }
  230602. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230603. {
  230604. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230605. ? kCGInterpolationLow
  230606. : kCGInterpolationHigh);
  230607. }
  230608. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230609. {
  230610. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230611. }
  230612. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230613. {
  230614. if (replaceExistingContents)
  230615. {
  230616. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230617. CGContextClearRect (context, cgRect);
  230618. #else
  230619. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230620. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230621. CGContextClearRect (context, cgRect);
  230622. else
  230623. #endif
  230624. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230625. #endif
  230626. fillCGRect (cgRect, false);
  230627. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230628. }
  230629. else
  230630. {
  230631. if (state->fillType.isColour())
  230632. {
  230633. CGContextFillRect (context, cgRect);
  230634. }
  230635. else if (state->fillType.isGradient())
  230636. {
  230637. CGContextSaveGState (context);
  230638. CGContextClipToRect (context, cgRect);
  230639. drawGradient();
  230640. CGContextRestoreGState (context);
  230641. }
  230642. else
  230643. {
  230644. CGContextSaveGState (context);
  230645. CGContextClipToRect (context, cgRect);
  230646. drawImage (state->fillType.image, state->fillType.transform, true);
  230647. CGContextRestoreGState (context);
  230648. }
  230649. }
  230650. }
  230651. void fillPath (const Path& path, const AffineTransform& transform)
  230652. {
  230653. CGContextSaveGState (context);
  230654. if (state->fillType.isColour())
  230655. {
  230656. flip();
  230657. applyTransform (transform);
  230658. createPath (path);
  230659. if (path.isUsingNonZeroWinding())
  230660. CGContextFillPath (context);
  230661. else
  230662. CGContextEOFillPath (context);
  230663. }
  230664. else
  230665. {
  230666. createPath (path, transform);
  230667. if (path.isUsingNonZeroWinding())
  230668. CGContextClip (context);
  230669. else
  230670. CGContextEOClip (context);
  230671. if (state->fillType.isGradient())
  230672. drawGradient();
  230673. else
  230674. drawImage (state->fillType.image, state->fillType.transform, true);
  230675. }
  230676. CGContextRestoreGState (context);
  230677. }
  230678. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230679. {
  230680. const int iw = sourceImage.getWidth();
  230681. const int ih = sourceImage.getHeight();
  230682. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230683. CGContextSaveGState (context);
  230684. CGContextSetAlpha (context, state->fillType.getOpacity());
  230685. flip();
  230686. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230687. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230688. if (fillEntireClipAsTiles)
  230689. {
  230690. #if JUCE_IOS
  230691. CGContextDrawTiledImage (context, imageRect, image);
  230692. #else
  230693. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230694. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230695. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230696. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230697. CGContextDrawTiledImage (context, imageRect, image);
  230698. else
  230699. #endif
  230700. {
  230701. // Fallback to manually doing a tiled fill on 10.4
  230702. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230703. int x = 0, y = 0;
  230704. while (x > clip.origin.x) x -= iw;
  230705. while (y > clip.origin.y) y -= ih;
  230706. const int right = (int) (clip.origin.x + clip.size.width);
  230707. const int bottom = (int) (clip.origin.y + clip.size.height);
  230708. while (y < bottom)
  230709. {
  230710. for (int x2 = x; x2 < right; x2 += iw)
  230711. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230712. y += ih;
  230713. }
  230714. }
  230715. #endif
  230716. }
  230717. else
  230718. {
  230719. CGContextDrawImage (context, imageRect, image);
  230720. }
  230721. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230722. CGContextRestoreGState (context);
  230723. }
  230724. void drawLine (const Line<float>& line)
  230725. {
  230726. if (state->fillType.isColour())
  230727. {
  230728. CGContextSetLineCap (context, kCGLineCapSquare);
  230729. CGContextSetLineWidth (context, 1.0f);
  230730. CGContextSetRGBStrokeColor (context,
  230731. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230732. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230733. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230734. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230735. CGContextStrokeLineSegments (context, cgLine, 1);
  230736. }
  230737. else
  230738. {
  230739. Path p;
  230740. p.addLineSegment (line, 1.0f);
  230741. fillPath (p, AffineTransform::identity);
  230742. }
  230743. }
  230744. void drawVerticalLine (const int x, float top, float bottom)
  230745. {
  230746. if (state->fillType.isColour())
  230747. {
  230748. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230749. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230750. #else
  230751. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230752. // the x co-ord slightly to trick it..
  230753. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230754. #endif
  230755. }
  230756. else
  230757. {
  230758. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230759. }
  230760. }
  230761. void drawHorizontalLine (const int y, float left, float right)
  230762. {
  230763. if (state->fillType.isColour())
  230764. {
  230765. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230766. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230767. #else
  230768. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230769. // the x co-ord slightly to trick it..
  230770. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230771. #endif
  230772. }
  230773. else
  230774. {
  230775. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230776. }
  230777. }
  230778. void setFont (const Font& newFont)
  230779. {
  230780. if (state->font != newFont)
  230781. {
  230782. state->fontRef = 0;
  230783. state->font = newFont;
  230784. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230785. if (mf != 0)
  230786. {
  230787. state->fontRef = mf->fontRef;
  230788. CGContextSetFont (context, state->fontRef);
  230789. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230790. state->fontTransform = mf->renderingTransform;
  230791. state->fontTransform.a *= state->font.getHorizontalScale();
  230792. CGContextSetTextMatrix (context, state->fontTransform);
  230793. }
  230794. }
  230795. }
  230796. const Font getFont()
  230797. {
  230798. return state->font;
  230799. }
  230800. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230801. {
  230802. if (state->fontRef != 0 && state->fillType.isColour())
  230803. {
  230804. if (transform.isOnlyTranslation())
  230805. {
  230806. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230807. CGGlyph g = glyphNumber;
  230808. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230809. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230810. }
  230811. else
  230812. {
  230813. CGContextSaveGState (context);
  230814. flip();
  230815. applyTransform (transform);
  230816. CGAffineTransform t = state->fontTransform;
  230817. t.d = -t.d;
  230818. CGContextSetTextMatrix (context, t);
  230819. CGGlyph g = glyphNumber;
  230820. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230821. CGContextRestoreGState (context);
  230822. }
  230823. }
  230824. else
  230825. {
  230826. Path p;
  230827. Font& f = state->font;
  230828. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230829. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230830. .followedBy (transform));
  230831. }
  230832. }
  230833. private:
  230834. CGContextRef context;
  230835. const CGFloat flipHeight;
  230836. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230837. CGFunctionCallbacks gradientCallbacks;
  230838. mutable Rectangle<int> lastClipRect;
  230839. mutable bool lastClipRectIsValid;
  230840. struct SavedState
  230841. {
  230842. SavedState()
  230843. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230844. {
  230845. }
  230846. SavedState (const SavedState& other)
  230847. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230848. fontTransform (other.fontTransform)
  230849. {
  230850. }
  230851. ~SavedState()
  230852. {
  230853. }
  230854. FillType fillType;
  230855. Font font;
  230856. CGFontRef fontRef;
  230857. CGAffineTransform fontTransform;
  230858. };
  230859. ScopedPointer <SavedState> state;
  230860. OwnedArray <SavedState> stateStack;
  230861. HeapBlock <PixelARGB> gradientLookupTable;
  230862. int numGradientLookupEntries;
  230863. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230864. {
  230865. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230866. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230867. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230868. colour.unpremultiply();
  230869. outData[0] = colour.getRed() / 255.0f;
  230870. outData[1] = colour.getGreen() / 255.0f;
  230871. outData[2] = colour.getBlue() / 255.0f;
  230872. outData[3] = colour.getAlpha() / 255.0f;
  230873. }
  230874. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230875. {
  230876. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  230877. --numGradientLookupEntries;
  230878. CGShadingRef result = 0;
  230879. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230880. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230881. if (gradient.isRadial)
  230882. {
  230883. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230884. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230885. function, true, true);
  230886. }
  230887. else
  230888. {
  230889. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230890. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230891. function, true, true);
  230892. }
  230893. CGFunctionRelease (function);
  230894. return result;
  230895. }
  230896. void drawGradient()
  230897. {
  230898. flip();
  230899. applyTransform (state->fillType.transform);
  230900. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230901. // you draw a gradient with high quality interp enabled).
  230902. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230903. CGContextSetAlpha (context, state->fillType.getOpacity());
  230904. CGContextDrawShading (context, shading);
  230905. CGShadingRelease (shading);
  230906. }
  230907. void createPath (const Path& path) const
  230908. {
  230909. CGContextBeginPath (context);
  230910. Path::Iterator i (path);
  230911. while (i.next())
  230912. {
  230913. switch (i.elementType)
  230914. {
  230915. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230916. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230917. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230918. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230919. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230920. default: jassertfalse; break;
  230921. }
  230922. }
  230923. }
  230924. void createPath (const Path& path, const AffineTransform& transform) const
  230925. {
  230926. CGContextBeginPath (context);
  230927. Path::Iterator i (path);
  230928. while (i.next())
  230929. {
  230930. switch (i.elementType)
  230931. {
  230932. case Path::Iterator::startNewSubPath:
  230933. transform.transformPoint (i.x1, i.y1);
  230934. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230935. break;
  230936. case Path::Iterator::lineTo:
  230937. transform.transformPoint (i.x1, i.y1);
  230938. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230939. break;
  230940. case Path::Iterator::quadraticTo:
  230941. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230942. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230943. break;
  230944. case Path::Iterator::cubicTo:
  230945. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230946. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230947. break;
  230948. case Path::Iterator::closePath:
  230949. CGContextClosePath (context); break;
  230950. default:
  230951. jassertfalse;
  230952. break;
  230953. }
  230954. }
  230955. }
  230956. void flip() const
  230957. {
  230958. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230959. }
  230960. void applyTransform (const AffineTransform& transform) const
  230961. {
  230962. CGAffineTransform t;
  230963. t.a = transform.mat00;
  230964. t.b = transform.mat10;
  230965. t.c = transform.mat01;
  230966. t.d = transform.mat11;
  230967. t.tx = transform.mat02;
  230968. t.ty = transform.mat12;
  230969. CGContextConcatCTM (context, t);
  230970. }
  230971. JUCE_DECLARE_NON_COPYABLE (CoreGraphicsContext);
  230972. };
  230973. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230974. {
  230975. return new CoreGraphicsContext (context, height);
  230976. }
  230977. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230978. const Image juce_loadWithCoreImage (InputStream& input)
  230979. {
  230980. MemoryBlock data;
  230981. input.readIntoMemoryBlock (data, -1);
  230982. #if JUCE_IOS
  230983. JUCE_AUTORELEASEPOOL
  230984. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230985. length: data.getSize()
  230986. freeWhenDone: NO]];
  230987. if (image != nil)
  230988. {
  230989. CGImageRef loadedImage = image.CGImage;
  230990. #else
  230991. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230992. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230993. CGDataProviderRelease (provider);
  230994. if (imageSource != 0)
  230995. {
  230996. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230997. CFRelease (imageSource);
  230998. #endif
  230999. if (loadedImage != 0)
  231000. {
  231001. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  231002. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  231003. && alphaInfo != kCGImageAlphaNoneSkipLast
  231004. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  231005. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  231006. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  231007. hasAlphaChan, Image::NativeImage);
  231008. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  231009. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  231010. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  231011. CGContextFlush (cgImage->context);
  231012. #if ! JUCE_IOS
  231013. CFRelease (loadedImage);
  231014. #endif
  231015. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  231016. // to find out whether the file they just loaded the image from had an alpha channel or not.
  231017. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  231018. return image;
  231019. }
  231020. }
  231021. return Image::null;
  231022. }
  231023. #endif
  231024. #endif
  231025. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  231026. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231027. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231028. // compiled on its own).
  231029. #if JUCE_INCLUDED_FILE
  231030. class NSViewComponentPeer;
  231031. END_JUCE_NAMESPACE
  231032. @interface NSEvent (JuceDeviceDelta)
  231033. - (float) deviceDeltaX;
  231034. - (float) deviceDeltaY;
  231035. @end
  231036. #define JuceNSView MakeObjCClassName(JuceNSView)
  231037. @interface JuceNSView : NSView<NSTextInput>
  231038. {
  231039. @public
  231040. NSViewComponentPeer* owner;
  231041. NSNotificationCenter* notificationCenter;
  231042. String* stringBeingComposed;
  231043. bool textWasInserted;
  231044. }
  231045. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  231046. - (void) dealloc;
  231047. - (BOOL) isOpaque;
  231048. - (void) drawRect: (NSRect) r;
  231049. - (void) mouseDown: (NSEvent*) ev;
  231050. - (void) asyncMouseDown: (NSEvent*) ev;
  231051. - (void) mouseUp: (NSEvent*) ev;
  231052. - (void) asyncMouseUp: (NSEvent*) ev;
  231053. - (void) mouseDragged: (NSEvent*) ev;
  231054. - (void) mouseMoved: (NSEvent*) ev;
  231055. - (void) mouseEntered: (NSEvent*) ev;
  231056. - (void) mouseExited: (NSEvent*) ev;
  231057. - (void) rightMouseDown: (NSEvent*) ev;
  231058. - (void) rightMouseDragged: (NSEvent*) ev;
  231059. - (void) rightMouseUp: (NSEvent*) ev;
  231060. - (void) otherMouseDown: (NSEvent*) ev;
  231061. - (void) otherMouseDragged: (NSEvent*) ev;
  231062. - (void) otherMouseUp: (NSEvent*) ev;
  231063. - (void) scrollWheel: (NSEvent*) ev;
  231064. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  231065. - (void) frameChanged: (NSNotification*) n;
  231066. - (void) viewDidMoveToWindow;
  231067. - (void) keyDown: (NSEvent*) ev;
  231068. - (void) keyUp: (NSEvent*) ev;
  231069. // NSTextInput Methods
  231070. - (void) insertText: (id) aString;
  231071. - (void) doCommandBySelector: (SEL) aSelector;
  231072. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  231073. - (void) unmarkText;
  231074. - (BOOL) hasMarkedText;
  231075. - (long) conversationIdentifier;
  231076. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  231077. - (NSRange) markedRange;
  231078. - (NSRange) selectedRange;
  231079. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  231080. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  231081. - (NSArray*) validAttributesForMarkedText;
  231082. - (void) flagsChanged: (NSEvent*) ev;
  231083. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231084. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  231085. #endif
  231086. - (BOOL) becomeFirstResponder;
  231087. - (BOOL) resignFirstResponder;
  231088. - (BOOL) acceptsFirstResponder;
  231089. - (void) asyncRepaint: (id) rect;
  231090. - (NSArray*) getSupportedDragTypes;
  231091. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  231092. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  231093. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  231094. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  231095. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  231096. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  231097. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  231098. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  231099. @end
  231100. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  231101. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231102. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  231103. #else
  231104. @interface JuceNSWindow : NSWindow
  231105. #endif
  231106. {
  231107. @private
  231108. NSViewComponentPeer* owner;
  231109. bool isZooming;
  231110. }
  231111. - (void) setOwner: (NSViewComponentPeer*) owner;
  231112. - (BOOL) canBecomeKeyWindow;
  231113. - (void) becomeKeyWindow;
  231114. - (BOOL) windowShouldClose: (id) window;
  231115. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  231116. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  231117. - (void) zoom: (id) sender;
  231118. @end
  231119. BEGIN_JUCE_NAMESPACE
  231120. class NSViewComponentPeer : public ComponentPeer
  231121. {
  231122. public:
  231123. NSViewComponentPeer (Component* const component,
  231124. const int windowStyleFlags,
  231125. NSView* viewToAttachTo);
  231126. ~NSViewComponentPeer();
  231127. void* getNativeHandle() const;
  231128. void setVisible (bool shouldBeVisible);
  231129. void setTitle (const String& title);
  231130. void setPosition (int x, int y);
  231131. void setSize (int w, int h);
  231132. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  231133. const Rectangle<int> getBounds (const bool global) const;
  231134. const Rectangle<int> getBounds() const;
  231135. const Point<int> getScreenPosition() const;
  231136. const Point<int> localToGlobal (const Point<int>& relativePosition);
  231137. const Point<int> globalToLocal (const Point<int>& screenPosition);
  231138. void setAlpha (float newAlpha);
  231139. void setMinimised (bool shouldBeMinimised);
  231140. bool isMinimised() const;
  231141. void setFullScreen (bool shouldBeFullScreen);
  231142. bool isFullScreen() const;
  231143. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231144. const BorderSize getFrameSize() const;
  231145. bool setAlwaysOnTop (bool alwaysOnTop);
  231146. void toFront (bool makeActiveWindow);
  231147. void toBehind (ComponentPeer* other);
  231148. void setIcon (const Image& newIcon);
  231149. const StringArray getAvailableRenderingEngines();
  231150. int getCurrentRenderingEngine() throw();
  231151. void setCurrentRenderingEngine (int index);
  231152. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231153. for example having more than one juce plugin loaded into a host, then when a
  231154. method is called, the actual code that runs might actually be in a different module
  231155. than the one you expect... So any calls to library functions or statics that are
  231156. made inside obj-c methods will probably end up getting executed in a different DLL's
  231157. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231158. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231159. virtual methods of an object that's known to live inside the right module's space.
  231160. */
  231161. virtual void redirectMouseDown (NSEvent* ev);
  231162. virtual void redirectMouseUp (NSEvent* ev);
  231163. virtual void redirectMouseDrag (NSEvent* ev);
  231164. virtual void redirectMouseMove (NSEvent* ev);
  231165. virtual void redirectMouseEnter (NSEvent* ev);
  231166. virtual void redirectMouseExit (NSEvent* ev);
  231167. virtual void redirectMouseWheel (NSEvent* ev);
  231168. void sendMouseEvent (NSEvent* ev);
  231169. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231170. virtual bool redirectKeyDown (NSEvent* ev);
  231171. virtual bool redirectKeyUp (NSEvent* ev);
  231172. virtual void redirectModKeyChange (NSEvent* ev);
  231173. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231174. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231175. #endif
  231176. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231177. virtual bool isOpaque();
  231178. virtual void drawRect (NSRect r);
  231179. virtual bool canBecomeKeyWindow();
  231180. virtual bool windowShouldClose();
  231181. virtual void redirectMovedOrResized();
  231182. virtual void viewMovedToWindow();
  231183. virtual NSRect constrainRect (NSRect r);
  231184. static void showArrowCursorIfNeeded();
  231185. static void updateModifiers (NSEvent* e);
  231186. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231187. static int getKeyCodeFromEvent (NSEvent* ev)
  231188. {
  231189. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231190. int keyCode = unmodified[0];
  231191. if (keyCode == 0x19) // (backwards-tab)
  231192. keyCode = '\t';
  231193. else if (keyCode == 0x03) // (enter)
  231194. keyCode = '\r';
  231195. else
  231196. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231197. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231198. {
  231199. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231200. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231201. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231202. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231203. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231204. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231205. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231206. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231207. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231208. if (keyCode == numPadConversions [i])
  231209. keyCode = numPadConversions [i + 1];
  231210. }
  231211. return keyCode;
  231212. }
  231213. static int64 getMouseTime (NSEvent* e)
  231214. {
  231215. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231216. + (int64) ([e timestamp] * 1000.0);
  231217. }
  231218. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231219. {
  231220. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231221. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231222. }
  231223. static int getModifierForButtonNumber (const NSInteger num)
  231224. {
  231225. return num == 0 ? ModifierKeys::leftButtonModifier
  231226. : (num == 1 ? ModifierKeys::rightButtonModifier
  231227. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231228. }
  231229. virtual void viewFocusGain();
  231230. virtual void viewFocusLoss();
  231231. bool isFocused() const;
  231232. void grabFocus();
  231233. void textInputRequired (const Point<int>& position);
  231234. void repaint (const Rectangle<int>& area);
  231235. void performAnyPendingRepaintsNow();
  231236. NSWindow* window;
  231237. JuceNSView* view;
  231238. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231239. static ModifierKeys currentModifiers;
  231240. static ComponentPeer* currentlyFocusedPeer;
  231241. static Array<int> keysCurrentlyDown;
  231242. private:
  231243. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  231244. };
  231245. END_JUCE_NAMESPACE
  231246. @implementation JuceNSView
  231247. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231248. withFrame: (NSRect) frame
  231249. {
  231250. [super initWithFrame: frame];
  231251. owner = owner_;
  231252. stringBeingComposed = 0;
  231253. textWasInserted = false;
  231254. notificationCenter = [NSNotificationCenter defaultCenter];
  231255. [notificationCenter addObserver: self
  231256. selector: @selector (frameChanged:)
  231257. name: NSViewFrameDidChangeNotification
  231258. object: self];
  231259. if (! owner_->isSharedWindow)
  231260. {
  231261. [notificationCenter addObserver: self
  231262. selector: @selector (frameChanged:)
  231263. name: NSWindowDidMoveNotification
  231264. object: owner_->window];
  231265. }
  231266. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231267. return self;
  231268. }
  231269. - (void) dealloc
  231270. {
  231271. [notificationCenter removeObserver: self];
  231272. delete stringBeingComposed;
  231273. [super dealloc];
  231274. }
  231275. - (void) drawRect: (NSRect) r
  231276. {
  231277. if (owner != 0)
  231278. owner->drawRect (r);
  231279. }
  231280. - (BOOL) isOpaque
  231281. {
  231282. return owner == 0 || owner->isOpaque();
  231283. }
  231284. - (void) mouseDown: (NSEvent*) ev
  231285. {
  231286. if (JUCEApplication::isStandaloneApp())
  231287. [self asyncMouseDown: ev];
  231288. else
  231289. // In some host situations, the host will stop modal loops from working
  231290. // correctly if they're called from a mouse event, so we'll trigger
  231291. // the event asynchronously..
  231292. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231293. withObject: ev
  231294. waitUntilDone: NO];
  231295. }
  231296. - (void) asyncMouseDown: (NSEvent*) ev
  231297. {
  231298. if (owner != 0)
  231299. owner->redirectMouseDown (ev);
  231300. }
  231301. - (void) mouseUp: (NSEvent*) ev
  231302. {
  231303. if (! JUCEApplication::isStandaloneApp())
  231304. [self asyncMouseUp: ev];
  231305. else
  231306. // In some host situations, the host will stop modal loops from working
  231307. // correctly if they're called from a mouse event, so we'll trigger
  231308. // the event asynchronously..
  231309. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231310. withObject: ev
  231311. waitUntilDone: NO];
  231312. }
  231313. - (void) asyncMouseUp: (NSEvent*) ev
  231314. {
  231315. if (owner != 0)
  231316. owner->redirectMouseUp (ev);
  231317. }
  231318. - (void) mouseDragged: (NSEvent*) ev
  231319. {
  231320. if (owner != 0)
  231321. owner->redirectMouseDrag (ev);
  231322. }
  231323. - (void) mouseMoved: (NSEvent*) ev
  231324. {
  231325. if (owner != 0)
  231326. owner->redirectMouseMove (ev);
  231327. }
  231328. - (void) mouseEntered: (NSEvent*) ev
  231329. {
  231330. if (owner != 0)
  231331. owner->redirectMouseEnter (ev);
  231332. }
  231333. - (void) mouseExited: (NSEvent*) ev
  231334. {
  231335. if (owner != 0)
  231336. owner->redirectMouseExit (ev);
  231337. }
  231338. - (void) rightMouseDown: (NSEvent*) ev
  231339. {
  231340. [self mouseDown: ev];
  231341. }
  231342. - (void) rightMouseDragged: (NSEvent*) ev
  231343. {
  231344. [self mouseDragged: ev];
  231345. }
  231346. - (void) rightMouseUp: (NSEvent*) ev
  231347. {
  231348. [self mouseUp: ev];
  231349. }
  231350. - (void) otherMouseDown: (NSEvent*) ev
  231351. {
  231352. [self mouseDown: ev];
  231353. }
  231354. - (void) otherMouseDragged: (NSEvent*) ev
  231355. {
  231356. [self mouseDragged: ev];
  231357. }
  231358. - (void) otherMouseUp: (NSEvent*) ev
  231359. {
  231360. [self mouseUp: ev];
  231361. }
  231362. - (void) scrollWheel: (NSEvent*) ev
  231363. {
  231364. if (owner != 0)
  231365. owner->redirectMouseWheel (ev);
  231366. }
  231367. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231368. {
  231369. (void) ev;
  231370. return YES;
  231371. }
  231372. - (void) frameChanged: (NSNotification*) n
  231373. {
  231374. (void) n;
  231375. if (owner != 0)
  231376. owner->redirectMovedOrResized();
  231377. }
  231378. - (void) viewDidMoveToWindow
  231379. {
  231380. if (owner != 0)
  231381. owner->viewMovedToWindow();
  231382. }
  231383. - (void) asyncRepaint: (id) rect
  231384. {
  231385. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231386. [self setNeedsDisplayInRect: *r];
  231387. }
  231388. - (void) keyDown: (NSEvent*) ev
  231389. {
  231390. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231391. textWasInserted = false;
  231392. if (target != 0)
  231393. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231394. else
  231395. deleteAndZero (stringBeingComposed);
  231396. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231397. [super keyDown: ev];
  231398. }
  231399. - (void) keyUp: (NSEvent*) ev
  231400. {
  231401. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231402. [super keyUp: ev];
  231403. }
  231404. - (void) insertText: (id) aString
  231405. {
  231406. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231407. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231408. if ([newText length] > 0)
  231409. {
  231410. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231411. if (target != 0)
  231412. {
  231413. target->insertTextAtCaret (nsStringToJuce (newText));
  231414. textWasInserted = true;
  231415. }
  231416. }
  231417. deleteAndZero (stringBeingComposed);
  231418. }
  231419. - (void) doCommandBySelector: (SEL) aSelector
  231420. {
  231421. (void) aSelector;
  231422. }
  231423. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231424. {
  231425. (void) selectionRange;
  231426. if (stringBeingComposed == 0)
  231427. stringBeingComposed = new String();
  231428. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231429. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231430. if (target != 0)
  231431. {
  231432. const Range<int> currentHighlight (target->getHighlightedRegion());
  231433. target->insertTextAtCaret (*stringBeingComposed);
  231434. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231435. textWasInserted = true;
  231436. }
  231437. }
  231438. - (void) unmarkText
  231439. {
  231440. if (stringBeingComposed != 0)
  231441. {
  231442. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231443. if (target != 0)
  231444. {
  231445. target->insertTextAtCaret (*stringBeingComposed);
  231446. textWasInserted = true;
  231447. }
  231448. }
  231449. deleteAndZero (stringBeingComposed);
  231450. }
  231451. - (BOOL) hasMarkedText
  231452. {
  231453. return stringBeingComposed != 0;
  231454. }
  231455. - (long) conversationIdentifier
  231456. {
  231457. return (long) (pointer_sized_int) self;
  231458. }
  231459. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231460. {
  231461. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231462. if (target != 0)
  231463. {
  231464. const Range<int> r ((int) theRange.location,
  231465. (int) (theRange.location + theRange.length));
  231466. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231467. }
  231468. return nil;
  231469. }
  231470. - (NSRange) markedRange
  231471. {
  231472. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231473. : NSMakeRange (NSNotFound, 0);
  231474. }
  231475. - (NSRange) selectedRange
  231476. {
  231477. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231478. if (target != 0)
  231479. {
  231480. const Range<int> highlight (target->getHighlightedRegion());
  231481. if (! highlight.isEmpty())
  231482. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231483. }
  231484. return NSMakeRange (NSNotFound, 0);
  231485. }
  231486. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231487. {
  231488. (void) theRange;
  231489. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231490. if (comp == 0)
  231491. return NSMakeRect (0, 0, 0, 0);
  231492. const Rectangle<int> bounds (comp->getScreenBounds());
  231493. return NSMakeRect (bounds.getX(),
  231494. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231495. bounds.getWidth(),
  231496. bounds.getHeight());
  231497. }
  231498. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231499. {
  231500. (void) thePoint;
  231501. return NSNotFound;
  231502. }
  231503. - (NSArray*) validAttributesForMarkedText
  231504. {
  231505. return [NSArray array];
  231506. }
  231507. - (void) flagsChanged: (NSEvent*) ev
  231508. {
  231509. if (owner != 0)
  231510. owner->redirectModKeyChange (ev);
  231511. }
  231512. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231513. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231514. {
  231515. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231516. return true;
  231517. return [super performKeyEquivalent: ev];
  231518. }
  231519. #endif
  231520. - (BOOL) becomeFirstResponder
  231521. {
  231522. if (owner != 0)
  231523. owner->viewFocusGain();
  231524. return true;
  231525. }
  231526. - (BOOL) resignFirstResponder
  231527. {
  231528. if (owner != 0)
  231529. owner->viewFocusLoss();
  231530. return true;
  231531. }
  231532. - (BOOL) acceptsFirstResponder
  231533. {
  231534. return owner != 0 && owner->canBecomeKeyWindow();
  231535. }
  231536. - (NSArray*) getSupportedDragTypes
  231537. {
  231538. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231539. }
  231540. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231541. {
  231542. return owner != 0 && owner->sendDragCallback (type, sender);
  231543. }
  231544. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231545. {
  231546. if ([self sendDragCallback: 0 sender: sender])
  231547. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231548. else
  231549. return NSDragOperationNone;
  231550. }
  231551. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231552. {
  231553. if ([self sendDragCallback: 0 sender: sender])
  231554. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231555. else
  231556. return NSDragOperationNone;
  231557. }
  231558. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231559. {
  231560. [self sendDragCallback: 1 sender: sender];
  231561. }
  231562. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231563. {
  231564. [self sendDragCallback: 1 sender: sender];
  231565. }
  231566. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231567. {
  231568. (void) sender;
  231569. return YES;
  231570. }
  231571. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231572. {
  231573. return [self sendDragCallback: 2 sender: sender];
  231574. }
  231575. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231576. {
  231577. (void) sender;
  231578. }
  231579. @end
  231580. @implementation JuceNSWindow
  231581. - (void) setOwner: (NSViewComponentPeer*) owner_
  231582. {
  231583. owner = owner_;
  231584. isZooming = false;
  231585. }
  231586. - (BOOL) canBecomeKeyWindow
  231587. {
  231588. return owner != 0 && owner->canBecomeKeyWindow();
  231589. }
  231590. - (void) becomeKeyWindow
  231591. {
  231592. [super becomeKeyWindow];
  231593. if (owner != 0)
  231594. owner->grabFocus();
  231595. }
  231596. - (BOOL) windowShouldClose: (id) window
  231597. {
  231598. (void) window;
  231599. return owner == 0 || owner->windowShouldClose();
  231600. }
  231601. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231602. {
  231603. (void) screen;
  231604. if (owner != 0)
  231605. frameRect = owner->constrainRect (frameRect);
  231606. return frameRect;
  231607. }
  231608. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231609. {
  231610. (void) window;
  231611. if (isZooming)
  231612. return proposedFrameSize;
  231613. NSRect frameRect = [self frame];
  231614. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231615. frameRect.size = proposedFrameSize;
  231616. if (owner != 0)
  231617. frameRect = owner->constrainRect (frameRect);
  231618. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231619. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231620. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231621. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231622. return frameRect.size;
  231623. }
  231624. - (void) zoom: (id) sender
  231625. {
  231626. isZooming = true;
  231627. [super zoom: sender];
  231628. isZooming = false;
  231629. }
  231630. - (void) windowWillMove: (NSNotification*) notification
  231631. {
  231632. (void) notification;
  231633. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231634. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231635. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231636. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231637. }
  231638. @end
  231639. BEGIN_JUCE_NAMESPACE
  231640. ModifierKeys NSViewComponentPeer::currentModifiers;
  231641. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231642. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231643. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231644. {
  231645. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231646. return true;
  231647. if (keyCode >= 'A' && keyCode <= 'Z'
  231648. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231649. return true;
  231650. if (keyCode >= 'a' && keyCode <= 'z'
  231651. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231652. return true;
  231653. return false;
  231654. }
  231655. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231656. {
  231657. int m = 0;
  231658. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231659. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231660. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231661. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231662. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231663. }
  231664. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231665. {
  231666. updateModifiers (ev);
  231667. int keyCode = getKeyCodeFromEvent (ev);
  231668. if (keyCode != 0)
  231669. {
  231670. if (isKeyDown)
  231671. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231672. else
  231673. keysCurrentlyDown.removeValue (keyCode);
  231674. }
  231675. }
  231676. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231677. {
  231678. return NSViewComponentPeer::currentModifiers;
  231679. }
  231680. void ModifierKeys::updateCurrentModifiers() throw()
  231681. {
  231682. currentModifiers = NSViewComponentPeer::currentModifiers;
  231683. }
  231684. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231685. const int windowStyleFlags,
  231686. NSView* viewToAttachTo)
  231687. : ComponentPeer (component_, windowStyleFlags),
  231688. window (0),
  231689. view (0),
  231690. isSharedWindow (viewToAttachTo != 0),
  231691. fullScreen (false),
  231692. insideDrawRect (false),
  231693. #if USE_COREGRAPHICS_RENDERING
  231694. usingCoreGraphics (true),
  231695. #else
  231696. usingCoreGraphics (false),
  231697. #endif
  231698. recursiveToFrontCall (false)
  231699. {
  231700. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231701. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231702. [view setPostsFrameChangedNotifications: YES];
  231703. if (isSharedWindow)
  231704. {
  231705. window = [viewToAttachTo window];
  231706. [viewToAttachTo addSubview: view];
  231707. }
  231708. else
  231709. {
  231710. r.origin.x = (float) component->getX();
  231711. r.origin.y = (float) component->getY();
  231712. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231713. unsigned int style = 0;
  231714. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231715. style = NSBorderlessWindowMask;
  231716. else
  231717. style = NSTitledWindowMask;
  231718. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231719. style |= NSMiniaturizableWindowMask;
  231720. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231721. style |= NSClosableWindowMask;
  231722. if ((windowStyleFlags & windowIsResizable) != 0)
  231723. style |= NSResizableWindowMask;
  231724. window = [[JuceNSWindow alloc] initWithContentRect: r
  231725. styleMask: style
  231726. backing: NSBackingStoreBuffered
  231727. defer: YES];
  231728. [((JuceNSWindow*) window) setOwner: this];
  231729. [window orderOut: nil];
  231730. [window setDelegate: (JuceNSWindow*) window];
  231731. [window setOpaque: component->isOpaque()];
  231732. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231733. if (component->isAlwaysOnTop())
  231734. [window setLevel: NSFloatingWindowLevel];
  231735. [window setContentView: view];
  231736. [window setAutodisplay: YES];
  231737. [window setAcceptsMouseMovedEvents: YES];
  231738. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231739. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231740. [window setReleasedWhenClosed: YES];
  231741. [window retain];
  231742. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231743. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231744. }
  231745. const float alpha = component->getAlpha();
  231746. if (alpha < 1.0f)
  231747. setAlpha (alpha);
  231748. setTitle (component->getName());
  231749. }
  231750. NSViewComponentPeer::~NSViewComponentPeer()
  231751. {
  231752. view->owner = 0;
  231753. [view removeFromSuperview];
  231754. [view release];
  231755. if (! isSharedWindow)
  231756. {
  231757. [((JuceNSWindow*) window) setOwner: 0];
  231758. [window close];
  231759. [window release];
  231760. }
  231761. }
  231762. void* NSViewComponentPeer::getNativeHandle() const
  231763. {
  231764. return view;
  231765. }
  231766. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231767. {
  231768. if (isSharedWindow)
  231769. {
  231770. [view setHidden: ! shouldBeVisible];
  231771. }
  231772. else
  231773. {
  231774. if (shouldBeVisible)
  231775. {
  231776. [window orderFront: nil];
  231777. handleBroughtToFront();
  231778. }
  231779. else
  231780. {
  231781. [window orderOut: nil];
  231782. }
  231783. }
  231784. }
  231785. void NSViewComponentPeer::setTitle (const String& title)
  231786. {
  231787. const ScopedAutoReleasePool pool;
  231788. if (! isSharedWindow)
  231789. [window setTitle: juceStringToNS (title)];
  231790. }
  231791. void NSViewComponentPeer::setPosition (int x, int y)
  231792. {
  231793. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231794. }
  231795. void NSViewComponentPeer::setSize (int w, int h)
  231796. {
  231797. setBounds (component->getX(), component->getY(), w, h, false);
  231798. }
  231799. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231800. {
  231801. fullScreen = isNowFullScreen;
  231802. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231803. if (isSharedWindow)
  231804. {
  231805. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231806. if ([view frame].size.width != r.size.width
  231807. || [view frame].size.height != r.size.height)
  231808. [view setNeedsDisplay: true];
  231809. [view setFrame: r];
  231810. }
  231811. else
  231812. {
  231813. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231814. [window setFrame: [window frameRectForContentRect: r]
  231815. display: true];
  231816. }
  231817. }
  231818. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231819. {
  231820. NSRect r = [view frame];
  231821. if (global && [view window] != 0)
  231822. {
  231823. r = [view convertRect: r toView: nil];
  231824. NSRect wr = [[view window] frame];
  231825. r.origin.x += wr.origin.x;
  231826. r.origin.y += wr.origin.y;
  231827. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231828. }
  231829. else
  231830. {
  231831. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231832. }
  231833. return Rectangle<int> (convertToRectInt (r));
  231834. }
  231835. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231836. {
  231837. return getBounds (! isSharedWindow);
  231838. }
  231839. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231840. {
  231841. return getBounds (true).getPosition();
  231842. }
  231843. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231844. {
  231845. return relativePosition + getScreenPosition();
  231846. }
  231847. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231848. {
  231849. return screenPosition - getScreenPosition();
  231850. }
  231851. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231852. {
  231853. if (constrainer != 0)
  231854. {
  231855. NSRect current = [window frame];
  231856. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231857. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231858. Rectangle<int> pos (convertToRectInt (r));
  231859. Rectangle<int> original (convertToRectInt (current));
  231860. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231861. if ([window inLiveResize])
  231862. #else
  231863. if ([window respondsToSelector: @selector (inLiveResize)]
  231864. && [window performSelector: @selector (inLiveResize)])
  231865. #endif
  231866. {
  231867. constrainer->checkBounds (pos, original,
  231868. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231869. false, false, true, true);
  231870. }
  231871. else
  231872. {
  231873. constrainer->checkBounds (pos, original,
  231874. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231875. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231876. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231877. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231878. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231879. }
  231880. r.origin.x = pos.getX();
  231881. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231882. r.size.width = pos.getWidth();
  231883. r.size.height = pos.getHeight();
  231884. }
  231885. return r;
  231886. }
  231887. void NSViewComponentPeer::setAlpha (float newAlpha)
  231888. {
  231889. if (! isSharedWindow)
  231890. [window setAlphaValue: (CGFloat) newAlpha];
  231891. else
  231892. [view setAlphaValue: (CGFloat) newAlpha];
  231893. }
  231894. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231895. {
  231896. if (! isSharedWindow)
  231897. {
  231898. if (shouldBeMinimised)
  231899. [window miniaturize: nil];
  231900. else
  231901. [window deminiaturize: nil];
  231902. }
  231903. }
  231904. bool NSViewComponentPeer::isMinimised() const
  231905. {
  231906. return window != 0 && [window isMiniaturized];
  231907. }
  231908. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231909. {
  231910. if (! isSharedWindow)
  231911. {
  231912. Rectangle<int> r (lastNonFullscreenBounds);
  231913. setMinimised (false);
  231914. if (fullScreen != shouldBeFullScreen)
  231915. {
  231916. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231917. {
  231918. fullScreen = true;
  231919. [window performZoom: nil];
  231920. }
  231921. else
  231922. {
  231923. if (shouldBeFullScreen)
  231924. r = Desktop::getInstance().getMainMonitorArea();
  231925. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231926. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231927. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231928. }
  231929. }
  231930. }
  231931. }
  231932. bool NSViewComponentPeer::isFullScreen() const
  231933. {
  231934. return fullScreen;
  231935. }
  231936. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231937. {
  231938. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  231939. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  231940. return false;
  231941. NSPoint p;
  231942. p.x = (float) position.getX();
  231943. p.y = (float) position.getY();
  231944. NSView* v = [view hitTest: p];
  231945. if (trueIfInAChildWindow)
  231946. return v != nil;
  231947. return v == view;
  231948. }
  231949. const BorderSize NSViewComponentPeer::getFrameSize() const
  231950. {
  231951. BorderSize b;
  231952. if (! isSharedWindow)
  231953. {
  231954. NSRect v = [view convertRect: [view frame] toView: nil];
  231955. NSRect w = [window frame];
  231956. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231957. b.setBottom ((int) v.origin.y);
  231958. b.setLeft ((int) v.origin.x);
  231959. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231960. }
  231961. return b;
  231962. }
  231963. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231964. {
  231965. if (! isSharedWindow)
  231966. {
  231967. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231968. : NSNormalWindowLevel];
  231969. }
  231970. return true;
  231971. }
  231972. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231973. {
  231974. if (isSharedWindow)
  231975. {
  231976. [[view superview] addSubview: view
  231977. positioned: NSWindowAbove
  231978. relativeTo: nil];
  231979. }
  231980. if (window != 0 && component->isVisible())
  231981. {
  231982. if (makeActiveWindow)
  231983. [window makeKeyAndOrderFront: nil];
  231984. else
  231985. [window orderFront: nil];
  231986. if (! recursiveToFrontCall)
  231987. {
  231988. recursiveToFrontCall = true;
  231989. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231990. handleBroughtToFront();
  231991. recursiveToFrontCall = false;
  231992. }
  231993. }
  231994. }
  231995. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231996. {
  231997. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231998. jassert (otherPeer != 0); // wrong type of window?
  231999. if (otherPeer != 0)
  232000. {
  232001. if (isSharedWindow)
  232002. {
  232003. [[view superview] addSubview: view
  232004. positioned: NSWindowBelow
  232005. relativeTo: otherPeer->view];
  232006. }
  232007. else
  232008. {
  232009. [window orderWindow: NSWindowBelow
  232010. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  232011. : nil ];
  232012. }
  232013. }
  232014. }
  232015. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  232016. {
  232017. // to do..
  232018. }
  232019. void NSViewComponentPeer::viewFocusGain()
  232020. {
  232021. if (currentlyFocusedPeer != this)
  232022. {
  232023. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  232024. currentlyFocusedPeer->handleFocusLoss();
  232025. currentlyFocusedPeer = this;
  232026. handleFocusGain();
  232027. }
  232028. }
  232029. void NSViewComponentPeer::viewFocusLoss()
  232030. {
  232031. if (currentlyFocusedPeer == this)
  232032. {
  232033. currentlyFocusedPeer = 0;
  232034. handleFocusLoss();
  232035. }
  232036. }
  232037. void juce_HandleProcessFocusChange()
  232038. {
  232039. NSViewComponentPeer::keysCurrentlyDown.clear();
  232040. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  232041. {
  232042. if (Process::isForegroundProcess())
  232043. {
  232044. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  232045. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  232046. }
  232047. else
  232048. {
  232049. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  232050. // turn kiosk mode off if we lose focus..
  232051. Desktop::getInstance().setKioskModeComponent (0);
  232052. }
  232053. }
  232054. }
  232055. bool NSViewComponentPeer::isFocused() const
  232056. {
  232057. return isSharedWindow ? this == currentlyFocusedPeer
  232058. : (window != 0 && [window isKeyWindow]);
  232059. }
  232060. void NSViewComponentPeer::grabFocus()
  232061. {
  232062. if (window != 0)
  232063. {
  232064. [window makeKeyWindow];
  232065. [window makeFirstResponder: view];
  232066. viewFocusGain();
  232067. }
  232068. }
  232069. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  232070. {
  232071. }
  232072. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  232073. {
  232074. String unicode (nsStringToJuce ([ev characters]));
  232075. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  232076. int keyCode = getKeyCodeFromEvent (ev);
  232077. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  232078. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  232079. if (unicode.isNotEmpty() || keyCode != 0)
  232080. {
  232081. if (isKeyDown)
  232082. {
  232083. bool used = false;
  232084. while (unicode.length() > 0)
  232085. {
  232086. juce_wchar textCharacter = unicode[0];
  232087. unicode = unicode.substring (1);
  232088. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232089. textCharacter = 0;
  232090. used = handleKeyUpOrDown (true) || used;
  232091. used = handleKeyPress (keyCode, textCharacter) || used;
  232092. }
  232093. return used;
  232094. }
  232095. else
  232096. {
  232097. if (handleKeyUpOrDown (false))
  232098. return true;
  232099. }
  232100. }
  232101. return false;
  232102. }
  232103. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  232104. {
  232105. updateKeysDown (ev, true);
  232106. bool used = handleKeyEvent (ev, true);
  232107. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232108. {
  232109. // for command keys, the key-up event is thrown away, so simulate one..
  232110. updateKeysDown (ev, false);
  232111. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  232112. }
  232113. // (If we're running modally, don't allow unused keystrokes to be passed
  232114. // along to other blocked views..)
  232115. if (Component::getCurrentlyModalComponent() != 0)
  232116. used = true;
  232117. return used;
  232118. }
  232119. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  232120. {
  232121. updateKeysDown (ev, false);
  232122. return handleKeyEvent (ev, false)
  232123. || Component::getCurrentlyModalComponent() != 0;
  232124. }
  232125. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  232126. {
  232127. keysCurrentlyDown.clear();
  232128. handleKeyUpOrDown (true);
  232129. updateModifiers (ev);
  232130. handleModifierKeysChange();
  232131. }
  232132. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232133. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  232134. {
  232135. if ([ev type] == NSKeyDown)
  232136. return redirectKeyDown (ev);
  232137. else if ([ev type] == NSKeyUp)
  232138. return redirectKeyUp (ev);
  232139. return false;
  232140. }
  232141. #endif
  232142. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  232143. {
  232144. updateModifiers (ev);
  232145. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  232146. }
  232147. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  232148. {
  232149. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232150. sendMouseEvent (ev);
  232151. }
  232152. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  232153. {
  232154. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232155. sendMouseEvent (ev);
  232156. showArrowCursorIfNeeded();
  232157. }
  232158. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232159. {
  232160. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232161. sendMouseEvent (ev);
  232162. }
  232163. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232164. {
  232165. currentModifiers = currentModifiers.withoutMouseButtons();
  232166. sendMouseEvent (ev);
  232167. showArrowCursorIfNeeded();
  232168. }
  232169. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232170. {
  232171. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232172. currentModifiers = currentModifiers.withoutMouseButtons();
  232173. sendMouseEvent (ev);
  232174. }
  232175. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232176. {
  232177. currentModifiers = currentModifiers.withoutMouseButtons();
  232178. sendMouseEvent (ev);
  232179. }
  232180. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232181. {
  232182. updateModifiers (ev);
  232183. float x = 0, y = 0;
  232184. @try
  232185. {
  232186. x = [ev deviceDeltaX] * 0.5f;
  232187. y = [ev deviceDeltaY] * 0.5f;
  232188. }
  232189. @catch (...)
  232190. {}
  232191. if (x == 0 && y == 0)
  232192. {
  232193. x = [ev deltaX] * 10.0f;
  232194. y = [ev deltaY] * 10.0f;
  232195. }
  232196. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232197. }
  232198. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232199. {
  232200. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232201. if (mouse.getComponentUnderMouse() == 0
  232202. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232203. {
  232204. [[NSCursor arrowCursor] set];
  232205. }
  232206. }
  232207. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232208. {
  232209. NSString* bestType
  232210. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232211. if (bestType == nil)
  232212. return false;
  232213. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232214. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232215. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232216. if (list == nil)
  232217. return false;
  232218. StringArray files;
  232219. if ([list isKindOfClass: [NSArray class]])
  232220. {
  232221. NSArray* items = (NSArray*) list;
  232222. for (unsigned int i = 0; i < [items count]; ++i)
  232223. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232224. }
  232225. if (files.size() == 0)
  232226. return false;
  232227. if (type == 0)
  232228. handleFileDragMove (files, pos);
  232229. else if (type == 1)
  232230. handleFileDragExit (files);
  232231. else if (type == 2)
  232232. handleFileDragDrop (files, pos);
  232233. return true;
  232234. }
  232235. bool NSViewComponentPeer::isOpaque()
  232236. {
  232237. return component == 0 || component->isOpaque();
  232238. }
  232239. void NSViewComponentPeer::drawRect (NSRect r)
  232240. {
  232241. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232242. return;
  232243. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232244. if (! component->isOpaque())
  232245. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232246. #if USE_COREGRAPHICS_RENDERING
  232247. if (usingCoreGraphics)
  232248. {
  232249. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232250. insideDrawRect = true;
  232251. handlePaint (context);
  232252. insideDrawRect = false;
  232253. }
  232254. else
  232255. #endif
  232256. {
  232257. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232258. (int) (r.size.width + 0.5f),
  232259. (int) (r.size.height + 0.5f),
  232260. ! getComponent()->isOpaque());
  232261. const int xOffset = -roundToInt (r.origin.x);
  232262. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232263. const NSRect* rects = 0;
  232264. NSInteger numRects = 0;
  232265. [view getRectsBeingDrawn: &rects count: &numRects];
  232266. const Rectangle<int> clipBounds (temp.getBounds());
  232267. RectangleList clip;
  232268. for (int i = 0; i < numRects; ++i)
  232269. {
  232270. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232271. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232272. roundToInt (rects[i].size.width),
  232273. roundToInt (rects[i].size.height))));
  232274. }
  232275. if (! clip.isEmpty())
  232276. {
  232277. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232278. insideDrawRect = true;
  232279. handlePaint (context);
  232280. insideDrawRect = false;
  232281. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232282. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232283. CGColorSpaceRelease (colourSpace);
  232284. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232285. CGImageRelease (image);
  232286. }
  232287. }
  232288. }
  232289. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232290. {
  232291. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232292. #if USE_COREGRAPHICS_RENDERING
  232293. s.add ("CoreGraphics Renderer");
  232294. #endif
  232295. return s;
  232296. }
  232297. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232298. {
  232299. return usingCoreGraphics ? 1 : 0;
  232300. }
  232301. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232302. {
  232303. #if USE_COREGRAPHICS_RENDERING
  232304. if (usingCoreGraphics != (index > 0))
  232305. {
  232306. usingCoreGraphics = index > 0;
  232307. [view setNeedsDisplay: true];
  232308. }
  232309. #endif
  232310. }
  232311. bool NSViewComponentPeer::canBecomeKeyWindow()
  232312. {
  232313. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232314. }
  232315. bool NSViewComponentPeer::windowShouldClose()
  232316. {
  232317. if (! isValidPeer (this))
  232318. return YES;
  232319. handleUserClosingWindow();
  232320. return NO;
  232321. }
  232322. void NSViewComponentPeer::redirectMovedOrResized()
  232323. {
  232324. handleMovedOrResized();
  232325. }
  232326. void NSViewComponentPeer::viewMovedToWindow()
  232327. {
  232328. if (isSharedWindow)
  232329. window = [view window];
  232330. }
  232331. void Desktop::createMouseInputSources()
  232332. {
  232333. mouseSources.add (new MouseInputSource (0, true));
  232334. }
  232335. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232336. {
  232337. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232338. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232339. // is apparently still available in 64-bit apps..
  232340. if (enableOrDisable)
  232341. {
  232342. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232343. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232344. }
  232345. else
  232346. {
  232347. SetSystemUIMode (kUIModeNormal, 0);
  232348. }
  232349. }
  232350. class AsyncRepaintMessage : public CallbackMessage
  232351. {
  232352. public:
  232353. NSViewComponentPeer* const peer;
  232354. const Rectangle<int> rect;
  232355. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232356. : peer (peer_), rect (rect_)
  232357. {
  232358. }
  232359. void messageCallback()
  232360. {
  232361. if (ComponentPeer::isValidPeer (peer))
  232362. peer->repaint (rect);
  232363. }
  232364. };
  232365. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232366. {
  232367. if (insideDrawRect)
  232368. {
  232369. (new AsyncRepaintMessage (this, area))->post();
  232370. }
  232371. else
  232372. {
  232373. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232374. (float) area.getWidth(), (float) area.getHeight())];
  232375. }
  232376. }
  232377. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232378. {
  232379. [view displayIfNeeded];
  232380. }
  232381. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232382. {
  232383. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232384. }
  232385. const Image juce_createIconForFile (const File& file)
  232386. {
  232387. const ScopedAutoReleasePool pool;
  232388. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232389. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232390. [NSGraphicsContext saveGraphicsState];
  232391. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232392. [image drawAtPoint: NSMakePoint (0, 0)
  232393. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232394. operation: NSCompositeSourceOver fraction: 1.0f];
  232395. [[NSGraphicsContext currentContext] flushGraphics];
  232396. [NSGraphicsContext restoreGraphicsState];
  232397. return Image (result);
  232398. }
  232399. const int KeyPress::spaceKey = ' ';
  232400. const int KeyPress::returnKey = 0x0d;
  232401. const int KeyPress::escapeKey = 0x1b;
  232402. const int KeyPress::backspaceKey = 0x7f;
  232403. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232404. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232405. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232406. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232407. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232408. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232409. const int KeyPress::endKey = NSEndFunctionKey;
  232410. const int KeyPress::homeKey = NSHomeFunctionKey;
  232411. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232412. const int KeyPress::insertKey = -1;
  232413. const int KeyPress::tabKey = 9;
  232414. const int KeyPress::F1Key = NSF1FunctionKey;
  232415. const int KeyPress::F2Key = NSF2FunctionKey;
  232416. const int KeyPress::F3Key = NSF3FunctionKey;
  232417. const int KeyPress::F4Key = NSF4FunctionKey;
  232418. const int KeyPress::F5Key = NSF5FunctionKey;
  232419. const int KeyPress::F6Key = NSF6FunctionKey;
  232420. const int KeyPress::F7Key = NSF7FunctionKey;
  232421. const int KeyPress::F8Key = NSF8FunctionKey;
  232422. const int KeyPress::F9Key = NSF9FunctionKey;
  232423. const int KeyPress::F10Key = NSF10FunctionKey;
  232424. const int KeyPress::F11Key = NSF1FunctionKey;
  232425. const int KeyPress::F12Key = NSF12FunctionKey;
  232426. const int KeyPress::F13Key = NSF13FunctionKey;
  232427. const int KeyPress::F14Key = NSF14FunctionKey;
  232428. const int KeyPress::F15Key = NSF15FunctionKey;
  232429. const int KeyPress::F16Key = NSF16FunctionKey;
  232430. const int KeyPress::numberPad0 = 0x30020;
  232431. const int KeyPress::numberPad1 = 0x30021;
  232432. const int KeyPress::numberPad2 = 0x30022;
  232433. const int KeyPress::numberPad3 = 0x30023;
  232434. const int KeyPress::numberPad4 = 0x30024;
  232435. const int KeyPress::numberPad5 = 0x30025;
  232436. const int KeyPress::numberPad6 = 0x30026;
  232437. const int KeyPress::numberPad7 = 0x30027;
  232438. const int KeyPress::numberPad8 = 0x30028;
  232439. const int KeyPress::numberPad9 = 0x30029;
  232440. const int KeyPress::numberPadAdd = 0x3002a;
  232441. const int KeyPress::numberPadSubtract = 0x3002b;
  232442. const int KeyPress::numberPadMultiply = 0x3002c;
  232443. const int KeyPress::numberPadDivide = 0x3002d;
  232444. const int KeyPress::numberPadSeparator = 0x3002e;
  232445. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232446. const int KeyPress::numberPadEquals = 0x30030;
  232447. const int KeyPress::numberPadDelete = 0x30031;
  232448. const int KeyPress::playKey = 0x30000;
  232449. const int KeyPress::stopKey = 0x30001;
  232450. const int KeyPress::fastForwardKey = 0x30002;
  232451. const int KeyPress::rewindKey = 0x30003;
  232452. #endif
  232453. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232454. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232455. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232456. // compiled on its own).
  232457. #if JUCE_INCLUDED_FILE
  232458. #if JUCE_MAC
  232459. namespace MouseCursorHelpers
  232460. {
  232461. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232462. {
  232463. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232464. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232465. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232466. [im release];
  232467. return c;
  232468. }
  232469. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232470. {
  232471. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232472. BufferedInputStream buf (fileStream, 4096);
  232473. PNGImageFormat pngFormat;
  232474. Image im (pngFormat.decodeImage (buf));
  232475. if (im.isValid())
  232476. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232477. jassertfalse;
  232478. return 0;
  232479. }
  232480. }
  232481. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232482. {
  232483. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232484. }
  232485. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232486. {
  232487. const ScopedAutoReleasePool pool;
  232488. NSCursor* c = 0;
  232489. switch (type)
  232490. {
  232491. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232492. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232493. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232494. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232495. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232496. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232497. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232498. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232499. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232500. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232501. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232502. case UpDownResizeCursor:
  232503. case TopEdgeResizeCursor:
  232504. case BottomEdgeResizeCursor:
  232505. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232506. case TopLeftCornerResizeCursor:
  232507. case BottomRightCornerResizeCursor:
  232508. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232509. case TopRightCornerResizeCursor:
  232510. case BottomLeftCornerResizeCursor:
  232511. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232512. case UpDownLeftRightResizeCursor:
  232513. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232514. default:
  232515. jassertfalse;
  232516. break;
  232517. }
  232518. [c retain];
  232519. return c;
  232520. }
  232521. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232522. {
  232523. [((NSCursor*) cursorHandle) release];
  232524. }
  232525. void MouseCursor::showInAllWindows() const
  232526. {
  232527. showInWindow (0);
  232528. }
  232529. void MouseCursor::showInWindow (ComponentPeer*) const
  232530. {
  232531. NSCursor* c = (NSCursor*) getHandle();
  232532. if (c == 0)
  232533. c = [NSCursor arrowCursor];
  232534. [c set];
  232535. }
  232536. #else
  232537. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232538. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232539. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232540. void MouseCursor::showInAllWindows() const {}
  232541. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232542. #endif
  232543. #endif
  232544. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232545. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232546. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232547. // compiled on its own).
  232548. #if JUCE_INCLUDED_FILE
  232549. class NSViewComponentInternal : public ComponentMovementWatcher
  232550. {
  232551. Component* const owner;
  232552. NSViewComponentPeer* currentPeer;
  232553. bool wasShowing;
  232554. public:
  232555. NSView* const view;
  232556. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232557. : ComponentMovementWatcher (owner_),
  232558. owner (owner_),
  232559. currentPeer (0),
  232560. wasShowing (false),
  232561. view (view_)
  232562. {
  232563. [view_ retain];
  232564. if (owner_->isShowing())
  232565. componentPeerChanged();
  232566. }
  232567. ~NSViewComponentInternal()
  232568. {
  232569. [view removeFromSuperview];
  232570. [view release];
  232571. }
  232572. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232573. {
  232574. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232575. // The ComponentMovementWatcher version of this method avoids calling
  232576. // us when the top-level comp is resized, but for an NSView we need to know this
  232577. // because with inverted co-ords, we need to update the position even if the
  232578. // top-left pos hasn't changed
  232579. if (comp.isOnDesktop() && wasResized)
  232580. componentMovedOrResized (wasMoved, wasResized);
  232581. }
  232582. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232583. {
  232584. Component* const topComp = owner->getTopLevelComponent();
  232585. if (topComp->getPeer() != 0)
  232586. {
  232587. const Point<int> pos (topComp->getLocalPoint (owner, Point<int>()));
  232588. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  232589. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232590. [view setFrame: r];
  232591. }
  232592. }
  232593. void componentPeerChanged()
  232594. {
  232595. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232596. if (currentPeer != peer)
  232597. {
  232598. if ([view superview] != nil)
  232599. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  232600. // override the call and use it as a sign that they're being deleted, which breaks everything..
  232601. currentPeer = peer;
  232602. if (peer != 0)
  232603. {
  232604. [peer->view addSubview: view];
  232605. componentMovedOrResized (false, false);
  232606. }
  232607. }
  232608. [view setHidden: ! owner->isShowing()];
  232609. }
  232610. void componentVisibilityChanged (Component&)
  232611. {
  232612. componentPeerChanged();
  232613. }
  232614. const Rectangle<int> getViewBounds() const
  232615. {
  232616. NSRect r = [view frame];
  232617. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  232618. }
  232619. private:
  232620. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  232621. };
  232622. NSViewComponent::NSViewComponent()
  232623. {
  232624. }
  232625. NSViewComponent::~NSViewComponent()
  232626. {
  232627. }
  232628. void NSViewComponent::setView (void* view)
  232629. {
  232630. if (view != getView())
  232631. {
  232632. if (view != 0)
  232633. info = new NSViewComponentInternal ((NSView*) view, this);
  232634. else
  232635. info = 0;
  232636. }
  232637. }
  232638. void* NSViewComponent::getView() const
  232639. {
  232640. return info == 0 ? 0 : info->view;
  232641. }
  232642. void NSViewComponent::resizeToFitView()
  232643. {
  232644. if (info != 0)
  232645. setBounds (info->getViewBounds());
  232646. }
  232647. void NSViewComponent::paint (Graphics&)
  232648. {
  232649. }
  232650. #endif
  232651. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232652. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232653. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232654. // compiled on its own).
  232655. #if JUCE_INCLUDED_FILE
  232656. AppleRemoteDevice::AppleRemoteDevice()
  232657. : device (0),
  232658. queue (0),
  232659. remoteId (0)
  232660. {
  232661. }
  232662. AppleRemoteDevice::~AppleRemoteDevice()
  232663. {
  232664. stop();
  232665. }
  232666. namespace
  232667. {
  232668. io_object_t getAppleRemoteDevice()
  232669. {
  232670. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232671. io_iterator_t iter = 0;
  232672. io_object_t iod = 0;
  232673. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232674. && iter != 0)
  232675. {
  232676. iod = IOIteratorNext (iter);
  232677. }
  232678. IOObjectRelease (iter);
  232679. return iod;
  232680. }
  232681. bool createAppleRemoteInterface (io_object_t iod, void** device)
  232682. {
  232683. jassert (*device == 0);
  232684. io_name_t classname;
  232685. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232686. {
  232687. IOCFPlugInInterface** cfPlugInInterface = 0;
  232688. SInt32 score = 0;
  232689. if (IOCreatePlugInInterfaceForService (iod,
  232690. kIOHIDDeviceUserClientTypeID,
  232691. kIOCFPlugInInterfaceID,
  232692. &cfPlugInInterface,
  232693. &score) == kIOReturnSuccess)
  232694. {
  232695. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232696. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232697. device);
  232698. (void) hr;
  232699. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232700. }
  232701. }
  232702. return *device != 0;
  232703. }
  232704. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232705. {
  232706. if (result == kIOReturnSuccess)
  232707. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232708. }
  232709. }
  232710. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232711. {
  232712. if (queue != 0)
  232713. return true;
  232714. stop();
  232715. bool result = false;
  232716. io_object_t iod = getAppleRemoteDevice();
  232717. if (iod != 0)
  232718. {
  232719. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232720. result = true;
  232721. else
  232722. stop();
  232723. IOObjectRelease (iod);
  232724. }
  232725. return result;
  232726. }
  232727. void AppleRemoteDevice::stop()
  232728. {
  232729. if (queue != 0)
  232730. {
  232731. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232732. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232733. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232734. queue = 0;
  232735. }
  232736. if (device != 0)
  232737. {
  232738. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232739. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232740. device = 0;
  232741. }
  232742. }
  232743. bool AppleRemoteDevice::isActive() const
  232744. {
  232745. return queue != 0;
  232746. }
  232747. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232748. {
  232749. Array <int> cookies;
  232750. CFArrayRef elements;
  232751. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232752. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232753. return false;
  232754. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232755. {
  232756. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232757. // get the cookie
  232758. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232759. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232760. continue;
  232761. long number;
  232762. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232763. continue;
  232764. cookies.add ((int) number);
  232765. }
  232766. CFRelease (elements);
  232767. if ((*(IOHIDDeviceInterface**) device)
  232768. ->open ((IOHIDDeviceInterface**) device,
  232769. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232770. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232771. {
  232772. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232773. if (queue != 0)
  232774. {
  232775. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232776. for (int i = 0; i < cookies.size(); ++i)
  232777. {
  232778. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232779. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232780. }
  232781. CFRunLoopSourceRef eventSource;
  232782. if ((*(IOHIDQueueInterface**) queue)
  232783. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232784. {
  232785. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232786. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232787. {
  232788. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232789. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232790. return true;
  232791. }
  232792. }
  232793. }
  232794. }
  232795. return false;
  232796. }
  232797. void AppleRemoteDevice::handleCallbackInternal()
  232798. {
  232799. int totalValues = 0;
  232800. AbsoluteTime nullTime = { 0, 0 };
  232801. char cookies [12];
  232802. int numCookies = 0;
  232803. while (numCookies < numElementsInArray (cookies))
  232804. {
  232805. IOHIDEventStruct e;
  232806. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232807. break;
  232808. if ((int) e.elementCookie == 19)
  232809. {
  232810. remoteId = e.value;
  232811. buttonPressed (switched, false);
  232812. }
  232813. else
  232814. {
  232815. totalValues += e.value;
  232816. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232817. }
  232818. }
  232819. cookies [numCookies++] = 0;
  232820. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232821. static const char buttonPatterns[] =
  232822. {
  232823. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232824. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232825. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232826. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232827. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232828. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232829. 0x1f, 0x12, 0x04, 0x02, 0,
  232830. 0x1f, 0x12, 0x03, 0x02, 0,
  232831. 0x1f, 0x12, 0x1f, 0x12, 0,
  232832. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232833. 19, 0
  232834. };
  232835. int buttonNum = (int) menuButton;
  232836. int i = 0;
  232837. while (i < numElementsInArray (buttonPatterns))
  232838. {
  232839. if (strcmp (cookies, buttonPatterns + i) == 0)
  232840. {
  232841. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232842. break;
  232843. }
  232844. i += (int) strlen (buttonPatterns + i) + 1;
  232845. ++buttonNum;
  232846. }
  232847. }
  232848. #endif
  232849. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232850. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232851. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232852. // compiled on its own).
  232853. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232854. #if JUCE_MAC
  232855. END_JUCE_NAMESPACE
  232856. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232857. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232858. {
  232859. CriticalSection* contextLock;
  232860. bool needsUpdate;
  232861. }
  232862. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232863. - (bool) makeActive;
  232864. - (void) makeInactive;
  232865. - (void) reshape;
  232866. @end
  232867. @implementation ThreadSafeNSOpenGLView
  232868. - (id) initWithFrame: (NSRect) frameRect
  232869. pixelFormat: (NSOpenGLPixelFormat*) format
  232870. {
  232871. contextLock = new CriticalSection();
  232872. self = [super initWithFrame: frameRect pixelFormat: format];
  232873. if (self != nil)
  232874. [[NSNotificationCenter defaultCenter] addObserver: self
  232875. selector: @selector (_surfaceNeedsUpdate:)
  232876. name: NSViewGlobalFrameDidChangeNotification
  232877. object: self];
  232878. return self;
  232879. }
  232880. - (void) dealloc
  232881. {
  232882. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232883. delete contextLock;
  232884. [super dealloc];
  232885. }
  232886. - (bool) makeActive
  232887. {
  232888. const ScopedLock sl (*contextLock);
  232889. if ([self openGLContext] == 0)
  232890. return false;
  232891. [[self openGLContext] makeCurrentContext];
  232892. if (needsUpdate)
  232893. {
  232894. [super update];
  232895. needsUpdate = false;
  232896. }
  232897. return true;
  232898. }
  232899. - (void) makeInactive
  232900. {
  232901. const ScopedLock sl (*contextLock);
  232902. [NSOpenGLContext clearCurrentContext];
  232903. }
  232904. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232905. {
  232906. const ScopedLock sl (*contextLock);
  232907. needsUpdate = true;
  232908. }
  232909. - (void) update
  232910. {
  232911. const ScopedLock sl (*contextLock);
  232912. needsUpdate = true;
  232913. }
  232914. - (void) reshape
  232915. {
  232916. const ScopedLock sl (*contextLock);
  232917. needsUpdate = true;
  232918. }
  232919. @end
  232920. BEGIN_JUCE_NAMESPACE
  232921. class WindowedGLContext : public OpenGLContext
  232922. {
  232923. public:
  232924. WindowedGLContext (Component* const component,
  232925. const OpenGLPixelFormat& pixelFormat_,
  232926. NSOpenGLContext* sharedContext)
  232927. : renderContext (0),
  232928. pixelFormat (pixelFormat_)
  232929. {
  232930. jassert (component != 0);
  232931. NSOpenGLPixelFormatAttribute attribs [64];
  232932. int n = 0;
  232933. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232934. attribs[n++] = NSOpenGLPFAAccelerated;
  232935. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232936. attribs[n++] = NSOpenGLPFAColorSize;
  232937. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232938. pixelFormat.greenBits,
  232939. pixelFormat.blueBits);
  232940. attribs[n++] = NSOpenGLPFAAlphaSize;
  232941. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232942. attribs[n++] = NSOpenGLPFADepthSize;
  232943. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232944. attribs[n++] = NSOpenGLPFAStencilSize;
  232945. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232946. attribs[n++] = NSOpenGLPFAAccumSize;
  232947. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232948. pixelFormat.accumulationBufferGreenBits,
  232949. pixelFormat.accumulationBufferBlueBits,
  232950. pixelFormat.accumulationBufferAlphaBits);
  232951. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232952. attribs[n++] = NSOpenGLPFASampleBuffers;
  232953. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232954. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232955. attribs[n++] = NSOpenGLPFANoRecovery;
  232956. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232957. NSOpenGLPixelFormat* format
  232958. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232959. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232960. pixelFormat: format];
  232961. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232962. shareContext: sharedContext] autorelease];
  232963. const GLint swapInterval = 1;
  232964. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232965. [view setOpenGLContext: renderContext];
  232966. [format release];
  232967. viewHolder = new NSViewComponentInternal (view, component);
  232968. }
  232969. ~WindowedGLContext()
  232970. {
  232971. deleteContext();
  232972. viewHolder = 0;
  232973. }
  232974. void deleteContext()
  232975. {
  232976. makeInactive();
  232977. [renderContext clearDrawable];
  232978. [renderContext setView: nil];
  232979. [view setOpenGLContext: nil];
  232980. renderContext = nil;
  232981. }
  232982. bool makeActive() const throw()
  232983. {
  232984. jassert (renderContext != 0);
  232985. if ([renderContext view] != view)
  232986. [renderContext setView: view];
  232987. [view makeActive];
  232988. return isActive();
  232989. }
  232990. bool makeInactive() const throw()
  232991. {
  232992. [view makeInactive];
  232993. return true;
  232994. }
  232995. bool isActive() const throw()
  232996. {
  232997. return [NSOpenGLContext currentContext] == renderContext;
  232998. }
  232999. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233000. void* getRawContext() const throw() { return renderContext; }
  233001. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233002. {
  233003. }
  233004. void swapBuffers()
  233005. {
  233006. [renderContext flushBuffer];
  233007. }
  233008. bool setSwapInterval (const int numFramesPerSwap)
  233009. {
  233010. [renderContext setValues: (const GLint*) &numFramesPerSwap
  233011. forParameter: NSOpenGLCPSwapInterval];
  233012. return true;
  233013. }
  233014. int getSwapInterval() const
  233015. {
  233016. GLint numFrames = 0;
  233017. [renderContext getValues: &numFrames
  233018. forParameter: NSOpenGLCPSwapInterval];
  233019. return numFrames;
  233020. }
  233021. void repaint()
  233022. {
  233023. // we need to invalidate the juce view that holds this gl view, to make it
  233024. // cause a repaint callback
  233025. NSView* v = (NSView*) viewHolder->view;
  233026. NSRect r = [v frame];
  233027. // bit of a bodge here.. if we only invalidate the area of the gl component,
  233028. // it's completely covered by the NSOpenGLView, so the OS throws away the
  233029. // repaint message, thus never causing our paint() callback, and never repainting
  233030. // the comp. So invalidating just a little bit around the edge helps..
  233031. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  233032. }
  233033. void* getNativeWindowHandle() const { return viewHolder->view; }
  233034. NSOpenGLContext* renderContext;
  233035. ThreadSafeNSOpenGLView* view;
  233036. private:
  233037. OpenGLPixelFormat pixelFormat;
  233038. ScopedPointer <NSViewComponentInternal> viewHolder;
  233039. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  233040. };
  233041. OpenGLContext* OpenGLComponent::createContext()
  233042. {
  233043. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  233044. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  233045. return (c->renderContext != 0) ? c.release() : 0;
  233046. }
  233047. void* OpenGLComponent::getNativeWindowHandle() const
  233048. {
  233049. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  233050. : 0;
  233051. }
  233052. void juce_glViewport (const int w, const int h)
  233053. {
  233054. glViewport (0, 0, w, h);
  233055. }
  233056. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233057. OwnedArray <OpenGLPixelFormat>& results)
  233058. {
  233059. /* GLint attribs [64];
  233060. int n = 0;
  233061. attribs[n++] = AGL_RGBA;
  233062. attribs[n++] = AGL_DOUBLEBUFFER;
  233063. attribs[n++] = AGL_ACCELERATED;
  233064. attribs[n++] = AGL_NO_RECOVERY;
  233065. attribs[n++] = AGL_NONE;
  233066. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  233067. while (p != 0)
  233068. {
  233069. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  233070. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  233071. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  233072. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  233073. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  233074. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  233075. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  233076. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  233077. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  233078. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  233079. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  233080. results.add (pf);
  233081. p = aglNextPixelFormat (p);
  233082. }*/
  233083. //jassertfalse // can't see how you do this in cocoa!
  233084. }
  233085. #else
  233086. END_JUCE_NAMESPACE
  233087. @interface JuceGLView : UIView
  233088. {
  233089. }
  233090. + (Class) layerClass;
  233091. @end
  233092. @implementation JuceGLView
  233093. + (Class) layerClass
  233094. {
  233095. return [CAEAGLLayer class];
  233096. }
  233097. @end
  233098. BEGIN_JUCE_NAMESPACE
  233099. class GLESContext : public OpenGLContext
  233100. {
  233101. public:
  233102. GLESContext (UIViewComponentPeer* peer,
  233103. Component* const component_,
  233104. const OpenGLPixelFormat& pixelFormat_,
  233105. const GLESContext* const sharedContext,
  233106. NSUInteger apiType)
  233107. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  233108. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  233109. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  233110. {
  233111. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  233112. view.opaque = YES;
  233113. view.hidden = NO;
  233114. view.backgroundColor = [UIColor blackColor];
  233115. view.userInteractionEnabled = NO;
  233116. glLayer = (CAEAGLLayer*) [view layer];
  233117. [peer->view addSubview: view];
  233118. if (sharedContext != 0)
  233119. context = [[EAGLContext alloc] initWithAPI: apiType
  233120. sharegroup: [sharedContext->context sharegroup]];
  233121. else
  233122. context = [[EAGLContext alloc] initWithAPI: apiType];
  233123. createGLBuffers();
  233124. }
  233125. ~GLESContext()
  233126. {
  233127. deleteContext();
  233128. [view removeFromSuperview];
  233129. [view release];
  233130. freeGLBuffers();
  233131. }
  233132. void deleteContext()
  233133. {
  233134. makeInactive();
  233135. [context release];
  233136. context = nil;
  233137. }
  233138. bool makeActive() const throw()
  233139. {
  233140. jassert (context != 0);
  233141. [EAGLContext setCurrentContext: context];
  233142. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233143. return true;
  233144. }
  233145. void swapBuffers()
  233146. {
  233147. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233148. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233149. }
  233150. bool makeInactive() const throw()
  233151. {
  233152. return [EAGLContext setCurrentContext: nil];
  233153. }
  233154. bool isActive() const throw()
  233155. {
  233156. return [EAGLContext currentContext] == context;
  233157. }
  233158. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233159. void* getRawContext() const throw() { return glLayer; }
  233160. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233161. {
  233162. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233163. if (lastWidth != w || lastHeight != h)
  233164. {
  233165. lastWidth = w;
  233166. lastHeight = h;
  233167. freeGLBuffers();
  233168. createGLBuffers();
  233169. }
  233170. }
  233171. bool setSwapInterval (const int numFramesPerSwap)
  233172. {
  233173. numFrames = numFramesPerSwap;
  233174. return true;
  233175. }
  233176. int getSwapInterval() const
  233177. {
  233178. return numFrames;
  233179. }
  233180. void repaint()
  233181. {
  233182. }
  233183. void createGLBuffers()
  233184. {
  233185. makeActive();
  233186. glGenFramebuffersOES (1, &frameBufferHandle);
  233187. glGenRenderbuffersOES (1, &colorBufferHandle);
  233188. glGenRenderbuffersOES (1, &depthBufferHandle);
  233189. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233190. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233191. GLint width, height;
  233192. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233193. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233194. if (useDepthBuffer)
  233195. {
  233196. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233197. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233198. }
  233199. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233200. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233201. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233202. if (useDepthBuffer)
  233203. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233204. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233205. }
  233206. void freeGLBuffers()
  233207. {
  233208. if (frameBufferHandle != 0)
  233209. {
  233210. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233211. frameBufferHandle = 0;
  233212. }
  233213. if (colorBufferHandle != 0)
  233214. {
  233215. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233216. colorBufferHandle = 0;
  233217. }
  233218. if (depthBufferHandle != 0)
  233219. {
  233220. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233221. depthBufferHandle = 0;
  233222. }
  233223. }
  233224. private:
  233225. Component::SafePointer<Component> component;
  233226. OpenGLPixelFormat pixelFormat;
  233227. JuceGLView* view;
  233228. CAEAGLLayer* glLayer;
  233229. EAGLContext* context;
  233230. bool useDepthBuffer;
  233231. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233232. int numFrames;
  233233. int lastWidth, lastHeight;
  233234. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  233235. };
  233236. OpenGLContext* OpenGLComponent::createContext()
  233237. {
  233238. ScopedAutoReleasePool pool;
  233239. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233240. if (peer != 0)
  233241. return new GLESContext (peer, this, preferredPixelFormat,
  233242. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233243. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233244. return 0;
  233245. }
  233246. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233247. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233248. {
  233249. }
  233250. void juce_glViewport (const int w, const int h)
  233251. {
  233252. glViewport (0, 0, w, h);
  233253. }
  233254. #endif
  233255. #endif
  233256. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233257. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233258. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233259. // compiled on its own).
  233260. #if JUCE_INCLUDED_FILE
  233261. class JuceMainMenuHandler;
  233262. END_JUCE_NAMESPACE
  233263. using namespace JUCE_NAMESPACE;
  233264. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233265. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233266. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233267. #else
  233268. @interface JuceMenuCallback : NSObject
  233269. #endif
  233270. {
  233271. JuceMainMenuHandler* owner;
  233272. }
  233273. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233274. - (void) dealloc;
  233275. - (void) menuItemInvoked: (id) menu;
  233276. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233277. @end
  233278. BEGIN_JUCE_NAMESPACE
  233279. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233280. private DeletedAtShutdown
  233281. {
  233282. public:
  233283. static JuceMainMenuHandler* instance;
  233284. JuceMainMenuHandler()
  233285. : currentModel (0),
  233286. lastUpdateTime (0)
  233287. {
  233288. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233289. }
  233290. ~JuceMainMenuHandler()
  233291. {
  233292. setMenu (0);
  233293. jassert (instance == this);
  233294. instance = 0;
  233295. [callback release];
  233296. }
  233297. void setMenu (MenuBarModel* const newMenuBarModel)
  233298. {
  233299. if (currentModel != newMenuBarModel)
  233300. {
  233301. if (currentModel != 0)
  233302. currentModel->removeListener (this);
  233303. currentModel = newMenuBarModel;
  233304. if (currentModel != 0)
  233305. currentModel->addListener (this);
  233306. menuBarItemsChanged (0);
  233307. }
  233308. }
  233309. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233310. const String& name, const int menuId, const int tag)
  233311. {
  233312. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233313. action: nil
  233314. keyEquivalent: @""];
  233315. [item setTag: tag];
  233316. NSMenu* sub = createMenu (child, name, menuId, tag);
  233317. [parent setSubmenu: sub forItem: item];
  233318. [sub setAutoenablesItems: false];
  233319. [sub release];
  233320. }
  233321. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233322. const String& name, const int menuId, const int tag)
  233323. {
  233324. [parentItem setTag: tag];
  233325. NSMenu* menu = [parentItem submenu];
  233326. [menu setTitle: juceStringToNS (name)];
  233327. while ([menu numberOfItems] > 0)
  233328. [menu removeItemAtIndex: 0];
  233329. PopupMenu::MenuItemIterator iter (menuToCopy);
  233330. while (iter.next())
  233331. addMenuItem (iter, menu, menuId, tag);
  233332. [menu setAutoenablesItems: false];
  233333. [menu update];
  233334. }
  233335. void menuBarItemsChanged (MenuBarModel*)
  233336. {
  233337. lastUpdateTime = Time::getMillisecondCounter();
  233338. StringArray menuNames;
  233339. if (currentModel != 0)
  233340. menuNames = currentModel->getMenuBarNames();
  233341. NSMenu* menuBar = [NSApp mainMenu];
  233342. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233343. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233344. int menuId = 1;
  233345. for (int i = 0; i < menuNames.size(); ++i)
  233346. {
  233347. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233348. if (i >= [menuBar numberOfItems] - 1)
  233349. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233350. else
  233351. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233352. }
  233353. }
  233354. static void flashMenuBar (NSMenu* menu)
  233355. {
  233356. if ([[menu title] isEqualToString: @"Apple"])
  233357. return;
  233358. [menu retain];
  233359. const unichar f35Key = NSF35FunctionKey;
  233360. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233361. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233362. action: nil
  233363. keyEquivalent: f35String];
  233364. [item setTarget: nil];
  233365. [menu insertItem: item atIndex: [menu numberOfItems]];
  233366. [item release];
  233367. if ([menu indexOfItem: item] >= 0)
  233368. {
  233369. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233370. location: NSZeroPoint
  233371. modifierFlags: NSCommandKeyMask
  233372. timestamp: 0
  233373. windowNumber: 0
  233374. context: [NSGraphicsContext currentContext]
  233375. characters: f35String
  233376. charactersIgnoringModifiers: f35String
  233377. isARepeat: NO
  233378. keyCode: 0];
  233379. [menu performKeyEquivalent: f35Event];
  233380. if ([menu indexOfItem: item] >= 0)
  233381. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233382. }
  233383. [menu release];
  233384. }
  233385. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233386. {
  233387. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233388. {
  233389. NSMenuItem* m = [menu itemAtIndex: i];
  233390. if ([m tag] == info.commandID)
  233391. return m;
  233392. if ([m submenu] != 0)
  233393. {
  233394. NSMenuItem* found = findMenuItem ([m submenu], info);
  233395. if (found != 0)
  233396. return found;
  233397. }
  233398. }
  233399. return 0;
  233400. }
  233401. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233402. {
  233403. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233404. if (item != 0)
  233405. flashMenuBar ([item menu]);
  233406. }
  233407. void updateMenus()
  233408. {
  233409. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233410. menuBarItemsChanged (0);
  233411. }
  233412. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233413. {
  233414. if (currentModel != 0)
  233415. {
  233416. if (commandManager != 0)
  233417. {
  233418. ApplicationCommandTarget::InvocationInfo info (commandId);
  233419. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233420. commandManager->invoke (info, true);
  233421. }
  233422. currentModel->menuItemSelected (commandId, topLevelIndex);
  233423. }
  233424. }
  233425. MenuBarModel* currentModel;
  233426. uint32 lastUpdateTime;
  233427. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233428. const int topLevelMenuId, const int topLevelIndex)
  233429. {
  233430. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233431. if (text == 0)
  233432. text = @"";
  233433. if (iter.isSeparator)
  233434. {
  233435. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233436. }
  233437. else if (iter.isSectionHeader)
  233438. {
  233439. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233440. action: nil
  233441. keyEquivalent: @""];
  233442. [item setEnabled: false];
  233443. }
  233444. else if (iter.subMenu != 0)
  233445. {
  233446. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233447. action: nil
  233448. keyEquivalent: @""];
  233449. [item setTag: iter.itemId];
  233450. [item setEnabled: iter.isEnabled];
  233451. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233452. [sub setDelegate: nil];
  233453. [menuToAddTo setSubmenu: sub forItem: item];
  233454. [sub release];
  233455. }
  233456. else
  233457. {
  233458. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233459. action: @selector (menuItemInvoked:)
  233460. keyEquivalent: @""];
  233461. [item setTag: iter.itemId];
  233462. [item setEnabled: iter.isEnabled];
  233463. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233464. [item setTarget: (id) callback];
  233465. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233466. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233467. [item setRepresentedObject: info];
  233468. if (iter.commandManager != 0)
  233469. {
  233470. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233471. ->getKeyPressesAssignedToCommand (iter.itemId));
  233472. if (keyPresses.size() > 0)
  233473. {
  233474. const KeyPress& kp = keyPresses.getReference(0);
  233475. if (kp.getKeyCode() != KeyPress::backspaceKey
  233476. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233477. // every time you press the key while editing text)
  233478. {
  233479. juce_wchar key = kp.getTextCharacter();
  233480. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233481. key = NSBackspaceCharacter;
  233482. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233483. key = NSDeleteCharacter;
  233484. else if (key == 0)
  233485. key = (juce_wchar) kp.getKeyCode();
  233486. unsigned int mods = 0;
  233487. if (kp.getModifiers().isShiftDown())
  233488. mods |= NSShiftKeyMask;
  233489. if (kp.getModifiers().isCtrlDown())
  233490. mods |= NSControlKeyMask;
  233491. if (kp.getModifiers().isAltDown())
  233492. mods |= NSAlternateKeyMask;
  233493. if (kp.getModifiers().isCommandDown())
  233494. mods |= NSCommandKeyMask;
  233495. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233496. [item setKeyEquivalentModifierMask: mods];
  233497. }
  233498. }
  233499. }
  233500. }
  233501. }
  233502. JuceMenuCallback* callback;
  233503. private:
  233504. NSMenu* createMenu (const PopupMenu menu,
  233505. const String& menuName,
  233506. const int topLevelMenuId,
  233507. const int topLevelIndex)
  233508. {
  233509. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233510. [m setAutoenablesItems: false];
  233511. [m setDelegate: callback];
  233512. PopupMenu::MenuItemIterator iter (menu);
  233513. while (iter.next())
  233514. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233515. [m update];
  233516. return m;
  233517. }
  233518. };
  233519. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233520. END_JUCE_NAMESPACE
  233521. @implementation JuceMenuCallback
  233522. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233523. {
  233524. [super init];
  233525. owner = owner_;
  233526. return self;
  233527. }
  233528. - (void) dealloc
  233529. {
  233530. [super dealloc];
  233531. }
  233532. - (void) menuItemInvoked: (id) menu
  233533. {
  233534. NSMenuItem* item = (NSMenuItem*) menu;
  233535. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233536. {
  233537. // 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
  233538. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233539. // into the focused component and let it trigger the menu item indirectly.
  233540. NSEvent* e = [NSApp currentEvent];
  233541. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233542. {
  233543. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233544. {
  233545. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233546. if (peer != 0)
  233547. {
  233548. if ([e type] == NSKeyDown)
  233549. peer->redirectKeyDown (e);
  233550. else
  233551. peer->redirectKeyUp (e);
  233552. return;
  233553. }
  233554. }
  233555. }
  233556. NSArray* info = (NSArray*) [item representedObject];
  233557. owner->invoke ((int) [item tag],
  233558. (ApplicationCommandManager*) (pointer_sized_int)
  233559. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233560. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233561. }
  233562. }
  233563. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233564. {
  233565. (void) menu;
  233566. if (JuceMainMenuHandler::instance != 0)
  233567. JuceMainMenuHandler::instance->updateMenus();
  233568. }
  233569. @end
  233570. BEGIN_JUCE_NAMESPACE
  233571. namespace MainMenuHelpers
  233572. {
  233573. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  233574. {
  233575. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233576. {
  233577. PopupMenu::MenuItemIterator iter (*extraItems);
  233578. while (iter.next())
  233579. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233580. [menu addItem: [NSMenuItem separatorItem]];
  233581. }
  233582. NSMenuItem* item;
  233583. // Services...
  233584. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233585. action: nil keyEquivalent: @""];
  233586. [menu addItem: item];
  233587. [item release];
  233588. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233589. [menu setSubmenu: servicesMenu forItem: item];
  233590. [NSApp setServicesMenu: servicesMenu];
  233591. [servicesMenu release];
  233592. [menu addItem: [NSMenuItem separatorItem]];
  233593. // Hide + Show stuff...
  233594. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233595. action: @selector (hide:) keyEquivalent: @"h"];
  233596. [item setTarget: NSApp];
  233597. [menu addItem: item];
  233598. [item release];
  233599. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233600. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233601. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233602. [item setTarget: NSApp];
  233603. [menu addItem: item];
  233604. [item release];
  233605. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233606. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233607. [item setTarget: NSApp];
  233608. [menu addItem: item];
  233609. [item release];
  233610. [menu addItem: [NSMenuItem separatorItem]];
  233611. // Quit item....
  233612. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233613. action: @selector (terminate:) keyEquivalent: @"q"];
  233614. [item setTarget: NSApp];
  233615. [menu addItem: item];
  233616. [item release];
  233617. return menu;
  233618. }
  233619. // Since our app has no NIB, this initialises a standard app menu...
  233620. void rebuildMainMenu (const PopupMenu* extraItems)
  233621. {
  233622. // this can't be used in a plugin!
  233623. jassert (JUCEApplication::isStandaloneApp());
  233624. if (JUCEApplication::getInstance() != 0)
  233625. {
  233626. const ScopedAutoReleasePool pool;
  233627. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233628. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233629. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233630. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233631. [mainMenu setSubmenu: appMenu forItem: item];
  233632. [NSApp setMainMenu: mainMenu];
  233633. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233634. [appMenu release];
  233635. [mainMenu release];
  233636. }
  233637. }
  233638. }
  233639. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233640. const PopupMenu* extraAppleMenuItems)
  233641. {
  233642. if (getMacMainMenu() != newMenuBarModel)
  233643. {
  233644. const ScopedAutoReleasePool pool;
  233645. if (newMenuBarModel == 0)
  233646. {
  233647. delete JuceMainMenuHandler::instance;
  233648. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233649. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233650. extraAppleMenuItems = 0;
  233651. }
  233652. else
  233653. {
  233654. if (JuceMainMenuHandler::instance == 0)
  233655. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233656. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233657. }
  233658. }
  233659. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  233660. if (newMenuBarModel != 0)
  233661. newMenuBarModel->menuItemsChanged();
  233662. }
  233663. MenuBarModel* MenuBarModel::getMacMainMenu()
  233664. {
  233665. return JuceMainMenuHandler::instance != 0
  233666. ? JuceMainMenuHandler::instance->currentModel : 0;
  233667. }
  233668. void juce_initialiseMacMainMenu()
  233669. {
  233670. if (JuceMainMenuHandler::instance == 0)
  233671. MainMenuHelpers::rebuildMainMenu (0);
  233672. }
  233673. #endif
  233674. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233675. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233676. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233677. // compiled on its own).
  233678. #if JUCE_INCLUDED_FILE
  233679. #if JUCE_MAC
  233680. END_JUCE_NAMESPACE
  233681. using namespace JUCE_NAMESPACE;
  233682. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233683. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233684. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233685. #else
  233686. @interface JuceFileChooserDelegate : NSObject
  233687. #endif
  233688. {
  233689. StringArray* filters;
  233690. }
  233691. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233692. - (void) dealloc;
  233693. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233694. @end
  233695. @implementation JuceFileChooserDelegate
  233696. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233697. {
  233698. [super init];
  233699. filters = filters_;
  233700. return self;
  233701. }
  233702. - (void) dealloc
  233703. {
  233704. delete filters;
  233705. [super dealloc];
  233706. }
  233707. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233708. {
  233709. (void) sender;
  233710. const File f (nsStringToJuce (filename));
  233711. for (int i = filters->size(); --i >= 0;)
  233712. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233713. return true;
  233714. return f.isDirectory();
  233715. }
  233716. @end
  233717. BEGIN_JUCE_NAMESPACE
  233718. void FileChooser::showPlatformDialog (Array<File>& results,
  233719. const String& title,
  233720. const File& currentFileOrDirectory,
  233721. const String& filter,
  233722. bool selectsDirectory,
  233723. bool selectsFiles,
  233724. bool isSaveDialogue,
  233725. bool warnAboutOverwritingExistingFiles,
  233726. bool selectMultipleFiles,
  233727. FilePreviewComponent* extraInfoComponent)
  233728. {
  233729. const ScopedAutoReleasePool pool;
  233730. StringArray* filters = new StringArray();
  233731. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233732. filters->trim();
  233733. filters->removeEmptyStrings();
  233734. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233735. [delegate autorelease];
  233736. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233737. : [NSOpenPanel openPanel];
  233738. [panel setTitle: juceStringToNS (title)];
  233739. if (! isSaveDialogue)
  233740. {
  233741. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233742. [openPanel setCanChooseDirectories: selectsDirectory];
  233743. [openPanel setCanChooseFiles: selectsFiles];
  233744. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233745. }
  233746. [panel setDelegate: delegate];
  233747. if (isSaveDialogue || selectsDirectory)
  233748. [panel setCanCreateDirectories: YES];
  233749. String directory, filename;
  233750. if (currentFileOrDirectory.isDirectory())
  233751. {
  233752. directory = currentFileOrDirectory.getFullPathName();
  233753. }
  233754. else
  233755. {
  233756. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233757. filename = currentFileOrDirectory.getFileName();
  233758. }
  233759. if ([panel runModalForDirectory: juceStringToNS (directory)
  233760. file: juceStringToNS (filename)]
  233761. == NSOKButton)
  233762. {
  233763. if (isSaveDialogue)
  233764. {
  233765. results.add (File (nsStringToJuce ([panel filename])));
  233766. }
  233767. else
  233768. {
  233769. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233770. NSArray* urls = [openPanel filenames];
  233771. for (unsigned int i = 0; i < [urls count]; ++i)
  233772. {
  233773. NSString* f = [urls objectAtIndex: i];
  233774. results.add (File (nsStringToJuce (f)));
  233775. }
  233776. }
  233777. }
  233778. [panel setDelegate: nil];
  233779. }
  233780. #else
  233781. void FileChooser::showPlatformDialog (Array<File>& results,
  233782. const String& title,
  233783. const File& currentFileOrDirectory,
  233784. const String& filter,
  233785. bool selectsDirectory,
  233786. bool selectsFiles,
  233787. bool isSaveDialogue,
  233788. bool warnAboutOverwritingExistingFiles,
  233789. bool selectMultipleFiles,
  233790. FilePreviewComponent* extraInfoComponent)
  233791. {
  233792. const ScopedAutoReleasePool pool;
  233793. jassertfalse; //xxx to do
  233794. }
  233795. #endif
  233796. #endif
  233797. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233798. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233799. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233800. // compiled on its own).
  233801. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233802. END_JUCE_NAMESPACE
  233803. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233804. @interface NonInterceptingQTMovieView : QTMovieView
  233805. {
  233806. }
  233807. - (id) initWithFrame: (NSRect) frame;
  233808. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233809. - (NSView*) hitTest: (NSPoint) p;
  233810. @end
  233811. @implementation NonInterceptingQTMovieView
  233812. - (id) initWithFrame: (NSRect) frame
  233813. {
  233814. self = [super initWithFrame: frame];
  233815. [self setNextResponder: [self superview]];
  233816. return self;
  233817. }
  233818. - (void) dealloc
  233819. {
  233820. [super dealloc];
  233821. }
  233822. - (NSView*) hitTest: (NSPoint) point
  233823. {
  233824. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233825. }
  233826. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233827. {
  233828. return YES;
  233829. }
  233830. @end
  233831. BEGIN_JUCE_NAMESPACE
  233832. #define theMovie (static_cast <QTMovie*> (movie))
  233833. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233834. : movie (0)
  233835. {
  233836. setOpaque (true);
  233837. setVisible (true);
  233838. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233839. setView (view);
  233840. [view release];
  233841. }
  233842. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233843. {
  233844. closeMovie();
  233845. setView (0);
  233846. }
  233847. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233848. {
  233849. return true;
  233850. }
  233851. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233852. {
  233853. // unfortunately, QTMovie objects can only be created on the main thread..
  233854. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233855. QTMovie* movie = 0;
  233856. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233857. if (fin != 0)
  233858. {
  233859. movieFile = fin->getFile();
  233860. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233861. error: nil];
  233862. }
  233863. else
  233864. {
  233865. MemoryBlock temp;
  233866. movieStream->readIntoMemoryBlock (temp);
  233867. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233868. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233869. {
  233870. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233871. length: temp.getSize()]
  233872. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233873. MIMEType: @""]
  233874. error: nil];
  233875. if (movie != 0)
  233876. break;
  233877. }
  233878. }
  233879. return movie;
  233880. }
  233881. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233882. const bool isControllerVisible_)
  233883. {
  233884. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233885. }
  233886. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233887. const bool controllerVisible_)
  233888. {
  233889. closeMovie();
  233890. if (getPeer() == 0)
  233891. {
  233892. // To open a movie, this component must be visible inside a functioning window, so that
  233893. // the QT control can be assigned to the window.
  233894. jassertfalse;
  233895. return false;
  233896. }
  233897. movie = openMovieFromStream (movieStream, movieFile);
  233898. [theMovie retain];
  233899. QTMovieView* view = (QTMovieView*) getView();
  233900. [view setMovie: theMovie];
  233901. [view setControllerVisible: controllerVisible_];
  233902. setLooping (looping);
  233903. return movie != nil;
  233904. }
  233905. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233906. const bool isControllerVisible_)
  233907. {
  233908. // unfortunately, QTMovie objects can only be created on the main thread..
  233909. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233910. closeMovie();
  233911. if (getPeer() == 0)
  233912. {
  233913. // To open a movie, this component must be visible inside a functioning window, so that
  233914. // the QT control can be assigned to the window.
  233915. jassertfalse;
  233916. return false;
  233917. }
  233918. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233919. NSError* err;
  233920. if ([QTMovie canInitWithURL: url])
  233921. movie = [QTMovie movieWithURL: url error: &err];
  233922. [theMovie retain];
  233923. QTMovieView* view = (QTMovieView*) getView();
  233924. [view setMovie: theMovie];
  233925. [view setControllerVisible: controllerVisible];
  233926. setLooping (looping);
  233927. return movie != nil;
  233928. }
  233929. void QuickTimeMovieComponent::closeMovie()
  233930. {
  233931. stop();
  233932. QTMovieView* view = (QTMovieView*) getView();
  233933. [view setMovie: nil];
  233934. [theMovie release];
  233935. movie = 0;
  233936. movieFile = File::nonexistent;
  233937. }
  233938. bool QuickTimeMovieComponent::isMovieOpen() const
  233939. {
  233940. return movie != nil;
  233941. }
  233942. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233943. {
  233944. return movieFile;
  233945. }
  233946. void QuickTimeMovieComponent::play()
  233947. {
  233948. [theMovie play];
  233949. }
  233950. void QuickTimeMovieComponent::stop()
  233951. {
  233952. [theMovie stop];
  233953. }
  233954. bool QuickTimeMovieComponent::isPlaying() const
  233955. {
  233956. return movie != 0 && [theMovie rate] != 0;
  233957. }
  233958. void QuickTimeMovieComponent::setPosition (const double seconds)
  233959. {
  233960. if (movie != 0)
  233961. {
  233962. QTTime t;
  233963. t.timeValue = (uint64) (100000.0 * seconds);
  233964. t.timeScale = 100000;
  233965. t.flags = 0;
  233966. [theMovie setCurrentTime: t];
  233967. }
  233968. }
  233969. double QuickTimeMovieComponent::getPosition() const
  233970. {
  233971. if (movie == 0)
  233972. return 0.0;
  233973. QTTime t = [theMovie currentTime];
  233974. return t.timeValue / (double) t.timeScale;
  233975. }
  233976. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233977. {
  233978. [theMovie setRate: newSpeed];
  233979. }
  233980. double QuickTimeMovieComponent::getMovieDuration() const
  233981. {
  233982. if (movie == 0)
  233983. return 0.0;
  233984. QTTime t = [theMovie duration];
  233985. return t.timeValue / (double) t.timeScale;
  233986. }
  233987. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233988. {
  233989. looping = shouldLoop;
  233990. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233991. forKey: QTMovieLoopsAttribute];
  233992. }
  233993. bool QuickTimeMovieComponent::isLooping() const
  233994. {
  233995. return looping;
  233996. }
  233997. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233998. {
  233999. [theMovie setVolume: newVolume];
  234000. }
  234001. float QuickTimeMovieComponent::getMovieVolume() const
  234002. {
  234003. return movie != 0 ? [theMovie volume] : 0.0f;
  234004. }
  234005. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  234006. {
  234007. width = 0;
  234008. height = 0;
  234009. if (movie != 0)
  234010. {
  234011. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  234012. width = (int) s.width;
  234013. height = (int) s.height;
  234014. }
  234015. }
  234016. void QuickTimeMovieComponent::paint (Graphics& g)
  234017. {
  234018. if (movie == 0)
  234019. g.fillAll (Colours::black);
  234020. }
  234021. bool QuickTimeMovieComponent::isControllerVisible() const
  234022. {
  234023. return controllerVisible;
  234024. }
  234025. void QuickTimeMovieComponent::goToStart()
  234026. {
  234027. setPosition (0.0);
  234028. }
  234029. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  234030. const RectanglePlacement& placement)
  234031. {
  234032. int normalWidth, normalHeight;
  234033. getMovieNormalSize (normalWidth, normalHeight);
  234034. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  234035. {
  234036. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  234037. placement.applyTo (x, y, w, h,
  234038. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  234039. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  234040. if (w > 0 && h > 0)
  234041. {
  234042. setBounds (roundToInt (x), roundToInt (y),
  234043. roundToInt (w), roundToInt (h));
  234044. }
  234045. }
  234046. else
  234047. {
  234048. setBounds (spaceToFitWithin);
  234049. }
  234050. }
  234051. #if ! (JUCE_MAC && JUCE_64BIT)
  234052. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  234053. {
  234054. if (movieStream == 0)
  234055. return false;
  234056. File file;
  234057. QTMovie* movie = openMovieFromStream (movieStream, file);
  234058. if (movie != nil)
  234059. result = [movie quickTimeMovie];
  234060. return movie != nil;
  234061. }
  234062. #endif
  234063. #endif
  234064. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234065. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  234066. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234067. // compiled on its own).
  234068. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  234069. const int kilobytesPerSecond1x = 176;
  234070. END_JUCE_NAMESPACE
  234071. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  234072. @interface OpenDiskDevice : NSObject
  234073. {
  234074. @public
  234075. DRDevice* device;
  234076. NSMutableArray* tracks;
  234077. bool underrunProtection;
  234078. }
  234079. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  234080. - (void) dealloc;
  234081. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  234082. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234083. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  234084. @end
  234085. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  234086. @interface AudioTrackProducer : NSObject
  234087. {
  234088. JUCE_NAMESPACE::AudioSource* source;
  234089. int readPosition, lengthInFrames;
  234090. }
  234091. - (AudioTrackProducer*) init: (int) lengthInFrames;
  234092. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  234093. - (void) dealloc;
  234094. - (void) setupTrackProperties: (DRTrack*) track;
  234095. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  234096. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  234097. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  234098. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  234099. toMedia:(NSDictionary*)mediaInfo;
  234100. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  234101. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  234102. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234103. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234104. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234105. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234106. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234107. ioFlags:(uint32_t*)flags;
  234108. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  234109. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234110. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234111. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234112. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234113. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234114. ioFlags:(uint32_t*)flags;
  234115. @end
  234116. @implementation OpenDiskDevice
  234117. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  234118. {
  234119. [super init];
  234120. device = device_;
  234121. tracks = [[NSMutableArray alloc] init];
  234122. underrunProtection = true;
  234123. return self;
  234124. }
  234125. - (void) dealloc
  234126. {
  234127. [tracks release];
  234128. [super dealloc];
  234129. }
  234130. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  234131. {
  234132. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  234133. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  234134. [p setupTrackProperties: t];
  234135. [tracks addObject: t];
  234136. [t release];
  234137. [p release];
  234138. }
  234139. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234140. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234141. {
  234142. DRBurn* burn = [DRBurn burnForDevice: device];
  234143. if (! [device acquireExclusiveAccess])
  234144. {
  234145. *error = "Couldn't open or write to the CD device";
  234146. return;
  234147. }
  234148. [device acquireMediaReservation];
  234149. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234150. [d autorelease];
  234151. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234152. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234153. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234154. if (burnSpeed > 0)
  234155. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234156. if (! underrunProtection)
  234157. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234158. [burn setProperties: d];
  234159. [burn writeLayout: tracks];
  234160. for (;;)
  234161. {
  234162. JUCE_NAMESPACE::Thread::sleep (300);
  234163. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234164. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234165. {
  234166. [burn abort];
  234167. *error = "User cancelled the write operation";
  234168. break;
  234169. }
  234170. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234171. {
  234172. *error = "Write operation failed";
  234173. break;
  234174. }
  234175. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234176. {
  234177. break;
  234178. }
  234179. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234180. objectForKey: DRErrorStatusErrorStringKey];
  234181. if ([err length] > 0)
  234182. {
  234183. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234184. break;
  234185. }
  234186. }
  234187. [device releaseMediaReservation];
  234188. [device releaseExclusiveAccess];
  234189. }
  234190. @end
  234191. @implementation AudioTrackProducer
  234192. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234193. {
  234194. lengthInFrames = lengthInFrames_;
  234195. readPosition = 0;
  234196. return self;
  234197. }
  234198. - (void) setupTrackProperties: (DRTrack*) track
  234199. {
  234200. NSMutableDictionary* p = [[track properties] mutableCopy];
  234201. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234202. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234203. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234204. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234205. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234206. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234207. [track setProperties: p];
  234208. [p release];
  234209. }
  234210. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234211. {
  234212. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234213. if (s != nil)
  234214. s->source = source_;
  234215. return s;
  234216. }
  234217. - (void) dealloc
  234218. {
  234219. if (source != 0)
  234220. {
  234221. source->releaseResources();
  234222. delete source;
  234223. }
  234224. [super dealloc];
  234225. }
  234226. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234227. {
  234228. }
  234229. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234230. {
  234231. return true;
  234232. }
  234233. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234234. {
  234235. return lengthInFrames;
  234236. }
  234237. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234238. toMedia: (NSDictionary*) mediaInfo
  234239. {
  234240. if (source != 0)
  234241. source->prepareToPlay (44100 / 75, 44100);
  234242. readPosition = 0;
  234243. return true;
  234244. }
  234245. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234246. {
  234247. if (source != 0)
  234248. source->prepareToPlay (44100 / 75, 44100);
  234249. return true;
  234250. }
  234251. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234252. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234253. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234254. {
  234255. if (source != 0)
  234256. {
  234257. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234258. if (numSamples > 0)
  234259. {
  234260. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234261. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234262. info.buffer = &tempBuffer;
  234263. info.startSample = 0;
  234264. info.numSamples = numSamples;
  234265. source->getNextAudioBlock (info);
  234266. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  234267. JUCE_NAMESPACE::AudioData::LittleEndian,
  234268. JUCE_NAMESPACE::AudioData::Interleaved,
  234269. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  234270. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  234271. JUCE_NAMESPACE::AudioData::NativeEndian,
  234272. JUCE_NAMESPACE::AudioData::NonInterleaved,
  234273. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  234274. CDSampleFormat left (buffer, 2);
  234275. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  234276. CDSampleFormat right (buffer + 2, 2);
  234277. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  234278. readPosition += numSamples;
  234279. }
  234280. return numSamples * 4;
  234281. }
  234282. return 0;
  234283. }
  234284. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234285. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234286. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234287. ioFlags: (uint32_t*) flags
  234288. {
  234289. zeromem (buffer, bufferLength);
  234290. return bufferLength;
  234291. }
  234292. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234293. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234294. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234295. {
  234296. return true;
  234297. }
  234298. @end
  234299. BEGIN_JUCE_NAMESPACE
  234300. class AudioCDBurner::Pimpl : public Timer
  234301. {
  234302. public:
  234303. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234304. : device (0), owner (owner_)
  234305. {
  234306. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234307. if (dev != 0)
  234308. {
  234309. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234310. lastState = getDiskState();
  234311. startTimer (1000);
  234312. }
  234313. }
  234314. ~Pimpl()
  234315. {
  234316. stopTimer();
  234317. [device release];
  234318. }
  234319. void timerCallback()
  234320. {
  234321. const DiskState state = getDiskState();
  234322. if (state != lastState)
  234323. {
  234324. lastState = state;
  234325. owner.sendChangeMessage();
  234326. }
  234327. }
  234328. DiskState getDiskState() const
  234329. {
  234330. if ([device->device isValid])
  234331. {
  234332. NSDictionary* status = [device->device status];
  234333. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234334. if ([state isEqualTo: DRDeviceMediaStateNone])
  234335. {
  234336. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234337. return trayOpen;
  234338. return noDisc;
  234339. }
  234340. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234341. {
  234342. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234343. return writableDiskPresent;
  234344. else
  234345. return readOnlyDiskPresent;
  234346. }
  234347. }
  234348. return unknown;
  234349. }
  234350. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234351. const Array<int> getAvailableWriteSpeeds() const
  234352. {
  234353. Array<int> results;
  234354. if ([device->device isValid])
  234355. {
  234356. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234357. for (unsigned int i = 0; i < [speeds count]; ++i)
  234358. {
  234359. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234360. results.add (kbPerSec / kilobytesPerSecond1x);
  234361. }
  234362. }
  234363. return results;
  234364. }
  234365. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234366. {
  234367. if ([device->device isValid])
  234368. {
  234369. device->underrunProtection = shouldBeEnabled;
  234370. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234371. }
  234372. return false;
  234373. }
  234374. int getNumAvailableAudioBlocks() const
  234375. {
  234376. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234377. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234378. }
  234379. OpenDiskDevice* device;
  234380. private:
  234381. DiskState lastState;
  234382. AudioCDBurner& owner;
  234383. };
  234384. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234385. {
  234386. pimpl = new Pimpl (*this, deviceIndex);
  234387. }
  234388. AudioCDBurner::~AudioCDBurner()
  234389. {
  234390. }
  234391. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234392. {
  234393. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234394. if (b->pimpl->device == 0)
  234395. b = 0;
  234396. return b.release();
  234397. }
  234398. namespace
  234399. {
  234400. NSArray* findDiskBurnerDevices()
  234401. {
  234402. NSMutableArray* results = [NSMutableArray array];
  234403. NSArray* devs = [DRDevice devices];
  234404. for (int i = 0; i < [devs count]; ++i)
  234405. {
  234406. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234407. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234408. if (name != nil)
  234409. [results addObject: name];
  234410. }
  234411. return results;
  234412. }
  234413. }
  234414. const StringArray AudioCDBurner::findAvailableDevices()
  234415. {
  234416. NSArray* names = findDiskBurnerDevices();
  234417. StringArray s;
  234418. for (unsigned int i = 0; i < [names count]; ++i)
  234419. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234420. return s;
  234421. }
  234422. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234423. {
  234424. return pimpl->getDiskState();
  234425. }
  234426. bool AudioCDBurner::isDiskPresent() const
  234427. {
  234428. return getDiskState() == writableDiskPresent;
  234429. }
  234430. bool AudioCDBurner::openTray()
  234431. {
  234432. return pimpl->openTray();
  234433. }
  234434. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234435. {
  234436. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234437. DiskState oldState = getDiskState();
  234438. DiskState newState = oldState;
  234439. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234440. {
  234441. newState = getDiskState();
  234442. Thread::sleep (100);
  234443. }
  234444. return newState;
  234445. }
  234446. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234447. {
  234448. return pimpl->getAvailableWriteSpeeds();
  234449. }
  234450. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234451. {
  234452. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234453. }
  234454. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234455. {
  234456. return pimpl->getNumAvailableAudioBlocks();
  234457. }
  234458. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234459. {
  234460. if ([pimpl->device->device isValid])
  234461. {
  234462. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234463. return true;
  234464. }
  234465. return false;
  234466. }
  234467. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234468. bool ejectDiscAfterwards,
  234469. bool performFakeBurnForTesting,
  234470. int writeSpeed)
  234471. {
  234472. String error ("Couldn't open or write to the CD device");
  234473. if ([pimpl->device->device isValid])
  234474. {
  234475. error = String::empty;
  234476. [pimpl->device burn: listener
  234477. errorString: &error
  234478. ejectAfterwards: ejectDiscAfterwards
  234479. isFake: performFakeBurnForTesting
  234480. speed: writeSpeed];
  234481. }
  234482. return error;
  234483. }
  234484. #endif
  234485. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234486. void AudioCDReader::ejectDisk()
  234487. {
  234488. const ScopedAutoReleasePool p;
  234489. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234490. }
  234491. #endif
  234492. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234493. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234494. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234495. // compiled on its own).
  234496. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234497. namespace CDReaderHelpers
  234498. {
  234499. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234500. {
  234501. forEachXmlChildElementWithTagName (xml, child, "key")
  234502. if (child->getAllSubText().trim() == key)
  234503. return child->getNextElement();
  234504. return 0;
  234505. }
  234506. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234507. {
  234508. const XmlElement* const block = getElementForKey (xml, key);
  234509. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234510. }
  234511. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234512. // Returns NULL on success, otherwise a const char* representing an error.
  234513. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234514. {
  234515. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234516. if (xml == 0)
  234517. return "Couldn't parse XML in file";
  234518. const XmlElement* const dict = xml->getChildByName ("dict");
  234519. if (dict == 0)
  234520. return "Couldn't get top level dictionary";
  234521. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234522. if (sessions == 0)
  234523. return "Couldn't find sessions key";
  234524. const XmlElement* const session = sessions->getFirstChildElement();
  234525. if (session == 0)
  234526. return "Couldn't find first session";
  234527. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234528. if (leadOut < 0)
  234529. return "Couldn't find Leadout Block";
  234530. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234531. if (trackArray == 0)
  234532. return "Couldn't find Track Array";
  234533. forEachXmlChildElement (*trackArray, track)
  234534. {
  234535. const int trackValue = getIntValueForKey (*track, "Start Block");
  234536. if (trackValue < 0)
  234537. return "Couldn't find Start Block in the track";
  234538. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234539. }
  234540. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234541. return 0;
  234542. }
  234543. static void findDevices (Array<File>& cds)
  234544. {
  234545. File volumes ("/Volumes");
  234546. volumes.findChildFiles (cds, File::findDirectories, false);
  234547. for (int i = cds.size(); --i >= 0;)
  234548. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234549. cds.remove (i);
  234550. }
  234551. struct TrackSorter
  234552. {
  234553. static int getCDTrackNumber (const File& file)
  234554. {
  234555. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234556. }
  234557. static int compareElements (const File& first, const File& second)
  234558. {
  234559. const int firstTrack = getCDTrackNumber (first);
  234560. const int secondTrack = getCDTrackNumber (second);
  234561. jassert (firstTrack > 0 && secondTrack > 0);
  234562. return firstTrack - secondTrack;
  234563. }
  234564. };
  234565. }
  234566. const StringArray AudioCDReader::getAvailableCDNames()
  234567. {
  234568. Array<File> cds;
  234569. CDReaderHelpers::findDevices (cds);
  234570. StringArray names;
  234571. for (int i = 0; i < cds.size(); ++i)
  234572. names.add (cds.getReference(i).getFileName());
  234573. return names;
  234574. }
  234575. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234576. {
  234577. Array<File> cds;
  234578. CDReaderHelpers::findDevices (cds);
  234579. if (cds[index].exists())
  234580. return new AudioCDReader (cds[index]);
  234581. return 0;
  234582. }
  234583. AudioCDReader::AudioCDReader (const File& volume)
  234584. : AudioFormatReader (0, "CD Audio"),
  234585. volumeDir (volume),
  234586. currentReaderTrack (-1),
  234587. reader (0)
  234588. {
  234589. sampleRate = 44100.0;
  234590. bitsPerSample = 16;
  234591. numChannels = 2;
  234592. usesFloatingPointData = false;
  234593. refreshTrackLengths();
  234594. }
  234595. AudioCDReader::~AudioCDReader()
  234596. {
  234597. }
  234598. void AudioCDReader::refreshTrackLengths()
  234599. {
  234600. tracks.clear();
  234601. trackStartSamples.clear();
  234602. lengthInSamples = 0;
  234603. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234604. CDReaderHelpers::TrackSorter sorter;
  234605. tracks.sort (sorter);
  234606. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234607. if (toc.exists())
  234608. {
  234609. XmlDocument doc (toc);
  234610. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234611. (void) error; // could be logged..
  234612. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234613. }
  234614. }
  234615. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234616. int64 startSampleInFile, int numSamples)
  234617. {
  234618. while (numSamples > 0)
  234619. {
  234620. int track = -1;
  234621. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234622. {
  234623. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234624. {
  234625. track = i;
  234626. break;
  234627. }
  234628. }
  234629. if (track < 0)
  234630. return false;
  234631. if (track != currentReaderTrack)
  234632. {
  234633. reader = 0;
  234634. FileInputStream* const in = tracks [track].createInputStream();
  234635. if (in != 0)
  234636. {
  234637. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234638. AiffAudioFormat format;
  234639. reader = format.createReaderFor (bin, true);
  234640. if (reader == 0)
  234641. currentReaderTrack = -1;
  234642. else
  234643. currentReaderTrack = track;
  234644. }
  234645. }
  234646. if (reader == 0)
  234647. return false;
  234648. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234649. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234650. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234651. numSamples -= numAvailable;
  234652. startSampleInFile += numAvailable;
  234653. }
  234654. return true;
  234655. }
  234656. bool AudioCDReader::isCDStillPresent() const
  234657. {
  234658. return volumeDir.exists();
  234659. }
  234660. bool AudioCDReader::isTrackAudio (int trackNum) const
  234661. {
  234662. return tracks [trackNum].hasFileExtension (".aiff");
  234663. }
  234664. void AudioCDReader::enableIndexScanning (bool b)
  234665. {
  234666. // any way to do this on a Mac??
  234667. }
  234668. int AudioCDReader::getLastIndex() const
  234669. {
  234670. return 0;
  234671. }
  234672. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234673. {
  234674. return Array <int>();
  234675. }
  234676. #endif
  234677. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234678. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234679. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234680. // compiled on its own).
  234681. #if JUCE_INCLUDED_FILE
  234682. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234683. for example having more than one juce plugin loaded into a host, then when a
  234684. method is called, the actual code that runs might actually be in a different module
  234685. than the one you expect... So any calls to library functions or statics that are
  234686. made inside obj-c methods will probably end up getting executed in a different DLL's
  234687. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234688. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234689. virtual methods of an object that's known to live inside the right module's space.
  234690. */
  234691. class AppDelegateRedirector
  234692. {
  234693. public:
  234694. AppDelegateRedirector()
  234695. {
  234696. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234697. runLoop = CFRunLoopGetMain();
  234698. #else
  234699. runLoop = CFRunLoopGetCurrent();
  234700. #endif
  234701. CFRunLoopSourceContext sourceContext;
  234702. zerostruct (sourceContext);
  234703. sourceContext.info = this;
  234704. sourceContext.perform = runLoopSourceCallback;
  234705. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234706. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234707. }
  234708. virtual ~AppDelegateRedirector()
  234709. {
  234710. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234711. CFRunLoopSourceInvalidate (runLoopSource);
  234712. CFRelease (runLoopSource);
  234713. }
  234714. virtual NSApplicationTerminateReply shouldTerminate()
  234715. {
  234716. if (JUCEApplication::getInstance() != 0)
  234717. {
  234718. JUCEApplication::getInstance()->systemRequestedQuit();
  234719. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234720. return NSTerminateCancel;
  234721. }
  234722. return NSTerminateNow;
  234723. }
  234724. virtual void willTerminate()
  234725. {
  234726. JUCEApplication::appWillTerminateByForce();
  234727. }
  234728. virtual BOOL openFile (NSString* filename)
  234729. {
  234730. if (JUCEApplication::getInstance() != 0)
  234731. {
  234732. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234733. return YES;
  234734. }
  234735. return NO;
  234736. }
  234737. virtual void openFiles (NSArray* filenames)
  234738. {
  234739. StringArray files;
  234740. for (unsigned int i = 0; i < [filenames count]; ++i)
  234741. {
  234742. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234743. if (filename.containsChar (' '))
  234744. filename = filename.quoted('"');
  234745. files.add (filename);
  234746. }
  234747. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234748. {
  234749. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234750. }
  234751. }
  234752. virtual void focusChanged()
  234753. {
  234754. juce_HandleProcessFocusChange();
  234755. }
  234756. struct CallbackMessagePayload
  234757. {
  234758. MessageCallbackFunction* function;
  234759. void* parameter;
  234760. void* volatile result;
  234761. bool volatile hasBeenExecuted;
  234762. };
  234763. virtual void performCallback (CallbackMessagePayload* pl)
  234764. {
  234765. pl->result = (*pl->function) (pl->parameter);
  234766. pl->hasBeenExecuted = true;
  234767. }
  234768. virtual void deleteSelf()
  234769. {
  234770. delete this;
  234771. }
  234772. void postMessage (Message* const m)
  234773. {
  234774. messages.add (m);
  234775. CFRunLoopSourceSignal (runLoopSource);
  234776. CFRunLoopWakeUp (runLoop);
  234777. }
  234778. private:
  234779. CFRunLoopRef runLoop;
  234780. CFRunLoopSourceRef runLoopSource;
  234781. OwnedArray <Message, CriticalSection> messages;
  234782. void runLoopCallback()
  234783. {
  234784. int numDispatched = 0;
  234785. do
  234786. {
  234787. Message* const nextMessage = messages.removeAndReturn (0);
  234788. if (nextMessage == 0)
  234789. return;
  234790. const ScopedAutoReleasePool pool;
  234791. MessageManager::getInstance()->deliverMessage (nextMessage);
  234792. } while (++numDispatched <= 4);
  234793. CFRunLoopSourceSignal (runLoopSource);
  234794. CFRunLoopWakeUp (runLoop);
  234795. }
  234796. static void runLoopSourceCallback (void* info)
  234797. {
  234798. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  234799. }
  234800. };
  234801. END_JUCE_NAMESPACE
  234802. using namespace JUCE_NAMESPACE;
  234803. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234804. @interface JuceAppDelegate : NSObject
  234805. {
  234806. @private
  234807. id oldDelegate;
  234808. @public
  234809. AppDelegateRedirector* redirector;
  234810. }
  234811. - (JuceAppDelegate*) init;
  234812. - (void) dealloc;
  234813. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234814. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234815. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234816. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234817. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234818. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234819. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234820. - (void) performCallback: (id) info;
  234821. - (void) dummyMethod;
  234822. @end
  234823. @implementation JuceAppDelegate
  234824. - (JuceAppDelegate*) init
  234825. {
  234826. [super init];
  234827. redirector = new AppDelegateRedirector();
  234828. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234829. if (JUCEApplication::isStandaloneApp())
  234830. {
  234831. oldDelegate = [NSApp delegate];
  234832. [NSApp setDelegate: self];
  234833. }
  234834. else
  234835. {
  234836. oldDelegate = 0;
  234837. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234838. name: NSApplicationDidResignActiveNotification object: NSApp];
  234839. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234840. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234841. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234842. name: NSApplicationWillUnhideNotification object: NSApp];
  234843. }
  234844. return self;
  234845. }
  234846. - (void) dealloc
  234847. {
  234848. if (oldDelegate != 0)
  234849. [NSApp setDelegate: oldDelegate];
  234850. redirector->deleteSelf();
  234851. [super dealloc];
  234852. }
  234853. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234854. {
  234855. (void) app;
  234856. return redirector->shouldTerminate();
  234857. }
  234858. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234859. {
  234860. (void) aNotification;
  234861. redirector->willTerminate();
  234862. }
  234863. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234864. {
  234865. (void) app;
  234866. return redirector->openFile (filename);
  234867. }
  234868. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234869. {
  234870. (void) sender;
  234871. return redirector->openFiles (filenames);
  234872. }
  234873. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234874. {
  234875. (void) notification;
  234876. redirector->focusChanged();
  234877. }
  234878. - (void) applicationDidResignActive: (NSNotification*) notification
  234879. {
  234880. (void) notification;
  234881. redirector->focusChanged();
  234882. }
  234883. - (void) applicationWillUnhide: (NSNotification*) notification
  234884. {
  234885. (void) notification;
  234886. redirector->focusChanged();
  234887. }
  234888. - (void) performCallback: (id) info
  234889. {
  234890. if ([info isKindOfClass: [NSData class]])
  234891. {
  234892. AppDelegateRedirector::CallbackMessagePayload* pl
  234893. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234894. if (pl != 0)
  234895. redirector->performCallback (pl);
  234896. }
  234897. else
  234898. {
  234899. jassertfalse; // should never get here!
  234900. }
  234901. }
  234902. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234903. @end
  234904. BEGIN_JUCE_NAMESPACE
  234905. static JuceAppDelegate* juceAppDelegate = 0;
  234906. void MessageManager::runDispatchLoop()
  234907. {
  234908. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234909. {
  234910. const ScopedAutoReleasePool pool;
  234911. // must only be called by the message thread!
  234912. jassert (isThisTheMessageThread());
  234913. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234914. @try
  234915. {
  234916. [NSApp run];
  234917. }
  234918. @catch (NSException* e)
  234919. {
  234920. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234921. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234922. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234923. }
  234924. @finally
  234925. {
  234926. }
  234927. #else
  234928. [NSApp run];
  234929. #endif
  234930. }
  234931. }
  234932. void MessageManager::stopDispatchLoop()
  234933. {
  234934. quitMessagePosted = true;
  234935. [NSApp stop: nil];
  234936. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234937. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234938. }
  234939. namespace
  234940. {
  234941. bool isEventBlockedByModalComps (NSEvent* e)
  234942. {
  234943. if (Component::getNumCurrentlyModalComponents() == 0)
  234944. return false;
  234945. NSWindow* const w = [e window];
  234946. if (w == 0 || [w worksWhenModal])
  234947. return false;
  234948. bool isKey = false, isInputAttempt = false;
  234949. switch ([e type])
  234950. {
  234951. case NSKeyDown:
  234952. case NSKeyUp:
  234953. isKey = isInputAttempt = true;
  234954. break;
  234955. case NSLeftMouseDown:
  234956. case NSRightMouseDown:
  234957. case NSOtherMouseDown:
  234958. isInputAttempt = true;
  234959. break;
  234960. case NSLeftMouseDragged:
  234961. case NSRightMouseDragged:
  234962. case NSLeftMouseUp:
  234963. case NSRightMouseUp:
  234964. case NSOtherMouseUp:
  234965. case NSOtherMouseDragged:
  234966. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234967. return false;
  234968. break;
  234969. case NSMouseMoved:
  234970. case NSMouseEntered:
  234971. case NSMouseExited:
  234972. case NSCursorUpdate:
  234973. case NSScrollWheel:
  234974. case NSTabletPoint:
  234975. case NSTabletProximity:
  234976. break;
  234977. default:
  234978. return false;
  234979. }
  234980. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234981. {
  234982. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234983. NSView* const compView = (NSView*) peer->getNativeHandle();
  234984. if ([compView window] == w)
  234985. {
  234986. if (isKey)
  234987. {
  234988. if (compView == [w firstResponder])
  234989. return false;
  234990. }
  234991. else
  234992. {
  234993. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234994. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234995. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234996. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234997. return false;
  234998. }
  234999. }
  235000. }
  235001. if (isInputAttempt)
  235002. {
  235003. if (! [NSApp isActive])
  235004. [NSApp activateIgnoringOtherApps: YES];
  235005. Component* const modal = Component::getCurrentlyModalComponent (0);
  235006. if (modal != 0)
  235007. modal->inputAttemptWhenModal();
  235008. }
  235009. return true;
  235010. }
  235011. }
  235012. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  235013. {
  235014. jassert (isThisTheMessageThread()); // must only be called by the message thread
  235015. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  235016. while (! quitMessagePosted)
  235017. {
  235018. const ScopedAutoReleasePool pool;
  235019. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  235020. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  235021. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  235022. inMode: NSDefaultRunLoopMode
  235023. dequeue: YES];
  235024. if (e != 0 && ! isEventBlockedByModalComps (e))
  235025. [NSApp sendEvent: e];
  235026. if (Time::getMillisecondCounter() >= endTime)
  235027. break;
  235028. }
  235029. return ! quitMessagePosted;
  235030. }
  235031. void MessageManager::doPlatformSpecificInitialisation()
  235032. {
  235033. if (juceAppDelegate == 0)
  235034. juceAppDelegate = [[JuceAppDelegate alloc] init];
  235035. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  235036. // correctly (needed prior to 10.5)
  235037. if (! [NSThread isMultiThreaded])
  235038. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  235039. toTarget: juceAppDelegate
  235040. withObject: nil];
  235041. }
  235042. void MessageManager::doPlatformSpecificShutdown()
  235043. {
  235044. if (juceAppDelegate != 0)
  235045. {
  235046. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  235047. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  235048. [juceAppDelegate release];
  235049. juceAppDelegate = 0;
  235050. }
  235051. }
  235052. bool juce_postMessageToSystemQueue (Message* message)
  235053. {
  235054. juceAppDelegate->redirector->postMessage (message);
  235055. return true;
  235056. }
  235057. void MessageManager::broadcastMessage (const String& value)
  235058. {
  235059. }
  235060. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  235061. {
  235062. if (isThisTheMessageThread())
  235063. {
  235064. return (*callback) (data);
  235065. }
  235066. else
  235067. {
  235068. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  235069. // deadlock because the message manager is blocked from running, so can never
  235070. // call your function..
  235071. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  235072. const ScopedAutoReleasePool pool;
  235073. AppDelegateRedirector::CallbackMessagePayload cmp;
  235074. cmp.function = callback;
  235075. cmp.parameter = data;
  235076. cmp.result = 0;
  235077. cmp.hasBeenExecuted = false;
  235078. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  235079. withObject: [NSData dataWithBytesNoCopy: &cmp
  235080. length: sizeof (cmp)
  235081. freeWhenDone: NO]
  235082. waitUntilDone: YES];
  235083. return cmp.result;
  235084. }
  235085. }
  235086. #endif
  235087. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  235088. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235089. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235090. // compiled on its own).
  235091. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  235092. #if JUCE_MAC
  235093. END_JUCE_NAMESPACE
  235094. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  235095. @interface DownloadClickDetector : NSObject
  235096. {
  235097. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  235098. }
  235099. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  235100. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235101. request: (NSURLRequest*) request
  235102. frame: (WebFrame*) frame
  235103. decisionListener: (id<WebPolicyDecisionListener>) listener;
  235104. @end
  235105. @implementation DownloadClickDetector
  235106. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  235107. {
  235108. [super init];
  235109. ownerComponent = ownerComponent_;
  235110. return self;
  235111. }
  235112. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235113. request: (NSURLRequest*) request
  235114. frame: (WebFrame*) frame
  235115. decisionListener: (id <WebPolicyDecisionListener>) listener
  235116. {
  235117. (void) sender;
  235118. (void) request;
  235119. (void) frame;
  235120. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  235121. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  235122. [listener use];
  235123. else
  235124. [listener ignore];
  235125. }
  235126. @end
  235127. BEGIN_JUCE_NAMESPACE
  235128. class WebBrowserComponentInternal : public NSViewComponent
  235129. {
  235130. public:
  235131. WebBrowserComponentInternal (WebBrowserComponent* owner)
  235132. {
  235133. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  235134. frameName: @""
  235135. groupName: @""];
  235136. setView (webView);
  235137. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  235138. [webView setPolicyDelegate: clickListener];
  235139. }
  235140. ~WebBrowserComponentInternal()
  235141. {
  235142. [webView setPolicyDelegate: nil];
  235143. [clickListener release];
  235144. setView (0);
  235145. }
  235146. void goToURL (const String& url,
  235147. const StringArray* headers,
  235148. const MemoryBlock* postData)
  235149. {
  235150. NSMutableURLRequest* r
  235151. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235152. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235153. timeoutInterval: 30.0];
  235154. if (postData != 0 && postData->getSize() > 0)
  235155. {
  235156. [r setHTTPMethod: @"POST"];
  235157. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235158. length: postData->getSize()]];
  235159. }
  235160. if (headers != 0)
  235161. {
  235162. for (int i = 0; i < headers->size(); ++i)
  235163. {
  235164. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235165. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235166. [r setValue: juceStringToNS (headerValue)
  235167. forHTTPHeaderField: juceStringToNS (headerName)];
  235168. }
  235169. }
  235170. stop();
  235171. [[webView mainFrame] loadRequest: r];
  235172. }
  235173. void goBack()
  235174. {
  235175. [webView goBack];
  235176. }
  235177. void goForward()
  235178. {
  235179. [webView goForward];
  235180. }
  235181. void stop()
  235182. {
  235183. [webView stopLoading: nil];
  235184. }
  235185. void refresh()
  235186. {
  235187. [webView reload: nil];
  235188. }
  235189. void mouseMove (const MouseEvent&)
  235190. {
  235191. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  235192. // them work is to push them via this non-public method..
  235193. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  235194. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  235195. }
  235196. private:
  235197. WebView* webView;
  235198. DownloadClickDetector* clickListener;
  235199. };
  235200. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235201. : browser (0),
  235202. blankPageShown (false),
  235203. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235204. {
  235205. setOpaque (true);
  235206. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235207. }
  235208. WebBrowserComponent::~WebBrowserComponent()
  235209. {
  235210. deleteAndZero (browser);
  235211. }
  235212. void WebBrowserComponent::goToURL (const String& url,
  235213. const StringArray* headers,
  235214. const MemoryBlock* postData)
  235215. {
  235216. lastURL = url;
  235217. lastHeaders.clear();
  235218. if (headers != 0)
  235219. lastHeaders = *headers;
  235220. lastPostData.setSize (0);
  235221. if (postData != 0)
  235222. lastPostData = *postData;
  235223. blankPageShown = false;
  235224. browser->goToURL (url, headers, postData);
  235225. }
  235226. void WebBrowserComponent::stop()
  235227. {
  235228. browser->stop();
  235229. }
  235230. void WebBrowserComponent::goBack()
  235231. {
  235232. lastURL = String::empty;
  235233. blankPageShown = false;
  235234. browser->goBack();
  235235. }
  235236. void WebBrowserComponent::goForward()
  235237. {
  235238. lastURL = String::empty;
  235239. browser->goForward();
  235240. }
  235241. void WebBrowserComponent::refresh()
  235242. {
  235243. browser->refresh();
  235244. }
  235245. void WebBrowserComponent::paint (Graphics&)
  235246. {
  235247. }
  235248. void WebBrowserComponent::checkWindowAssociation()
  235249. {
  235250. if (isShowing())
  235251. {
  235252. if (blankPageShown)
  235253. goBack();
  235254. }
  235255. else
  235256. {
  235257. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235258. {
  235259. // when the component becomes invisible, some stuff like flash
  235260. // carries on playing audio, so we need to force it onto a blank
  235261. // page to avoid this, (and send it back when it's made visible again).
  235262. blankPageShown = true;
  235263. browser->goToURL ("about:blank", 0, 0);
  235264. }
  235265. }
  235266. }
  235267. void WebBrowserComponent::reloadLastURL()
  235268. {
  235269. if (lastURL.isNotEmpty())
  235270. {
  235271. goToURL (lastURL, &lastHeaders, &lastPostData);
  235272. lastURL = String::empty;
  235273. }
  235274. }
  235275. void WebBrowserComponent::parentHierarchyChanged()
  235276. {
  235277. checkWindowAssociation();
  235278. }
  235279. void WebBrowserComponent::resized()
  235280. {
  235281. browser->setSize (getWidth(), getHeight());
  235282. }
  235283. void WebBrowserComponent::visibilityChanged()
  235284. {
  235285. checkWindowAssociation();
  235286. }
  235287. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235288. {
  235289. return true;
  235290. }
  235291. #else
  235292. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235293. {
  235294. }
  235295. WebBrowserComponent::~WebBrowserComponent()
  235296. {
  235297. }
  235298. void WebBrowserComponent::goToURL (const String& url,
  235299. const StringArray* headers,
  235300. const MemoryBlock* postData)
  235301. {
  235302. }
  235303. void WebBrowserComponent::stop()
  235304. {
  235305. }
  235306. void WebBrowserComponent::goBack()
  235307. {
  235308. }
  235309. void WebBrowserComponent::goForward()
  235310. {
  235311. }
  235312. void WebBrowserComponent::refresh()
  235313. {
  235314. }
  235315. void WebBrowserComponent::paint (Graphics& g)
  235316. {
  235317. }
  235318. void WebBrowserComponent::checkWindowAssociation()
  235319. {
  235320. }
  235321. void WebBrowserComponent::reloadLastURL()
  235322. {
  235323. }
  235324. void WebBrowserComponent::parentHierarchyChanged()
  235325. {
  235326. }
  235327. void WebBrowserComponent::resized()
  235328. {
  235329. }
  235330. void WebBrowserComponent::visibilityChanged()
  235331. {
  235332. }
  235333. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235334. {
  235335. return true;
  235336. }
  235337. #endif
  235338. #endif
  235339. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235340. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235341. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235342. // compiled on its own).
  235343. #if JUCE_INCLUDED_FILE
  235344. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235345. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235346. #endif
  235347. #undef log
  235348. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235349. #define log(a) Logger::writeToLog (a)
  235350. #else
  235351. #define log(a)
  235352. #endif
  235353. #undef OK
  235354. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235355. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235356. {
  235357. if (err == noErr)
  235358. return true;
  235359. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235360. jassertfalse;
  235361. return false;
  235362. }
  235363. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235364. #else
  235365. #define OK(a) (a == noErr)
  235366. #endif
  235367. class CoreAudioInternal : public Timer
  235368. {
  235369. public:
  235370. CoreAudioInternal (AudioDeviceID id)
  235371. : inputLatency (0),
  235372. outputLatency (0),
  235373. callback (0),
  235374. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235375. audioProcID (0),
  235376. #endif
  235377. isSlaveDevice (false),
  235378. deviceID (id),
  235379. started (false),
  235380. sampleRate (0),
  235381. bufferSize (512),
  235382. numInputChans (0),
  235383. numOutputChans (0),
  235384. callbacksAllowed (true),
  235385. numInputChannelInfos (0),
  235386. numOutputChannelInfos (0)
  235387. {
  235388. jassert (deviceID != 0);
  235389. updateDetailsFromDevice();
  235390. AudioObjectPropertyAddress pa;
  235391. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235392. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235393. pa.mElement = kAudioObjectPropertyElementWildcard;
  235394. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235395. }
  235396. ~CoreAudioInternal()
  235397. {
  235398. AudioObjectPropertyAddress pa;
  235399. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235400. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235401. pa.mElement = kAudioObjectPropertyElementWildcard;
  235402. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235403. stop (false);
  235404. }
  235405. void allocateTempBuffers()
  235406. {
  235407. const int tempBufSize = bufferSize + 4;
  235408. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235409. tempInputBuffers.calloc (numInputChans + 2);
  235410. tempOutputBuffers.calloc (numOutputChans + 2);
  235411. int i, count = 0;
  235412. for (i = 0; i < numInputChans; ++i)
  235413. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235414. for (i = 0; i < numOutputChans; ++i)
  235415. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235416. }
  235417. // returns the number of actual available channels
  235418. void fillInChannelInfo (const bool input)
  235419. {
  235420. int chanNum = 0;
  235421. UInt32 size;
  235422. AudioObjectPropertyAddress pa;
  235423. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235424. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235425. pa.mElement = kAudioObjectPropertyElementMaster;
  235426. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235427. {
  235428. HeapBlock <AudioBufferList> bufList;
  235429. bufList.calloc (size, 1);
  235430. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235431. {
  235432. const int numStreams = bufList->mNumberBuffers;
  235433. for (int i = 0; i < numStreams; ++i)
  235434. {
  235435. const AudioBuffer& b = bufList->mBuffers[i];
  235436. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235437. {
  235438. String name;
  235439. {
  235440. char channelName [256];
  235441. zerostruct (channelName);
  235442. UInt32 nameSize = sizeof (channelName);
  235443. UInt32 channelNum = chanNum + 1;
  235444. pa.mSelector = kAudioDevicePropertyChannelName;
  235445. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235446. name = String::fromUTF8 (channelName, nameSize);
  235447. }
  235448. if (input)
  235449. {
  235450. if (activeInputChans[chanNum])
  235451. {
  235452. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235453. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235454. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235455. ++numInputChannelInfos;
  235456. }
  235457. if (name.isEmpty())
  235458. name << "Input " << (chanNum + 1);
  235459. inChanNames.add (name);
  235460. }
  235461. else
  235462. {
  235463. if (activeOutputChans[chanNum])
  235464. {
  235465. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235466. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235467. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235468. ++numOutputChannelInfos;
  235469. }
  235470. if (name.isEmpty())
  235471. name << "Output " << (chanNum + 1);
  235472. outChanNames.add (name);
  235473. }
  235474. ++chanNum;
  235475. }
  235476. }
  235477. }
  235478. }
  235479. }
  235480. void updateDetailsFromDevice()
  235481. {
  235482. stopTimer();
  235483. if (deviceID == 0)
  235484. return;
  235485. const ScopedLock sl (callbackLock);
  235486. Float64 sr;
  235487. UInt32 size = sizeof (Float64);
  235488. AudioObjectPropertyAddress pa;
  235489. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235490. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235491. pa.mElement = kAudioObjectPropertyElementMaster;
  235492. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235493. sampleRate = sr;
  235494. UInt32 framesPerBuf;
  235495. size = sizeof (framesPerBuf);
  235496. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235497. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235498. {
  235499. bufferSize = framesPerBuf;
  235500. allocateTempBuffers();
  235501. }
  235502. bufferSizes.clear();
  235503. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235504. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235505. {
  235506. HeapBlock <AudioValueRange> ranges;
  235507. ranges.calloc (size, 1);
  235508. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235509. {
  235510. bufferSizes.add ((int) ranges[0].mMinimum);
  235511. for (int i = 32; i < 2048; i += 32)
  235512. {
  235513. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235514. {
  235515. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235516. {
  235517. bufferSizes.addIfNotAlreadyThere (i);
  235518. break;
  235519. }
  235520. }
  235521. }
  235522. if (bufferSize > 0)
  235523. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235524. }
  235525. }
  235526. if (bufferSizes.size() == 0 && bufferSize > 0)
  235527. bufferSizes.add (bufferSize);
  235528. sampleRates.clear();
  235529. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235530. String rates;
  235531. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235532. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235533. {
  235534. HeapBlock <AudioValueRange> ranges;
  235535. ranges.calloc (size, 1);
  235536. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235537. {
  235538. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235539. {
  235540. bool ok = false;
  235541. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235542. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235543. ok = true;
  235544. if (ok)
  235545. {
  235546. sampleRates.add (possibleRates[i]);
  235547. rates << possibleRates[i] << ' ';
  235548. }
  235549. }
  235550. }
  235551. }
  235552. if (sampleRates.size() == 0 && sampleRate > 0)
  235553. {
  235554. sampleRates.add (sampleRate);
  235555. rates << sampleRate;
  235556. }
  235557. log ("sr: " + rates);
  235558. inputLatency = 0;
  235559. outputLatency = 0;
  235560. UInt32 lat;
  235561. size = sizeof (lat);
  235562. pa.mSelector = kAudioDevicePropertyLatency;
  235563. pa.mScope = kAudioDevicePropertyScopeInput;
  235564. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235565. inputLatency = (int) lat;
  235566. pa.mScope = kAudioDevicePropertyScopeOutput;
  235567. size = sizeof (lat);
  235568. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235569. outputLatency = (int) lat;
  235570. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235571. inChanNames.clear();
  235572. outChanNames.clear();
  235573. inputChannelInfo.calloc (numInputChans + 2);
  235574. numInputChannelInfos = 0;
  235575. outputChannelInfo.calloc (numOutputChans + 2);
  235576. numOutputChannelInfos = 0;
  235577. fillInChannelInfo (true);
  235578. fillInChannelInfo (false);
  235579. }
  235580. const StringArray getSources (bool input)
  235581. {
  235582. StringArray s;
  235583. HeapBlock <OSType> types;
  235584. const int num = getAllDataSourcesForDevice (deviceID, types);
  235585. for (int i = 0; i < num; ++i)
  235586. {
  235587. AudioValueTranslation avt;
  235588. char buffer[256];
  235589. avt.mInputData = &(types[i]);
  235590. avt.mInputDataSize = sizeof (UInt32);
  235591. avt.mOutputData = buffer;
  235592. avt.mOutputDataSize = 256;
  235593. UInt32 transSize = sizeof (avt);
  235594. AudioObjectPropertyAddress pa;
  235595. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235596. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235597. pa.mElement = kAudioObjectPropertyElementMaster;
  235598. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235599. {
  235600. DBG (buffer);
  235601. s.add (buffer);
  235602. }
  235603. }
  235604. return s;
  235605. }
  235606. int getCurrentSourceIndex (bool input) const
  235607. {
  235608. OSType currentSourceID = 0;
  235609. UInt32 size = sizeof (currentSourceID);
  235610. int result = -1;
  235611. AudioObjectPropertyAddress pa;
  235612. pa.mSelector = kAudioDevicePropertyDataSource;
  235613. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235614. pa.mElement = kAudioObjectPropertyElementMaster;
  235615. if (deviceID != 0)
  235616. {
  235617. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235618. {
  235619. HeapBlock <OSType> types;
  235620. const int num = getAllDataSourcesForDevice (deviceID, types);
  235621. for (int i = 0; i < num; ++i)
  235622. {
  235623. if (types[num] == currentSourceID)
  235624. {
  235625. result = i;
  235626. break;
  235627. }
  235628. }
  235629. }
  235630. }
  235631. return result;
  235632. }
  235633. void setCurrentSourceIndex (int index, bool input)
  235634. {
  235635. if (deviceID != 0)
  235636. {
  235637. HeapBlock <OSType> types;
  235638. const int num = getAllDataSourcesForDevice (deviceID, types);
  235639. if (((unsigned int) index) < (unsigned int) num)
  235640. {
  235641. AudioObjectPropertyAddress pa;
  235642. pa.mSelector = kAudioDevicePropertyDataSource;
  235643. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235644. pa.mElement = kAudioObjectPropertyElementMaster;
  235645. OSType typeId = types[index];
  235646. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235647. }
  235648. }
  235649. }
  235650. const String reopen (const BigInteger& inputChannels,
  235651. const BigInteger& outputChannels,
  235652. double newSampleRate,
  235653. int bufferSizeSamples)
  235654. {
  235655. String error;
  235656. log ("CoreAudio reopen");
  235657. callbacksAllowed = false;
  235658. stopTimer();
  235659. stop (false);
  235660. activeInputChans = inputChannels;
  235661. activeInputChans.setRange (inChanNames.size(),
  235662. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235663. false);
  235664. activeOutputChans = outputChannels;
  235665. activeOutputChans.setRange (outChanNames.size(),
  235666. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235667. false);
  235668. numInputChans = activeInputChans.countNumberOfSetBits();
  235669. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235670. // set sample rate
  235671. AudioObjectPropertyAddress pa;
  235672. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235673. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235674. pa.mElement = kAudioObjectPropertyElementMaster;
  235675. Float64 sr = newSampleRate;
  235676. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235677. {
  235678. error = "Couldn't change sample rate";
  235679. }
  235680. else
  235681. {
  235682. // change buffer size
  235683. UInt32 framesPerBuf = bufferSizeSamples;
  235684. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235685. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235686. {
  235687. error = "Couldn't change buffer size";
  235688. }
  235689. else
  235690. {
  235691. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235692. // correctly report their new settings until some random time in the future, so
  235693. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235694. // to make sure we're using the correct numbers..
  235695. updateDetailsFromDevice();
  235696. sampleRate = newSampleRate;
  235697. bufferSize = bufferSizeSamples;
  235698. if (sampleRates.size() == 0)
  235699. error = "Device has no available sample-rates";
  235700. else if (bufferSizes.size() == 0)
  235701. error = "Device has no available buffer-sizes";
  235702. else if (inputDevice != 0)
  235703. error = inputDevice->reopen (inputChannels,
  235704. outputChannels,
  235705. newSampleRate,
  235706. bufferSizeSamples);
  235707. }
  235708. }
  235709. callbacksAllowed = true;
  235710. return error;
  235711. }
  235712. bool start (AudioIODeviceCallback* cb)
  235713. {
  235714. if (! started)
  235715. {
  235716. callback = 0;
  235717. if (deviceID != 0)
  235718. {
  235719. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235720. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235721. #else
  235722. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235723. #endif
  235724. {
  235725. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235726. {
  235727. started = true;
  235728. }
  235729. else
  235730. {
  235731. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235732. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235733. #else
  235734. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235735. audioProcID = 0;
  235736. #endif
  235737. }
  235738. }
  235739. }
  235740. }
  235741. if (started)
  235742. {
  235743. const ScopedLock sl (callbackLock);
  235744. callback = cb;
  235745. }
  235746. if (inputDevice != 0)
  235747. return started && inputDevice->start (cb);
  235748. else
  235749. return started;
  235750. }
  235751. void stop (bool leaveInterruptRunning)
  235752. {
  235753. {
  235754. const ScopedLock sl (callbackLock);
  235755. callback = 0;
  235756. }
  235757. if (started
  235758. && (deviceID != 0)
  235759. && ! leaveInterruptRunning)
  235760. {
  235761. OK (AudioDeviceStop (deviceID, audioIOProc));
  235762. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235763. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235764. #else
  235765. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235766. audioProcID = 0;
  235767. #endif
  235768. started = false;
  235769. { const ScopedLock sl (callbackLock); }
  235770. // wait until it's definately stopped calling back..
  235771. for (int i = 40; --i >= 0;)
  235772. {
  235773. Thread::sleep (50);
  235774. UInt32 running = 0;
  235775. UInt32 size = sizeof (running);
  235776. AudioObjectPropertyAddress pa;
  235777. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235778. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235779. pa.mElement = kAudioObjectPropertyElementMaster;
  235780. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235781. if (running == 0)
  235782. break;
  235783. }
  235784. const ScopedLock sl (callbackLock);
  235785. }
  235786. if (inputDevice != 0)
  235787. inputDevice->stop (leaveInterruptRunning);
  235788. }
  235789. double getSampleRate() const
  235790. {
  235791. return sampleRate;
  235792. }
  235793. int getBufferSize() const
  235794. {
  235795. return bufferSize;
  235796. }
  235797. void audioCallback (const AudioBufferList* inInputData,
  235798. AudioBufferList* outOutputData)
  235799. {
  235800. int i;
  235801. const ScopedLock sl (callbackLock);
  235802. if (callback != 0)
  235803. {
  235804. if (inputDevice == 0)
  235805. {
  235806. for (i = numInputChans; --i >= 0;)
  235807. {
  235808. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235809. float* dest = tempInputBuffers [i];
  235810. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235811. + info.dataOffsetSamples;
  235812. const int stride = info.dataStrideSamples;
  235813. if (stride != 0) // if this is zero, info is invalid
  235814. {
  235815. for (int j = bufferSize; --j >= 0;)
  235816. {
  235817. *dest++ = *src;
  235818. src += stride;
  235819. }
  235820. }
  235821. }
  235822. }
  235823. if (! isSlaveDevice)
  235824. {
  235825. if (inputDevice == 0)
  235826. {
  235827. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235828. numInputChans,
  235829. tempOutputBuffers,
  235830. numOutputChans,
  235831. bufferSize);
  235832. }
  235833. else
  235834. {
  235835. jassert (inputDevice->bufferSize == bufferSize);
  235836. // Sometimes the two linked devices seem to get their callbacks in
  235837. // parallel, so we need to lock both devices to stop the input data being
  235838. // changed while inside our callback..
  235839. const ScopedLock sl2 (inputDevice->callbackLock);
  235840. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235841. inputDevice->numInputChans,
  235842. tempOutputBuffers,
  235843. numOutputChans,
  235844. bufferSize);
  235845. }
  235846. for (i = numOutputChans; --i >= 0;)
  235847. {
  235848. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235849. const float* src = tempOutputBuffers [i];
  235850. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235851. + info.dataOffsetSamples;
  235852. const int stride = info.dataStrideSamples;
  235853. if (stride != 0) // if this is zero, info is invalid
  235854. {
  235855. for (int j = bufferSize; --j >= 0;)
  235856. {
  235857. *dest = *src++;
  235858. dest += stride;
  235859. }
  235860. }
  235861. }
  235862. }
  235863. }
  235864. else
  235865. {
  235866. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235867. {
  235868. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235869. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235870. + info.dataOffsetSamples;
  235871. const int stride = info.dataStrideSamples;
  235872. if (stride != 0) // if this is zero, info is invalid
  235873. {
  235874. for (int j = bufferSize; --j >= 0;)
  235875. {
  235876. *dest = 0.0f;
  235877. dest += stride;
  235878. }
  235879. }
  235880. }
  235881. }
  235882. }
  235883. // called by callbacks
  235884. void deviceDetailsChanged()
  235885. {
  235886. if (callbacksAllowed)
  235887. startTimer (100);
  235888. }
  235889. void timerCallback()
  235890. {
  235891. stopTimer();
  235892. log ("CoreAudio device changed callback");
  235893. const double oldSampleRate = sampleRate;
  235894. const int oldBufferSize = bufferSize;
  235895. updateDetailsFromDevice();
  235896. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235897. {
  235898. callbacksAllowed = false;
  235899. stop (false);
  235900. updateDetailsFromDevice();
  235901. callbacksAllowed = true;
  235902. }
  235903. }
  235904. CoreAudioInternal* getRelatedDevice() const
  235905. {
  235906. UInt32 size = 0;
  235907. ScopedPointer <CoreAudioInternal> result;
  235908. AudioObjectPropertyAddress pa;
  235909. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235910. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235911. pa.mElement = kAudioObjectPropertyElementMaster;
  235912. if (deviceID != 0
  235913. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235914. && size > 0)
  235915. {
  235916. HeapBlock <AudioDeviceID> devs;
  235917. devs.calloc (size, 1);
  235918. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235919. {
  235920. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235921. {
  235922. if (devs[i] != deviceID && devs[i] != 0)
  235923. {
  235924. result = new CoreAudioInternal (devs[i]);
  235925. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235926. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235927. if (thisIsInput != otherIsInput
  235928. || (inChanNames.size() + outChanNames.size() == 0)
  235929. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235930. break;
  235931. result = 0;
  235932. }
  235933. }
  235934. }
  235935. }
  235936. return result.release();
  235937. }
  235938. int inputLatency, outputLatency;
  235939. BigInteger activeInputChans, activeOutputChans;
  235940. StringArray inChanNames, outChanNames;
  235941. Array <double> sampleRates;
  235942. Array <int> bufferSizes;
  235943. AudioIODeviceCallback* callback;
  235944. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235945. AudioDeviceIOProcID audioProcID;
  235946. #endif
  235947. ScopedPointer<CoreAudioInternal> inputDevice;
  235948. bool isSlaveDevice;
  235949. private:
  235950. CriticalSection callbackLock;
  235951. AudioDeviceID deviceID;
  235952. bool started;
  235953. double sampleRate;
  235954. int bufferSize;
  235955. HeapBlock <float> audioBuffer;
  235956. int numInputChans, numOutputChans;
  235957. bool callbacksAllowed;
  235958. struct CallbackDetailsForChannel
  235959. {
  235960. int streamNum;
  235961. int dataOffsetSamples;
  235962. int dataStrideSamples;
  235963. };
  235964. int numInputChannelInfos, numOutputChannelInfos;
  235965. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235966. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235967. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235968. const AudioTimeStamp* /*inNow*/,
  235969. const AudioBufferList* inInputData,
  235970. const AudioTimeStamp* /*inInputTime*/,
  235971. AudioBufferList* outOutputData,
  235972. const AudioTimeStamp* /*inOutputTime*/,
  235973. void* device)
  235974. {
  235975. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235976. return noErr;
  235977. }
  235978. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235979. {
  235980. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235981. switch (pa->mSelector)
  235982. {
  235983. case kAudioDevicePropertyBufferSize:
  235984. case kAudioDevicePropertyBufferFrameSize:
  235985. case kAudioDevicePropertyNominalSampleRate:
  235986. case kAudioDevicePropertyStreamFormat:
  235987. case kAudioDevicePropertyDeviceIsAlive:
  235988. intern->deviceDetailsChanged();
  235989. break;
  235990. case kAudioDevicePropertyBufferSizeRange:
  235991. case kAudioDevicePropertyVolumeScalar:
  235992. case kAudioDevicePropertyMute:
  235993. case kAudioDevicePropertyPlayThru:
  235994. case kAudioDevicePropertyDataSource:
  235995. case kAudioDevicePropertyDeviceIsRunning:
  235996. break;
  235997. }
  235998. return noErr;
  235999. }
  236000. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  236001. {
  236002. AudioObjectPropertyAddress pa;
  236003. pa.mSelector = kAudioDevicePropertyDataSources;
  236004. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236005. pa.mElement = kAudioObjectPropertyElementMaster;
  236006. UInt32 size = 0;
  236007. if (deviceID != 0
  236008. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236009. {
  236010. types.calloc (size, 1);
  236011. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  236012. return size / (int) sizeof (OSType);
  236013. }
  236014. return 0;
  236015. }
  236016. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  236017. };
  236018. class CoreAudioIODevice : public AudioIODevice
  236019. {
  236020. public:
  236021. CoreAudioIODevice (const String& deviceName,
  236022. AudioDeviceID inputDeviceId,
  236023. const int inputIndex_,
  236024. AudioDeviceID outputDeviceId,
  236025. const int outputIndex_)
  236026. : AudioIODevice (deviceName, "CoreAudio"),
  236027. inputIndex (inputIndex_),
  236028. outputIndex (outputIndex_),
  236029. isOpen_ (false),
  236030. isStarted (false)
  236031. {
  236032. CoreAudioInternal* device = 0;
  236033. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  236034. {
  236035. jassert (inputDeviceId != 0);
  236036. device = new CoreAudioInternal (inputDeviceId);
  236037. }
  236038. else
  236039. {
  236040. device = new CoreAudioInternal (outputDeviceId);
  236041. if (inputDeviceId != 0)
  236042. {
  236043. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  236044. device->inputDevice = secondDevice;
  236045. secondDevice->isSlaveDevice = true;
  236046. }
  236047. }
  236048. internal = device;
  236049. AudioObjectPropertyAddress pa;
  236050. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236051. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236052. pa.mElement = kAudioObjectPropertyElementWildcard;
  236053. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236054. }
  236055. ~CoreAudioIODevice()
  236056. {
  236057. AudioObjectPropertyAddress pa;
  236058. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236059. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236060. pa.mElement = kAudioObjectPropertyElementWildcard;
  236061. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236062. }
  236063. const StringArray getOutputChannelNames()
  236064. {
  236065. return internal->outChanNames;
  236066. }
  236067. const StringArray getInputChannelNames()
  236068. {
  236069. if (internal->inputDevice != 0)
  236070. return internal->inputDevice->inChanNames;
  236071. else
  236072. return internal->inChanNames;
  236073. }
  236074. int getNumSampleRates()
  236075. {
  236076. return internal->sampleRates.size();
  236077. }
  236078. double getSampleRate (int index)
  236079. {
  236080. return internal->sampleRates [index];
  236081. }
  236082. int getNumBufferSizesAvailable()
  236083. {
  236084. return internal->bufferSizes.size();
  236085. }
  236086. int getBufferSizeSamples (int index)
  236087. {
  236088. return internal->bufferSizes [index];
  236089. }
  236090. int getDefaultBufferSize()
  236091. {
  236092. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  236093. if (getBufferSizeSamples(i) >= 512)
  236094. return getBufferSizeSamples(i);
  236095. return 512;
  236096. }
  236097. const String open (const BigInteger& inputChannels,
  236098. const BigInteger& outputChannels,
  236099. double sampleRate,
  236100. int bufferSizeSamples)
  236101. {
  236102. isOpen_ = true;
  236103. if (bufferSizeSamples <= 0)
  236104. bufferSizeSamples = getDefaultBufferSize();
  236105. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  236106. isOpen_ = lastError.isEmpty();
  236107. return lastError;
  236108. }
  236109. void close()
  236110. {
  236111. isOpen_ = false;
  236112. internal->stop (false);
  236113. }
  236114. bool isOpen()
  236115. {
  236116. return isOpen_;
  236117. }
  236118. int getCurrentBufferSizeSamples()
  236119. {
  236120. return internal != 0 ? internal->getBufferSize() : 512;
  236121. }
  236122. double getCurrentSampleRate()
  236123. {
  236124. return internal != 0 ? internal->getSampleRate() : 0;
  236125. }
  236126. int getCurrentBitDepth()
  236127. {
  236128. return 32; // no way to find out, so just assume it's high..
  236129. }
  236130. const BigInteger getActiveOutputChannels() const
  236131. {
  236132. return internal != 0 ? internal->activeOutputChans : BigInteger();
  236133. }
  236134. const BigInteger getActiveInputChannels() const
  236135. {
  236136. BigInteger chans;
  236137. if (internal != 0)
  236138. {
  236139. chans = internal->activeInputChans;
  236140. if (internal->inputDevice != 0)
  236141. chans |= internal->inputDevice->activeInputChans;
  236142. }
  236143. return chans;
  236144. }
  236145. int getOutputLatencyInSamples()
  236146. {
  236147. if (internal == 0)
  236148. return 0;
  236149. // this seems like a good guess at getting the latency right - comparing
  236150. // this with a round-trip measurement, it gets it to within a few millisecs
  236151. // for the built-in mac soundcard
  236152. return internal->outputLatency + internal->getBufferSize() * 2;
  236153. }
  236154. int getInputLatencyInSamples()
  236155. {
  236156. if (internal == 0)
  236157. return 0;
  236158. return internal->inputLatency + internal->getBufferSize() * 2;
  236159. }
  236160. void start (AudioIODeviceCallback* callback)
  236161. {
  236162. if (internal != 0 && ! isStarted)
  236163. {
  236164. if (callback != 0)
  236165. callback->audioDeviceAboutToStart (this);
  236166. isStarted = true;
  236167. internal->start (callback);
  236168. }
  236169. }
  236170. void stop()
  236171. {
  236172. if (isStarted && internal != 0)
  236173. {
  236174. AudioIODeviceCallback* const lastCallback = internal->callback;
  236175. isStarted = false;
  236176. internal->stop (true);
  236177. if (lastCallback != 0)
  236178. lastCallback->audioDeviceStopped();
  236179. }
  236180. }
  236181. bool isPlaying()
  236182. {
  236183. if (internal->callback == 0)
  236184. isStarted = false;
  236185. return isStarted;
  236186. }
  236187. const String getLastError()
  236188. {
  236189. return lastError;
  236190. }
  236191. int inputIndex, outputIndex;
  236192. private:
  236193. ScopedPointer<CoreAudioInternal> internal;
  236194. bool isOpen_, isStarted;
  236195. String lastError;
  236196. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236197. {
  236198. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236199. switch (pa->mSelector)
  236200. {
  236201. case kAudioHardwarePropertyDevices:
  236202. intern->deviceDetailsChanged();
  236203. break;
  236204. case kAudioHardwarePropertyDefaultOutputDevice:
  236205. case kAudioHardwarePropertyDefaultInputDevice:
  236206. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236207. break;
  236208. }
  236209. return noErr;
  236210. }
  236211. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  236212. };
  236213. class CoreAudioIODeviceType : public AudioIODeviceType
  236214. {
  236215. public:
  236216. CoreAudioIODeviceType()
  236217. : AudioIODeviceType ("CoreAudio"),
  236218. hasScanned (false)
  236219. {
  236220. }
  236221. ~CoreAudioIODeviceType()
  236222. {
  236223. }
  236224. void scanForDevices()
  236225. {
  236226. hasScanned = true;
  236227. inputDeviceNames.clear();
  236228. outputDeviceNames.clear();
  236229. inputIds.clear();
  236230. outputIds.clear();
  236231. UInt32 size;
  236232. AudioObjectPropertyAddress pa;
  236233. pa.mSelector = kAudioHardwarePropertyDevices;
  236234. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236235. pa.mElement = kAudioObjectPropertyElementMaster;
  236236. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236237. {
  236238. HeapBlock <AudioDeviceID> devs;
  236239. devs.calloc (size, 1);
  236240. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236241. {
  236242. const int num = size / (int) sizeof (AudioDeviceID);
  236243. for (int i = 0; i < num; ++i)
  236244. {
  236245. char name [1024];
  236246. size = sizeof (name);
  236247. pa.mSelector = kAudioDevicePropertyDeviceName;
  236248. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236249. {
  236250. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236251. const int numIns = getNumChannels (devs[i], true);
  236252. const int numOuts = getNumChannels (devs[i], false);
  236253. if (numIns > 0)
  236254. {
  236255. inputDeviceNames.add (nameString);
  236256. inputIds.add (devs[i]);
  236257. }
  236258. if (numOuts > 0)
  236259. {
  236260. outputDeviceNames.add (nameString);
  236261. outputIds.add (devs[i]);
  236262. }
  236263. }
  236264. }
  236265. }
  236266. }
  236267. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236268. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236269. }
  236270. const StringArray getDeviceNames (bool wantInputNames) const
  236271. {
  236272. jassert (hasScanned); // need to call scanForDevices() before doing this
  236273. if (wantInputNames)
  236274. return inputDeviceNames;
  236275. else
  236276. return outputDeviceNames;
  236277. }
  236278. int getDefaultDeviceIndex (bool forInput) const
  236279. {
  236280. jassert (hasScanned); // need to call scanForDevices() before doing this
  236281. AudioDeviceID deviceID;
  236282. UInt32 size = sizeof (deviceID);
  236283. // if they're asking for any input channels at all, use the default input, so we
  236284. // get the built-in mic rather than the built-in output with no inputs..
  236285. AudioObjectPropertyAddress pa;
  236286. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236287. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236288. pa.mElement = kAudioObjectPropertyElementMaster;
  236289. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236290. {
  236291. if (forInput)
  236292. {
  236293. for (int i = inputIds.size(); --i >= 0;)
  236294. if (inputIds[i] == deviceID)
  236295. return i;
  236296. }
  236297. else
  236298. {
  236299. for (int i = outputIds.size(); --i >= 0;)
  236300. if (outputIds[i] == deviceID)
  236301. return i;
  236302. }
  236303. }
  236304. return 0;
  236305. }
  236306. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236307. {
  236308. jassert (hasScanned); // need to call scanForDevices() before doing this
  236309. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236310. if (d == 0)
  236311. return -1;
  236312. return asInput ? d->inputIndex
  236313. : d->outputIndex;
  236314. }
  236315. bool hasSeparateInputsAndOutputs() const { return true; }
  236316. AudioIODevice* createDevice (const String& outputDeviceName,
  236317. const String& inputDeviceName)
  236318. {
  236319. jassert (hasScanned); // need to call scanForDevices() before doing this
  236320. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236321. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236322. String deviceName (outputDeviceName);
  236323. if (deviceName.isEmpty())
  236324. deviceName = inputDeviceName;
  236325. if (index >= 0)
  236326. return new CoreAudioIODevice (deviceName,
  236327. inputIds [inputIndex],
  236328. inputIndex,
  236329. outputIds [outputIndex],
  236330. outputIndex);
  236331. return 0;
  236332. }
  236333. private:
  236334. StringArray inputDeviceNames, outputDeviceNames;
  236335. Array <AudioDeviceID> inputIds, outputIds;
  236336. bool hasScanned;
  236337. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236338. {
  236339. int total = 0;
  236340. UInt32 size;
  236341. AudioObjectPropertyAddress pa;
  236342. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236343. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236344. pa.mElement = kAudioObjectPropertyElementMaster;
  236345. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236346. {
  236347. HeapBlock <AudioBufferList> bufList;
  236348. bufList.calloc (size, 1);
  236349. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236350. {
  236351. const int numStreams = bufList->mNumberBuffers;
  236352. for (int i = 0; i < numStreams; ++i)
  236353. {
  236354. const AudioBuffer& b = bufList->mBuffers[i];
  236355. total += b.mNumberChannels;
  236356. }
  236357. }
  236358. }
  236359. return total;
  236360. }
  236361. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  236362. };
  236363. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236364. {
  236365. return new CoreAudioIODeviceType();
  236366. }
  236367. #undef log
  236368. #endif
  236369. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236370. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236371. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236372. // compiled on its own).
  236373. #if JUCE_INCLUDED_FILE
  236374. #if JUCE_MAC
  236375. namespace CoreMidiHelpers
  236376. {
  236377. static bool logError (const OSStatus err, const int lineNum)
  236378. {
  236379. if (err == noErr)
  236380. return true;
  236381. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236382. jassertfalse;
  236383. return false;
  236384. }
  236385. #undef CHECK_ERROR
  236386. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236387. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236388. {
  236389. String result;
  236390. CFStringRef str = 0;
  236391. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236392. if (str != 0)
  236393. {
  236394. result = PlatformUtilities::cfStringToJuceString (str);
  236395. CFRelease (str);
  236396. str = 0;
  236397. }
  236398. MIDIEntityRef entity = 0;
  236399. MIDIEndpointGetEntity (endpoint, &entity);
  236400. if (entity == 0)
  236401. return result; // probably virtual
  236402. if (result.isEmpty())
  236403. {
  236404. // endpoint name has zero length - try the entity
  236405. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236406. if (str != 0)
  236407. {
  236408. result += PlatformUtilities::cfStringToJuceString (str);
  236409. CFRelease (str);
  236410. str = 0;
  236411. }
  236412. }
  236413. // now consider the device's name
  236414. MIDIDeviceRef device = 0;
  236415. MIDIEntityGetDevice (entity, &device);
  236416. if (device == 0)
  236417. return result;
  236418. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236419. if (str != 0)
  236420. {
  236421. const String s (PlatformUtilities::cfStringToJuceString (str));
  236422. CFRelease (str);
  236423. // if an external device has only one entity, throw away
  236424. // the endpoint name and just use the device name
  236425. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236426. {
  236427. result = s;
  236428. }
  236429. else if (! result.startsWithIgnoreCase (s))
  236430. {
  236431. // prepend the device name to the entity name
  236432. result = (s + " " + result).trimEnd();
  236433. }
  236434. }
  236435. return result;
  236436. }
  236437. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236438. {
  236439. String result;
  236440. // Does the endpoint have connections?
  236441. CFDataRef connections = 0;
  236442. int numConnections = 0;
  236443. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236444. if (connections != 0)
  236445. {
  236446. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236447. if (numConnections > 0)
  236448. {
  236449. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236450. for (int i = 0; i < numConnections; ++i, ++pid)
  236451. {
  236452. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236453. MIDIObjectRef connObject;
  236454. MIDIObjectType connObjectType;
  236455. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236456. if (err == noErr)
  236457. {
  236458. String s;
  236459. if (connObjectType == kMIDIObjectType_ExternalSource
  236460. || connObjectType == kMIDIObjectType_ExternalDestination)
  236461. {
  236462. // Connected to an external device's endpoint (10.3 and later).
  236463. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236464. }
  236465. else
  236466. {
  236467. // Connected to an external device (10.2) (or something else, catch-all)
  236468. CFStringRef str = 0;
  236469. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236470. if (str != 0)
  236471. {
  236472. s = PlatformUtilities::cfStringToJuceString (str);
  236473. CFRelease (str);
  236474. }
  236475. }
  236476. if (s.isNotEmpty())
  236477. {
  236478. if (result.isNotEmpty())
  236479. result += ", ";
  236480. result += s;
  236481. }
  236482. }
  236483. }
  236484. }
  236485. CFRelease (connections);
  236486. }
  236487. if (result.isNotEmpty())
  236488. return result;
  236489. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236490. return getEndpointName (endpoint, false);
  236491. }
  236492. static MIDIClientRef getGlobalMidiClient()
  236493. {
  236494. static MIDIClientRef globalMidiClient = 0;
  236495. if (globalMidiClient == 0)
  236496. {
  236497. String name ("JUCE");
  236498. if (JUCEApplication::getInstance() != 0)
  236499. name = JUCEApplication::getInstance()->getApplicationName();
  236500. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236501. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236502. CFRelease (appName);
  236503. }
  236504. return globalMidiClient;
  236505. }
  236506. class MidiPortAndEndpoint
  236507. {
  236508. public:
  236509. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236510. : port (port_), endPoint (endPoint_)
  236511. {
  236512. }
  236513. ~MidiPortAndEndpoint()
  236514. {
  236515. if (port != 0)
  236516. MIDIPortDispose (port);
  236517. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236518. MIDIEndpointDispose (endPoint);
  236519. }
  236520. void send (const MIDIPacketList* const packets)
  236521. {
  236522. if (port != 0)
  236523. MIDISend (port, endPoint, packets);
  236524. else
  236525. MIDIReceived (endPoint, packets);
  236526. }
  236527. MIDIPortRef port;
  236528. MIDIEndpointRef endPoint;
  236529. };
  236530. class MidiPortAndCallback;
  236531. static CriticalSection callbackLock;
  236532. static Array<MidiPortAndCallback*> activeCallbacks;
  236533. class MidiPortAndCallback
  236534. {
  236535. public:
  236536. MidiPortAndCallback (MidiInputCallback& callback_)
  236537. : input (0), active (false), callback (callback_), concatenator (2048)
  236538. {
  236539. }
  236540. ~MidiPortAndCallback()
  236541. {
  236542. active = false;
  236543. {
  236544. const ScopedLock sl (callbackLock);
  236545. activeCallbacks.removeValue (this);
  236546. }
  236547. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236548. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236549. }
  236550. void handlePackets (const MIDIPacketList* const pktlist)
  236551. {
  236552. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236553. const ScopedLock sl (callbackLock);
  236554. if (activeCallbacks.contains (this) && active)
  236555. {
  236556. const MIDIPacket* packet = &pktlist->packet[0];
  236557. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236558. {
  236559. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236560. input, callback);
  236561. packet = MIDIPacketNext (packet);
  236562. }
  236563. }
  236564. }
  236565. MidiInput* input;
  236566. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236567. volatile bool active;
  236568. private:
  236569. MidiInputCallback& callback;
  236570. MidiDataConcatenator concatenator;
  236571. };
  236572. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236573. {
  236574. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236575. }
  236576. }
  236577. const StringArray MidiOutput::getDevices()
  236578. {
  236579. StringArray s;
  236580. const ItemCount num = MIDIGetNumberOfDestinations();
  236581. for (ItemCount i = 0; i < num; ++i)
  236582. {
  236583. MIDIEndpointRef dest = MIDIGetDestination (i);
  236584. if (dest != 0)
  236585. {
  236586. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236587. if (name.isEmpty())
  236588. name = "<error>";
  236589. s.add (name);
  236590. }
  236591. else
  236592. {
  236593. s.add ("<error>");
  236594. }
  236595. }
  236596. return s;
  236597. }
  236598. int MidiOutput::getDefaultDeviceIndex()
  236599. {
  236600. return 0;
  236601. }
  236602. MidiOutput* MidiOutput::openDevice (int index)
  236603. {
  236604. MidiOutput* mo = 0;
  236605. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236606. {
  236607. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236608. CFStringRef pname;
  236609. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236610. {
  236611. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236612. MIDIPortRef port;
  236613. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236614. {
  236615. mo = new MidiOutput();
  236616. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236617. }
  236618. CFRelease (pname);
  236619. }
  236620. }
  236621. return mo;
  236622. }
  236623. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236624. {
  236625. MidiOutput* mo = 0;
  236626. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236627. MIDIEndpointRef endPoint;
  236628. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236629. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236630. {
  236631. mo = new MidiOutput();
  236632. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236633. }
  236634. CFRelease (name);
  236635. return mo;
  236636. }
  236637. MidiOutput::~MidiOutput()
  236638. {
  236639. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236640. }
  236641. void MidiOutput::reset()
  236642. {
  236643. }
  236644. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236645. {
  236646. return false;
  236647. }
  236648. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236649. {
  236650. }
  236651. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236652. {
  236653. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236654. if (message.isSysEx())
  236655. {
  236656. const int maxPacketSize = 256;
  236657. int pos = 0, bytesLeft = message.getRawDataSize();
  236658. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236659. HeapBlock <MIDIPacketList> packets;
  236660. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236661. packets->numPackets = numPackets;
  236662. MIDIPacket* p = packets->packet;
  236663. for (int i = 0; i < numPackets; ++i)
  236664. {
  236665. p->timeStamp = 0;
  236666. p->length = jmin (maxPacketSize, bytesLeft);
  236667. memcpy (p->data, message.getRawData() + pos, p->length);
  236668. pos += p->length;
  236669. bytesLeft -= p->length;
  236670. p = MIDIPacketNext (p);
  236671. }
  236672. mpe->send (packets);
  236673. }
  236674. else
  236675. {
  236676. MIDIPacketList packets;
  236677. packets.numPackets = 1;
  236678. packets.packet[0].timeStamp = 0;
  236679. packets.packet[0].length = message.getRawDataSize();
  236680. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236681. mpe->send (&packets);
  236682. }
  236683. }
  236684. const StringArray MidiInput::getDevices()
  236685. {
  236686. StringArray s;
  236687. const ItemCount num = MIDIGetNumberOfSources();
  236688. for (ItemCount i = 0; i < num; ++i)
  236689. {
  236690. MIDIEndpointRef source = MIDIGetSource (i);
  236691. if (source != 0)
  236692. {
  236693. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236694. if (name.isEmpty())
  236695. name = "<error>";
  236696. s.add (name);
  236697. }
  236698. else
  236699. {
  236700. s.add ("<error>");
  236701. }
  236702. }
  236703. return s;
  236704. }
  236705. int MidiInput::getDefaultDeviceIndex()
  236706. {
  236707. return 0;
  236708. }
  236709. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236710. {
  236711. jassert (callback != 0);
  236712. using namespace CoreMidiHelpers;
  236713. MidiInput* newInput = 0;
  236714. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236715. {
  236716. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236717. if (endPoint != 0)
  236718. {
  236719. CFStringRef name;
  236720. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236721. {
  236722. MIDIClientRef client = getGlobalMidiClient();
  236723. if (client != 0)
  236724. {
  236725. MIDIPortRef port;
  236726. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236727. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236728. {
  236729. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236730. {
  236731. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236732. newInput = new MidiInput (getDevices() [index]);
  236733. mpc->input = newInput;
  236734. newInput->internal = mpc;
  236735. const ScopedLock sl (callbackLock);
  236736. activeCallbacks.add (mpc.release());
  236737. }
  236738. else
  236739. {
  236740. CHECK_ERROR (MIDIPortDispose (port));
  236741. }
  236742. }
  236743. }
  236744. }
  236745. CFRelease (name);
  236746. }
  236747. }
  236748. return newInput;
  236749. }
  236750. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236751. {
  236752. jassert (callback != 0);
  236753. using namespace CoreMidiHelpers;
  236754. MidiInput* mi = 0;
  236755. MIDIClientRef client = getGlobalMidiClient();
  236756. if (client != 0)
  236757. {
  236758. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236759. mpc->active = false;
  236760. MIDIEndpointRef endPoint;
  236761. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236762. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236763. {
  236764. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236765. mi = new MidiInput (deviceName);
  236766. mpc->input = mi;
  236767. mi->internal = mpc;
  236768. const ScopedLock sl (callbackLock);
  236769. activeCallbacks.add (mpc.release());
  236770. }
  236771. CFRelease (name);
  236772. }
  236773. return mi;
  236774. }
  236775. MidiInput::MidiInput (const String& name_)
  236776. : name (name_)
  236777. {
  236778. }
  236779. MidiInput::~MidiInput()
  236780. {
  236781. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236782. }
  236783. void MidiInput::start()
  236784. {
  236785. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236786. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236787. }
  236788. void MidiInput::stop()
  236789. {
  236790. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236791. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236792. }
  236793. #undef CHECK_ERROR
  236794. #else // Stubs for iOS...
  236795. MidiOutput::~MidiOutput() {}
  236796. void MidiOutput::reset() {}
  236797. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236798. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236799. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236800. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236801. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236802. const StringArray MidiInput::getDevices() { return StringArray(); }
  236803. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236804. #endif
  236805. #endif
  236806. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236807. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236808. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236809. // compiled on its own).
  236810. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236811. #if ! JUCE_QUICKTIME
  236812. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236813. #endif
  236814. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236815. class QTCameraDeviceInteral;
  236816. END_JUCE_NAMESPACE
  236817. @interface QTCaptureCallbackDelegate : NSObject
  236818. {
  236819. @public
  236820. CameraDevice* owner;
  236821. QTCameraDeviceInteral* internal;
  236822. int64 firstPresentationTime;
  236823. int64 averageTimeOffset;
  236824. }
  236825. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236826. - (void) dealloc;
  236827. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236828. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236829. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236830. fromConnection: (QTCaptureConnection*) connection;
  236831. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236832. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236833. fromConnection: (QTCaptureConnection*) connection;
  236834. @end
  236835. BEGIN_JUCE_NAMESPACE
  236836. class QTCameraDeviceInteral
  236837. {
  236838. public:
  236839. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236840. {
  236841. const ScopedAutoReleasePool pool;
  236842. session = [[QTCaptureSession alloc] init];
  236843. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236844. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236845. input = 0;
  236846. audioInput = 0;
  236847. audioDevice = 0;
  236848. fileOutput = 0;
  236849. imageOutput = 0;
  236850. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236851. internalDev: this];
  236852. NSError* err = 0;
  236853. [device retain];
  236854. [device open: &err];
  236855. if (err == 0)
  236856. {
  236857. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236858. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236859. [session addInput: input error: &err];
  236860. if (err == 0)
  236861. {
  236862. resetFile();
  236863. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236864. [imageOutput setDelegate: callbackDelegate];
  236865. if (err == 0)
  236866. {
  236867. [session startRunning];
  236868. return;
  236869. }
  236870. }
  236871. }
  236872. openingError = nsStringToJuce ([err description]);
  236873. DBG (openingError);
  236874. }
  236875. ~QTCameraDeviceInteral()
  236876. {
  236877. [session stopRunning];
  236878. [session removeOutput: imageOutput];
  236879. [session release];
  236880. [input release];
  236881. [device release];
  236882. [audioDevice release];
  236883. [audioInput release];
  236884. [fileOutput release];
  236885. [imageOutput release];
  236886. [callbackDelegate release];
  236887. }
  236888. void resetFile()
  236889. {
  236890. [fileOutput recordToOutputFileURL: nil];
  236891. [session removeOutput: fileOutput];
  236892. [fileOutput release];
  236893. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236894. [session removeInput: audioInput];
  236895. [audioInput release];
  236896. audioInput = 0;
  236897. [audioDevice release];
  236898. audioDevice = 0;
  236899. [fileOutput setDelegate: callbackDelegate];
  236900. }
  236901. void addDefaultAudioInput()
  236902. {
  236903. NSError* err = nil;
  236904. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236905. if ([audioDevice open: &err])
  236906. [audioDevice retain];
  236907. else
  236908. audioDevice = nil;
  236909. if (audioDevice != 0)
  236910. {
  236911. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236912. [session addInput: audioInput error: &err];
  236913. }
  236914. }
  236915. void addListener (CameraDevice::Listener* listenerToAdd)
  236916. {
  236917. const ScopedLock sl (listenerLock);
  236918. if (listeners.size() == 0)
  236919. [session addOutput: imageOutput error: nil];
  236920. listeners.addIfNotAlreadyThere (listenerToAdd);
  236921. }
  236922. void removeListener (CameraDevice::Listener* listenerToRemove)
  236923. {
  236924. const ScopedLock sl (listenerLock);
  236925. listeners.removeValue (listenerToRemove);
  236926. if (listeners.size() == 0)
  236927. [session removeOutput: imageOutput];
  236928. }
  236929. void callListeners (CIImage* frame, int w, int h)
  236930. {
  236931. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236932. Image image (cgImage);
  236933. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236934. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236935. CGContextFlush (cgImage->context);
  236936. const ScopedLock sl (listenerLock);
  236937. for (int i = listeners.size(); --i >= 0;)
  236938. {
  236939. CameraDevice::Listener* const l = listeners[i];
  236940. if (l != 0)
  236941. l->imageReceived (image);
  236942. }
  236943. }
  236944. QTCaptureDevice* device;
  236945. QTCaptureDeviceInput* input;
  236946. QTCaptureDevice* audioDevice;
  236947. QTCaptureDeviceInput* audioInput;
  236948. QTCaptureSession* session;
  236949. QTCaptureMovieFileOutput* fileOutput;
  236950. QTCaptureDecompressedVideoOutput* imageOutput;
  236951. QTCaptureCallbackDelegate* callbackDelegate;
  236952. String openingError;
  236953. Array<CameraDevice::Listener*> listeners;
  236954. CriticalSection listenerLock;
  236955. };
  236956. END_JUCE_NAMESPACE
  236957. @implementation QTCaptureCallbackDelegate
  236958. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236959. internalDev: (QTCameraDeviceInteral*) d
  236960. {
  236961. [super init];
  236962. owner = owner_;
  236963. internal = d;
  236964. firstPresentationTime = 0;
  236965. averageTimeOffset = 0;
  236966. return self;
  236967. }
  236968. - (void) dealloc
  236969. {
  236970. [super dealloc];
  236971. }
  236972. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236973. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236974. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236975. fromConnection: (QTCaptureConnection*) connection
  236976. {
  236977. if (internal->listeners.size() > 0)
  236978. {
  236979. const ScopedAutoReleasePool pool;
  236980. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236981. CVPixelBufferGetWidth (videoFrame),
  236982. CVPixelBufferGetHeight (videoFrame));
  236983. }
  236984. }
  236985. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236986. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236987. fromConnection: (QTCaptureConnection*) connection
  236988. {
  236989. const Time now (Time::getCurrentTime());
  236990. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236991. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236992. #else
  236993. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236994. #endif
  236995. int64 presentationTime = (hosttime != nil)
  236996. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236997. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236998. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236999. if (firstPresentationTime == 0)
  237000. {
  237001. firstPresentationTime = presentationTime;
  237002. averageTimeOffset = timeDiff;
  237003. }
  237004. else
  237005. {
  237006. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  237007. }
  237008. }
  237009. @end
  237010. BEGIN_JUCE_NAMESPACE
  237011. class QTCaptureViewerComp : public NSViewComponent
  237012. {
  237013. public:
  237014. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  237015. {
  237016. const ScopedAutoReleasePool pool;
  237017. captureView = [[QTCaptureView alloc] init];
  237018. [captureView setCaptureSession: internal->session];
  237019. setSize (640, 480); // xxx need to somehow get the movie size - how?
  237020. setView (captureView);
  237021. }
  237022. ~QTCaptureViewerComp()
  237023. {
  237024. setView (0);
  237025. [captureView setCaptureSession: nil];
  237026. [captureView release];
  237027. }
  237028. QTCaptureView* captureView;
  237029. };
  237030. CameraDevice::CameraDevice (const String& name_, int index)
  237031. : name (name_)
  237032. {
  237033. isRecording = false;
  237034. internal = new QTCameraDeviceInteral (this, index);
  237035. }
  237036. CameraDevice::~CameraDevice()
  237037. {
  237038. stopRecording();
  237039. delete static_cast <QTCameraDeviceInteral*> (internal);
  237040. internal = 0;
  237041. }
  237042. Component* CameraDevice::createViewerComponent()
  237043. {
  237044. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  237045. }
  237046. const String CameraDevice::getFileExtension()
  237047. {
  237048. return ".mov";
  237049. }
  237050. void CameraDevice::startRecordingToFile (const File& file, int quality)
  237051. {
  237052. stopRecording();
  237053. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237054. d->callbackDelegate->firstPresentationTime = 0;
  237055. file.deleteFile();
  237056. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  237057. // out wrong, so we'll put some audio in there too..,
  237058. d->addDefaultAudioInput();
  237059. [d->session addOutput: d->fileOutput error: nil];
  237060. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  237061. for (;;)
  237062. {
  237063. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  237064. if (connection == 0)
  237065. break;
  237066. QTCompressionOptions* options = 0;
  237067. NSString* mediaType = [connection mediaType];
  237068. if ([mediaType isEqualToString: QTMediaTypeVideo])
  237069. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  237070. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  237071. : @"QTCompressionOptions240SizeH264Video"];
  237072. else if ([mediaType isEqualToString: QTMediaTypeSound])
  237073. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  237074. [d->fileOutput setCompressionOptions: options forConnection: connection];
  237075. }
  237076. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  237077. isRecording = true;
  237078. }
  237079. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  237080. {
  237081. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237082. if (d->callbackDelegate->firstPresentationTime != 0)
  237083. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  237084. return Time();
  237085. }
  237086. void CameraDevice::stopRecording()
  237087. {
  237088. if (isRecording)
  237089. {
  237090. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  237091. isRecording = false;
  237092. }
  237093. }
  237094. void CameraDevice::addListener (Listener* listenerToAdd)
  237095. {
  237096. if (listenerToAdd != 0)
  237097. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  237098. }
  237099. void CameraDevice::removeListener (Listener* listenerToRemove)
  237100. {
  237101. if (listenerToRemove != 0)
  237102. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  237103. }
  237104. const StringArray CameraDevice::getAvailableDevices()
  237105. {
  237106. const ScopedAutoReleasePool pool;
  237107. StringArray results;
  237108. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237109. for (int i = 0; i < (int) [devs count]; ++i)
  237110. {
  237111. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  237112. results.add (nsStringToJuce ([dev localizedDisplayName]));
  237113. }
  237114. return results;
  237115. }
  237116. CameraDevice* CameraDevice::openDevice (int index,
  237117. int minWidth, int minHeight,
  237118. int maxWidth, int maxHeight)
  237119. {
  237120. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  237121. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  237122. return d.release();
  237123. return 0;
  237124. }
  237125. #endif
  237126. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  237127. #endif
  237128. #endif
  237129. END_JUCE_NAMESPACE
  237130. #endif
  237131. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  237132. #endif
  237133. #endif